[Nym3-commit] r62 - trunk

nym3-devel@lists.noreply.org nym3-devel@lists.noreply.org
Mon, 02 Aug 2004 23:18:09 +0200


Author: jr
Date: 2004-08-02 23:18:07 +0200 (Mon, 02 Aug 2004)
New Revision: 62

Modified:
   trunk/Config.py
   trunk/Main.py
   trunk/Message.py
Log:
- add the user policy HoldSURBs(Config.my)
- processing of policy command(Main.py)
- advanced parsing of policy Command(Message.py)



Modified: trunk/Config.py
===================================================================
--- trunk/Config.py	2004-08-02 21:12:51 UTC (rev 61)
+++ trunk/Config.py	2004-08-02 21:18:07 UTC (rev 62)
@@ -4,9 +4,10 @@
 default_settings = { 'quota' : 10 * 2**20, 'usage' : 0,
 		     'idKey' : None, 'encKey' : None, 'policy' : None,
 		     'SendMsgAfter' : 24, 'SendSummaryAfter' : 12, 
-		     'MaxSURBsPerDay' : 10, 'EncryptSummaryAfter' : '24',
+		     'MaxSURBsPerDay' : 10, 'EncryptSummaryAfter' : 24,
 		     'HoldUntilAck' : 'Always', 'ShutdownPhrase' : None,
-                     'nSurbs' : 0, 'up' : False, 'cr' : ""}
+		     'HoldSURBs' : 5,
+		     'nSurbs' : 0, 'up' : False, 'cr' : ""}
 
 #up : the user account has been initialized and the answer to the challenge is correct
 #cr : response to the challenge

