[Nym3-commit] r467 - trunk/nymbaron/Server

laurent at conuropsis.org laurent at conuropsis.org
Wed Mar 8 22:21:55 CET 2006


Author: laurent
Date: 2006-03-08 22:21:54 +0100 (Wed, 08 Mar 2006)
New Revision: 467

Modified:
   trunk/nymbaron/Server/User.py
Log:
Indentation

Modified: trunk/nymbaron/Server/User.py
===================================================================
--- trunk/nymbaron/Server/User.py	2006-03-08 21:01:55 UTC (rev 466)
+++ trunk/nymbaron/Server/User.py	2006-03-08 21:21:54 UTC (rev 467)
@@ -75,10 +75,10 @@
 
     paddingLen = PAYLOAD_LEN - SINGLETON_PAYLOAD_OVERHEAD - overhead - compressedLen
     if paddingLen >= 0:
-	return 1
+        return 1
 
     if uncompressedFragmentPrefix:
-	compressedLen += len(uncompressedFragmentPrefix)
+        compressedLen += len(uncompressedFragmentPrefix)
 
     p = mixminion.Fragments.FragmentationParams(compressedLen, overhead)
 
@@ -94,100 +94,100 @@
     f.close()
     (outr, outw) = os.pipe()
     if os.fork() == 0:
-	sys.stdin.close()
-	os.close(outr)
-	os.dup2(outw, sys.stdout.fileno())
-	os.execlp("mixminion", "mixminion", "inspect-surb", fname)
-	sys.exit(0)
+        sys.stdin.close()
+        os.close(outr)
+        os.dup2(outw, sys.stdout.fileno())
+        os.execlp("mixminion", "mixminion", "inspect-surb", fname)
+        sys.exit(0)
     else:
-	os.close(outw)
-	foo = os.fdopen(outr)
-	out = foo.read()
-	foo.close() #TODO do we need to close outr?
-	os.wait()
-	os.unlink(fname)
-	try:
-	    expDate = re.search("Expires at: (.*)\n", out).group(1)
-	    used = re.search("Used: (.*)[\n$]", out).group(1)
-	    eD = time.strptime(expDate, "%Y-%m-%d %H:%M:%S GMT")
-	    return calendar.timegm(eD) > time.time() and used == "no"
-	except AttributeError, inst:
-	    sys.stderr.write("Bug\n")
-	    print inst
-	    sys.exit(2)
-	except ValueError:
-	    #TODO temporary cruft, we should get the expiracy date through the
-	    #library
-	    sys.stderr.write("Wrong date format, unable to determine expiracy" +
-		    " date\n")
-	    sys.exit(2)
+        os.close(outw)
+        foo = os.fdopen(outr)
+        out = foo.read()
+        foo.close() #TODO do we need to close outr?
+        os.wait()
+        os.unlink(fname)
+        try:
+            expDate = re.search("Expires at: (.*)\n", out).group(1)
+            used = re.search("Used: (.*)[\n$]", out).group(1)
+            eD = time.strptime(expDate, "%Y-%m-%d %H:%M:%S GMT")
+            return calendar.timegm(eD) > time.time() and used == "no"
+        except AttributeError, inst:
+            sys.stderr.write("Bug\n")
+            print inst
+            sys.exit(2)
+        except ValueError:
+            #TODO temporary cruft, we should get the expiracy date through the
+            #library
+            sys.stderr.write("Wrong date format, unable to determine expiracy" +
+                    " date\n")
+            sys.exit(2)
     
 class User:
     """Hold user data. Specifically, this means:
-	
-	- username is the nym of the account. It is used to reference the
-	  account, but also as localpart of the email adress of the nym account.
-	- received is the list of received messages that have not been
-	  acknowledged yet.
-	- nSurbs is a upper bound on the number of surbs that can be used to
-	  send command messages to the nymholder
-	- seqNo is the index that will be given to the next message received by
-	  this nym account. It is included in the synopsis of the message and
-	  incremented after that. Starts at 0.
-	- idKey is the identification key of the nymholder (used to verify
-	  signatures)
-	- encKey is the encryption key of the nymholder (used to encrypt
-	  messages)
-	- usage is the volume of data in the account on the server
-	- quota is the maximum volume of data in the account on the server
-	- index is a dictionary mid -> (time, status) where time is the time at
-	  which the message was received, and status describes the status of the
-	  message (whereas synopsis was sent, wheres message has been
-	  deleted...)
-	- mbox is a dictionary mid -> encrypted message
-	- syn is a list of (l, status, content) where l is the list of mids
-	  whose synopsis is in the content, status tells whether the content is
-	  encrypted or not and content contains the synopsis or encrypted
-	  synopses"""
+        
+        - username is the nym of the account. It is used to reference the
+          account, but also as localpart of the email adress of the nym account.
+        - received is the list of received messages that have not been
+          acknowledged yet.
+        - nSurbs is a upper bound on the number of surbs that can be used to
+          send command messages to the nymholder
+        - seqNo is the index that will be given to the next message received by
+          this nym account. It is included in the synopsis of the message and
+          incremented after that. Starts at 0.
+        - idKey is the identification key of the nymholder (used to verify
+          signatures)
+        - encKey is the encryption key of the nymholder (used to encrypt
+          messages)
+        - usage is the volume of data in the account on the server
+        - quota is the maximum volume of data in the account on the server
+        - index is a dictionary mid -> (time, status) where time is the time at
+          which the message was received, and status describes the status of the
+          message (whereas synopsis was sent, wheres message has been
+          deleted...)
+        - mbox is a dictionary mid -> encrypted message
+        - syn is a list of (l, status, content) where l is the list of mids
+          whose synopsis is in the content, status tells whether the content is
+          encrypted or not and content contains the synopsis or encrypted
+          synopses"""
     def __init__(self, username, config, create = 0):
         """0 : load user data throw an error if the user doesn't exist
         1 : create user data throw an error if the user exists
         _ : load a user data, if it doesn't exist create a new user silently
