This file is indexed.

/usr/share/pyshared/pyevolve/Network.py is in python-pyevolve 0.6~rc1+svn398+dfsg-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
"""

:mod:`Network` -- network utility module
============================================================================

In this module you'll find all the network related implementation

.. versionadded:: 0.6
   The *Network* module.

"""
from __future__ import with_statement
import threading
import socket
import time
import sys
import Util
import cPickle

try:
    import zlib
    ZLIB_SUPPORT = True
except ImportError:
    ZLIB_SUPPORT = False

import Consts
import logging

def getMachineIP():
   """ Return all the IPs from current machine.

   Example:
      >>> Util.getMachineIP()
      ['200.12.124.181', '192.168.0.1']      

   :rtype: a python list with the string IPs

   """
   hostname = socket.gethostname()
   addresses = socket.getaddrinfo(hostname, None)
   ips = [x[4][0] for x in addresses]
   return ips

class UDPThreadBroadcastClient(threading.Thread):
   """ The Broadcast UDP client thread class.

   This class is a thread to serve as Pyevolve client on the UDP
   datagrams, it is used to send data over network lan/wan.

   Example:
      >>> s = Network.UDPThreadClient('192.168.0.2', 1500, 666)
      >>> s.setData("Test data")
      >>> s.start()
      >>> s.join()

   :param host: the hostname to bind the socket on sender (this is NOT the target host)
   :param port: the sender port (this is NOT the target port)
   :param target_port: the destination port target

   """
   def __init__(self, host, port, target_port):
      threading.Thread.__init__(self)
      self.host = host
      self.port = port
      self.targetPort = target_port
      self.data = None
      self.sentBytes = None
      self.sentBytesLock = threading.Lock()

      self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
      self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
      self.sock.bind((host, port))     

   def setData(self, data):
      """ Set the data to send

      :param data: the data to send

      """
      self.data = data

   def getData(self):
      """ Get the data to send

      :rtype: data to send

      """
      return self.data

   def close(self):
      """ Close the internal socket """
      self.sock.close()

   def getSentBytes(self):
      """ Returns the number of sent bytes. The use of this method makes sense 
      when you already have sent the data
         
      :rtype: sent bytes

      """
      sent = None
      with self.sentBytesLock:
         if self.sentBytes is None:
            Util.raiseException('Bytes sent is None')
         else: sent = self.sentBytes
      return sent

   def send(self):
      """ Broadcasts the data """
      return self.sock.sendto(self.data, (Consts.CDefBroadcastAddress, self.targetPort))
   
   def run(self):
      """ Method called when you call *.start()* of the thread """
      if self.data is None:
         Util.raiseException('You must set the data with setData method', ValueError)

      with self.sentBytesLock:
         self.sentBytes = self.send()
      self.close()

class UDPThreadUnicastClient(threading.Thread):
   """ The Unicast UDP client thread class.

   This class is a thread to serve as Pyevolve client on the UDP
   datagrams, it is used to send data over network lan/wan.

   Example:
      >>> s = Network.UDPThreadClient('192.168.0.2', 1500)
      >>> s.setData("Test data")
      >>> s.setTargetHost('192.168.0.50', 666)
      >>> s.start()
      >>> s.join()

   :param host: the hostname to bind the socket on sender (this is not the target host)
   :param port: the sender port (this is not the target port)
   :param pool_size: the size of send pool
   :param timeout: the time interval to check if the client have data to send

   """
   def __init__(self, host, port, pool_size=10, timeout=0.5):
      threading.Thread.__init__(self)
      self.host = host
      self.port = port
      self.target = []
      self.sendPool = []
      self.poolSize = pool_size
      self.sendPoolLock = threading.Lock()
      self.timeout = timeout

      self.doshutdown = False

      self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
      #self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
      self.sock.bind((host, port))     

   def poolLength(self):
      """ Returns the size of the pool
      
      :rtype: integer

      """
      with self.sendPoolLock:
         ret = len(self.sendPool)
      return ret

   def popPool(self):
      """ Return the last data received on the pool

      :rtype: object

      """
      with self.sendPoolLock:
         ret = self.sendPool.pop()
      return ret

   def isReady(self):
      """ Returns True when there is data on the pool or False when not
         
      :rtype: boolean
      
      """
      with self.sendPoolLock:
         ret = True if len(self.sendPool) >= 1 else False
      return ret

   def shutdown(self):
      """  Shutdown the server thread, when called, this method will stop
      the thread on the next socket timeout """
      self.doshutdown = True

   def addData(self, data):
      """ Set the data to send

      :param data: the data to send

      """
      if self.poolLength() >= self.poolSize:
         logging.warning('the send pool is full, consider increasing the pool size or decreasing the timeout !')
         return

      with self.sendPoolLock:
         self.sendPool.append(data)

   def setTargetHost(self, host, port):
      """ Set the host/port of the target, the destination

      :param host: the target host
      :param port: the target port

      .. note:: the host will be ignored when using broadcast mode
      """
      del self.target[:]
      self.target.append((host, port))

   def setMultipleTargetHost(self, address_list):
      """ Sets multiple host/port targets, the destinations
      
      :param address_list: a list with tuples (ip, port)
      """
      del self.target[:]
      self.target = address_list[:]

   def close(self):
      """ Close the internal socket """
      self.sock.close()

   def send(self, data):
      """ Send the data

      :param data: the data to send
      :rtype: bytes sent to each destination
      """
      bytes = -1
      for destination in self.target:
         bytes = self.sock.sendto(data, destination)
      return bytes
   
   def run(self):
      """ Method called when you call *.start()* of the thread """
      if len(self.target) <= 0:
         Util.raiseException('You must set the target(s) before send data', ValueError)

      while True:
         if self.doshutdown: break

         while self.isReady():
            data = self.popPool()
            self.send(data)

         time.sleep(self.timeout)
      
      self.close()

