[or-cvs] r16913: {projects} This actually implements the other half of yesterdays commit (projects/gettor)

ioerror at seul.org ioerror at seul.org
Mon Sep 15 21:26:45 UTC 2008


Author: ioerror
Date: 2008-09-15 17:26:45 -0400 (Mon, 15 Sep 2008)
New Revision: 16913

Modified:
   projects/gettor/gettor.py
   projects/gettor/gettor_blacklist.py
   projects/gettor/gettor_config.py
   projects/gettor/gettor_log.py
   projects/gettor/gettor_requests.py
   projects/gettor/gettor_responses.py
Log:
This actually implements the other half of yesterdays commit. There was an error with the patch. We've refactored some code and added getopts. Major code change by kaner.


Modified: projects/gettor/gettor.py
===================================================================
--- projects/gettor/gettor.py	2008-09-15 14:32:04 UTC (rev 16912)
+++ projects/gettor/gettor.py	2008-09-15 21:26:45 UTC (rev 16913)
@@ -54,28 +54,57 @@
 except ImportError:
     antigravity = None
 
+import sys
+import getopt
+import gettext
 import gettor_blacklist
 import gettor_requests
 import gettor_responses
 from gettor_log import gettorLogger
+from gettor_config import gettorConf
 
-log = gettorLogger()
 
+def usage():
+    print "Usage: gettor.py [-c CONFIG|-h]"
+    print ""
+
 if __name__ == "__main__":
 
+    # Parse args
+    try:
+        opts, args = getopt.getopt(sys.argv[1:], 'hc:', ['help', 'config='])
+    except getopt.GetoptError:
+        usage()
+        sys.exit(1)
+ 
+    config = None
+    for c, optarg in opts:
+        if c in ("-h", "--help"):
+            usage()
+            sys.exit(0)
+        if c in ("-c", "--config"):
+            config = optarg
 
+    if config != None:
+        conf = gettorConf(config)
+    else:
+        conf = gettorConf()
+    log  = gettorLogger()
+    locale = conf.getLocale()
+    trans = gettext.translation("gettor", "/usr/share/locale", [locale]) 
+    trans.install()
     rawMessage = gettor_requests.getMessage()
     parsedMessage = gettor_requests.parseMessage(rawMessage)
 
     if not parsedMessage:
-        log.log("No parsed message. Dropping message.")
+        log.log(_("No parsed message. Dropping message."))
         exit(0)
 
     signature = False
     signature = gettor_requests.verifySignature(rawMessage)
-    log.log("Signature is : " + str(signature))
+    log.log(_("Signature is: %s") % str(signature))
     replyTo = False
-    srcEmail = "gettor at torproject.org"
+    srcEmail = conf.getSrcEmail()
 
     # TODO XXX:
     # Make the zip files and ensure they match packageList
@@ -84,7 +113,7 @@
     #   vidalia-bundle-0.2.0.29-rc-0.1.6.exe \
     #   vidalia-bundle-0.2.0.29-rc-0.1.6.exe.asc
     #
