コード例 #1
0
ファイル: dhcp.py プロジェクト: databus23/staticdhcpd
def _logInvalidValue(name, value, subnet, serial):
    logging.writeLog("Invalid value for %(subnet)s:%(serial)i:%(name)s: %(value)s" % {
     'subnet': subnet,
     'serial': serial,
     'name': name,
     'value': value,
    })
コード例 #2
0
ファイル: dhcp.py プロジェクト: databus23/staticdhcpd
 def _logDHCPAccess(self, mac):
     """
     Increments the number of times the given MAC address has accessed this
     server. If the value exceeds the policy threshold, the MAC is ignored as
     potentially belonging to a malicious user.
     
     @type mac: basestring
     @param mac: The MAC being evaluated.
     
     @rtype: bool
     @return: True if the MAC's request should be processed.
     """
     if config.ENABLE_SUSPEND:
         with self._stats_lock:
             assignments = self._dhcp_assignments.get(mac)
             if not assignments:
                 self._dhcp_assignments[mac] = 1
             else:
                 self._dhcp_assignments[mac] = assignments + 1
                 if assignments + 1 > config.SUSPEND_THRESHOLD:
                     logging.writeLog('%(mac)s issuing too many requests; ignoring for %(time)i seconds' % {
                      'mac': mac,
                      'time': config.MISBEHAVING_CLIENT_TIMEOUT,
                     })
                     self._ignored_addresses.append([mac, config.MISBEHAVING_CLIENT_TIMEOUT])
                     return False
     return True
コード例 #3
0
ファイル: web.py プロジェクト: databus23/staticdhcpd
 def _doResponse(self):
     """
     Renders the current state of the memory-log as HTML for consumption by
     the client.
     """
     try:
         self.send_response(200)
         self.send_header('Content-type', 'text/html')
         self.send_header('Last-modified', time.strftime('%a, %d %b %Y %H:%M:%S %Z'))
         self.end_headers()
         
         self.wfile.write('<html><head><title>%(name)s log</title></head><body>' % {'name': config.SYSTEM_NAME,})
         self.wfile.write('<div style="width: 950px; margin-left: auto; margin-right: auto; border: 1px solid black;">')
         
         self.wfile.write('<div>Statistics:<div style="text-size: 0.9em; margin-left: 20px;">')
         for (timestamp, packets, discarded, time_taken, ignored_macs) in logging.readPollRecords():
             if packets:
                 turnaround = time_taken / packets
             else:
                 turnaround = 0.0
             self.wfile.write("%(time)s : received: %(received)i; discarded: %(discarded)i; turnaround: %(turnaround)fs/pkt; ignored MACs: %(ignored)i<br/>" % {
              'time': time.ctime(timestamp),
              'received': packets,
              'discarded': discarded,
              'turnaround': turnaround,
              'ignored': ignored_macs,
             })
         self.wfile.write("</div></div><br/>")
         
         self.wfile.write('<div>Events:<div style="text-size: 0.9em; margin-left: 20px;">')
         for (timestamp, line) in logging.readLog():
             self.wfile.write("%(time)s : %(line)s<br/>" % {
              'time': time.ctime(timestamp),
              'line': cgi.escape(line),
             })
         self.wfile.write("</div></div><br/>")
         
         self.wfile.write('<div style="text-align: center;">')
         self.wfile.write('<small>Summary generated %(time)s</small><br/>' % {
          'time': time.asctime(),
         })
         self.wfile.write('<small>%(server)s:%(port)i | PID: %(pid)i | v%(core_version)s | <a href="http://uguu.ca/" onclick="window.open(this.href); return false;">uguu.ca</a></small><br/>' % {
          'pid': os.getpid(),
          'server': config.DHCP_SERVER_IP,
          'port': config.DHCP_SERVER_PORT,
          'core_version': VERSION,
         })
         self.wfile.write('<form action="/" method="post"><div style="display: inline;">')
         self.wfile.write('<label for="key">Key: </label><input type="password" name="key" id="key"/>')
         if config.USE_CACHE:
             self.wfile.write('<input type="submit" value="Flush cache and write log to disk"/>')
         else:
             self.wfile.write('<input type="submit" value="Write log to disk"/>')
         self.wfile.write('</div></form>')
         self.wfile.write('</div>')
         
         self.wfile.write("</div></body></html>")
     except Exception, e:
         logging.writeLog("Problem while serving response in Web module: %(error)s" % {'error': str(e),})
