summaryrefslogtreecommitdiff
path: root/cesar/maximus/python/lib/proto/maximus_proto.py
blob: 67e6d9f0123909fdeedf232b2827d34532be6ab3 (plain)
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
#! usr/bin/env python

#print __name__

from fcall import *
from sta_proto import StaProto
from time import time
from uuid import getnode
import threading

# For unitary test purpose
from time import sleep
import os, pipes

# Constants
SIZE_OF_VLANTAG = SIZE_OF_U32 # in octets
MIN_VALUE_OF_VLANTAG = 0x81000000
MAX_VALUE_OF_VLANTAG = 0x8100FFFF
MIN_SIZE_OF_HEADER = SIZE_OF_DST + SIZE_OF_SRC + SIZE_OF_TYPE # in octets
MMTYPE_OFFSET = SIZE_OF_DST + SIZE_OF_SRC + SIZE_OF_TYPE + SIZE_OF_MMV # in octets
SIZE_OF_MMTYPE = SIZE_OF_U16 # in octets

# For unitary test purpose
class Struct:
    pass
class Proto(threading.Thread):
    def __init__(self, proto):
        threading.Thread.__init__(self)
        self.__proto = proto
    def run(self):
        print "Launching proto..."
        os.system(self.__proto)
    def stop(self):
        print "Stopping proto..."
        os.system("killall " + self.__proto)

class Sniff(threading.Thread):

    def __init__(self, maximus):
        
        # Initialize thread
        threading.Thread.__init__(self)
        self.__run = True
        
        # Contains the network interface to sniff,
        # the destination mac address to filter,
        # and the FCALL to have access to the list of received MMEs
        self.__maximus = maximus
        
        # Create a socket
        self.__my_socket = my_sniff_init(iface=self.__maximus.network_interface)

    def run(self):
        print "Starting sniff..."
        
        while self.__run is True:
            # Sniff until a MME is received
            mme = sniff(my_socket=self.__my_socket, lfilter=lambda x: x.type == HPAV_MTYPE_MME and x.dst == self.__maximus.mac_address, count=1, timeout=1)
            
            if len(mme) != 0:
                # When a MME is received, copy it into the list of received MMEs
                # (the received MME will be processed later)
                self.__maximus.semaphore.acquire()
                self.__maximus.fcall.__class__.rsp_list.append(mme[0])
                self.__maximus.semaphore.release()

    def stop(self):
        print "Stopping sniff..."
        self.__run = False