class UDPThreadServer(threading.Thread):
   """ The UDP server thread class.

   This class is a thread to serve as Pyevolve server on the UDP
   datagrams, it is used to receive data from network lan/wan.

   Example:
      >>> s = UDPThreadServer("192.168.0.2", 666, 10)
      >>> s.start()
      >>> s.shutdown()

   :param host: the host to bind the server
   :param port: the server port to bind
   :param poolSize: the size of the server pool
   :param timeout: the socket timeout

   .. note:: this thread implements a pool to keep the received data,
             the *poolSize* parameter specifies how much individuals
             we must keep on the pool until the *popPool* method 
             is called; when the pool is full, the sever will
             discard the received individuals.

   """
   def __init__(self, host, port, poolSize=10, timeout=3):
      threading.Thread.__init__(self)
      self.recvPool = []
      self.recvPoolLock = threading.Lock()
      self.bufferSize = 4096
      self.host = host
      self.port = port
      self.timeout = timeout
      self.doshutdown = False
      self.poolSize = poolSize

      self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
      #self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
      self.sock.bind((host, port))     
      self.sock.settimeout(self.timeout)

   def shutdown(self):
      """  Shutdown the server thread, when called, this method will stop
      the thread on the next socket timeout """
      self.doshutdown = True

   def isReady(self):
      """ Returns True when there is data on the pool or False when not
         
      :rtype: boolean
      
      """
      with self.recvPoolLock:
         ret = True if len(self.recvPool) >= 1 else False
      return ret
    
   def poolLength(self):
      """ Returns the size of the pool
      
      :rtype: integer

      """
      with self.recvPoolLock:
         ret = len(self.recvPool)
      return ret

   def popPool(self):
      """ Return the last data received on the pool

      :rtype: object

      """
      with self.recvPoolLock:
         ret = self.recvPool.pop()
      return ret

   def close(self):
      """ Closes the internal socket """
      self.sock.close()

   def setBufferSize(self, size):
      """ Sets the receive buffer size
      
      :param size: integer

      """
      self.bufferSize = size

   def getBufferSize(self):
      """ Gets the current receive buffer size

      :rtype: integer

      """
      return self.bufferSize

   def getData(self):
      """ Calls the socket *recvfrom* method and waits for the data,
      when the data is received, the method will return a tuple
      with the IP of the sender and the data received. When a timeout
      exception occurs, the method return None.
      
      :rtype: tuple (sender ip, data) or None when timeout exception

      """
      try:
         data, sender = self.sock.recvfrom(self.bufferSize)
      except socket.timeout:
         return None
      return (sender[0], data)
      
   def run(self):
      """ Called when the thread is started by the user. This method
      is the main of the thread, when called, it will enter in loop
      to wait data or shutdown when needed.
      """
      while True:
         # Get the data
         data = self.getData()
         # Shutdown called
         if self.doshutdown: break
         # The pool is full
         if self.poolLength() >= self.poolSize:
            continue
         # There is no data received
         if data == None: continue
         # It's a packet from myself
         if data[0] == self.host:
            continue
         with self.recvPoolLock:
            self.recvPool.append(data)

      self.close()

def pickleAndCompress(obj, level=9):
   """ Pickles the object and compress the dumped string with zlib
   
   :param obj: the object to be pickled
   :param level: the compression level, 9 is the best
                    and -1 is to not compress

   """
   pickled = cPickle.dumps(obj)
   if level < 0: return pickled
   else:
      if not ZLIB_SUPPORT:
         Util.raiseException('zlib not found !', ImportError)
      pickled_zlib = zlib.compress(pickled, level)
      return pickled_zlib

def unpickleAndDecompress(obj_dump, decompress=True):
   """ Decompress a zlib compressed string and unpickle the data
   
   :param obj: the object to be decompressend and unpickled
   """
   if decompress:
      if not ZLIB_SUPPORT:
         Util.raiseException('zlib not found !', ImportError)
      obj_decompress = zlib.decompress(obj_dump)
   else:
      obj_decompress = obj_dump
   return cPickle.loads(obj_decompress)

if __name__ == "__main__":
   arg = sys.argv[1]
   myself = getMachineIP()

   if arg == "server":
      s = UDPThreadServer(myself[0], 666)
      s.start()
      
      while True:
         print ".",
         time.sleep(10)
         if s.isReady():
            item = s.popPool()
            print item
         time.sleep(4)
         s.shutdown()
         break


   elif arg == "client":
      print "Binding on %s..." % myself[0]
      s = UDPThreadUnicastClient(myself[0], 1500)
      s.setData("dsfssdfsfddf")
      s.setTargetHost(myself[0], 666)
      s.start()
      s.join()
      print s.getSentBytes()
     
   print "end..."