[or-cvs] r24118: {arm} Refactoring of ip address related helpers. (in arm/trunk/src: . util)

Damian Johnson atagar1 at gmail.com
Sat Jan 22 22:56:52 UTC 2011


Author: atagar
Date: 2011-01-22 22:56:52 +0000 (Sat, 22 Jan 2011)
New Revision: 24118

Modified:
   arm/trunk/src/starter.py
   arm/trunk/src/util/connections.py
Log:
Refactoring of ip address related helpers.



Modified: arm/trunk/src/starter.py
===================================================================
--- arm/trunk/src/starter.py	2011-01-22 22:54:26 UTC (rev 24117)
+++ arm/trunk/src/starter.py	2011-01-22 22:56:52 UTC (rev 24118)
@@ -88,29 +88,6 @@
 # torrc entries that are scrubbed when dumping
 PRIVATE_TORRC_ENTRIES = ["HashedControlPassword", "Bridge", "HiddenServiceDir"]
 
-def isValidIpAddr(ipStr):
-  """
-  Returns true if input is a valid IPv4 address, false otherwise.
-  """
-  
-  for i in range(4):
-    if i < 3:
-      divIndex = ipStr.find(".")
-      if divIndex == -1: return False # expected a period to be valid
-      octetStr = ipStr[:divIndex]
-      ipStr = ipStr[divIndex + 1:]
-    else:
-      octetStr = ipStr
-    
-    try:
-      octet = int(octetStr)
-      if not octet >= 0 or not octet <= 255: return False
-    except ValueError:
-      # address value isn't an integer
-      return False
-  
-  return True
-
 def _loadConfigurationDescriptions(pathPrefix):
   """
   Attempts to load descriptions for tor's configuration options, fetching them
@@ -324,7 +301,7 @@
   controlAddr = param["startup.interface.ipAddress"]
   controlPort = param["startup.interface.port"]
   
-  if not isValidIpAddr(controlAddr):
+  if not util.connections.isValidIpAddress(controlAddr):
     print "'%s' isn't a valid IP address" % controlAddr
     sys.exit()
   elif controlPort < 0 or controlPort > 65535:
@@ -409,5 +386,4 @@
     _dumpConfig()
   
   interface.controller.startTorMonitor(time.time() - initTime, expandedEvents, param["startup.blindModeEnabled"])
-  conn.close()
 

Modified: arm/trunk/src/util/connections.py
===================================================================
--- arm/trunk/src/util/connections.py	2011-01-22 22:54:26 UTC (rev 24117)
+++ arm/trunk/src/util/connections.py	2011-01-22 22:56:52 UTC (rev 24118)
@@ -85,6 +85,45 @@
 def loadConfig(config):
   config.update(CONFIG)
 
+def isValidIpAddress(ipStr):
+  """
+  Returns true if input is a valid IPv4 address, false otherwise.
+  """
+  
+  # checks if theres four period separated values
+  if not ipStr.count(".") == 3: return False
+  
+  # checks that each value in the octet are decimal values between 0-255
+  for ipComp in ipStr.split("."):
+    if not ipComp.isdigit() or int(ipComp) < 0 or int(ipComp) > 255:
+      return False
+  
+  return True
+
+def ipAddressIsPrivate(ipAddr):
+  """
+  Provides true if the IP address belongs on the local network or belongs to
+  loopback, false otherwise. These include:
+  Private ranges: 10.*, 172.16.* - 172.31.*, 192.168.*
+  Loopback: 127.*
+  
+  Arguments:
+    ipAddr - IP address to be checked
+  """
+  
+  # checks for any of the simple wildcard ranges
+  if ipAddr.startswith("10.") or ipAddr.startswith("192.168.") or ipAddr.startswith("127."):
+    return True
+  
+  # checks for the 172.16.* - 172.31.* range
+  if ipAddr.startswith("172.") and ipAddr.count(".") == 3:
+    secondOctet = ipAddr[4:ipAddr.find(".", 4)]
+    
+    if secondOctet.isdigit() and int(secondOctet) >= 16 and int(secondOctet) <= 31:
+      return True
+  
+  return False
+
 def getResolverCommand(resolutionCmd, processName, processPid = ""):
   """
   Provides the command that would be processed for the given resolver type.
@@ -333,6 +372,7 @@
         break
     
     self._connections = []        # connection cache (latest results)
+    self._resolutionCounter = 0   # number of successful connection resolutions
     self._isPaused = False
     self._halt = False            # terminates thread if true
     self._cond = threading.Condition()  # used for pausing the thread
@@ -371,6 +411,7 @@
         lookupTime = time.time() - resolveStart
         
         self._connections = connResults
+        self._resolutionCounter += 1
         
         newMinDefaultRate = 100 * lookupTime
         if self.defaultRate < newMinDefaultRate:
@@ -428,6 +469,14 @@
     if self._halt: return []
     else: return list(self._connections)
   
+  def getResolutionCount(self):
+    """
+    Provides the number of successful resolutions so far. This can be used to
+    determine if the connection results are new for the caller or not.
+    """
+    
+    return self._resolutionCounter
+  
   def setPaused(self, isPause):
     """
     Allows or prevents further connection resolutions (this still makes use of



More information about the tor-commits mailing list