-	"""
+        """
         self.datafile = config.path + os.sep + username + '.dat'
-	self.config = config
-	self.username = username
-	self.index = None
-	self.mbox = None
-	self.syn = None
-	self.data = None
-	self.lock = None
+        self.config = config
+        self.username = username
+        self.index = None
+        self.mbox = None
+        self.syn = None
+        self.data = None
+        self.lock = None
         self._abort = False
-	try:
+        try:
             self._lock()
-	except OSError: # Can happen for invalid usernames.
-			# TODO : validate username against sensible pattern.
-	    raise NoSuchUser()
-	try:
-	    f = open(self.datafile, 'r')
+        except OSError: # Can happen for invalid usernames.
+                        # TODO : validate username against sensible pattern.
+            raise NoSuchUser()
+        try:
+            f = open(self.datafile, 'r')
             if (create == 1):
-		f.close()
-		del self
-		raise AlreadySuchUser
-	    self.data = pickle.load(f)
-	    f.close()
-	except IOError:
-	    if create == 0:
+                f.close()
+                del self
+                raise AlreadySuchUser
+            self.data = pickle.load(f)
+            f.close()
+        except IOError:
+            if create == 0:
                 raise NoSuchUser()
-	    self.data = config.default_settings
-	    self.data['username'] = username
-    	    self.data['received'] = []
-	    self.data['nSurbs'] = 0
-	    self.data['seqNo'] = 0
+            self.data = config.default_settings
+            self.data['username'] = username
+            self.data['received'] = []
+            self.data['nSurbs'] = 0
+            self.data['seqNo'] = 0
 
     def __del__(self):
-	"""Flush the information contained in this User to the disk
-	"""
+        """Flush the information contained in this User to the disk
+        """
         if (not self._abort):
             self._save_index()
             self._save_synbox()
@@ -196,23 +196,23 @@
         self._release()
     
     def __getitem__(self, key):
-	"""Gets the fields of this Object as if a hashtable
-	"""
-	return self.data[key]
+        """Gets the fields of this Object as if a hashtable
+        """
+        return self.data[key]
 
     def __setitem__(self, key, value):
-	"""Sets the fields of this Object as if a hashtable"""
-	self.data[key] = value
+        """Sets the fields of this Object as if a hashtable"""
+        self.data[key] = value
 
     def _lock(self):
-	"""Lock the user. For well behaved functions."""
-	self.lock = mixminion.Common.Lockfile(self.config.path + os.sep + 
-					      self.username + '.lck')
-	self.lock.acquire(blocking = 1)
+        """Lock the user. For well behaved functions."""
+        self.lock = mixminion.Common.Lockfile(self.config.path + os.sep + 
+                                              self.username + '.lck')
+        self.lock.acquire(blocking = 1)
 
     def _release(self):
-	"""Releases the lock"""
-	if self.lock:
+        """Releases the lock"""
+        if self.lock:
             self.lock.release()
 
     def abort(self):
@@ -226,65 +226,65 @@
             self._abort = True
 
     def timecmp(self, a, b):
-	return cmp(self.index[a]['time'], self.index[b]['time'])
+        return cmp(self.index[a]['time'], self.index[b]['time'])
 
     def quota(self):
-	"""Gets the quota, the maximum data size authorized"""
-	return self.data['quota']
+        """Gets the quota, the maximum data size authorized"""
+        return self.data['quota']
 
     def usage(self):