コード例 #4
0
ファイル: dhcp.py プロジェクト: databus23/staticdhcpd
 def _sendDHCPPacket(self, packet, address, response_type, mac, client_ip, pxe):
     """
     Sends the given packet to the right destination based on its properties.
     
     If the request originated from a host that knows its own IP, the packet
     is transmitted via unicast; in the event of a relayed request, it is sent
     to the 'server port', rather than the 'client port', per RFC 2131.
     
     If it was picked up as a broadcast packet, it is sent to the local subnet
     via the same mechanism, but to the 'client port'.
     
     @type packet: L{libpydhcpserver.dhcp_packet.DHCPPacket}
     @param packet: The packet to be transmitted.
     @type address: tuple
     @param address: The address from which the packet was received:
         (host, port)
     @type response_type: basestring
     @param response_type: The DHCP subtype of this response: 'OFFER', 'ACK',
         'NAK'
     @type mac: basestring
     @param mac: The MAC of the client for which this packet is destined.
     @type client_ip: basestring
     @param client_ip: The IP being assigned to the client.
     @type pxe: bool
     @param pxe: True if the packet was received via the PXE port
     
     @rtype: int
     @return: The number of bytes transmitted.
     """
     ip = port = None
     if address[0] not in ('255.255.255.255', '0.0.0.0', ''): #Unicast.
         giaddr = packet.getOption("giaddr")
         if giaddr and not giaddr == [0,0,0,0]: #Relayed request.
             ip = '.'.join(map(str, giaddr))
             port = self._server_port
         else: #Request directly from client, routed or otherwise.
             ip = address[0]
             if pxe:
                 port = address[1] or self._client_port #BSD doesn't seem to preserve port information
             else:
                 port = self._client_port
     else: #Broadcast.
         ip = '255.255.255.255'
         port = self._client_port
         
     packet.setOption('server_identifier', ipToList(self._server_address))
     bytes = self._sendDHCPPacketTo(packet, ip, port, pxe)
     logging.writeLog('DHCP%(type)s sent to %(mac)s for %(client)s via %(ip)s:%(port)i %(pxe)s[%(bytes)i bytes]' % {
          'type': response_type,
          'mac': mac,
          'client': client_ip,
          'bytes': bytes,
          'ip': ip,
          'port': port,
          'pxe': pxe and '(PXE) ' or '',
     })
     return bytes
コード例 #5
0
ファイル: dhcp.py プロジェクト: databus23/staticdhcpd
 def _handleDHCPLeaseQuery(self, packet, source_address, pxe):
     """
     Evaluates a DHCPLEASEQUERY request from a relay and determines whether
     a DHCPLEASEACTIVE or DHCPLEASEUNKNOWN should be sent.
     
     The logic here is to make sure the MAC isn't ignored or acting
     maliciously, then check the database to see whether it has an assigned
     IP. If it does, DHCPLEASEACTIVE is sent. Otherwise, DHCPLEASEUNKNOWN is
     sent.
     
     @type packet: L{libpydhcpserver.dhcp_packet.DHCPPacket}
     @param packet: The DHCPREQUEST to be evaluated.
     @type source_address: tuple
     @param source_address: The address (host, port) from which the request
         was received.
     @type pxe: bool
     @param pxe: True if the packet was received on the PXE port.
     """
     if not self._evaluateRelay(packet, pxe):
         return
         
     start_time = time.time()
     mac = None
     try:
         mac = packet.getHardwareAddress()
     except:
         pass
     if not mac: #IP/client-ID-based lookup; not supported.
         self._logDiscardedPacket()
         return
         
     if not [None for (ignored_mac, timeout) in self._ignored_addresses if mac == ignored_mac]:
         if not self._logDHCPAccess(mac):
             self._logDiscardedPacket()
             return
             
         logging.writeLog('DHCPLEASEQUERY for %(mac)s' % {
          'mac': mac,
         })
         
         try:
             result = self._database.lookupMAC(mac) or config.handleUnknownMAC(mac)
             if result:
                 packet.transformToDHCPLeaseActivePacket()
                 if packet.setOption('yiaddr', ipToList(result[0])):
                     self._sendDHCPPacket(packet, source_address, 'LEASEACTIVE', mac, result[0], pxe)
                 else:
                     _logInvalidValue('ip', result[0], result[-2], result[-1])
             else:
                 packet.transformToDHCPLeaseUnknownPacket()
                 self._sendDHCPPacket(packet, source_address, 'LEASEUNKNOWN', mac, '?.?.?.?', pxe)
         except Exception, e:
             logging.sendErrorReport('Unable to respond for %(mac)s' % {'mac': mac,}, e)
コード例 #6
0
 def flushCache(self):
     """
     Resets the cache to an empty state, forcing all lookups to pull fresh
     data.
     """
     if conf.USE_CACHE:
         self._cache_lock.acquire()
         try:
             self._mac_cache = {}
             self._subnet_cache = {}
             logging.writeLog("Flushed DHCP cache")
         finally:
             self._cache_lock.release()