class MaximusProto:

    def __init__(self):
        
        # Initialize time values
        self.__start_time_value = time()
        self.__max_time_value = 0
        self.__wait_time_value = 0
        
        # Compute source mac address
        src = hex(getnode()).strip('0x').strip('L')
        pad_len = SIZE_OF_SRC * 2 - len(src)
        src = pad_len * '0' + src
        self.mac_address = ''
        for i in range (0, len(src), 2):
            self.mac_address += src[i:i+2]
            if i < len(src)-2:
                self.mac_address += ':'
        self.mac_address = self.mac_address.lower()
        
        # Set default network interface to "br0"
        self.network_interface = "br0"
        
        # Thread
        self.semaphore = None
        self.background = None
        
        # For unitary test purpose
        self.UNIT_TEST = False

    def handler(self, signum, frame):
        print "Signal handler called with signal", signum
        self.uninit()
        exit(0)

    def init(self, argv):
        """Only following optional command line arguments are taken into account:
        -t / --max-tick-value
        -a / --mac-address
        -n / --network-interface
        Others are not applicable and are ignored.
        """
        for i in range (1, len(argv)):
            if argv[i] == '-t' or argv[i] == '--max-tick-value':
                if i+1 < len(argv):
                    self.__max_time_value = self.__start_time_value + (float(argv[i+1])/float(25000000)) # in seconds
            elif argv[i] == '-a' or argv[i] == '--mac-address':
                if i+1 < len(argv):
                    self.mac_address = argv[i+1].lower()
            elif argv[i] == '-n' or argv[i] == '--network-interface':
                if i+1 < len(argv):
                    self.network_interface = argv[i+1]
            elif argv[i] == '-u' or argv[i] == '--unit-test':
                # For unitary test purpose
                self.UNIT_TEST = True
            
            # In case of unitary test, launch the proto station
            elif argv[i] == '-e' or argv[i] == '--station-executable':
                if self.UNIT_TEST and i+1 < len(argv):
                    self.background = Proto(argv[i+1])
                    self.background.start()
                    sleep(2)
                    self.read_file = os.open(FUNCTION_CALL_READ_FILE, os.O_RDWR)
                    self.write_file = os.open(FUNCTION_CALL_WRITE_FILE, os.O_RDWR)
        
        print "Configuration:"
        print "mac address =", self.mac_address
        print "network interface =", self.network_interface
        
        # Create a FCALL to have access to the list of received MMEs
        self.fcall = Fcall("fcall", self)
        
        # Launch the sniff thread
        if not self.UNIT_TEST:
            self.semaphore = threading.Semaphore()
            self.background = Sniff(self)
            self.background.start()
        
        # Set the signal handler
        signal.signal(signal.SIGINT, self.handler)

    def uninit(self):
        self.background.stop()

    def process(self):
        """Listen to network interface.
        """
        time_value = 0 # time value until which to process
        if self.__max_time_value == 0:
            time_value = self.__wait_time_value
        elif self.__wait_time_value != 0:
            time_value = min(self.__max_time_value, self.__wait_time_value)
        
        if self.__max_time_value != 0:
            if (time() >= self.__max_time_value):
                print "Max tick value is reached!"
                exit(1)
        
        if not self.UNIT_TEST:
            # If a MME FCALL has been received, read it
            self.semaphore.acquire()
            rsp_nb = len(self.fcall.__class__.rsp_list)
            self.semaphore.release()
            if rsp_nb != 0:
                print "Number of received MME(s):", rsp_nb
                self.semaphore.acquire()
                mme = self.fcall.__class__.rsp_list.pop(0)
                self.semaphore.release()
                
                # Read the MMTYPE (LITTLE-ENDIAN)
                mmtype = hptoh16(mme.payload.load[SIZE_OF_MMV:SIZE_OF_MMV+SIZE_OF_MMTYPE])
                
                if mmtype == INTERFACE_FCALL_MMTYPE:
                    return read(mme, self)
        
        # In case of unitary test
        else:
            print "Receiving an MME..."
            sleep(2)
            mme = Struct()
            mme.payload = Struct()
            mme.payload.load = os.read(self.read_file, INTERFACE_FCALL_PAYLOAD_OFFSET)
            
            # Read the payload length (BIG-ENDIAN)
            length = ntoh16(mme.payload.load[INTERFACE_FCALL_PAYLOAD_OFFSET-SIZE_OF_U16:INTERFACE_FCALL_PAYLOAD_OFFSET])
            
            mme.payload.load += os.read(self.read_file, length)
            return read(mme, self)

    def create_sta(self, mac_address):
        """Create a stub station object.
        A new argument has to be passed:
        the MAC address of the destination,
        in the scapy Python module format (i.e. "xx:xx:xx:xx:xx:xx").
        Return the stub station object.
        """
        return StaProto(mac_address)

    def create_fcall(self, name):
        """Return a new created Fcall object.
        """
        return Fcall(name, self)

    def create_probe(self):
        """Return a new created Fcall object.
        """
        return Fcall('probe', self)

    def send_mpdu(self, mpdu):
        """As it is not applicable on the Gidel prototype or final product,
        throw an error.
        """
        raise Error("NOT APPLICABLE")

    def set_mpdu_rx(self, user_cb, create_pb_function):
        """As it is not applicable on the Gidel prototype or final product,
        throw an error.
        """
        raise Error("NOT APPLICABLE")

    def send_msdu(self, msdu, station_id):
        """If message type is DATA or MME,
        send an Ethernet frame to network interface,
        else do nothing.
        """
        if msdu.get_type() is 'ETHERNET_TYPE_DATA' or msdu.get_type() is 'ETHERNET_TYPE_MME':
            
            if len(msdu.get()) < MIN_SIZE_OF_HEADER:
                raise Error('Ethernet Frame length')
            
            # Set Ether Header: dst, src, vlantag (optional), type
            #
            ether = Ether()
            
            # Set dst
            begin = 0
            end = SIZE_OF_DST
            address = hex(ntoh48(msdu.get()[begin:end])).strip('0x').strip('L')
            dst = ''
            for i in range (0, len(address), 2):
                dst += address[i:i+2]
                if i < len(address)-2:
                    dst += ':'
            ether.dst = dst.lower()
            
            # Set src
            begin = end
            end += SIZE_OF_SRC
            address = hex(ntoh48(msdu.get()[begin:end])).strip('0x').strip('L')
            src = ''
            for i in range (0, len(address), 2):
                src += address[i:i+2]
                if i < len(address)-2:
                    src += ':'
            ether.src = src.lower()
            
            # Check vlantag
            begin = end
            if ntoh32(msdu.get()[begin:end + SIZE_OF_VLANTAG]) <= MAX_VALUE_OF_VLANTAG\
            and ntoh32(msdu.get()[begin:end + SIZE_OF_VLANTAG]) >= MIN_VALUE_OF_VLANTAG:
                # Set vlantag
                end += SIZE_OF_VLANTAG
                ether.vlantag = ntoh32(msdu.get()[begin:end])
            
            # Set type
            begin = end
            end += SIZE_OF_TYPE
            ether.type = ntoh16(msdu.get()[begin:end])
            
            # Set Ether Payload
            ether.payload = msdu.get()[end:]
            
            if not self.UNIT_TEST:
                # Send the Ethernet frame to network interface
                sendp(ether, iface=self.network_interface)
            
            # In case of unitary test
            else:
                os.write(self.write_file, msdu.get())

    def set_msdu_rx(self, user_cb, create_eth_function, create_mme_function, create_buffer_function, create_sniffer_function):
        """As it is not applicable on the Gidel prototype or final product,
        throw an error.
        """
        raise Error("NOT APPLICABLE")

    def wait(self, tick_value=None):
        """Wait during the specified value (converted from ticks to seconds).
        OR Wait until all responses to sent function messages in asynchronous mode are received.
        """
        if tick_value is not None:
            self.__wait_time_value = time() + tick_value/25000000 # in seconds
            while self.__wait_time_value > time():
                self.process()
            self.__wait_time_value = 0
        else:
            while len(self.fcall.__class__.cb_dict) > 0:
                self.process()

    def disturb_channel(self, enable=True):
        """As it is not applicable on the Gidel prototype or final product,
        throw an error.
        """
        raise Error("NOT APPLICABLE")

    def get_date(self):
        """Return real date in seconds.
        """
        return time() - self.__start_time_value

    def set_freq(self, frequency):
        """As it is not applicable on the Gidel prototype or final product,
        throw an error.
        """
        raise Error("NOT APPLICABLE")

    def get_freq(self):
        """As it is not applicable on the Gidel prototype or final product,
        throw an error.
        """
        raise Error("NOT APPLICABLE")

    def set_snr(self, snr):
        """As it is not applicable on the Gidel prototype or final product,
        throw an error.
        """
        raise Error("NOT APPLICABLE")

    def set_snr_from_src(self, snr, src, both_directions):
        """As it is not applicable on the Gidel prototype or final product,
        throw an error.
        """
        raise Error("NOT APPLICABLE")

    def set_snr_to_dst(self, snr, dst, both_directions):
        """As it is not applicable on the Gidel prototype or final product,
        throw an error.
        """
        raise Error("NOT APPLICABLE")

    def set_snr_from_src_to_dst(self, snr, src, dst, both_directions):
        """As it is not applicable on the Gidel prototype or final product,
        throw an error.
        """
        raise Error("NOT APPLICABLE")

    def activate_false_alarm(self, average_duration, std_deviation):
        """As it is not applicable on the Gidel prototype or final product,
        throw an error.
        """
        raise Error("NOT APPLICABLE")

    def deactivate_false_alarm(self):
        """As it is not applicable on the Gidel prototype or final product,
        throw an error.
        """
        raise Error("NOT APPLICABLE")

    def is_station_idle(self, station_id):
        """As it is not applicable on the Gidel prototype or final product,
        throw an error.
        """
        raise Error("NOT APPLICABLE")