Modified: trunk/Main.py
===================================================================
--- trunk/Main.py	2004-08-02 21:12:51 UTC (rev 61)
+++ trunk/Main.py	2004-08-02 21:18:07 UTC (rev 62)
@@ -29,94 +29,95 @@
     - run appropriate actions"""
     sr = Message.StrReader(msg)
     try:
-        h = sr.readHeader()
-        if(h.sig != Crypto.pk_check_signature(msg[Message.sigLength:],nymuser.idKey)):
-            print "Invalid signature"
-            print e
-            sys.exit(2) #TODO is it the smart error code
-        comList = sr.readCommandCToSList()
+	h = sr.readHeader()
+	if(h.sig != Crypto.pk_check_signature(msg[Message.sigLength:],nymuser.idKey)):
+	    print "Invalid signature"
+	    print e
+	    sys.exit(2) #TODO is it the smart error code
+	comList = sr.readCommandCToSList()
     except ParseError, inst:
-        print inst
-        sys.exit(2) #TODO error code
+	print inst
+	sys.exit(2) #TODO error code
     if(h.nym == ""):
-        try:
-            if(len(comList) != 3):
-                raise Exception("Bad formed account message")
-            #this may be an account setup message
-            #we suppose there is a exactly 1 Create Command in the message, 1 Newpk, and 1 surb
-            #more will raise an error
+	try:
+	    if(len(comList) != 3):
+		raise Exception("Bad formed account message")
+	    #this may be an account setup message
+	    #we suppose there is a exactly 1 Create Command in the message, 1 Newpk, and 1 surb
+	    #more will raise an error
 
-            nymUser = None
-            #phase 1 we look for the command create
-            for idx, com in enumerate(comList):
-                if(com.ct()==0):
-                    #the Create command
-                    for i, pnym in enumerate(self.list):
-                        if(User.add(pnym)):
-                            nymUser=User.User(pnym)
-                            break
-                    if(nymUser == None):
-                        #TODO send an Error message to the client when surbs become available?
-                        print "All nyms proposed in the list were already attribuated"
-                        break
-                    del(comList[idx])
-                    break
-            #phase 2 we look for the command surb
-            for idx, com in enumerate(comList):
-                if(com.ct()==2):
-                    if(nymUser == None):
-                        #TODO send Error message?
-                        sys.exit(2) #TODO change 2
-                    else:
-                        nymUser.addSurbs(com.surbs)
-                        del(comList[idx])
-                        break
-            #phase 3 the last command should be a Newpk
-            com = comList[0]
-            if(com.ct() != 3):
-                raise Exception("Bad formed account message")
-            nymUser.setKeys(com.kid,com.kenc)
-        except Exception, inst: #do we keep Exception or do change it?
-            #SyntaxError could be better
-            print inst
-            sys.exit(2) #TODO smart error code
+	    nymUser = None
+	    #phase 1 we look for the command create
+	    for idx, com in enumerate(comList):
+		if(com.ct()==0):
+		    #the Create command
+		    for i, pnym in enumerate(self.list):
+			if(User.add(pnym)):
+			    nymUser=User.User(pnym)
+			    break
+		    if(nymUser == None):
+			#TODO send an Error message to the client when surbs become available?
+			print "All nyms proposed in the list were already attribuated"
+			break
+		    del(comList[idx])
+		    break
+	    #phase 2 we look for the command surb
+	    for idx, com in enumerate(comList):
+		if(com.ct()==2):
+		    if(nymUser == None):
+			#TODO send Error message?
+			sys.exit(2) #TODO change 2
+		    else:
+			nymUser.addSurbs(com.surbs)
+			del(comList[idx])
+			break
+	    #phase 3 the last command should be a Newpk
+	    com = comList[0]
+	    if(com.ct() != 3):
+		raise Exception("Bad formed account message")
+	    nymUser.setKeys(com.kid,com.kenc)
+	except Exception, inst: #do we keep Exception or do change it?
+	    #SyntaxError could be better
+	    print inst
+	    sys.exit(2) #TODO smart error code
     else:
-        try:
-            nymUser = User.user(h.nym)
-        except User.NoSuchUser:
-            print "No such user"
-            sys.exit(73) #TODO is it the smart error code
-        
-        for com in comList:
-            if (com.ct() == 0):
-                #we ignore the Create command if it comes from the nymholder of an account, should we rise an error?
-                pass
-            elif (com.ct() == 1):
-                if (nymUser.isInitialized() and (nymUser.data['up'] == False)):
-                    if(nymUser['cr'] == com.cr):
-                        nymUser['up'] = True
-                #if the account is not initialized, or if it is already up we ignore Create2 messages
-            elif (nymUser.data['up'] == True):
-                if (com.ct() == 2):
-                    if( len(com.surbs) == 0):
-                        nymUser.delSurbs()
-                    else:
-                        nymUser.addSurbs(com.surbs)
-                elif (com.ct() == 3):
-                    nymUser.setKeys(com.kid,com.kenc)
-                elif (com.ct() == 4):
-                    pass
-                elif (com.ct() == 5):
-                    pass
-                elif (com.ct() == 6):
-                    pass
-                elif (com.ct() == 7):
-                    pass
-                elif (com.ct() == 8):
-                    pass
-                else:
-                    pass
-                    
+	try:
+	    nymUser = User.user(h.nym)
+	except User.NoSuchUser:
+	    print "No such user"
+	    sys.exit(73) #TODO is it the smart error code
+	
+	for com in comList:
+	    if (com.ct() == 0):
+		#we ignore the Create command if it comes from the nymholder of an account, should we rise an error?
+		pass
+	    elif (com.ct() == 1):
+		if (nymUser.isInitialized() and (nymUser.data['up'] == False)):
+		    if(nymUser['cr'] == com.cr):
+			nymUser['up'] = True
+		#if the account is not initialized, or if it is already up we ignore Create2 messages
+	    elif (nymUser.data['up'] == True):
+		if (com.ct() == 2):
+		    if( len(com.surbs) == 0):
+			nymUser.delSurbs()
+		    else:
+			nymUser.addSurbs(com.surbs)
+		elif (com.ct() == 3):
+		    nymUser.setKeys(com.kid,com.kenc)
+		elif (com.ct() == 4):
+		    pass
+		elif (com.ct() == 5):
+		    pass
+		elif (com.ct() == 6):
+		    pass
+		elif (com.ct() == 7):
+		    pass
+		elif (com.ct() == 8):
+		    if(com.opt in Common.userPolicy):
+			nymUser.data[com.opt] = com.val
+		else:
+		    pass
+		    
     
 if __name__ == '__main__':
     optlist, pholder = getopt.getopt(sys.argv[1:], 'd:')

Modified: trunk/Message.py
===================================================================
--- trunk/Message.py	2004-08-02 21:12:51 UTC (rev 61)
+++ trunk/Message.py	2004-08-02 21:18:07 UTC (rev 62)
@@ -3,17 +3,17 @@
 
 class ParseError(Exception):
 	"""ParseError : error raised if anything goes wrong during parsing"""
-        def __init__(self,value):
-                self.value=value
-        def __str__(self):
-                return repr(self.value)
+	def __init__(self,value):
+		self.value=value
+	def __str__(self):
+		return repr(self.value)
 
 class BadArgument(Exception):
 	"""BadArgument : error raised if a function is given an irrelevant argument"""
-        def __init__(self,value):
-                self.value=value
-        def __str__(self):
-                return repr(self.value)
+	def __init__(self,value):
+		self.value=value
+	def __str__(self):
+		return repr(self.value)
 
 def strToIntBE(s):
 	"""return the Int coded by the string s with the big endian convention"""
@@ -53,20 +53,20 @@
 
 class StrReader:
 	"""wraps a string and gives method to read it chunk by chunk"""
-        def __init__(self,s):
+	def __init__(self,s):
 	    """initialize by wrapping a string"""
-            self.s = s
-            self.a = 0
-            self.b = 0
+	    self.s = s
+	    self.a = 0
+	    self.b = 0
 	def isEnd(self):
 		"""True if we have read the whole string"""
 		return (b == len(s))
-        def next(self,n):
+	def next(self,n):
 		"""return the next n characters"""
 		if(n<0):
 			raise BadArgument("StrReader.next : n < 0")
 		self.a = self.b
-                self.b = self.b + n
+		self.b = self.b + n
 		return self.s[self.a:self.b]
 	def readHeader(self):
 		"""Read next header from the string"""
@@ -188,7 +188,7 @@
 			self.sig = chr(0) * sigLength
 		else:
 			if(len(sig) != sigLength):
-				raise BadArgument("Buildheader.__init__ : sig length doesn't match sigLength")  
+				raise BadArgument("Buildheader.__init__ : sig length doesn't match sigLength")	
 		self.nl = len(nym)
 		self.nym = nym
 		self.seqNo = seqNo
@@ -210,36 +210,36 @@
 
 ## class ReadHeader(Header):
 ##     def __init__(self,sr):
-##         """builds a header from a StrReader 
-##         sig : signature
-##         nl : nym length
-##         nym : nym
-##         seqNo : sequence number which identifies the message
-##         length : header length"""
-##         try:
-##             self.sig = sr.next(sigLength)
-##             self.nl = ord(sr.next(1))
-##             self.nym = sr.next(nl)
-##             self.seqNo = sr.next(seqNoLength)
-##             self.length = sr.b
-##         except IndexError:
-##             raise ParseError("Parse Error : Header too short")
-        
+##	   """builds a header from a StrReader 
+##	   sig : signature
+##	   nl : nym length
+##	   nym : nym
+##	   seqNo : sequence number which identifies the message
+##	   length : header length"""
+##	   try:
+##	       self.sig = sr.next(sigLength)
+##	       self.nl = ord(sr.next(1))
+##	       self.nym = sr.next(nl)
+##	       self.seqNo = sr.next(seqNoLength)
+##	       self.length = sr.b
+##	   except IndexError:
+##	       raise ParseError("Parse Error : Header too short")
+	
 ## class BuiltHeader(Header):
 ##     def __init__(self,nym,seqNo):