-	"""Gets the usage, the actual data size used"""
-	sum = 0
-	try:
-	    sum = os.stat(self.surbfile())[6]
-	except: pass
-	try:
-	    sum = sum + os.stat(self.indexfile())[6]
-	except: pass
-	try:
-	    sum = sum + os.stat(self.synboxfile())[6]
-	except: pass
-	try:
-	    sum = sum + os.stat(self.mboxfile())[6]
-	except: pass
-	self.data['usage'] = sum
-	return sum
+        """Gets the usage, the actual data size used"""
+        sum = 0
+        try:
+            sum = os.stat(self.surbfile())[6]
+        except: pass
+        try:
+            sum = sum + os.stat(self.indexfile())[6]
+        except: pass
+        try:
+            sum = sum + os.stat(self.synboxfile())[6]
+        except: pass
+        try:
+            sum = sum + os.stat(self.mboxfile())[6]
+        except: pass
+        self.data['usage'] = sum
+        return sum
 
     def received(self, seqNo):
-	self['received'].append(seqNo)
+        self['received'].append(seqNo)
 
     def idKey(self):
-	"""Gets the user public key used for identification"""
+        """Gets the user public key used for identification"""
         return self.data['idKey']
 
     def encKey(self):
-	"""Gets the user public key used for encryption"""
+        """Gets the user public key used for encryption"""
         return self.data['encKey']
 
     def blobify(self, l):
         """encrypts a set of synopses
         l is a list of tuples (mid, status, synopsis) """
-	if len(l) == 0:
+        if len(l) == 0:
             return None
         s = ""
         m = []
         for mid, status, syn in l:
-	    assert status == "clear"
-	    assert len(mid) == 1
-	    m = m + mid
-	    #print "mid = %s, status = %s, syn = %s\n" % (str(mid), str(status), str(syn))
+            assert status == "clear"
+            assert len(mid) == 1
+            m = m + mid
+            #print "mid = %s, status = %s, syn = %s\n" % (str(mid), str(status), str(syn))
             s = s + mid[0] + intToStrBE(len(syn), 2) + syn
         return (m, 'encrypted', Crypto.nym_encrypt(s, self.encKey()))
 
     def getSyn(self, mid):
-	"""Retrieve a blurb consisting of the synopsis of the
-	   requested synopsis mid. May contain unwanted synopsis
-	   too."""
-	self.load_synbox()
-	for i, (midlist, status, synblob) in enumerate(self.syn):
-	    if mid in midlist:
+        """Retrieve a blurb consisting of the synopsis of the
+           requested synopsis mid. May contain unwanted synopsis
+           too."""
+        self.load_synbox()
+        for i, (midlist, status, synblob) in enumerate(self.syn):
+            if mid in midlist:
                 return i, (midlist, status, synblob)