-    distDir = "/var/lib/gettor/pkg/"
+    distDir = conf.getDistDir()
     packageList = {
         "windows-bundle": distDir + "windows-bundle.z",
         "macosx-panther-ppc-bundle": distDir + "macosx-panther-ppc-bundle.z",
@@ -100,17 +129,17 @@
         previouslyHelped = gettor_blacklist.blackList(replyTo)
     
     if not replyTo:
-        log.log("No help dispatched. Invalid reply address for user.")
+        log.log(_("No help dispatched. Invalid reply address for user."))
         exit(0)
 
     if not signature and previouslyHelped:
-        log.log("Unsigned messaged to gettor by blacklisted user dropped.")
+        log.log(_("Unsigned messaged to gettor by blacklisted user dropped."))
         exit(0)
 
     if not signature and not previouslyHelped:
         # Reply with some help and bail out
         gettor_blacklist.blackList(replyTo, True)
-        message = """
+        message = _("""
 Hello! This is the "get tor" robot.
 
 Unfortunately, we won't answer you at this address. We only process
@@ -123,14 +152,14 @@
 
 (We apologize if you didn't ask for this mail. Since your email is from
 a service that doesn't use DKIM, we're sending a short explanation,
-and then we'll ignore this email address for the next day or so.)
-        """
+and then we'll ignore this email address for the next day or so.
+        """)
         gettor_responses.sendHelp(message, srcEmail, replyTo)
-        log.log("Unsigned messaged to gettor. We issued some help about using DKIM.")
+        log.log(_("Unsigned messaged to gettor. We issued some help about using DKIM."))
         exit(0)
 
     if signature:
-        log.log("Signed messaged to gettor.")
+        log.log(_("Signed messaged to gettor."))
         
         try:
             package = gettor_requests.parseRequest(parsedMessage, packageList)
@@ -138,18 +167,20 @@
             package = None
 
         if package != None:
-            log.log("Package: " + str(package) + " selected.")
-            message = "Here's your requested software as a zip file. Please " + \
-            "unzip the package and verify the signature."
+            log.log(_("Package: %s selected.") % str(package))
+            message = _("""
+Here's your requested software as a zip file. Please unzip the 
+package and verify the signature.
+            """)
             gettor_responses.sendPackage(message, srcEmail, replyTo, packageList[package])  
             exit(0)
         else:
-            message = ["Hello, I'm a robot. "]
-            message.append("Your request was not understood. Please select one of the following package names:\n")
+            message = [_("Hello, I'm a robot. ")]
+            message.append(_("Your request was not understood. Please select one of the following package names:\n"))
 
             for key in packageList.keys():
                 message.append(key + "\n")
-            message.append("Please send me another email. It only needs a single package name anywhere in the body of your email.\n")
+            message.append(_("Please send me another email. It only needs a single package name anywhere in the body of your email.\n"))
             gettor_responses.sendHelp(''.join(message), srcEmail, replyTo)
-            log.log("Signed messaged to gettor. We issued some help about proper email formatting.")
+            log.log(_("Signed messaged to gettor. We issued some help about proper email formatting."))
             exit(0)

Modified: projects/gettor/gettor_blacklist.py
===================================================================
--- projects/gettor/gettor_blacklist.py	2008-09-15 14:32:04 UTC (rev 16912)
+++ projects/gettor/gettor_blacklist.py	2008-09-15 21:26:45 UTC (rev 16913)
@@ -5,9 +5,11 @@
 
 import hashlib
 import os
+from gettor_config import gettorConf
 
-stateDir = "/var/lib/gettor/"
-blStateDir = stateDir + "bl/"
+conf = gettorConf()
+stateDir = conf.getStateDir()
+blStateDir = conf.getBlStateDir()
 
 def blackList(address, createEntry=False):
     """ 
@@ -30,7 +32,7 @@
 
     return False
 
-def lookupBlackListEntry(privateAddress, stateDir="/var/lib/gettor/bl/"):
+def lookupBlackListEntry(privateAddress):
     """ Check to see if we have a blacklist entry for the given address. """
     entry = stateDir + str(privateAddress)
     try:
@@ -39,9 +41,9 @@
         return False
     return True
 
-def createBlackListEntry(privateAddress, stateDir="/var/lib/gettor/bl/"):
+def createBlackListEntry(privateAddress):
     """ Create a zero byte file that represents the address in our blacklist. """
-    entry = stateDir + str(privateAddress)
+    entry = blStateDir + str(privateAddress)
     stat = None
     try:
         stat = os.stat(entry)
@@ -54,9 +56,9 @@
             return False
     return False
 
-def removeBlackListEntry(privateAddress, stateDir="/var/lib/gettor/bl/"):
+def removeBlackListEntry(privateAddress):
     """ Remove the zero byte file that represents an entry in our blacklist."""
-    entry = stateDir + str(privateAddress)
+    entry = blStateDir + str(privateAddress)
     stat = None
     try:
         entry = os.unlink(entry)
@@ -70,7 +72,7 @@
     privateAddress = hash.hexdigest()
     return privateAddress
 
-def prepBLStateDir(stateDir = "/var/lib/gettor/"):
+def prepBLStateDir():
     stat = None
     try:
         stat = os.stat(stateDir)

Modified: projects/gettor/gettor_config.py
===================================================================
--- projects/gettor/gettor_config.py	2008-09-15 14:32:04 UTC (rev 16912)
+++ projects/gettor/gettor_config.py	2008-09-15 21:26:45 UTC (rev 16913)
@@ -71,7 +71,7 @@
             self.config.set("global", "distDir", self.distDir)
 
         if self.config.has_option("global", "locale"):
-            self.lang = self.config.get("global", "locale")
+            self.locale = self.config.get("global", "locale")
         else:
             self.config.set("global", "locale", self.locale)
 
@@ -101,8 +101,8 @@
     def getDistDir(self):
         return self.distDir
 
-    def getLang(self):
-        return self.lang
+    def getLocale(self):
+        return self.locale
 
     def getLogSubSystem(self):
         return self.logSubSystem

Modified: projects/gettor/gettor_log.py
===================================================================
--- projects/gettor/gettor_log.py	2008-09-15 14:32:04 UTC (rev 16912)
+++ projects/gettor/gettor_log.py	2008-09-15 21:26:45 UTC (rev 16913)
@@ -31,9 +31,18 @@
                 self.logfd = open(logfile, "a+")
             except:
                 self.logfd = None
+
+    def _del_(self):
+        if logger == "file" and self.logfd == None:
+            self.logfd.close()
     
     def log(self, message):
-        now = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
+        # Syslog does not need a timestamp
+        if self.logger == "syslog":
+            now = ""
+        else:
+            now = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
+
         message = self.logPrefix + now + " : "+ message
 
         # By default, we'll just drop the message
@@ -46,7 +55,6 @@
             
         elif self.logger == "file":
             self.logfd.write(message)
-            self.logfd.close()
 
         elif self.logger == "stdout":
             print message

Modified: projects/gettor/gettor_requests.py
===================================================================
--- projects/gettor/gettor_requests.py	2008-09-15 14:32:04 UTC (rev 16912)
+++ projects/gettor/gettor_requests.py	2008-09-15 21:26:45 UTC (rev 16913)
@@ -62,23 +62,23 @@
         "source-bundle": "/var/lib/gettor/pkg/source-bundle.z"
         }
 
-    print "Fetching raw message."
+    print _("Fetching raw message.")
     rawMessage = getMessage()
     # This doesn't work without DNS ( no wifi on board current airplane )
-    print "Verifying signature of message."
+    print _("Verifying signature of message.")
     signature = verifySignature(rawMessage)
-    print "Parsing Message."
+    print _("Parsing Message.")
     parsedMessage = parseMessage(rawMessage)
-    print "Parsing reply."
+    print _("Parsing reply.")
     parsedReply = parseReply(parsedMessage)
-    print "Parsing package request."
+    print _("Parsing package request.")
     package = parseRequest(parsedMessage, packageList)
     if package == None:
         package = "help"        
     else:
         package = packageList[package]
 
-    print "The signature status of the email is: " + str(signature)
-    print "The email requested the following reply address: " + parsedReply
-    print "It looks like the email requested the following package: " + package
-    print "We would select the following package file: " + package
+    print _("The signature status of the email is: %s") % str(signature)
+    print _("The email requested the following reply address: %s") % parsedReply
+    print _("It looks like the email requested the following package: %s") % package
+    print _("We would select the following package file: ") % package

Modified: projects/gettor/gettor_responses.py
===================================================================
--- projects/gettor/gettor_responses.py	2008-09-15 14:32:04 UTC (rev 16912)
+++ projects/gettor/gettor_responses.py	2008-09-15 21:26:45 UTC (rev 16913)
@@ -32,7 +32,7 @@
     message = StringIO.StringIO()
     mime = MimeWriter.MimeWriter(message)
     mime.addheader('MIME-Version', '1.0')
-    mime.addheader('Subject', 'Re: Your "get tor" request')
+    mime.addheader('Subject', _('Re: Your "get tor" request'))
     mime.addheader('To', recipient)
     mime.addheader('From', ourAddress)
     mime.startmultipartbody('mixed')



More information about the tor-commits mailing list