-##         """Builds a header from a nym and and sequence number
-##         sig : signature
-##         nl : nym length
-##         nym : nym
-##         seqNo : sequence number which identifies the message
-##         length : header length"""
-##         if(len(seqNo) != seqNoLength):
-##             raise BadArgument("Buildheader.__init__ : seqNo length doesn't match seqNoLength")  
-##         self.sig = chr(0) * sigLength
-##         self.nl = len(nym)
-##         self.nym = nym
-##         self.seqNo = seqNo
-##         self.length = sigLength + 1 + self.nl + seqNoLength
+##	   """Builds a header from a nym and and sequence number
+##	   sig : signature
+##	   nl : nym length
+##	   nym : nym
+##	   seqNo : sequence number which identifies the message
+##	   length : header length"""
+##	   if(len(seqNo) != seqNoLength):
+##	       raise BadArgument("Buildheader.__init__ : seqNo length doesn't match seqNoLength")  
+##	   self.sig = chr(0) * sigLength
+##	   self.nl = len(nym)
+##	   self.nym = nym
+##	   self.seqNo = seqNo
+##	   self.length = sigLength + 1 + self.nl + seqNoLength
 
 class CommandCToS:
 	"""CommandCToS astract class
@@ -546,28 +546,81 @@
 		"""return a int for the code of the command"""
 		return 8
 	def fromData(self,opt,val):
-		"""Fill a Policy Object from 2 str : the option name and its value
-		It is the caller work to convert adequatly into a string the value he wants to be sent"""
-		#TODO check the option names' validity and the argument
-		#it's a lot of trouble -> later
-		#for the time being we suppose the developper knows what he does and does not create an message that will exceed the command body max size
+		"""Fill a Policy Object from 1 str : the option name
+		and its value (either a str or a int depending on the option
+		"""
 		if(len(opt)>255):
 			raise BadArgument("Policy.fromData : Option name length too big")
-		self.opt=opt
-		self.val=val
-		#command body is small enough
+		if(opt in Common.userPolicy):
+			self.opt=opt
+		if(opt == "SendMsgAfter"):
+			if( val > pow(256,2) ):
+				raise BadArgument("Policy.fromData : Option value too long")
+			self.val=val
+		elif (opt == "SendSummaryAfter"):
+			if( val > pow(256,2) ):
+				raise BadArgument("Policy.fromData : Option value too long")
+			self.val=val
+		elif (opt == "EncryptSummaryAfter"):
+			if( val > pow(256,2) ):
+				raise BadArgument("Policy.fromData : Option value too long")
+			self.val=val
+		elif (opt == "MaxSURBsPerDay"):
+			if( val > pow(256,2) ):
+				raise BadArgument("Policy.fromData : Option value too long")
+			self.val=val
+		elif (opt == "HoldSURBs"):
+			if( val > pow(256,2) ):
+				raise BadArgument("Policy.fromData : Option value too long")
+			self.val=val
+		elif (opt == "HoldUntilAck"):
+			if(val in [ 'never', 'quota', 'always' ]):
+				self.val=val
+		elif (opt == "ShutdownPhrase"):
+			if( len(val) + 1 + len(opt) > pow(256,3) ):
+				raise BadArgument("Policy.fromData : Option value too long")
+			self.val=val
 	def fromStrReader(self,sr,cs):
 		"""Fill a Policy Object from a StrReader
 		raise ParseError if it is malformed"""
 		try:
 			le=ord(sr.next(1))
 			self.opt=sr.next(le)
-			self.val=sr.next(cs-1-le)
+			inter=sr.next(cs-1-le)
+			if(self.opt == "SendMsgAfter"):
+				if(len(inter)!=2):
+					raise ParseError("Bad Formed Command : Policy")
+				self.val=strToIntBE(inter)
+			elif (self.opt == "SendSummaryAfter"):
+				if(len(inter)!=2):
+					raise ParseError("Bad Formed Command : Policy")
+				self.val=strToIntBE(inter)
+			elif (opt == "EncryptSummaryAfter"):
+				if(len(inter)!=2):
+					raise ParseError("Bad Formed Command : Policy")
+				self.val=strToIntBE(inter)
+			elif (opt == "MaxSURBsPerDay"):
+				if(len(inter)!=2):
+					raise ParseError("Bad Formed Command : Policy")
+				self.val=strToIntBE(inter)
+			elif (opt == "HoldSURBs"):
+				if(len(inter)!=2):
+					raise ParseError("Bad Formed Command : Policy")
+				self.val=strToIntBE(inter)
+			elif (opt == "HoldUntilAck"):
+				if(inter in [ 'never', 'quota', 'always' ]):
+					self.val=inter
+			elif (opt == "ShutdownPhrase"):
+				self.val=inter
 		except (IndexError,BadArgument):
 			raise ParseError("Bad Formed Command : Policy")
 	def __str__(self):
 		"""Give the string of the Command that would be sent in a control message"""
-		s=chr(len(self.opt))+self.opt+self.val
+		s=chr(len(self.opt))+self.opt
+		if(self.opt in Common.userPolicy[:5]):
+			s = s + intToStrBE(self.val,2)
+		if(self.opt in Common.userPolicy[5:]):
+			s = s + self.val
 		if(len(s)>=pow(256,3)): #should not be possible, otherwise bug
 			raise BadArgument("Policy.__str__ : command body too long")
 		return chr(8)+intToStrBE(len(s),3)+s