-	raise ValueError()
+        raise ValueError()
 
     def getMail(self, mid):
         """Retrieve an encrypted mail with a given mid from the mbox
@@ -296,420 +296,420 @@
             raise ValueError()
         
     def midAfter(self, mid):
-	"""Retrieve mids of messages that came strictly after message `mid'
+        """Retrieve mids of messages that came strictly after message `mid'
         the elements of the output are ordered by ascending
         order of arrival time"""
-	self.load_index()
+        self.load_index()
 
-	ret = []
-	#TODO if the mid can't be found in the index tab, what do we do?
-	if mid == Mail.oldestMid:
+        ret = []
+        #TODO if the mid can't be found in the index tab, what do we do?
+        if mid == Mail.oldestMid:
             ret = self.index.keys()
-	else:
-	    midtime = self.index[mid]['time']
-	    for msg in self.index.keys():
-		if self.index[msg]['time'] > midtime:
+        else:
+            midtime = self.index[mid]['time']
+            for msg in self.index.keys():
+                if self.index[msg]['time'] > midtime:
                     ret.append(msg)
-	ret.sort(self.timecmp)
-	return ret
+        ret.sort(self.timecmp)
+        return ret
     
     def _save_data(self):
-	"""Flush to the disk the non message related data contained by this User object
-	"""
-	if self.data == None:
+        """Flush to the disk the non message related data contained by this User object
+        """
+        if self.data == None:
             return
-	f = open(self.datafile, 'w')
-	pickle.dump(self.data, f)
-	f.close()
+        f = open(self.datafile, 'w')
+        pickle.dump(self.data, f)
+        f.close()
 
     def surbfile(self):
-	"""Gets the path to file containing the surbs to send messages to the nymholder
-	"""
-	return self.config.path + os.sep + self.data['username'] + '.surbs'
+        """Gets the path to file containing the surbs to send messages to the nymholder
+        """
+        return self.config.path + os.sep + self.data['username'] + '.surbs'
 
     def advanced_send(self, msg, add_status = True):
-	"""Sends a message to the nymholder through the mixminion network,
-	using the surbs provided by the nymholder. Adds a status control
-	message if the add_status argument is True. Also updates the number
-	of surbs"""
-	#TODO add the filling of the remaining place available in the the
-	#message by syns and msgs here
-	statusc = Message.Status()
-	nMsg = 0
-	usage = 0
-	cmsg = msg
-	if add_status:
-	    #determine the status elements, the number of surbs is assumed
-	    #to stay equal to its value
-	    self.load_index()
-	    for _, v in self.index.iteritems():
-		if v['status'] in [lifeCycle['nothing-sent'], lifeCycle['synopsis-sent']]:
-		    nMsg += 1
-	    usage = self.usage()
-	    statusc.fromData(nMsg, 0, self.quota(), usage, self['received'])
-	    cmsg += str(statusc)
-	nb_req_surb = getNPacketsToEncode(cmsg, 0)
-	if add_status:
-	    while True:
-		statusc.fromData(nMsg, self['nSurbs'] - nb_req_surb,
-			self.quota(), usage, self['received'])
-		cmsg = msg + str(statusc)
-		act_nb = getNPacketsToEncode(cmsg, 0)
-		old_nb_req_surb = nb_req_surb
-		nb_req_surb = act_nb
-		if nb_req_surb <= old_nb_req_surb:
-		    break
-       	if nb_req_surb > self['nSurbs']:
-	    #TODO
-	    # - send an Error message "low on surbs" if a surb is available
-	    # - store the message we couldn't send for later
-	    return 1
-	#TODO debbuging cruft
-	print "%d surbs used to send control messages" % nb_req_surb
-	self['nSurbs'] -= nb_req_surb
-	self['received'] = []
-	return self.send(cmsg)
-	    	
+        """Sends a message to the nymholder through the mixminion network,
+        using the surbs provided by the nymholder. Adds a status control
+        message if the add_status argument is True. Also updates the number
+        of surbs"""
+        #TODO add the filling of the remaining place available in the the
+        #message by syns and msgs here
+        statusc = Message.Status()
+        nMsg = 0
+        usage = 0
+        cmsg = msg
+        if add_status:
+            #determine the status elements, the number of surbs is assumed
+            #to stay equal to its value
+            self.load_index()
+            for _, v in self.index.iteritems():
+                if v['status'] in [lifeCycle['nothing-sent'], lifeCycle['synopsis-sent']]:
+                    nMsg += 1
+            usage = self.usage()
+            statusc.fromData(nMsg, 0, self.quota(), usage, self['received'])
+            cmsg += str(statusc)
+        nb_req_surb = getNPacketsToEncode(cmsg, 0)
+        if add_status:
+            while True:
+                statusc.fromData(nMsg, self['nSurbs'] - nb_req_surb,
+                        self.quota(), usage, self['received'])
+                cmsg = msg + str(statusc)
+                act_nb = getNPacketsToEncode(cmsg, 0)
+                old_nb_req_surb = nb_req_surb
+                nb_req_surb = act_nb
+                if nb_req_surb <= old_nb_req_surb:
+                    break
+        if nb_req_surb > self['nSurbs']:
+            #TODO
+            # - send an Error message "low on surbs" if a surb is available
+            # - store the message we couldn't send for later
+            return 1
+        #TODO debbuging cruft
+        print "%d surbs used to send control messages" % nb_req_surb
+        self['nSurbs'] -= nb_req_surb
+        self['received'] = []
+        return self.send(cmsg)
+                    
 
     def send(self, msg):
-	"""Sends a message to the nymholder through the mixminion network,
-	using the surbs provided by the nymholder"""
-	fname = Mail.tmpFileMsg(msg)
-	if self.config.online:
-	    ec = os.system("mixminion send -R " + self.surbfile() + " -i " +
-		fname)
-	else:
-	    ec = 0
-	if self.config.DEBUG:
-	    print "Message file left in " + fname
-	else:
-	    os.unlink(fname)
-	return ec
+        """Sends a message to the nymholder through the mixminion network,
+        using the surbs provided by the nymholder"""
+        fname = Mail.tmpFileMsg(msg)
+        if self.config.online:
+            ec = os.system("mixminion send -R " + self.surbfile() + " -i " +
+                fname)
+        else:
+            ec = 0
+        if self.config.DEBUG:
+            print "Message file left in " + fname
+        else:
+            os.unlink(fname)
+        return ec
 
     def clean_surbs(self):
-	"""Inspect the surbs and delete the used/outdated"""
-	pass
-	fname = self.surbfile()
-	f = open(fname, "r")
-	buffer = f.read()
-	f.close()
-	surbs = parseReplyBlocks(buffer)
-	goods = []
-	nr = 0
-	for surb in surbs:
-	    surbp = surb.pack() #the value of surb as a string
-	    if check_surb(surbp):
-		goods.append(surbp)
-	    else:
-		nr = nr + 1
-	f = open(self.surbfile(), "w")
-	for surbp in goods:
-	    f.write(surbp)
-	self.data['nSurbs'] = len(goods)
-	print "%d surbs removed" % nr
-	f.close()
+        """Inspect the surbs and delete the used/outdated"""
+        pass
+        fname = self.surbfile()
+        f = open(fname, "r")
+        buffer = f.read()
+        f.close()
+        surbs = parseReplyBlocks(buffer)
+        goods = []
+        nr = 0
+        for surb in surbs:
+            surbp = surb.pack() #the value of surb as a string
+            if check_surb(surbp):
+                goods.append(surbp)
+            else:
+                nr = nr + 1
+        f = open(self.surbfile(), "w")
+        for surbp in goods:
+            f.write(surbp)
+        self.data['nSurbs'] = len(goods)
+        print "%d surbs removed" % nr
+        f.close()
 
     def addSurbs(self, newsurbs):
-	"""Adds newsurbs to the store of surbs. We make sure they are neither
-	used, nor already present"""
-	#TODO call to mixminion to remove once the clientAPI is ok
-	#load the surbs
-	fname = self.surbfile()
-	surbslist = []
-	try:
-	    f = open(fname, "r")
-	    surbs = f.read()
-	    f.close()
-	    #TODO catch the possible parseError here?
-	    surbslist = parseReplyBlocks(surbs)
-	except IOError:
-	    surbslist = []
-	#keep the not used ones
-	olds = []
-	goods = []
-	for surb in surbslist:
-	    surbp = surb.pack()
-	    olds.append(surbp)
-	try:
-	    #add the new ones
-	    newsurbslist = parseReplyBlocks(newsurbs)
-	    for newsurb in newsurbslist:
-		newsurbp = newsurb.pack()
-		if (not newsurbp in (olds + goods)) and check_surb(newsurbp):
-		    goods.append(newsurbp)
-	    #save the result    
-	    self['nSurbs'] = self['nSurbs'] + len(goods)
-	    fname = self.surbfile()
-	    f = open(fname, "a")
-	    for surbp in goods:
-		f.write(surbp)
-	    f.close()
-	    print "%d surbs added" % len(goods)
-	except ParseError:
-	    #the provided binary data isn't a succession of binary surbs
-	    return
-	
+        """Adds newsurbs to the store of surbs. We make sure they are neither
+        used, nor already present"""
+        #TODO call to mixminion to remove once the clientAPI is ok
+        #load the surbs
+        fname = self.surbfile()
+        surbslist = []
+        try:
+            f = open(fname, "r")
+            surbs = f.read()
+            f.close()
+            #TODO catch the possible parseError here?
+            surbslist = parseReplyBlocks(surbs)
+        except IOError:
+            surbslist = []
+        #keep the not used ones
+        olds = []
+        goods = []
+        for surb in surbslist:
+            surbp = surb.pack()
+            olds.append(surbp)
+        try:
+            #add the new ones
+            newsurbslist = parseReplyBlocks(newsurbs)
+            for newsurb in newsurbslist:
+                newsurbp = newsurb.pack()
+                if (not newsurbp in (olds + goods)) and check_surb(newsurbp):
+                    goods.append(newsurbp)
+            #save the result    
+            self['nSurbs'] = self['nSurbs'] + len(goods)
+            fname = self.surbfile()
+            f = open(fname, "a")
+            for surbp in goods:
+                f.write(surbp)
+            f.close()
+            print "%d surbs added" % len(goods)
+        except ParseError:
+            #the provided binary data isn't a succession of binary surbs
+            return
+        
     def delSurbs(self):
-	"""Deletes all the surbs of the surb store"""
-	fname = self.surbfile()
+        """Deletes all the surbs of the surb store"""
+        fname = self.surbfile()
         os.unlink(fname)
-	self.data['nSurbs'] = 0
+        self.data['nSurbs'] = 0
 
     def load_mbox(self):
-	"""Loads the mailbox from the disk"""
-	if not self.mbox == None:
+        """Loads the mailbox from the disk"""
+        if not self.mbox == None:
             return
-	mbox = self.mboxfile()
-	try:
-	    f = open(mbox, 'r')
-	    self.mbox = pickle.load(f)
-	    f.close()
-	except IOError:
-	    self.mbox = {}
+        mbox = self.mboxfile()
+        try:
+            f = open(mbox, 'r')
+            self.mbox = pickle.load(f)
+            f.close()
+        except IOError:
+            self.mbox = {}
 
     def mboxfile(self):
-	"""Gets the mailbox file name"""
-	return self.config.path + os.sep + self.data['username'] + '.mbox'
+        """Gets the mailbox file name"""
+        return self.config.path + os.sep + self.data['username'] + '.mbox'
 
     def _save_mbox(self):
-	"""Flushs the mailbox to the disk"""
-	if self.mbox == None:
+        """Flushs the mailbox to the disk"""
+        if self.mbox == None:
             return
-	mbox = self.mboxfile()
-	f = open(mbox, 'w')
-	pickle.dump(self.mbox, f)
-	f.close()
+        mbox = self.mboxfile()
+        f = open(mbox, 'w')
+        pickle.dump(self.mbox, f)
+        f.close()
 
     def synboxfile(self):
-	"""Gets the synbox file name"""
-	return self.config.path + os.sep + self.data['username'] + '.syn'
+        """Gets the synbox file name"""
+        return self.config.path + os.sep + self.data['username'] + '.syn'
 
     def indexfile(self):
-	"""Gets the index filename"""
-	return self.config.path + os.sep + self.data['username'] + '.idx'
-	
+        """Gets the index filename"""
+        return self.config.path + os.sep + self.data['username'] + '.idx'
+        
     def load_synbox(self):
-	"""Loads the synbox, structure containing synopses, from the disk"""
-	if not self.syn == None:
+        """Loads the synbox, structure containing synopses, from the disk"""
+        if not self.syn == None:
             return
-	synbox = self.synboxfile()
-	try:
-	    f = open(synbox, 'r')
-	    self.syn = pickle.load(f)
-	    f.close()
-	except IOError:
-	    self.syn = []
+        synbox = self.synboxfile()
+        try:
+            f = open(synbox, 'r')
+            self.syn = pickle.load(f)
+            f.close()
+        except IOError:
+            self.syn = []
 
     def _save_synbox(self):
-	"""Flushs the synbox to the disk"""
-	if self.syn == None:
+        """Flushs the synbox to the disk"""
+        if self.syn == None:
             return
-	synbox = self.synboxfile()
-	f = open(synbox, 'w')
-	pickle.dump(self.syn, f)
-	f.close()
+        synbox = self.synboxfile()
+        f = open(synbox, 'w')
+        pickle.dump(self.syn, f)
+        f.close()
     
     def load_index(self):
-	"""Loads the index, a structure associating to a message of given mid
-	the time of its arrival and its position in the lifecycle"""
-	if not self.index == None:
+        """Loads the index, a structure associating to a message of given mid
+        the time of its arrival and its position in the lifecycle"""
+        if not self.index == None:
             return
-	index = self.indexfile()
-	try:
-	    f = open(index, 'r')
-	    self.index = pickle.load(f)
-	    f.close()
-	except IOError:
-	    self.index = {}
+        index = self.indexfile()
+        try:
+            f = open(index, 'r')
+            self.index = pickle.load(f)
+            f.close()
+        except IOError:
+            self.index = {}
     
     def _save_index(self):
-	"""Flushes the index to the disk"""
-	if self.index == None:
+        """Flushes the index to the disk"""
+        if self.index == None:
             return
-	index = self.indexfile()
-	f = open(index, 'w')
-	pickle.dump(self.index, f)
-	f.close()
+        index = self.indexfile()
+        f = open(index, 'w')
+        pickle.dump(self.index, f)
+        f.close()
         
     def store(self, msg):
-	"Stores an incoming message"
-	syn = Mail.synopsize(msg, self.data['seqNo'])
-	self.data['seqNo'] += 1
-	# Store the mail.
-	self.load_mbox()
-	self.load_index()
-	mid = Mail.genMid()
-	while self.index.has_key(mid):
+        "Stores an incoming message"
+        syn = Mail.synopsize(msg, self.data['seqNo'])
+        self.data['seqNo'] += 1
+        # Store the mail.
+        self.load_mbox()
+        self.load_index()
+        mid = Mail.genMid()
+        while self.index.has_key(mid):
             mid = Mail.genMid()
-	self.mbox[mid] = Crypto.nym_encrypt(msg, self.data['encKey']) 
-	# store the synopsis
-	self.load_synbox()
-	self.syn.append(([mid], 'clear', syn))
+        self.mbox[mid] = Crypto.nym_encrypt(msg, self.data['encKey']) 
+        # store the synopsis
+        self.load_synbox()
+        self.syn.append(([mid], 'clear', syn))
 
-	# create an index entry for the synopsis
-	self.index[mid] = {'time' : int(time.time()),
-			   'status' : lifeCycle['nothing-sent'] }
+        # create an index entry for the synopsis
+        self.index[mid] = {'time' : int(time.time()),
+                           'status' : lifeCycle['nothing-sent'] }
 
     def delete_msg(self, mid):
-	"""Deletes a stored message. Delete the synopsis if possible"""
-	self.load_index()
+        """Deletes a stored message. Delete the synopsis if possible"""
+        self.load_index()
 
-	if not self.index.has_key(mid):
+        if not self.index.has_key(mid):
             return
-	self.load_mbox()
-	if self.mbox.has_key(mid):
+        self.load_mbox()
+        if self.mbox.has_key(mid):
             del self.mbox[mid]
-	self.index[mid]['status'] = lifeCycle['deleted']
-	self.load_synbox()
+        self.index[mid]['status'] = lifeCycle['deleted']
+        self.load_synbox()
 
-	try:
-	    i, (sl, _, _) = self.getSyn(mid)
-	except ValueError: return
-	candelete = True
-	for omid in sl:
-	    if not self.index[omid]['status'] == lifeCycle['deleted']:
-		candelete = False
-		break
-	if candelete:
-	    del self.syn[i]
-	    for omid in sl:
+        try:
+            i, (sl, _, _) = self.getSyn(mid)
+        except ValueError: return
+        candelete = True
+        for omid in sl:
+            if not self.index[omid]['status'] == lifeCycle['deleted']:
+                candelete = False
+                break
+        if candelete:
+            del self.syn[i]
+            for omid in sl:
                 del self.index[omid]
 
     def setKeys(self, kid, kenc):
         """Set the identity and encryption key of the user, ASN.1 encoded"""
-	self.data['idKey'] = kid
-	self.data['encKey'] = kenc
+        self.data['idKey'] = kid
+        self.data['encKey'] = kenc
 
     def isUp(self):
-	"""Tells whether the account is up, ready to handle messages of the
-	nymholder"""
-	return self['up']
+        """Tells whether the account is up, ready to handle messages of the
+        nymholder"""
+        return self['up']
 
     def setUp(self):
-	"""Sets the up status"""
-	self['up'] = True
-	if self.config.setupscript:
-	    os.system(self.config.setupscript + (" %s" % self.username))
+        """Sets the up status"""
+        self['up'] = True
+        if self.config.setupscript:
+            os.system(self.config.setupscript + (" %s" % self.username))
 
     def checkMessageSign(self, m, s):
-	"""Checks s is the signature of message m using sha1, RSA-OAEP and
-	the public key of this user"""
-	try:
-	    key = _cr.pk_decode_public_key(self['idKey'])
-	    return (_cr.sha1(m) == _cr.pk_check_signature(s, key))
-	except _cr.CryptoError: return False
-	    
+        """Checks s is the signature of message m using sha1, RSA-OAEP and
+        the public key of this user"""
+        try:
+            key = _cr.pk_decode_public_key(self['idKey'])
+            return (_cr.sha1(m) == _cr.pk_check_signature(s, key))
+        except _cr.CryptoError: return False
+            
     def checkChallenge(self, cr):
-	"""Checks the correctness of the challenge"""
+        """Checks the correctness of the challenge"""
         return (self['cr'] == cr)
 
     def encryptSyn(self, i, j):
         """Replace in the synbox the syn between i and j-1
         by an encrypted blob. Initially the syn have to be in clear
         raise an error if it is not the case"""
-	self.load_synbox()
-	l = self.syn[i:j]
-	if l == []:
-	    return
+        self.load_synbox()
+        l = self.syn[i:j]
+        if l == []:
+            return
         self.syn[i:j] = [self.blobify(l)]
 
     def encOldSyn(self):
-	"""Encrypt synopsis we had in clear for too long"""
-	try:
-	    firstclear = binsearch(self.syn, lambda x: (x[1] == 'clear'))
-	except: return
-	
-	offset = firstclear
-	last = len(self.syn)
-	size = last - offset
+        """Encrypt synopsis we had in clear for too long"""
+        try:
+            firstclear = binsearch(self.syn, lambda x: (x[1] == 'clear'))
+        except: return
+        
+        offset = firstclear
+        last = len(self.syn)
+        size = last - offset
 
-	while offset + maxSynPerBlob < last:
-	    self.encryptSyn(offset, offset + maxSynPerBlob)
-	    offset = offset + 1
-	    last = last - maxSynPerBlob
+        while offset + maxSynPerBlob < last:
+            self.encryptSyn(offset, offset + maxSynPerBlob)
+            offset = offset + 1
+            last = last - maxSynPerBlob
 
-	if offset + 1 >= last:
+        if offset + 1 >= last:
             return
-	# See if among the few remaining synopses, some are considered
-	# too old
-	try:
-	    now = time.time()
-	    propyoung = lambda x: self.index[x[0][0]]['time'] +\
-		self['EncryptSummaryAfter'] * 30 * 60 > now
-	    fyoung = binsearch(self.syn[offset:], propyoung)
-	except:
-	    fyoung = last
-	self.encryptSyn(offset, fyoung)
+        # See if among the few remaining synopses, some are considered
+        # too old
+        try:
+            now = time.time()
+            propyoung = lambda x: self.index[x[0][0]]['time'] +\
+                self['EncryptSummaryAfter'] * 30 * 60 > now
+            fyoung = binsearch(self.syn[offset:], propyoung)
+        except:
+            fyoung = last
+        self.encryptSyn(offset, fyoung)
 
     def markMid(self, l, mark):
         """The status of the mids in l which had a status
         previous to mark in the lifeCycle are set to mark"""
-	if l:
-	    self.load_index()
-	    for e in l:
-		if (self.index[e]['status'] < mark):
-		    self.index[e]['status'] = mark
+        if l:
+            self.load_index()
+            for e in l:
+                if (self.index[e]['status'] < mark):
+                    self.index[e]['status'] = mark
         
     def hasMail(self, mid):
-	"""Checks whether the server holds a mail for a given mid"""
-	self.load_index()
-	try:
-	    return self.index[mid]['status'] != lifeCycle['deleted']
-	except:
-	    return False
+        """Checks whether the server holds a mail for a given mid"""
+        self.load_index()
+        try:
+            return self.index[mid]['status'] != lifeCycle['deleted']
+        except:
+            return False
         
     def prepareSummary(self, num, after):
-	"""Return a list of (midList, bitfield, synblob) suitable for
-	   a SUMMARY reply. Consider only mids older than `after', and
-	   no more than `num'. May change the synbox if encryption is
-	   necessary."""
-	def bfprepare(t):
-	    bfl = [self.hasMail(i) for i in t[0]]
-	    u = (t[0], Mail.bf(bfl), t[2])
-	    return u
+        """Return a list of (midList, bitfield, synblob) suitable for
+           a SUMMARY reply. Consider only mids older than `after', and
+           no more than `num'. May change the synbox if encryption is
+           necessary."""
+        def bfprepare(t):
+            bfl = [self.hasMail(i) for i in t[0]]
+            u = (t[0], Mail.bf(bfl), t[2])
+            return u
         #load the structures
         self.load_index()
         self.load_synbox()
         self.load_mbox()
         # Prepare the midList.
         midList = self.midAfter(after)[:num]
-	if len(midList) == 0:
+        if len(midList) == 0:
             return []
         ret = []
-	# Hold the clear syn
-	clearlist = []
-	nsyn = 0
+        # Hold the clear syn
+        clearlist = []
+        nsyn = 0
         while midList and (len(clearlist) + nsyn < num):
             # look for the synblob containing midList[0]
-	    try:
-		i, u = self.getSyn(midList[0])
-	    except:
-		self.syn = self.syn + clearlist
-		print str(midList)
-		print str(self.syn)
-		print "Doh. Exception."
-		return ret
+            try:
+                i, u = self.getSyn(midList[0])
+            except:
+                self.syn = self.syn + clearlist
+                print str(midList)
+                print str(self.syn)
+                print "Doh. Exception."
+                return ret
             if u[1] == 'clear':
-		clearlist.append(u)
-		del self.syn[i]
-		del midList[0]
-		if len(clearlist) == 8:
-		    foo = self.blobify(clearlist)
-		    self.syn.append(foo)
-		    ret.append(bfprepare(foo))
-		    nsyn += 8
-		    clearlist = []
-		continue
-	    elif u[1] == 'encrypted':
-		for i in u[0]:
-		    if i in midList:
+                clearlist.append(u)
+                del self.syn[i]
+                del midList[0]
+                if len(clearlist) == 8:
+                    foo = self.blobify(clearlist)
+                    self.syn.append(foo)
+                    ret.append(bfprepare(foo))
+                    nsyn += 8
+                    clearlist = []
+                continue
+            elif u[1] == 'encrypted':
+                for i in u[0]:
+                    if i in midList:
                         midList.remove(i)
-		# Can we afford to add this blob?
-		if len(u[0]) + nsyn + len(clearlist) > num:
+                # Can we afford to add this blob?
+                if len(u[0]) + nsyn + len(clearlist) > num:
                     continue
-		ret.append(bfprepare(u))
-	if clearlist:
-	    foo = self.blobify(clearlist)
-	    self.syn.append(foo)
-	    ret.append(bfprepare(foo))
-	return ret
+                ret.append(bfprepare(u))
+        if clearlist:
+            foo = self.blobify(clearlist)
+            self.syn.append(foo)
+            ret.append(bfprepare(foo))
+        return ret



More information about the Nym3-commit mailing list