コード例 #7
0
ファイル: dhcp.py プロジェクト: databus23/staticdhcpd
 def _handleDHCPDecline(self, packet, source_address, pxe):
     """
     Informs the operator of a potential IP collision on the network.
     
     This function checks to make sure the MAC isn't ignored or acting
     maliciously, then checks the database to see whether it has an assigned
     IP. If it does, and the IP it thinks it has a right to matches this IP,
     then a benign message is logged and the operator is informed; if not,
     the decline is flagged as a malicious act.
     
     @type packet: L{libpydhcpserver.dhcp_packet.DHCPPacket}
     @param packet: The DHCPDISCOVER to be evaluated.
     @type source_address: tuple
     @param source_address: The address (host, port) from which the request
         was received.
     @type pxe: bool
     @param pxe: True if the packet was received on the PXE port.
     """
     if not self._evaluateRelay(packet, pxe):
         return
         
     start_time = time.time()
     mac = packet.getHardwareAddress()
     if not [None for (ignored_mac, timeout) in self._ignored_addresses if mac == ignored_mac]:
         if not self._logDHCPAccess(mac):
             self._logDiscardedPacket()
             return
             
         if '.'.join(map(str, packet.getOption("server_identifier"))) == self._server_address: #Rejected!
             ip = '.'.join(map(str, packet.getOption("requested_ip_address")))
             result = self._database.lookupMAC(mac) or config.handleUnknownMAC(mac)
             if result and result[0] == ip: #Known client.
                 logging.writeLog('DHCPDECLINE from %(mac)s for %(ip)s on (%(subnet)s, %(serial)i)' % {
                  'ip': ip,
                  'mac': mac,
                  'subnet': result[9],
                  'serial': result[10],
                 })
                 logging.sendDeclineReport(mac, ip, result[9], result[10])
             else:
                 logging.writeLog('Misconfigured client %(mac)s sent DHCPDECLINE for %(ip)s' % {
                  'ip': ip,
                  'mac': mac,
                 })
         else:
             self._logDiscardedPacket()
     else:
         self._logDiscardedPacket()
     self._logTimeTaken(time.time() - start_time)
コード例 #8
0
ファイル: web.py プロジェクト: databus23/staticdhcpd
 def run(self):
     """
     Runs the Web server indefinitely.
     
     In the event of an unexpected error, e-mail will be sent and processing
     will continue with the next request.
     """
     logging.writeLog('Running Web server')
     while True:
         try:
             self._web_server.handle_request()
         except select.error:
             logging.writeLog('Suppressed non-fatal select() error in Web module')
         except Exception, e:
             logging.sendErrorReport('Unhandled exception', e)
コード例 #9
0
ファイル: web.py プロジェクト: databus23/staticdhcpd
 def do_HEAD(self):
     """
     Handles all HTTP HEAD requests.
     
     This involves lying about the existence of files and telling the browser
     to always pull a fresh copy.
     """
     if not self.path in self._allowed_pages:
             self.send_response(404)
             return
             
     try:
         self.send_response(200)
         self.send_header('Content-type', 'text/html')
         self.send_header('Last-modified', time.strftime('%a, %d %b %Y %H:%M:%S %Z'))
         self.end_headers()
     except Exception, e:
         logging.writeLog("Problem while processing HEAD in Web module: %(error)s" % {'error': str(e),})
コード例 #10
0
ファイル: web.py プロジェクト: databus23/staticdhcpd
 def __init__(self):
     """
     Sets up the Web server.
     
     @raise Exception: If a problem occurs while binding the sockets needed
         to handle HTTP traffic.
     """
     threading.Thread.__init__(self)
     self.daemon = True
     
     self._web_server = BaseHTTPServer.HTTPServer(
      (
       '.'.join([str(int(o)) for o in config.WEB_IP.split('.')]),
       int(config.WEB_PORT)
      ),
      _WebServer
     )
     
     logging.writeLog('Configured Web server')
コード例 #11
0
ファイル: dhcp.py プロジェクト: databus23/staticdhcpd
 def __init__(self):
     """
     Sets up the DHCP server.
     
     @raise Exception: If a problem occurs while binding the sockets needed
         to handle DHCP traffic.
     """
     threading.Thread.__init__(self)
     self.daemon = True
     
     self._dhcp_server = _DHCPServer(
      '.'.join([str(int(o)) for o in config.DHCP_SERVER_IP.split('.')]),
      int(config.DHCP_SERVER_PORT),
      int(config.DHCP_CLIENT_PORT),
      config.PXE_PORT and int(config.PXE_PORT)
     )
     _dhcp_servers.append(self._dhcp_server) #Add this server to the global list.
     
     logging.writeLog('Configured DHCP server')
コード例 #12
0
ファイル: dhcp.py プロジェクト: databus23/staticdhcpd
 def _evaluateRelay(self, packet, pxe):
     """
     Determines whether the received packet belongs to a relayed request or
     not and decides whether it should be allowed based on policy.
     
     @type packet: L{libpydhcpserver.dhcp_packet.DHCPPacket}
     @param packet: The packet to be evaluated.
     @type pxe: bool
     @param pxe: Whether the request is PXE
     """
     giaddr = packet.getOption("giaddr")
     if not giaddr == [0,0,0,0]: #Relayed request.
         if not config.ALLOW_DHCP_RELAYS: #Ignore it.
             return False
         elif config.ALLOWED_DHCP_RELAYS and not '.'.join(map(str, giaddr)) in config.ALLOWED_DHCP_RELAYS:
             logging.writeLog('Relayed request from unauthorized relay %(ip)s ignored' % {
              'ip': '.'.join(map(str, giaddr)),
             })
             return False
     elif not config.ALLOW_LOCAL_DHCP and not pxe: #Local request, but denied.
         return False
     return True
