Source

imalse / core / real / node.py

  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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
from ftplib import FTP
import os
import socket
import select
import sys
import mimetypes
import threading
import time
import struct

from core.real.jedie_python_ping.ping import verbose_ping

__all__ = ['PhysicalNode']

class StoppableThread(threading.Thread):
    
    """A thread class with a custom stop function."""
    
    def __init__(self):
        threading.Thread.__init__(self)
        self.stop_event = threading.Event()

    def stop(self):
        """Stop the thread."""
        if self.isAlive() == True:
            # set event to signal thread to terminate
            self.stop_event.set()
            # block calling thread until thread really has terminated
            self.join()

class PingThread(StoppableThread):
    
    """Stoppable thread to perform pings in a separate thread."""
    
    def __init__(self, data):
        self.data = data
        StoppableThread.__init__(self)

    def run(self):
        """Ping hosts based on the given parameters."""        
        verbose_ping(self.data.hostname, self.data.timeout,\
                      self.data.packet_size, self.data.interval,\
                      self.data.num_packets)

class PhysicalNode(object):
    
    """
    
    A node can maintain a lot of sockets.
    This is an abstraction of an physical node. 
    Will use sockets to send real data to the network.
    
    """
    
    proto_map = {'udp':socket.SOCK_STREAM, 'tcp':socket.SOCK_STREAM}
    NODE_TYPE = 'real'

    def __init__(self):
        self.sockets = dict()
        self.pings = dict()
        self.cmd_set = None

    def start(self):
        """Start the node."""    
        if self.cmd_set:
            self.cmd_set.start()
        else:
            print 'The command set has not been set'

    #################################
    ###  File System              ###
    #################################
    def get_file_list(self, max_number, suffix, directory):
        """
        
        Search and return files present in the directory and 
        its subdirectories.
        
        """
        files = []
        for _path, _subdirs, _files in os.walk(directory):
            for name in _files:
                if os.path.splitext(name)[1] in suffix \
                and len(files) < max_number:
                    n_file = str(os.path.join(os.path.abspath(_path), name))
                    files.append(n_file)

        return files

    def load_file(self, l_file):
        """Open a file."""
        fid = open(l_file, 'r')
        return fid.read()

    #################################
    ###  Some Utility Function    ###
    #################################
    @property
    def now(self): 
        """Return the current time."""
        return time.time()

    def sleep(self, duration, call_back=None):
        """Let the node sleep.
        
        Keyword arguments:
        duration -- duration that the node sleeps in seconds
        call_back -- if specified, this will be called when the node awakes.
        
        """               
        time.sleep(duration)
        if call_back: 
            call_back()

    def create_timer(self, seconds, call_back):
        """Create a timer that calls a call_back after an amount of seconds."""
        timer = threading.Timer(seconds, call_back)
        timer.start()

    #################################
    ###  Network Related          ###
    #################################
    def set_master_sock(self, sock):
        """Set a socket as the master socket."""
        self.sockets[sock]['type'] = 'master'
    
    @property
    def master_sock(self):
        """Return the master socket."""               
        for sock, val in self.sockets.iteritems():
            if val['type'] == 'master': return sock
        
        return None
    
    @property
    def client_socks(self):
        """Return an array containing the client sockets."""
        sockets = []
        
        for sock, val in self.sockets.iteritems():
            if val['type'] == 'client': 
                sockets.append(sock)
        
        return sockets

    def create_sock(self, desc):
        """Create and return a new socket.
        
        Keyword arguments:
        desc -- the address and port it tries to connect to and the type of 
                the connection.
        
        """       
        sock = socket.socket(socket.AF_INET, self.proto_map[desc['proto']])
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sockets[sock] = desc
        return sock

    def bind(self, sock, port):
        """Bind the socket to port"""
        print 'addr_port, ', port
        sock.bind(port)

    def listen(self, sock, backlog):
        """Listen for connections made to the socket. 
        
        Keyword arguments:
        backlog -- specifies the maximum number of queued connections.
        
        """
        sock.listen(backlog)

    def accept(self, sock):
        """Accept a connection and add the socket to the 'client_sock" map."""
        assert( self.sockets[sock]['type'] == 'server')
        client_sock, address = sock.accept()        
        self.sockets[client_sock] = {
                'addr': address,
                'type':'client'
                }
        return client_sock, address

    def recv(self, sock, bufsize, dispatcher, threaded=False):
        """Call a receive function. Default choice is not threaded.
        
        Keyword arguments:
        sock -- the socket in question
        bufsize -- the maximum buffer size
        dispatcher -- a function handler that will manipulate the data
        threaded -- if true a new thread will be created to avoid
                    blocking the main process. Only supported by 'real' nodes. 
                    Threading is not allowed for simulated nodes. 
        """
        
        if threaded:
            self.thread_recv(sock, bufsize, dispatcher)
        else:
            self.block_recv(sock, bufsize, dispatcher)

    def block_recv(self, sock, bufsize, dispatcher):
        """Receive data from the socket with this blocking function."""
        while True:
            try:
                data = sock.recv(bufsize)                
            except socket.error as err:
                print 'exception in socket [%s] with error:[%s]' % (sock, err)
                print 'this sock will be closed'
                self.close_sock(sock)
                return
            if not data: 
                break
           
            if dispatcher(sock, data) == 'fail':
                print 'sock_recv dispatcher fail, data, ', data
                break

    def thread_recv(self, sock, bufsize, dispatcher):
        """Receive data from the socket in a separate thread."""
        try:
            recv_th = threading.Thread(target = self.block_recv,
                    args=(sock, bufsize, dispatcher))
            recv_th.daemon = True
            recv_th.start()
            # while True: time.sleep(100)
        except (KeyboardInterrupt, SystemExit):
            print '\n! Receive Keyboard interrupt, quitting threads. \n'

    def send(self, sock, data):
        """Send data to the socket."""
        sock.send(data)

    def connect(self, sock, addr_port):
        """Connect to a remote socket at addr_port."""
        try:
            sock.connect(addr_port)
            data = sock.recv(512)
            if data == 'connect_ack':
                return 'recv_ack'
            else:
                raise Exception('unknown info from server')
        except socket.error as err:
            self.close_sock(sock)
            print err
            return 'connection_refused'
        except socket.timeout as err:
            print err
            return 'request_timeout'

    def sendto(self, sock, data, addr, port):
        """
        
        Send data to the socket. The destination socket is specified
        by the address.
        
        """        
        sock.sendto(data, (addr, port))  
    
    def close_socks(self, socket_ids):
        """Specific sockets will be closed. 
        
        Keyword arguments:
        socket_ids -- specifies which sockets will be closed.
        
        """
        socks_set = [self.client_socks[i] for i in socket_ids]
        for sock in socks_set:
            sock.close()
            del self.sockets[sock]

    def close_sock(self, sock):
        """Close a specific socket."""
        sock.close()
        del self.sockets[sock]

    #################################
    ###       Webserver         ###
    #################################
    def start_webservice(self):
        PORT = 80
        BACKLOG = 5
        RCV_BUFF_SIZE = 512
        
        try:
            server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM )
            server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            server_socket.bind(('', PORT))
            server_socket.listen(BACKLOG)
        except socket.error:
            sys.exit()
        
        active_sockets = [server_socket]
        
        while True:
            # Establish connection with client and check for data.
            try:
                inputready, outputready, exceptready = \
                    select.select(active_sockets, active_sockets, [])

            except select.error, error:
                break
            except socket.error, error:
                break
            
            for sock in inputready:
                #Server socket                
                if sock == server_socket:
                    client_socket, address = server_socket.accept()                                        
                    active_sockets.append(client_socket)
                    
                #Client sockets
                else:
                    try: 
                        data = sock.recv(RCV_BUFF_SIZE)
                        
                        if data: 
                            self.parse_data(data, sock)
                        else:                            
                            sock.close()
                            active_sockets.remove(sock)
                    except socket.error, error:
                        print error
                        sock.close()
                        active_sockets.remove(sock)
    
    def parse_data(self, data, sock):                
        #HTTP header is on the first line
        data = data.splitlines()
        header = data[0].split(' ')
        
        if header[0] == 'GET' and header[2] == 'HTTP/1.1':    
            #A dot before the slash is needed to open subfolders
            if header[1][1:] == '':                
                    header[1] = './index.html'               
            else:
                header[1] = '.' + header[1]                
            
            try:
                file = open(header[1], 'r')
                read_data = file.read()
                file_type, file_encoding = mimetypes.guess_type(header[1])
                
                response = 'HTTP/1.1 200 OK\r\n'            
                response += 'Content-Length: ' + str(len(read_data)) + '\r\n'
                response += 'Content-Type: ' + file_type + '\r\n\r\n'
                response += read_data
                
                sock.sendall(response)                            
                file.close()                
            
            #If the file can't be found, 404 error.
            except IOError as err:                            
                sock.send('HTTP/1.1 404 Not Found\r\n\r\n404 Not Found')              
        #If the command isn't a GET, 501 error.
        else:
            sock.send('HTTP/1.1 501 Not Implemented\r\n\r\n501 Not Implemented')
            
                       

    #################################
    ###       Application         ###
    #################################
    def ping(self, sock, data, threaded=False):
        """Send ping traffic to hosts.
        
        Keyword arguments:
        sock -- the used socket
        data -- contains the server information
        threaded -- create a separate thread if true
        
        """
        
        if threaded:
            ping_th = PingThread(data)
            self.pings[sock] = ping_th
            ping_th.run()
        else:            
            verbose_ping(data.hostname, data.timeout, data.packet_size, data.interval, data.num_packets)

    def ftp_upload(self, data, host, user, password):
        """Upload data to a ftp sever"""
        print 'ftp_upload'
        print 'try to login to host [%s] with user [%s] and password [%s]'\
            % (host, user, password)
        ftp = FTP(host, user, password)
        print 'try to upload file %s' % (data)
        ftp.storbinary('STOR %s'%(os.path.basename(data)), open(data, 'rb'))
        self.sleep(0.1)
        print 'upload file finish %s' % (data)

    def stop_app(self, sock, app_name):
        """Stop the threads performing the pings."""
        if app_name == 'ping':
            self.pings[sock].stop()
            del self.pings[sock]

    def dispatcher(self, sock, data):
        """Initialize the dispatcher."""
        self.cmd_set.dispatcher(sock, data)
        
    def get_checksum(self, msg):
        """
        
        This function calculates checksums. The loop takes 2 characters at a time.
        
        """
        checksum = 0
        
        for i in range(0, len(msg), 2):
            val = (ord(msg[i]) << 8) + (ord(msg[i+1]) )
            checksum = checksum + val
         
        checksum = (checksum >> 16) + (checksum & 0xffff)
        checksum = ~checksum & 0xffff     
        return checksum
 
    def construct_packet(self, source_ip, dest_ip):
        """Construct the tcp syn packet."""       
        # ip header fields
        ihl = 5
        version = 4
        tos = 0
        tot_len = 20 + 20   
        packet_id = 54321  
        frag_off = 0
        ttl = 255
        protocol = socket.IPPROTO_TCP
        check = 10 
        saddr = socket.inet_aton ( source_ip )  
        daddr = socket.inet_aton ( dest_ip )
         
        ihl_version = (version << 4) + ihl
         
        # the ! in the pack format string means network order
        ip_header = struct.pack('!BBHHHBBH4s4s' , ihl_version, tos, tot_len, packet_id, frag_off, ttl, protocol, check, saddr, daddr)
         
        # tcp header fields
        source_port = 1234   
        dest_port = 80   
        seq = 0
        ack_seq = 0
        doff = 5    #4 bit field, size of tcp header, 5 * 4 = 20 bytes
        #tcp flags
        fin = 0
        syn = 1
        rst = 0
        psh = 0
        ack = 0
        urg = 0
        window = socket.htons (5840)    #   maximum allowed window size
        check = 0
        urg_ptr = 0
         
        offset_res = (doff << 4) + 0
        tcp_flags = fin + (syn << 1) + (rst << 2) + (psh <<3) + (ack << 4) + (urg << 5)
         
        # the ! in the pack format string means network order
        tcp_header = struct.pack('!HHLLBBHHH', source_port, dest_port, seq,\
                         ack_seq, offset_res, tcp_flags, window, check, urg_ptr)
         
        # pseudo header fields
        source_address = socket.inet_aton( source_ip )
        dest_address = socket.inet_aton(dest_ip)
        placeholder = 0
        protocol = socket.IPPROTO_TCP
        tcp_length = len(tcp_header)
         
        psh = struct.pack('!4s4sBBH', source_address, dest_address, placeholder,\
                          protocol , tcp_length)
        psh = psh + tcp_header
         
        tcp_checksum = self.get_checksum(psh)
     
        # make the tcp header again and fill the correct checksum
        tcp_header = struct.pack('!HHLLBBHHH' , source_port, dest_port, seq, ack_seq, offset_res, tcp_flags,  window, tcp_checksum , urg_ptr)
         
        # final full packet - syn packets dont have any data
        return ip_header + tcp_header