コード例 #13
0
ファイル: web.py プロジェクト: databus23/staticdhcpd
 def do_POST(self):
     """
     Handles all HTTP POST requests.
     
     This checks to see if the user entered the flush key and, if so,
     flushes the cache and writes the memory-log to disk.
     """
     try:
         (ctype, pdict) = cgi.parse_header(self.headers.getheader('content-type'))
         if ctype == 'application/x-www-form-urlencoded':
             query = parse_qs(self.rfile.read(int(self.headers.getheader('content-length'))))
             key = query.get('key')
             if key:
                 if hashlib.md5(key[0]).hexdigest() == config.WEB_RELOAD_KEY:
                     dhcp.flushCache()
                     if logging.logToDisk():
                         logging.writeLog("Wrote log to '%(log)s'" % {'log': config.LOG_FILE,})
                     else:
                         logging.writeLog("Unable to write log to '%(log)s'" % {'log': config.LOG_FILE,})
                 else:
                     logging.writeLog("Invalid Web-access-key provided")
     except Exception, e:
         logging.writeLog("Problem while processing POST in Web module: %(error)s" % {'error': str(e),})
コード例 #14
0
ファイル: dhcp.py プロジェクト: databus23/staticdhcpd
                 })
                 self._logDiscardedPacket()
         else:
             packet.transformToDHCPNackPacket()
             self._sendDHCPPacket(packet, source_address, 'NAK', mac, s_ip, pxe)
     except Exception, e:
         logging.sendErrorReport('Unable to respond to %(mac)s' % {'mac': mac,}, e)
 elif not sid and ciaddr and not ip: #RENEWING or REBINDING
     if config.NAK_RENEWALS and not pxe:
         packet.transformToDHCPNackPacket()
         self._sendDHCPPacket(packet, source_address, 'NAK', mac, 'NAK_RENEWALS', pxe)
     else:
         renew = source_address[0] not in ('255.255.255.255', '0.0.0.0', '')
         if renew:
             logging.writeLog('DHCPREQUEST:RENEW from %(mac)s' % {
              'mac': mac,
             })
         else:
             logging.writeLog('DHCPREQUEST:REBIND from %(mac)s' % {
              'mac': mac,
             })
             
         try:
             result = self._database.lookupMAC(mac) or config.handleUnknownMAC(mac)
             if result and result[0] == s_ciaddr:
                 packet.transformToDHCPAckPacket()
                 pxe_options = packet.extractPXEOptions()
                 vendor_options = packet.extractVendorOptions()
                 packet.setOption('yiaddr', ciaddr)
                 self._loadDHCPPacket(packet, result)
                 if config.loadDHCPPacket(
コード例 #15
0
def run(conf_file=''):
    '''
      run Particle Swarm Optimizer
      @conf_file if a configuration-file name is specified, it is imported and used
       give the name of the file WITHOUT the .py - extension! see conf.py for more details
    '''
    if 'conf' in dir(): del conf  # eliminate configuration from earlier times
    # NOTE: Python seems not to care about this del - method. It's hard to reset values in a module
    #       just by reimporting it. If the conf-modules change, it's no problem though
    if not conf_file == '': exec("import %s as conf" % conf_file)
    else: import conf as conf
    if 'logging' in dir(): del logging  # see comment above
    import logging
    if 'fitness' in dir(): del fitness  # see comment above
    import fitness

    moreTrials = True  # there is always one - the default
    trials = conf.trialgen()
    while (moreTrials):  # runs while there are more trial conditions
        global actRun
        logging.log[conf.actTrialName] = dict()
        logging.log[conf.actTrialName]['pBestLog'] = dict()
        logging.log[conf.actTrialName]['gBestLog'] = dict()
        logging.log[conf.actTrialName]['meanFitnessLog'] = dict()
        logging.log[conf.actTrialName]['georankLog'] = dict()
        logging.log[conf.actTrialName]['closenessLog'] = dict()
        logging.iterLog = {}
        logging.resetLogs(conf)

        if conf.logConsole:
            print '-----------------------------------------------------------------------------------------------'
            print 'Starting trial: ' + conf.actTrialName
            if not conf_file == '':
                print '  I used this config file: ' + str(conf_file)
            print '  dimensions: ' + str(conf.dimensions)
            print '  swarm size: ' + str(conf.numberOfParticles)
            print '  topology: ' + conf.topology
            print '  function: ' + conf.function
            print '  generations: ' + str(conf.maxIterations)
            if conf.averageOver > 1:
                print '  averaged over ' + str(conf.averageOver) + ' runs'

        for r in range(conf.averageOver):
            iterations = 0
            setup(conf, logging)
            if conf.logConsole:
                print '----------------- run nr: ' + str(actRun).rjust(
                    2) + ' in trial: ' + conf.actTrialName.ljust(
                        20) + '------------------------------------'
                titlestr = '                   '
                if conf.logMeanFitness: titlestr += 'mean fitness |'.rjust(15)
                if conf.logPBest: titlestr += 'mean pbest |'.rjust(15)
                if conf.logGBest: titlestr += 'gbest so far |'.rjust(15)
                if conf.logGeoRank: titlestr += 'avg. georank |'.rjust(15)
                if conf.logCloseness: titlestr += 'avg. closeness |'.rjust(10)
                print titlestr
                print '-----------------------------------------------------------------------------------------------'

            while iterations <= conf.maxIterations:

                sumFitness = 0
                sumPBests = 0
                # Make the "next locations" current and then
                # test their fitness.
                for p in particles:
                    for d in range(conf.dimensions):
                        p.current[d] = p.next[d]
                    act_fitness = fitness.fitness(p, conf)

                    # adjust personal best
                    if conf.isEqualOrBetterThan(
                            act_fitness, p.bestSoFar) or not p.bestSoFar:
                        p.bestSoFar = act_fitness
                        for d in range(conf.dimensions):
                            p.best[d] = p.current[d]

                    global gbest
                    global bestParticle
                    if bestParticle == None: bestParticle = particles[0]
                    # reached new global best?
                    if conf.isEqualOrBetterThan(act_fitness,
                                                gbest) or not gbest:
                        gbest = act_fitness
                        bestParticle = p

                    sumFitness += act_fitness
                    sumPBests += p.bestSoFar

                # end of: for p in particles

                # recalculate next for each particle
                pid = 0
                for p in particles:
                    n = getNeighborWithBestFitness(pid, conf)
                    for d in range(conf.dimensions):
                        # individual and soacial influence
                        iFactor = conf.iWeight * randMM(conf.iMin, conf.iMax)
                        sFactor = conf.sWeight * randMM(conf.sMin, conf.sMax)
                        # this helps to compare against a form of random search
                        if conf.random_search:
                            pDelta[d] = randMM(conf.initMin,
                                               conf.initMax) - p.current[d]
                            nDelta[d] = randMM(conf.initMin,
                                               conf.initMax) - p.current[d]
                        else:
                            pDelta[d] = p.best[d] - p.current[
                                d]  # the 'cognitive' orientation
                            nDelta[d] = n.best[d] - p.current[
                                d]  # the 'social' orientation
                        delta = (iFactor * pDelta[d]) + (sFactor * nDelta[d])

                        # acceleration: gradually going from acc_max to acc_min ("cooling down")
                        acc = conf.acc_max - ((conf.acc_max - conf.acc_min) /
                                              conf.maxIterations) * iterations

                        # calculating the next velocity from old velocity + individual and social influence
                        new_vel = (p.velocity[d] * acc) + delta
                        p.velocity[d] = constrict(new_vel, conf)
                        # updating the next position
                        p.next[d] = p.current[d] + p.velocity[d]
                    pid += 1
                # end of: for p in particles

                # log (if wanted)
                if iterations in logging.iterLog:
                    logging.logPoint(iterations,
                                     sumPBests / conf.numberOfParticles, gbest,
                                     sumFitness / conf.numberOfParticles, conf)

                if iterations in conf.logPopulationAt:
                    logging.logPopulation(particles, iterations, actRun, conf)

                iterations += 1
            # end of: while iterations <= maxIterations
            actRun += 1
            random.seed()  # we should reseed the randomizer for each new run!
        # end of one run, start new trial?

        try:
            conf.actTrialName = trials.next()
        except:
            moreTrials = False
    # end of trial - while

    logging.writeLog(conf)
コード例 #16
0
ファイル: dhcp.py プロジェクト: databus23/staticdhcpd
 def flushCache(self):
     """
     Flushes the DHCP cache.
     """
     self._database.flushCache()
     logging.writeLog("Flushed DHCP cache")
コード例 #17
0
ファイル: base.py プロジェクト: 9220520209/pypso
def run(conf_file=''):
  ''' 
    run Particle Swarm Optimizer 
    @conf_file if a configuration-file name is specified, it is imported and used
     give the name of the file WITHOUT the .py - extension! see conf.py for more details
  '''
  if 'conf' in dir(): del conf  # eliminate configuration from earlier times
  # NOTE: Python seems not to care about this del - method. It's hard to reset values in a module
  #       just by reimporting it. If the conf-modules change, it's no problem though
  if not conf_file=='': exec("import %s as conf"%conf_file)
  else: import conf as conf
  if 'logging' in dir(): del logging # see comment above 
  import logging
  if 'fitness' in dir(): del fitness # see comment above
  import fitness

  moreTrials = True # there is always one - the default
  trials = conf.trialgen()
  while(moreTrials): # runs while there are more trial conditions
    global actRun
    logging.log[conf.actTrialName] = dict()
    logging.log[conf.actTrialName]['pBestLog'] = dict()
    logging.log[conf.actTrialName]['gBestLog'] = dict()
    logging.log[conf.actTrialName]['meanFitnessLog'] = dict()
    logging.log[conf.actTrialName]['georankLog'] = dict()
    logging.log[conf.actTrialName]['closenessLog'] = dict()
    logging.iterLog = {}
    logging.resetLogs(conf)

    if conf.logConsole:
      print '-----------------------------------------------------------------------------------------------'
      print 'Starting trial: ' + conf.actTrialName
      if not conf_file == '': print '  I used this config file: ' + str(conf_file)
      print '  dimensions: ' + str(conf.dimensions)
      print '  swarm size: ' + str(conf.numberOfParticles)
      print '  topology: ' + conf.topology
      print '  function: ' + conf.function
      print '  generations: ' + str(conf.maxIterations)
      if conf.averageOver > 1 : print '  averaged over ' + str(conf.averageOver) + ' runs'

    for r in range(conf.averageOver):
      iterations = 0 
      setup(conf,logging)
      if conf.logConsole: 
        print '----------------- run nr: ' + str(actRun).rjust(2) + ' in trial: ' + conf.actTrialName.ljust(20) + '------------------------------------'
        titlestr =  '                   '
        if conf.logMeanFitness: titlestr += 'mean fitness |'.rjust(15)
        if conf.logPBest: titlestr += 'mean pbest |'.rjust(15)
        if conf.logGBest: titlestr += 'gbest so far |'.rjust(15)
        if conf.logGeoRank: titlestr += 'avg. georank |'.rjust(15)
        if conf.logCloseness: titlestr += 'avg. closeness |'.rjust(10)
        print titlestr
        print '-----------------------------------------------------------------------------------------------'
      
      while iterations <= conf.maxIterations:
 
        sumFitness = 0
        sumPBests = 0
        # Make the "next locations" current and then 
        # test their fitness. 
        for p in particles:
          for d in range(conf.dimensions):
            p.current[d] = p.next[d]
          act_fitness = fitness.fitness(p,conf)
        
          # adjust personal best
          if conf.isEqualOrBetterThan(act_fitness,p.bestSoFar) or not p.bestSoFar:
            p.bestSoFar = act_fitness
            for d in range(conf.dimensions):
              p.best[d] = p.current[d]
        
          global gbest
          global bestParticle
          if bestParticle == None: bestParticle = particles[0]
          # reached new global best?
          if conf.isEqualOrBetterThan(act_fitness,gbest) or not gbest: 
            gbest = act_fitness
            bestParticle = p
        
          sumFitness += act_fitness
          sumPBests += p.bestSoFar
  
        # end of: for p in particles
  
          
        # recalculate next for each particle
        pid = 0
        for p in particles:
          n = getNeighborWithBestFitness(pid,conf)
          for d in range(conf.dimensions):
            # individual and soacial influence
            iFactor = conf.iWeight * randMM(conf.iMin,conf.iMax)
            sFactor = conf.sWeight * randMM(conf.sMin,conf.sMax)
            # this helps to compare against a form of random search
            if conf.random_search:
              pDelta[d] = randMM(conf.initMin,conf.initMax) - p.current[d]
              nDelta[d] = randMM(conf.initMin,conf.initMax) - p.current[d]
            else:
              pDelta[d] = p.best[d] - p.current[d] # the 'cognitive' orientation
              nDelta[d] = n.best[d] - p.current[d] # the 'social' orientation
            delta = (iFactor * pDelta[d]) + (sFactor * nDelta[d])
            
            # acceleration: gradually going from acc_max to acc_min ("cooling down")
            acc = conf.acc_max - ((conf.acc_max - conf.acc_min)/conf.maxIterations) * iterations 

            # calculating the next velocity from old velocity + individual and social influence
            new_vel = (p.velocity[d] * acc) + delta
            p.velocity[d] = constrict(new_vel,conf)
            # updating the next position 
            p.next[d] = p.current[d] + p.velocity[d]
          pid += 1
        # end of: for p in particles
       
        # log (if wanted) 
        if iterations in logging.iterLog:
          logging.logPoint(iterations, sumPBests / conf.numberOfParticles, gbest, sumFitness / conf.numberOfParticles,conf)
        
        if iterations in conf.logPopulationAt: logging.logPopulation(particles,iterations,actRun,conf)
        
        iterations += 1
      # end of: while iterations <= maxIterations 
      actRun += 1
      random.seed() # we should reseed the randomizer for each new run!  
    # end of one run, start new trial?

    try:
      conf.actTrialName = trials.next()
    except:
      moreTrials = False
  # end of trial - while

  logging.writeLog(conf)
コード例 #18
0
ファイル: dhcp.py プロジェクト: databus23/staticdhcpd
 def _handleDHCPInform(self, packet, source_address, pxe):
     """
     Evaluates a DHCPINFORM request from a client and determines whether a
     DHCPACK should be sent.
     
     The logic here is to make sure the MAC isn't ignored or acting
     maliciously, then check the database to see whether it has an assigned
     IP. If it does, and the IP it thinks it has a right to matches this IP,
     then an ACK is sent, along with all relevant options; if not, the
     request is ignored.
     
     @type packet: L{libpydhcpserver.dhcp_packet.DHCPPacket}
     @param packet: The DHCPREQUEST to be evaluated.
     @type source_address: tuple
     @param source_address: The address (host, port) from which the request
         was received.
     @type pxe: bool
     @param pxe: True if the packet was received on the PXE port.
     """
     if not self._evaluateRelay(packet, pxe):
         return
         
     start_time = time.time()
     mac = packet.getHardwareAddress()
     if not [None for (ignored_mac, timeout) in self._ignored_addresses if mac == ignored_mac]:
         if not self._logDHCPAccess(mac):
             self._logDiscardedPacket()
             return
             
         ciaddr = packet.getOption("ciaddr")
         giaddr = packet.getOption("giaddr")
         s_ciaddr = '.'.join(map(str, ciaddr))
         if not ciaddr or ciaddr == [0,0,0,0]:
             ciaddr = None
         if not giaddr or giaddr == [0,0,0,0]:
             giaddr = None
         else:
             giaddr = tuple(giaddr)
             
         logging.writeLog('DHCPINFORM from %(mac)s' % {
          'mac': mac,
         })
         
         if not ciaddr:
             logging.writeLog('%(mac)s sent malformed packet; ignoring for %(time)i seconds' % {
              'mac': mac,
              'time': config.UNAUTHORIZED_CLIENT_TIMEOUT,
             })
             with self._stats_lock:
                 self._ignored_addresses.append([mac, config.UNAUTHORIZED_CLIENT_TIMEOUT])
             self._logDiscardedPacket()
             return
             
         try:
             result = self._database.lookupMAC(mac) or config.handleUnknownMAC(mac)
             if result:
                 packet.transformToDHCPAckPacket()
                 pxe_options = packet.extractPXEOptions()
                 vendor_options = packet.extractVendorOptions()
                 self._loadDHCPPacket(packet, result, True)
                 if config.loadDHCPPacket(
                  packet,
                  mac, tuple(ipToList(result[0])), giaddr,
                  result[9], result[10],
                  pxe and pxe_options, vendor_options
                 ):
                     self._sendDHCPPacket(packet, source_address, 'ACK', mac, s_ciaddr, pxe)
                 else:
                     logging.writeLog('Ignoring %(mac)s per loadDHCPPacket()' % {
                      'mac': mac,
                     })
                     self._logDiscardedPacket()
             else:
                 logging.writeLog('%(mac)s unknown; ignoring for %(time)i seconds' % {
                  'mac': mac,
                  'time': config.UNAUTHORIZED_CLIENT_TIMEOUT,
                 })
                 with self._stats_lock:
                     self._ignored_addresses.append([mac, config.UNAUTHORIZED_CLIENT_TIMEOUT])
                 self._logDiscardedPacket()
         except Exception, e:
             logging.sendErrorReport('Unable to respond to %(mac)s' % {'mac': mac,}, e)
コード例 #19
0
ファイル: dhcp.py プロジェクト: databus23/staticdhcpd
 def _handleDHCPRequest(self, packet, source_address, pxe):
     """
     Evaluates a DHCPREQUEST request from a client and determines whether a
     DHCPACK should be sent.
     
     The logic here is to make sure the MAC isn't ignored or acting
     maliciously, then check the database to see whether it has an assigned
     IP. If it does, and the IP it thinks it has a right to matches this IP,
     then an ACK is sent, along with all relevant options; if not, a DHCPNAK
     is sent to inform the client that it is not allowed to use the requested
     IP, forcing it to DISCOVER a new one.
     
     If policy forbids RENEW and REBIND operations, perhaps to prepare for a
     new configuration rollout, all such requests are NAKed immediately.
     
     @type packet: L{libpydhcpserver.dhcp_packet.DHCPPacket}
     @param packet: The DHCPREQUEST to be evaluated.
     @type source_address: tuple
     @param source_address: The address (host, port) from which the request
         was received.
     @type pxe: bool
     @param pxe: True if the packet was received on the PXE port.
     """
     if not self._evaluateRelay(packet, pxe):
         return
         
     start_time = time.time()
     mac = packet.getHardwareAddress()
     if not [None for (ignored_mac, timeout) in self._ignored_addresses if mac == ignored_mac]:
         if not self._logDHCPAccess(mac):
             self._logDiscardedPacket()
             return
             
         ip = packet.getOption("requested_ip_address")
         sid = packet.getOption("server_identifier")
         ciaddr = packet.getOption("ciaddr")
         giaddr = packet.getOption("giaddr")
         s_ip = ip and '.'.join(map(str, ip))
         s_sid = sid and '.'.join(map(str, sid))
         s_ciaddr = ciaddr and '.'.join(map(str, ciaddr))
         
         if not ip or ip == [0,0,0,0]:
             ip = None
         if not sid or sid == [0,0,0,0]:
             sid = None
         if not ciaddr or ciaddr == [0,0,0,0]:
             ciaddr = None
         if not giaddr or giaddr == [0,0,0,0]:
             giaddr = None
         else:
             giaddr = tuple(giaddr)
             
         if sid and not ciaddr: #SELECTING
             if s_sid == self._server_address: #Chosen!
                 logging.writeLog('DHCPREQUEST:SELECTING from %(mac)s' % {
                  'mac': mac,
                 })
                 try:
                     result = self._database.lookupMAC(mac) or config.handleUnknownMAC(mac)
                     if result and (not ip or result[0] == s_ip):
                         packet.transformToDHCPAckPacket()
                         pxe_options = packet.extractPXEOptions()
                         vendor_options = packet.extractVendorOptions()
                         self._loadDHCPPacket(packet, result)
                         if config.loadDHCPPacket(
                          packet,
                          mac, tuple(ipToList(result[0])), giaddr,
                          result[9], result[10],
                          pxe and pxe_options, vendor_options
                         ):
                             self._sendDHCPPacket(packet, source_address, 'ACK', mac, s_ip, pxe)
                         else:
                             logging.writeLog('Ignoring %(mac)s per loadDHCPPacket()' % {
                              'mac': mac,
                             })
                             self._logDiscardedPacket()
                     else:
                         packet.transformToDHCPNackPacket()
                         self._sendDHCPPacket(packet, source_address, 'NAK', mac, 'NO-MATCH', pxe)
                 except Exception, e:
                     logging.sendErrorReport('Unable to respond to %(mac)s' % {'mac': mac,}, e)
             else:
                 self._logDiscardedPacket()
         elif not sid and not ciaddr and ip: #INIT-REBOOT
             logging.writeLog('DHCPREQUEST:INIT-REBOOT from %(mac)s' % {
              'mac': mac,
             })
             try:
                 result = self._database.lookupMAC(mac) or config.handleUnknownMAC(mac)
                 if result and result[0] == s_ip:
                     packet.transformToDHCPAckPacket()
                     pxe_options = packet.extractPXEOptions()
                     vendor_options = packet.extractVendorOptions()
                     self._loadDHCPPacket(packet, result)
                     if config.loadDHCPPacket(
                      packet,
                      mac, tuple(ip), giaddr,
                      result[9], result[10],
                      pxe and pxe_options, vendor_options
                     ):
                         self._sendDHCPPacket(packet, source_address, 'ACK', mac, s_ip, pxe)
                     else:
                         logging.writeLog('Ignoring %(mac)s per loadDHCPPacket()' % {
                          'mac': mac,
                         })
                         self._logDiscardedPacket()
                 else:
                     packet.transformToDHCPNackPacket()
                     self._sendDHCPPacket(packet, source_address, 'NAK', mac, s_ip, pxe)
             except Exception, e:
                 logging.sendErrorReport('Unable to respond to %(mac)s' % {'mac': mac,}, e)
コード例 #20
0
ファイル: dhcp.py プロジェクト: databus23/staticdhcpd
 def _handleDHCPDiscover(self, packet, source_address, pxe):
     """
     Evaluates a DHCPDISCOVER request from a client and determines whether a
     DHCPOFFER should be sent.
     
     The logic here is to make sure the MAC isn't ignored or acting
     maliciously, then check the database to see whether it has an assigned
     IP. If it does, that IP is offered, along with all relevant options; if
     not, the MAC is ignored to mitigate spam from follow-up DHCPDISCOVERS.
     
     @type packet: L{libpydhcpserver.dhcp_packet.DHCPPacket}
     @param packet: The DHCPDISCOVER to be evaluated.
     @type source_address: tuple
     @param source_address: The address (host, port) from which the request
         was received.
     @type pxe: bool
     @param pxe: True if the packet was received on the PXE port.
     """
     if not self._evaluateRelay(packet, pxe):
         return
         
     start_time = time.time()
     mac = packet.getHardwareAddress()
     if not [None for (ignored_mac, timeout) in self._ignored_addresses if mac == ignored_mac]:
         if not self._logDHCPAccess(mac):
             self._logDiscardedPacket()
             return
             
         logging.writeLog('DHCPDISCOVER from %(mac)s' % {
          'mac': mac,
         })
         
         try:
             result = self._database.lookupMAC(mac) or config.handleUnknownMAC(mac)
             if result:
                 rapid_commit = not packet.getOption('rapid_commit') is None
                 if rapid_commit:
                     packet.transformToDHCPAckPacket()
                     packet.forceOption('rapid_commit', [])
                 else:
                     packet.transformToDHCPOfferPacket()
                 pxe_options = packet.extractPXEOptions()
                 vendor_options = packet.extractVendorOptions()
                     
                 self._loadDHCPPacket(packet, result)
                 giaddr = packet.getOption("giaddr")
                 if not giaddr or giaddr == [0,0,0,0]:
                     giaddr = None
                 else:
                     giaddr = tuple(giaddr)
                 if config.loadDHCPPacket(
                  packet,
                  mac, tuple(ipToList(result[0])), giaddr,
                  result[9], result[10],
                  pxe and pxe_options, vendor_options
                 ):
                     if rapid_commit:
                         self._sendDHCPPacket(packet, source_address, 'ACK-rapid', mac, result[0], pxe)
                     else:
                         self._sendDHCPPacket(packet, source_address, 'OFFER', mac, result[0], pxe)
                 else:
                     logging.writeLog('Ignoring %(mac)s per loadDHCPPacket()' % {
                      'mac': mac,
                     })
                     self._logDiscardedPacket()
             else:
                 if config.AUTHORITATIVE:
                     packet.transformToDHCPNackPacket()
                     self._sendDHCPPacket(packet, source_address, 'NAK', mac, '?.?.?.?', pxe)
                 else:
                     logging.writeLog('%(mac)s unknown; ignoring for %(time)i seconds' % {
                      'mac': mac,
                      'time': config.UNAUTHORIZED_CLIENT_TIMEOUT,
                     })
                     with self._stats_lock:
                         self._ignored_addresses.append([mac, config.UNAUTHORIZED_CLIENT_TIMEOUT])
         except Exception, e:
             logging.sendErrorReport('Unable to respond to %(mac)s' % {'mac': mac,}, e)