Statistics
| Branch: | Revision:

ml / ml.c @ ffb63fbb

History | View | Annotate | Download (60 KB)

1
/*
2
 *          Policy Management
3
 *
4
 *          NEC Europe Ltd. PROPRIETARY INFORMATION
5
 *
6
 * This software is supplied under the terms of a license agreement
7
 * or nondisclosure agreement with NEC Europe Ltd. and may not be
8
 * copied or disclosed except in accordance with the terms of that
9
 * agreement.
10
 *
11
 *      Copyright (c) 2009 NEC Europe Ltd. All Rights Reserved.
12
 *
13
 * Authors: Kristian Beckers  <beckers@nw.neclab.eu>
14
 *          Sebastian Kiesel  <kiesel@nw.neclab.eu>
15
 *          
16
 *
17
 * NEC Europe Ltd. DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED,
18
 * INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY
19
 * AND FITNESS FOR A PARTICULAR PURPOSE AND THE WARRANTY AGAINST LATENT
20
 * DEFECTS, WITH RESPECT TO THE PROGRAM AND THE ACCOMPANYING
21
 * DOCUMENTATION.
22
 *
23
 * No Liability For Consequential Damages IN NO EVENT SHALL NEC Europe
24
 * Ltd., NEC Corporation OR ANY OF ITS SUBSIDIARIES BE LIABLE FOR ANY
25
 * DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS
26
 * OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF INFORMATION, OR
27
 * OTHER PECUNIARY LOSS AND INDIRECT, CONSEQUENTIAL, INCIDENTAL,
28
 * ECONOMIC OR PUNITIVE DAMAGES) ARISING OUT OF THE USE OF OR INABILITY
29
 * TO USE THIS PROGRAM, EVEN IF NEC Europe Ltd. HAS BEEN ADVISED OF THE
30
 * POSSIBILITY OF SUCH DAMAGES.
31
 *
32
 *     THIS HEADER MAY NOT BE EXTRACTED OR MODIFIED IN ANY WAY.
33
 */
34

    
35
#include <arpa/inet.h>
36
#ifndef WIN32
37
#include <netinet/in.h>
38
#include <sys/socket.h>
39
#endif
40
#include <fcntl.h>
41
#include <event2/event.h>
42
#include <stdlib.h>
43
#include <unistd.h>
44
#include <stdio.h>
45
#include <stddef.h>
46
#include <stdint.h>
47
#include <string.h>
48
#include <sys/types.h>
49
#include <arpa/inet.h>
50
#include <netdb.h>
51
#include <errno.h>
52
#include <time.h>
53
#include <math.h>
54
#include "msg_types.h"
55
#include "util/udpSocket.h"
56
#include "util/stun.h"
57
#include "transmissionHandler.h"
58

    
59
#define LOG_MODULE "[ml] "
60
#include "ml_log.h"
61

    
62
/**************************** START OF INTERNALS ***********************/
63

    
64
/*
65
 * a pointer to a libevent instance
66
 */
67
struct event_base *base;
68

    
69
/*
70
 * define the nr of connections the messaging layer can handle
71
 */
72
#define CONNECTBUFSIZE 10000
73
/*
74
 * define the nr of data that can be received parallel
75
 */
76
#define RECVDATABUFSIZE 10000
77
/*
78
 * define an array for message multiplexing
79
 */
80
#define MSGMULTIPLEXSIZE 127
81

    
82

    
83
/*
84
 * timeout before thinking that the STUN server can't be connected
85
 */
86
#define NAT_TRAVERSAL_TIMEOUT { 1, 0 }
87

    
88
/*
89
 * timeout before thinking of an mtu problem (check MAX_TRIALS as well)
90
 */
91
#define PMTU_TIMEOUT { 0, 500000 }
92

    
93
/*
94
 * retry sending connection messages this many times before reducing pmtu
95
 */
96
#define MAX_TRIALS 3
97

    
98
/*
99
 * default timeout value between the first and the last received packet of a message
100
 */
101
#define RECV_TIMEOUT_DEFAULT { 2, 0 }
102

    
103
/*
104
 * global variables
105
 */
106
/*
107
 * define a buffer of pointers to connect structures
108
 */
109
connect_data *connectbuf[CONNECTBUFSIZE];
110

    
111
/*
112
 * define a pointer buffer with pointers to recv_data structures
113
 */
114
recvdata *recvdatabuf[RECVDATABUFSIZE];
115

    
116
/*
117
 * define a pointer buffer for message multiplexing
118
 */
119
receive_data_cb recvcbbuf[MSGMULTIPLEXSIZE];
120

    
121
/*
122
 * stun server address
123
 */
124
struct sockaddr_in stun_server;
125

    
126
/*
127
 * receive timeout
128
 */
129
static struct timeval recv_timeout = RECV_TIMEOUT_DEFAULT;
130

    
131
/*
132
 * boolean NAT traversal successful if true
133
 */
134
boolean NAT_traversal;
135

    
136
/*
137
 * file descriptor for local socket
138
 */
139
evutil_socket_t socketfd;
140

    
141
/*
142
 * local socketID
143
 */
144
socket_ID local_socketID;
145

    
146
socketID_handle loc_socketID = &local_socketID;
147

    
148
/*
149
 * callback function pointers
150
 */
151
/*
152
 * monitoring module callbacks
153
 */
154
get_recv_pkt_inf_cb get_Recv_pkt_inf_cb = NULL;
155
get_send_pkt_inf_cb get_Send_pkt_inf_cb = NULL;
156
set_monitoring_header_pkt_cb set_Monitoring_header_pkt_cb = NULL;
157
get_recv_data_inf_cb get_Recv_data_inf_cb = NULL;
158
get_send_data_inf_cb get_Send_data_inf_cb = NULL;
159
set_monitoring_header_data_cb set_Monitoring_header_data_cb = NULL;
160
/*
161
 * connection callbacks
162
 */
163
receive_connection_cb receive_Connection_cb = NULL;
164
connection_failed_cb failed_Connection_cb = NULL;
165
/*
166
 * local socketID callback
167
 */
168
receive_localsocketID_cb receive_SocketID_cb;
169

    
170
/*
171
 * boolean that defines if received data is transmitted to the upper layer
172
 * via callback or via upper layer polling
173
 */
174
boolean recv_data_callback;
175

    
176
/*
177
 * helper function to get rid of a warning
178
 */
179
int min(int a, int b) {
180
        if (a > b) return b;
181
        return a;
182
}
183

    
184
/*
185
 * convert a socketID to a string. It uses a static buffer, so either strdup is needed, or the string will get lost!
186
 */
187
const char *conid_to_string(int con_id)
188
{
189
        static char s[INET_ADDRSTRLEN+1+5+1+INET_ADDRSTRLEN+1+5+1];
190
        mlSocketIDToString(&connectbuf[con_id]->external_socketID, s, sizeof(s));
191
        return s;
192
}
193

    
194
void register_recv_localsocketID_cb(receive_localsocketID_cb local_socketID_cb)
195
{
196
        if (local_socketID_cb == NULL)
197
                error("ML : Register receive_localsocketID_cb: NULL ptr \n");
198
        else
199
        receive_SocketID_cb = local_socketID_cb;
200
}
201

    
202

    
203
//void keep_connection_alive(const int connectionID)
204
//{
205
//
206
//    // to be done with the NAT traversal
207
//    // send a message over the wire
208
//    printf("\n");
209
//
210
//}
211

    
212
void unsetStunServer()
213
{
214
        stun_server.sin_addr.s_addr = INADDR_NONE;
215
}
216

    
217
bool isStunDefined()
218
{
219
        return stun_server.sin_addr.s_addr != INADDR_NONE;
220
}
221

    
222
void send_msg(int con_id, int msg_type, char* msg, int msg_len, bool truncable, send_params * sParams) {
223
        socketaddrgen udpgen;
224
        bool retry;
225
        int pkt_len, offset;
226
        struct iovec iov[4];
227

    
228
        char h_pkt[MON_PKT_HEADER_SPACE];
229
        char h_data[MON_DATA_HEADER_SPACE];
230

    
231
        struct msg_header msg_h;
232

    
233
        debug("ML: send_msg to %s conID:%d extID:%d\n", conid_to_string(con_id), con_id, connectbuf[con_id]->external_connectionID);
234

    
235
        iov[0].iov_base = &msg_h;
236
        iov[0].iov_len = MSG_HEADER_SIZE;
237

    
238
        msg_h.local_con_id = con_id;
239
        msg_h.remote_con_id = connectbuf[con_id]->external_connectionID;
240
        msg_h.msg_type = msg_type;
241
        msg_h.msg_seq_num = connectbuf[con_id]->seqnr++;
242

    
243

    
244
        iov[1].iov_len = iov[2].iov_len = 0;
245
        iov[1].iov_base = h_pkt;
246
        iov[2].iov_base = h_data;
247

    
248

    
249
        if (connectbuf[con_id]->internal_connect)
250
                udpgen = connectbuf[con_id]->external_socketID.internal_addr;
251
        else
252
                udpgen = connectbuf[con_id]->external_socketID.external_addr;
253

    
254
        do{
255
                offset = 0;
256
                retry = false;
257
                // Monitoring layer hook
258
                if(set_Monitoring_header_data_cb != NULL) {
259
                        iov[2].iov_len = ((set_Monitoring_header_data_cb) (&(connectbuf[con_id]->external_socketID), msg_type));
260
                }
261
                msg_h.len_mon_data_hdr = iov[2].iov_len;
262

    
263
                if(get_Send_data_inf_cb != NULL && iov[2].iov_len != 0) {
264
                        mon_data_inf sd_data_inf;
265

    
266
                        memset(h_data, 0, MON_DATA_HEADER_SPACE);
267

    
268
                        sd_data_inf.remote_socketID = &(connectbuf[con_id]->external_socketID);
269
                        sd_data_inf.buffer = msg;
270
                        sd_data_inf.bufSize = msg_len;
271
                        sd_data_inf.msgtype = msg_type;
272
                        sd_data_inf.monitoringDataHeader = iov[2].iov_base;
273
                        sd_data_inf.monitoringDataHeaderLen = iov[2].iov_len;
274
                        sd_data_inf.priority = sParams->priority;
275
                        sd_data_inf.padding = sParams->padding;
276
                        sd_data_inf.confirmation = sParams->confirmation;
277
                        sd_data_inf.reliable = sParams->reliable;
278
                        memset(&sd_data_inf.arrival_time, 0, sizeof(struct timeval));
279

    
280
                        (get_Send_data_inf_cb) ((void *) &sd_data_inf);
281
                }
282

    
283
                do {
284
                        if(set_Monitoring_header_pkt_cb != NULL) {
285
                                iov[1].iov_len = (set_Monitoring_header_pkt_cb) (&(connectbuf[con_id]->external_socketID), msg_type);
286
                        }
287
                        pkt_len = min(connectbuf[con_id]->pmtusize - iov[2].iov_len - iov[1].iov_len - iov[0].iov_len, msg_len - offset) ;
288

    
289
                        iov[3].iov_len = pkt_len;
290
                        iov[3].iov_base = msg + offset;
291

    
292
                        //fill header
293
                        msg_h.len_mon_packet_hdr = iov[1].iov_len;
294
                        msg_h.offset = offset;
295
                        msg_h.msg_length = truncable ? pkt_len : msg_len;
296

    
297
                        //monitoring layer hook
298
                        if(get_Send_pkt_inf_cb != NULL && iov[1].iov_len) {
299
                                mon_pkt_inf pkt_info;
300

    
301
                                memset(h_pkt,0,MON_PKT_HEADER_SPACE);
302

    
303
                                pkt_info.remote_socketID = &(connectbuf[con_id]->external_socketID);
304
                                pkt_info.buffer = msg + offset;
305
                                pkt_info.bufSize = pkt_len;
306
                                pkt_info.msgtype = msg_type;
307
                                pkt_info.dataID = connectbuf[con_id]->seqnr;
308
                                pkt_info.offset = offset;
309
                                pkt_info.datasize = msg_len;
310
                                pkt_info.monitoringHeaderLen = iov[1].iov_len;
311
                                pkt_info.monitoringHeader = iov[1].iov_base;
312
                                pkt_info.ttl = -1;
313
                                memset(&(pkt_info.arrival_time),0,sizeof(struct timeval));
314

    
315
                                (get_Send_pkt_inf_cb) ((void *) &pkt_info);
316
                        }
317

    
318
                        debug("ML: sending packet to %s with rconID:%d lconID:%d\n", conid_to_string(con_id), msg_h.remote_con_id, msg_h.local_con_id);
319
                        switch(sendPacket(socketfd, iov, 4, &udpgen.udpaddr)) {
320
                                case MSGLEN:
321
                                        info("ML: sending message failed, reducing MTU from %d to %d (to:%s conID:%d lconID:%d msgsize:%d offset:%d)\n", connectbuf[con_id]->pmtusize, pmtu_decrement(connectbuf[con_id]->pmtusize), conid_to_string(con_id), msg_h.remote_con_id, msg_h.local_con_id, msg_len, offset);
322
                                        // TODO: pmtu decremented here, but not in the "truncable" packet. That is currently resent without changing the claimed pmtu. Might need to be changed.
323
                                        connectbuf[con_id]->pmtusize = pmtu_decrement(connectbuf[con_id]->pmtusize);
324
                                        if (connectbuf[con_id]->pmtusize > 0) {
325
                                                connectbuf[con_id]->delay = true;
326
                                                retry = true;
327
                                        }
328
                                        offset = msg_len; // exit the while
329
                                        break;
330
                                case FAILURE:
331
                                        info("ML: sending message failed (to:%s conID:%d lconID:%d msgsize:%d offset:%d)\n", conid_to_string(con_id), msg_h.remote_con_id, msg_h.local_con_id, msg_len, offset);
332
                                        offset = msg_len; // exit the while
333
                                        break;
334
                                case OK:
335
                                        //update
336
                                        offset += pkt_len;
337
                                        //transmit data header only in the first packet
338
                                        iov[2].iov_len = 0;
339
                                        break;
340
                        }
341
                } while(offset != msg_len && !truncable);
342
        } while(retry);
343
}
344

    
345
void pmtu_timeout_cb(int fd, short event, void *arg);
346

    
347
void reschedule_conn_msg(int con_id)
348
{
349
        if (connectbuf[con_id]->timeout_event) {
350
                /* delete old timout */        
351
                event_del(connectbuf[con_id]->timeout_event);
352
                event_free(connectbuf[con_id]->timeout_event);
353
        }
354
        connectbuf[con_id]->timeout_event = event_new(base, -1, EV_TIMEOUT, &pmtu_timeout_cb, (void *) (long)con_id);
355
        evtimer_add(connectbuf[con_id]->timeout_event, &connectbuf[con_id]->timeout_value);
356
}
357

    
358
void send_conn_msg(int con_id, int buf_size, int command_type)
359
{
360
        if (buf_size < sizeof(struct conn_msg)) {
361
                error("ML: requested connection message size is too small\n");
362
                return;
363
        }
364

    
365
        if(connectbuf[con_id]->ctrl_msg_buf == NULL) {
366
                connectbuf[con_id]->ctrl_msg_buf = malloc(buf_size);
367
                memset(connectbuf[con_id]->ctrl_msg_buf, 0, buf_size);
368
        }
369

    
370
        if(connectbuf[con_id]->ctrl_msg_buf == NULL) {
371
                error("ML: can not allocate memory for connection message\n");
372
                return;
373
        }
374

    
375
        struct conn_msg *msg_header = (struct conn_msg*) connectbuf[con_id]->ctrl_msg_buf;
376

    
377
        msg_header->comand_type = command_type;
378
        msg_header->pmtu_size = connectbuf[con_id]->pmtusize;
379

    
380
        memcpy(&(msg_header->sock_id), loc_socketID, sizeof(socket_ID));
381

    
382
        send_msg(con_id, ML_CON_MSG, connectbuf[con_id]->ctrl_msg_buf, buf_size, true, &(connectbuf[con_id]->defaultSendParams));
383
}
384

    
385
void send_conn_msg_with_pmtu_discovery(int con_id, int buf_size, int command_type)
386
{
387
        struct timeval tout = PMTU_TIMEOUT;
388
        connectbuf[con_id]->timeout_value = tout;
389
        connectbuf[con_id]->trials = 1;
390
        send_conn_msg(con_id, buf_size, command_type);
391
        reschedule_conn_msg(con_id);
392
}
393

    
394
void resend_conn_msg(int con_id)
395
{
396
        connectbuf[con_id]->trials++;
397
        send_conn_msg(con_id, connectbuf[con_id]->pmtusize, connectbuf[con_id]->status);
398
        reschedule_conn_msg(con_id);
399
}
400

    
401
void recv_conn_msg(struct msg_header *msg_h, char *msgbuf, int msg_size, struct sockaddr_in *recv_addr)
402
{
403
        struct conn_msg *con_msg;
404
        int free_con_id, con_id;
405

    
406
        time_t now = time(NULL);
407
        double timediff = 0.0;
408
        char sock_id_str[1000];
409
        
410
        msgbuf += msg_h->len_mon_data_hdr;
411
        msg_size -= msg_h->len_mon_data_hdr;
412
        con_msg = (struct conn_msg *)msgbuf;
413
        
414
        //decode sock_id for debug messages
415
        mlSocketIDToString(&con_msg->sock_id,sock_id_str,999);
416

    
417
        // Monitoring layer hook
418
        if(get_Recv_data_inf_cb != NULL) {
419
                // update pointer to the real data
420
                mon_data_inf recv_data_inf;
421
                recv_data_inf.remote_socketID = &(con_msg->sock_id);
422
                recv_data_inf.buffer = msgbuf;
423
                recv_data_inf.bufSize = msg_size;
424
                recv_data_inf.msgtype = msg_h->msg_type;
425
                recv_data_inf.monitoringDataHeaderLen = msg_h->len_mon_data_hdr;
426
                recv_data_inf.monitoringDataHeader = msg_h->len_mon_data_hdr ? msgbuf : NULL;
427
                gettimeofday(&recv_data_inf.arrival_time, NULL);
428
                recv_data_inf.firstPacketArrived = true;
429
                recv_data_inf.recvFragments = 1;
430
                recv_data_inf.priority = false;
431
                recv_data_inf.padding = false;
432
                recv_data_inf.confirmation = false;
433
                recv_data_inf.reliable = false;
434

    
435
                // send data recv callback to monitoring module
436
                (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
437
        }
438

    
439
        // check the connection command type
440
        switch (con_msg->comand_type) {
441
                /*
442
                * if INVITE: enter a new socket make new entry in connect array
443
                * send an ok
444
                */
445
                case INVITE:
446
                        info("ML: received INVITE from %s (size:%d)\n", sock_id_str, msg_size);
447
                        /*
448
                        * check if another connection for the external connectionID exist
449
                        * that was established within the last 2 seconds
450
                        */
451
                        free_con_id = -1;
452
                        for (con_id = 0; con_id < CONNECTBUFSIZE; con_id++) {
453
                                if (connectbuf[con_id] != NULL) {
454
                                        if (mlCompareSocketIDs(&(connectbuf[con_id]->external_socketID), &(con_msg->sock_id)) == 0) {
455
                                                //timediff = difftime(now, connectbuf[con_id]->starttime);        //TODO: why this timeout? Shouldn't the connection be closed instead if there is a timeout?
456
                                                //if (timediff < 2)
457
                                                //update remote connection ID
458
                                                if (connectbuf[con_id]->external_connectionID != msg_h->local_con_id) {
459
                                                        warn("ML: updating remote connection ID for %s: from %d to %d\n",sock_id_str, connectbuf[con_id]->external_connectionID, msg_h->local_con_id);
460
                                                        connectbuf[con_id]->external_connectionID = msg_h->local_con_id;
461
                                                }
462
                                                break;
463
                                        }
464
                                } else if(free_con_id == -1)
465
                                        free_con_id = con_id;
466
                        }
467

    
468
                        if (con_id == CONNECTBUFSIZE) {
469
                                // create an entry in the connecttrybuf
470
                                if(free_con_id == -1) {
471
                                        error("ML: no new connect_buf available\n");
472
                                        return;
473
                                }
474
                                connectbuf[free_con_id] = (connect_data *) malloc(sizeof(connect_data));
475
                                memset(connectbuf[free_con_id],0,sizeof(connect_data));
476
                                connectbuf[free_con_id]->connection_head = connectbuf[free_con_id]->connection_last = NULL;
477
                                connectbuf[free_con_id]->starttime = time(NULL);
478
                                memcpy(&(connectbuf[free_con_id]->external_socketID), &(con_msg->sock_id), sizeof(socket_ID));
479
                                connectbuf[free_con_id]->pmtusize = con_msg->pmtu_size;        // bootstrap pmtu from the other's size. Not strictly needed, but a good hint
480
                                connectbuf[free_con_id]->timeout_event = NULL;
481
                                connectbuf[free_con_id]->external_connectionID = msg_h->local_con_id;
482
                                connectbuf[free_con_id]->internal_connect =
483
                                        !compare_external_address_socketIDs(&(con_msg->sock_id), loc_socketID);
484
                                con_id = free_con_id;
485
                        }
486

    
487
                        //if(connectbuf[con_id]->status <= CONNECT) { //TODO: anwer anyway. Why the outher would invite otherwise?
488
                                //update status and send back answer
489
                                connectbuf[con_id]->status = CONNECT;
490
                                send_conn_msg_with_pmtu_discovery(con_id, con_msg->pmtu_size, CONNECT);
491
                        //}
492
                        break;
493
                case CONNECT:
494
                        info("ML: received CONNECT from %s (size:%d)\n", sock_id_str, msg_size);
495

    
496
                        if(msg_h->remote_con_id != -1 && connectbuf[msg_h->remote_con_id] == NULL) {
497
                                error("ML: received CONNECT for inexistent connection rconID:%d\n",msg_h->remote_con_id);
498
                                return;
499
                        }
500

    
501
                        /*
502
                        * check if the connection status is not already 1 or 2
503
                        */
504
                        if (connectbuf[msg_h->remote_con_id]->status == INVITE) {
505
                                // set the external connectionID
506
                                connectbuf[msg_h->remote_con_id]->external_connectionID = msg_h->local_con_id;
507
                                // change status con_msg the connection_data
508
                                connectbuf[msg_h->remote_con_id]->status = READY;
509
                                // change pmtusize in the connection_data: not needed. receiving a CONNECT means our INVITE went through. So why change pmtu?
510
                                //connectbuf[msg_h->remote_con_id]->pmtusize = con_msg->pmtu_size;
511

    
512
                                // send the READY
513
                                send_conn_msg_with_pmtu_discovery(msg_h->remote_con_id, con_msg->pmtu_size, READY);
514

    
515
                                if (receive_Connection_cb != NULL)
516
                                        (receive_Connection_cb) (msg_h->remote_con_id, NULL);
517

    
518
                                // call all registered callbacks
519
                                while(connectbuf[msg_h->remote_con_id]->connection_head != NULL) {
520
                                        struct receive_connection_cb_list *temp;
521
                                        temp = connectbuf[msg_h->remote_con_id]->connection_head;
522
                                        (temp->connection_cb) (msg_h->remote_con_id, temp->arg);
523
                                        connectbuf[msg_h->remote_con_id]->connection_head = temp->next;
524
                                        free(temp);
525
                                }
526
                                connectbuf[msg_h->remote_con_id]->connection_head =
527
                                        connectbuf[msg_h->remote_con_id]->connection_last = NULL;
528
                        } else {
529
                                // send the READY
530
                                send_conn_msg_with_pmtu_discovery(msg_h->remote_con_id, con_msg->pmtu_size, READY);
531
                        }
532

    
533
                        debug("ML: active connection established\n");
534
                        break;
535

    
536
                        /*
537
                        * if READY: find the entry in the connection array set the
538
                        * connection active change the pmtu size
539
                        */
540
                case READY:
541
                        info("ML: received READY from %s (size:%d)\n", sock_id_str, msg_size);
542
                        if(connectbuf[msg_h->remote_con_id] == NULL) {
543
                                error("ML: received READY for inexistent connection\n");
544
                                return;
545
                        }
546
                        /*
547
                        * checks if the connection is not already established
548
                        */
549
                        if (connectbuf[msg_h->remote_con_id]->status == CONNECT) {
550
                                // change status of the connection
551
                                connectbuf[msg_h->remote_con_id]->status = READY;
552
                                // change pmtusize: not needed. pmtu doesn't have to be symmetric
553
                                //connectbuf[msg_h->remote_con_id]->pmtusize = con_msg->pmtu_size;
554

    
555
                                if (receive_Connection_cb != NULL)
556
                                        (receive_Connection_cb) (msg_h->remote_con_id, NULL);
557

    
558
                                while(connectbuf[msg_h->remote_con_id]->connection_head != NULL) {
559
                                        struct receive_connection_cb_list *temp;
560
                                        temp = connectbuf[msg_h->remote_con_id]->connection_head;
561
                                        (temp->connection_cb) (msg_h->remote_con_id, temp->arg);
562
                                        connectbuf[msg_h->remote_con_id]->connection_head = temp->next;
563
                                        free(temp);
564
                                }
565
                                connectbuf[msg_h->remote_con_id]->connection_head =
566
                                        connectbuf[msg_h->remote_con_id]->connection_last = NULL;
567
                                debug("ML: passive connection established\n");
568
                        }
569
                        break;
570
        }
571
}
572

    
573
void recv_stun_msg(char *msgbuf, int recvSize)
574
{
575
        /*
576
        * create empty stun message struct
577
        */
578
        StunMessage resp;
579
        memset(&resp, 0, sizeof(StunMessage));
580
        /*
581
        * parse the message
582
        */
583
        int returnValue = 0;
584
        returnValue = recv_stun_message(msgbuf, recvSize, &resp);
585

    
586
        if (returnValue == 0) {
587
                /*
588
                * read the reflexive Address into the local_socketID
589
                */
590
                struct sockaddr_in reflexiveAddr = {0};
591
                reflexiveAddr.sin_family = AF_INET;
592
                reflexiveAddr.sin_addr.s_addr = htonl(resp.mappedAddress.ipv4.addr);
593
                reflexiveAddr.sin_port = htons(resp.mappedAddress.ipv4.port);
594
                socketaddrgen reflexiveAddres = {0};
595
                reflexiveAddres.udpaddr = reflexiveAddr;
596
                local_socketID.external_addr = reflexiveAddres;
597
                NAT_traversal = true;
598
                // callback to the upper layer indicating that the socketID is now
599
                // ready to use
600
                (receive_SocketID_cb) (&local_socketID, 0);
601
        }
602
}
603

    
604
//done
605
void recv_timeout_cb(int fd, short event, void *arg)
606
{
607
        int recv_id = (long) arg;
608
        debug("ML: recv_timeout_cb called. Timeout for id:%d\n",recv_id);
609

    
610
        if (recvdatabuf[recv_id] == NULL) {
611
                return;
612
        }
613

    
614

    
615
/*        if(recvdatabuf[recv_id]->status == ACTIVE) {
616
                //TODO make timeout at least a DEFINE
617
                struct timeval timeout = { 4, 0 };
618
                recvdatabuf[recv_id]->status = INACTIVE;
619
                event_base_once(base, -1, EV_TIMEOUT, recv_timeout_cb,
620
                        arg, &timeout);
621
                return;
622
        }
623
*/
624

    
625
        if(recvdatabuf[recv_id]->status == ACTIVE) {
626
                // Monitoring layer hook
627
                if(get_Recv_data_inf_cb != NULL) {
628
                        mon_data_inf recv_data_inf;
629

    
630
                        recv_data_inf.remote_socketID =
631
                                        &(connectbuf[recvdatabuf[recv_id]->connectionID]->external_socketID);
632
                        recv_data_inf.buffer = recvdatabuf[recv_id]->recvbuf;
633
                        recv_data_inf.bufSize = recvdatabuf[recv_id]->bufsize;
634
                        recv_data_inf.msgtype = recvdatabuf[recv_id]->msgtype;
635
                        recv_data_inf.monitoringDataHeaderLen = recvdatabuf[recv_id]->monitoringDataHeaderLen;
636
                        recv_data_inf.monitoringDataHeader = recvdatabuf[recv_id]->monitoringDataHeaderLen ?
637
                                recvdatabuf[recv_id]->recvbuf : NULL;
638
                        gettimeofday(&recv_data_inf.arrival_time, NULL);
639
                        recv_data_inf.firstPacketArrived = recvdatabuf[recv_id]->firstPacketArrived;
640
                        recv_data_inf.recvFragments = recvdatabuf[recv_id]->recvFragments;
641
                        recv_data_inf.priority = false;
642
                        recv_data_inf.padding = false;
643
                        recv_data_inf.confirmation = false;
644
                        recv_data_inf.reliable = false;
645

    
646
                        // send data recv callback to monitoring module
647

    
648
                        (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
649
                }
650

    
651
                // Get the right callback
652
                receive_data_cb receive_data_callback = recvcbbuf[recvdatabuf[recv_id]->msgtype];
653

    
654
                recv_params rParams;
655

    
656
                rParams.nrMissingBytes = recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->arrivedBytes;
657
                rParams.recvFragments = recvdatabuf[recv_id]->recvFragments;
658
                rParams.msgtype = recvdatabuf[recv_id]->msgtype;
659
                rParams.connectionID = recvdatabuf[recv_id]->connectionID;
660
                rParams.remote_socketID =
661
                        &(connectbuf[recvdatabuf[recv_id]->connectionID]->external_socketID);
662
                rParams.firstPacketArrived = recvdatabuf[recv_id]->firstPacketArrived;
663

    
664
                (receive_data_callback) (recvdatabuf[recv_id]->recvbuf + recvdatabuf[recv_id]->monitoringDataHeaderLen, recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->monitoringDataHeaderLen,
665
                        recvdatabuf[recv_id]->msgtype, &rParams);
666

    
667
                //clean up
668
                if (recvdatabuf[recv_id]->timeout_event) {
669
                        event_del(recvdatabuf[recv_id]->timeout_event);
670
                        event_free(recvdatabuf[recv_id]->timeout_event);
671
                        recvdatabuf[recv_id]->timeout_event = NULL;
672
                }
673
                free(recvdatabuf[recv_id]->recvbuf);
674
                free(recvdatabuf[recv_id]);
675
                recvdatabuf[recv_id] = NULL;
676
        }
677
}
678

    
679
// process a single recv data message
680
void recv_data_msg(struct msg_header *msg_h, char *msgbuf, int bufsize)
681
{
682
        debug("ML: received packet of size %d with rconID:%d lconID:%d type:%d offset:%d\n",bufsize,msg_h->remote_con_id,msg_h->local_con_id,msg_h->msg_type,msg_h->offset);
683

    
684
        int recv_id, free_recv_id = -1;
685

    
686
        if(connectbuf[msg_h->remote_con_id] == NULL) {
687
                debug("ML: Received a message not related to any opened connection!\n");
688
                return;
689
        }
690

    
691
        // check if a recv_data exist and enter data
692
        for (recv_id = 0; recv_id < RECVDATABUFSIZE; recv_id++)
693
                if (recvdatabuf[recv_id] != NULL) {
694
                        if (msg_h->remote_con_id == recvdatabuf[recv_id]->connectionID &&
695
                                        msg_h->msg_seq_num == recvdatabuf[recv_id]->seqnr)
696
                                                break;
697
                } else
698
                        if(free_recv_id == -1)
699
                                free_recv_id = recv_id;
700

    
701

    
702
        if(recv_id == RECVDATABUFSIZE) {
703
                //no recv_data found: create one
704
                recv_id = free_recv_id;
705
                recvdatabuf[recv_id] = (recvdata *) malloc(sizeof(recvdata));
706
                memset(recvdatabuf[recv_id], 0, sizeof(recvdata));
707
                recvdatabuf[recv_id]->connectionID = msg_h->remote_con_id;
708
                recvdatabuf[recv_id]->seqnr = msg_h->msg_seq_num;
709
                recvdatabuf[recv_id]->monitoringDataHeaderLen = msg_h->len_mon_data_hdr;
710
                recvdatabuf[recv_id]->bufsize = msg_h->msg_length + msg_h->len_mon_data_hdr;
711
                recvdatabuf[recv_id]->recvbuf = (char *) malloc(recvdatabuf[recv_id]->bufsize);
712
                recvdatabuf[recv_id]->arrivedBytes = 0;        //count this without the Mon headers
713
                /*
714
                * read the timeout data and set it
715
                */
716
                recvdatabuf[recv_id]->timeout_value = recv_timeout;
717
                recvdatabuf[recv_id]->timeout_event = NULL;
718
                recvdatabuf[recv_id]->recvID = recv_id;
719
                recvdatabuf[recv_id]->starttime = time(NULL);
720
                recvdatabuf[recv_id]->msgtype = msg_h->msg_type;
721

    
722
                // fill the buffer with zeros
723
                memset(recvdatabuf[recv_id]->recvbuf, 0, recvdatabuf[recv_id]->bufsize);
724
                debug(" new @ id:%d\n",recv_id);
725
        } else {        //message structure already exists, no need to create new
726
                debug(" found @ id:%d (arrived before this packet: bytes:%d fragments%d\n",recv_id, recvdatabuf[recv_id]->arrivedBytes, recvdatabuf[recv_id]->recvFragments);
727
        }
728

    
729
        //if first packet extract mon data header and advance pointer
730
        if (msg_h->offset == 0) {
731
                memcpy(recvdatabuf[recv_id]->recvbuf, msgbuf, msg_h->len_mon_data_hdr);
732
                msgbuf += msg_h->len_mon_data_hdr;
733
                bufsize -= msg_h->len_mon_data_hdr;
734
                recvdatabuf[recv_id]->firstPacketArrived = 1;
735
        }
736

    
737

    
738
        // increment fragmentnr
739
        recvdatabuf[recv_id]->recvFragments++;
740
        // increment the arrivedBytes
741
        recvdatabuf[recv_id]->arrivedBytes += bufsize;
742

    
743
        // enter the data into the buffer
744
        memcpy(recvdatabuf[recv_id]->recvbuf + msg_h->len_mon_data_hdr + msg_h->offset, msgbuf, bufsize);
745

    
746
        //TODO very basic checkif all fragments arrived: has to be reviewed
747
        if(recvdatabuf[recv_id]->arrivedBytes == recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->monitoringDataHeaderLen)
748
                recvdatabuf[recv_id]->status = COMPLETE; //buffer full -> msg completly arrived
749
        else
750
                recvdatabuf[recv_id]->status = ACTIVE;
751

    
752
        if (recv_data_callback) {
753
                if(recvdatabuf[recv_id]->status == COMPLETE) {
754
                        // Monitoring layer hook
755
                        if(get_Recv_data_inf_cb != NULL) {
756
                                mon_data_inf recv_data_inf;
757

    
758
                                recv_data_inf.remote_socketID =
759
                                         &(connectbuf[recvdatabuf[recv_id]->connectionID]->external_socketID);
760
                                recv_data_inf.buffer = recvdatabuf[recv_id]->recvbuf;
761
                                recv_data_inf.bufSize = recvdatabuf[recv_id]->bufsize;
762
                                recv_data_inf.msgtype = recvdatabuf[recv_id]->msgtype;
763
                                recv_data_inf.monitoringDataHeaderLen = recvdatabuf[recv_id]->monitoringDataHeaderLen;
764
                                recv_data_inf.monitoringDataHeader = recvdatabuf[recv_id]->monitoringDataHeaderLen ?
765
                                        recvdatabuf[recv_id]->recvbuf : NULL;
766
                                gettimeofday(&recv_data_inf.arrival_time, NULL);
767
                                recv_data_inf.firstPacketArrived = recvdatabuf[recv_id]->firstPacketArrived;
768
                                recv_data_inf.recvFragments = recvdatabuf[recv_id]->recvFragments;
769
                                recv_data_inf.priority = false;
770
                                recv_data_inf.padding = false;
771
                                recv_data_inf.confirmation = false;
772
                                recv_data_inf.reliable = false;
773

    
774
                                // send data recv callback to monitoring module
775

    
776
                                (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
777
                        }
778

    
779
                        // Get the right callback
780
                        receive_data_cb receive_data_callback = recvcbbuf[msg_h->msg_type];
781
                        if (receive_data_callback) {
782

    
783
                                recv_params rParams;
784

    
785
                                rParams.nrMissingBytes = recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->monitoringDataHeaderLen - recvdatabuf[recv_id]->arrivedBytes;
786
                                rParams.recvFragments = recvdatabuf[recv_id]->recvFragments;
787
                                rParams.msgtype = recvdatabuf[recv_id]->msgtype;
788
                                rParams.connectionID = recvdatabuf[recv_id]->connectionID;
789
                                rParams.remote_socketID =
790
                                        &(connectbuf[recvdatabuf[recv_id]->connectionID]->external_socketID);
791

    
792
                                char str[1000];
793
                                mlSocketIDToString(rParams.remote_socketID,str,999);
794
                                debug("ML: received message from conID:%d, %s\n",recvdatabuf[recv_id]->connectionID,str);
795
                                rParams.firstPacketArrived = recvdatabuf[recv_id]->firstPacketArrived;
796

    
797
                                (receive_data_callback) (recvdatabuf[recv_id]->recvbuf + recvdatabuf[recv_id]->monitoringDataHeaderLen, recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->monitoringDataHeaderLen,
798
                                        recvdatabuf[recv_id]->msgtype, (void *) &rParams);
799
                        } else {
800
                            warn("ML: callback not initialized for this message type: %d!\n",msg_h->msg_type);
801
                        }
802

    
803
                        //clean up
804
                        if (recvdatabuf[recv_id]->timeout_event) {
805
                                debug("ML: freeing timeout for %d",recv_id);
806
                                event_del(recvdatabuf[recv_id]->timeout_event);
807
                                event_free(recvdatabuf[recv_id]->timeout_event);
808
                                recvdatabuf[recv_id]->timeout_event = NULL;
809
                        } else {
810
                                debug("ML: received in 1 packet\n",recv_id);
811
                        }
812
                        free(recvdatabuf[recv_id]->recvbuf);
813
                        free(recvdatabuf[recv_id]);
814
                        recvdatabuf[recv_id] = NULL;
815
                } else { // not COMPLETE
816
                        if (!recvdatabuf[recv_id]->timeout_event) {
817
                                //start time out
818
                                //TODO make timeout at least a DEFINE
819
                                recvdatabuf[recv_id]->timeout_event = event_new(base, -1, EV_TIMEOUT, &recv_timeout_cb, (void *) (long)recv_id);
820
                                evtimer_add(recvdatabuf[recv_id]->timeout_event, &recv_timeout);
821
                        }
822
                }
823
        }
824
}
825

    
826
//done
827
void pmtu_timeout_cb(int fd, short event, void *arg)
828
{
829

    
830
        int con_id = (long) arg;
831
        pmtu new_pmtusize;
832

    
833
        debug("ML: pmtu timeout called (lcon:%d)\n",con_id);
834

    
835
        if(connectbuf[con_id] == NULL) {
836
                error("ML: pmtu timeout called on non existing con_id\n");
837
                return;
838
        }
839

    
840
        if(connectbuf[con_id]->status == READY) {
841
                // nothing to do anymore
842
                event_del(connectbuf[con_id]->timeout_event);
843
                event_free(connectbuf[con_id]->timeout_event);
844
                connectbuf[con_id]->timeout_event = NULL;
845
                return;
846
        }
847

    
848
        info("ML: pmtu timeout while connecting(to:%s lcon:%d status:%d size:%d trial:%d tout:%ld.%06ld)\n",conid_to_string(con_id), con_id, connectbuf[con_id]->status, connectbuf[con_id]->pmtusize, connectbuf[con_id]->trials, connectbuf[con_id]->timeout_value.tv_sec, connectbuf[con_id]->timeout_value.tv_usec);
849

    
850
        if(connectbuf[con_id]->delay || connectbuf[con_id]->trials == MAX_TRIALS - 1) {
851
                double delay = connectbuf[con_id]->timeout_value.tv_sec + connectbuf[con_id]->timeout_value.tv_usec / 1000000.0;
852
                delay = delay * 2;
853
                info("\tML: increasing pmtu timeout to %f sec\n", delay);
854
                connectbuf[con_id]->timeout_value.tv_sec = floor(delay);
855
                connectbuf[con_id]->timeout_value.tv_usec = fmod(delay, 1.0) * 1000000.0;
856
                if(connectbuf[con_id]->delay) {
857
                        connectbuf[con_id]->delay = false;
858
                        reschedule_conn_msg(con_id);
859
                }
860
        }
861

    
862
        if(connectbuf[con_id]->trials == MAX_TRIALS) {
863
                // decrement the pmtu size
864
                struct timeval tout = PMTU_TIMEOUT;
865
                info("\tML: decreasing pmtu estimate from %d to %d\n", connectbuf[con_id]->pmtusize, pmtu_decrement(connectbuf[con_id]->pmtusize));
866
                connectbuf[con_id]->pmtusize = pmtu_decrement(connectbuf[con_id]->pmtusize);
867
                connectbuf[con_id]->timeout_value = tout; 
868
                connectbuf[con_id]->trials = 0;
869
        }
870

    
871
        //error in PMTU discovery?
872
        if (connectbuf[con_id]->pmtusize == ERROR) {
873
                if (connectbuf[con_id]->internal_connect == true) {
874
                        //as of now we tried directly connecting, now let's try trough the NAT
875
                        connectbuf[con_id]->internal_connect = false;
876
                        connectbuf[con_id]->pmtusize = MAX;
877
                } else {
878
                        //nothing to do we have to give up
879
                        error("ML: Could not create connection with connectionID %i!\n",con_id);
880
                        // envoke the callback for failed connection establishment
881
                        if(failed_Connection_cb != NULL)
882
                                (failed_Connection_cb) (con_id, NULL);
883
                        // delete the connection entry
884
                        mlCloseConnection(con_id);
885
                        return;
886
                }
887
        }
888

    
889
        //retry
890
        resend_conn_msg(con_id);
891
}
892

    
893

    
894
int schedule_pmtu_timeout(int con_id)
895
{
896
        if (! connectbuf[con_id]->timeout_event) {
897
                struct timeval tout = PMTU_TIMEOUT;
898
                connectbuf[con_id]->timeout_value = tout;
899
                connectbuf[con_id]->trials = 1;
900
                connectbuf[con_id]->timeout_event = event_new(base, -1, EV_TIMEOUT, &pmtu_timeout_cb, (void *) (long)con_id);
901
                evtimer_add(connectbuf[con_id]->timeout_event, &connectbuf[con_id]->timeout_value);
902
        }
903
}
904

    
905
/*
906
 * decrements the mtu size
907
 */
908
pmtu pmtu_decrement(pmtu pmtusize)
909
{
910
        pmtu pmtu_return_size;
911
        switch(pmtusize) {
912
        case MAX:
913
                return DSL;
914
        case DSL:
915
                return DSLMEDIUM;
916
        case DSLMEDIUM:
917
                return DSLSLIM;
918
        case DSLSLIM:
919
                return BELOWDSL;
920
        case BELOWDSL:
921
                return MIN;
922
        case MIN:
923
                return ERROR;
924
        default:
925
                warn("ML: strange pmtu size encountered:%d, changing to some safe value:%d\n", pmtusize, MIN);
926
                return MIN;
927
        }
928
}
929

    
930
// called when an ICMP pmtu error message (type 3, code 4) is received
931
void pmtu_error_cb_th(char *msg, int msglen)
932
{
933
        debug("ML: pmtu_error callback called msg_size: %d\n",msglen);
934
        //TODO debug
935
        return;
936

    
937
    char *msgbufptr = NULL;
938
    int msgtype;
939
    int connectionID;
940
    pmtu pmtusize;
941
    pmtu new_pmtusize;
942
    int dead = 0;
943

    
944
    // check the packettype
945
    msgbufptr = &msg[0];
946

    
947
    // check the msgtype
948
    msgbufptr = &msg[1];
949
    memcpy(&msgtype, msgbufptr, 4);
950

    
951
    if (msgtype == 0) {
952

    
953
        // get the connectionID
954
        msgbufptr = &msg[5];
955
        memcpy(&connectionID, msgbufptr, 4);
956

    
957
        int msgtype_c = connectbuf[connectionID]->status;
958
//        pmtusize = connectbuf[connectionID]->pmtutrysize;
959

    
960
        if (msgtype_c != msgtype) {
961
            dead = 1;
962
        }
963

    
964

    
965
    } else if (msgtype == 1) {
966

    
967
        // read the connectionID
968
        msgbufptr = &msg[9];
969
        memcpy(&connectionID, msgbufptr, 4);
970

    
971
        int msgtype_c = connectbuf[connectionID]->status;
972
//        pmtusize = connectbuf[connectionID]->pmtutrysize;
973

    
974
        if (msgtype_c != msgtype) {
975
            dead = 1;
976
        }
977

    
978
    }
979
    // decrement the pmtu size
980
    new_pmtusize = pmtu_decrement(pmtusize);
981

    
982
//    connectbuf[connectionID]->pmtutrysize = new_pmtusize;
983

    
984
    if (new_pmtusize == ERROR) {
985
                error("ML:  Could not create connection with connectionID %i !\n",
986
                        connectionID);
987

    
988
                if(failed_Connection_cb != NULL)
989
                        (failed_Connection_cb) (connectionID, NULL);
990
                // set the message type to a non existent message
991
                msgtype = 2;
992
                // delete the connection entry
993
                 mlCloseConnection(connectionID);
994
        }
995

    
996
    if (msgtype == 0 && dead != 1) {
997

    
998
        // stop the timeout event
999
        // timeout_del(connectbuf[connectionID]->timeout);
1000
        /*
1001
         * libevent2
1002
         */
1003

    
1004
        // event_del(connectbuf[connectionID]->timeout);
1005

    
1006

    
1007
        // create and send a connection message
1008
//         create_conn_msg(new_pmtusize, connectionID,
1009
//                         &local_socketID, INVITE);
1010

    
1011
//        send_conn_msg(connectionID, new_pmtusize);
1012

    
1013
        // set a timeout event for the pmtu discovery
1014
        // timeout_set(connectbuf[connectionID]->timeout,pmtu_timeout_cb,(void
1015
        // *)&connectionID);
1016

    
1017
        // timeout_add(connectbuf[connectionID]->timeout,&connectbuf[connectionID]->timeout_value);
1018

    
1019
        /*
1020
         * libevent2
1021
         */
1022

    
1023
        struct event *ev;
1024
        ev = evtimer_new(base, pmtu_timeout_cb,
1025
                         (void *) connectbuf[connectionID]);
1026

    
1027
        // connectbuf[connectionID]->timeout = ev;
1028

    
1029
        event_add(ev, &connectbuf[connectionID]->timeout_value);
1030

    
1031
    } else if (msgtype == 1 && dead != 1) {
1032

    
1033
        // stop the timeout event
1034
        // timeout_del(connectbuf[connectionID]->timeout);
1035

    
1036
        /*
1037
         * libevent2
1038
         */
1039
        // info("still here 11 \n");
1040
        // printf("ev %d \n",connectbuf[connectionID]->timeout);
1041
        // event_del(connectbuf[connectionID]->timeout );
1042
        // evtimer_del(connectbuf[connectionID]->timeout );
1043

    
1044

    
1045
//         // create and send a connection message
1046
//         create_conn_msg(new_pmtusize,
1047
//                         connectbuf[connectionID]->connectionID,
1048
//                         NULL, CONNECT);
1049

    
1050
        //send_conn_msg(connectionID, new_pmtusize);
1051

    
1052
        // set a timeout event for the pmtu discovery
1053
        // timeout_set(connectbuf[connectionID]->timeout,pmtu_timeout_cb,(void
1054
        // *)&connectionID);
1055
        // timeout_add(connectbuf[connectionID]->timeout,&connectbuf[connectionID]->timeout_value);
1056

    
1057
        /*
1058
         * libevent2
1059
         */
1060
        // struct event *ev;
1061
        // ev = evtimer_new(base,pmtu_timeout_cb, (void
1062
        // *)connectbuf[connectionID]);
1063
        // connectbuf[connectionID]->timeout = ev;
1064
        // event_add(ev,&connectbuf[connectionID]->timeout_value);
1065

    
1066
    }
1067
}
1068

    
1069
/*
1070
 * what to do once a packet arrived if it is a conn packet send it to
1071
 * recv_conn handler if it is a data packet send it to the recv_data
1072
 * handler
1073
 */
1074

    
1075
//done --
1076
void recv_pkg(int fd, short event, void *arg)
1077
{
1078
        debug("ML: recv_pkg called\n");
1079

    
1080
        struct msg_header *msg_h;
1081
        char msgbuf[MAX];
1082
        pmtu recvSize = MAX;
1083
        char *bufptr = msgbuf;
1084
        int ttl;
1085
        struct sockaddr_in recv_addr;
1086
        int msg_size;
1087

    
1088
        recvPacket(fd, msgbuf, &recvSize, &recv_addr, pmtu_error_cb_th, &ttl);
1089

    
1090

    
1091
        // check if it is not just an ERROR message
1092
        if(recvSize < 0)
1093
                return;
1094

    
1095
        // @TODO check if this simplistic STUN message recognition really always works, probably not
1096
        unsigned short stun_bind_response = 0x0101;
1097
        unsigned short * msgspot = (unsigned short *) msgbuf;
1098
        if (*msgspot == stun_bind_response) {
1099
                debug("ML: recv_pkg: parse stun message called\n");
1100
                recv_stun_msg(msgbuf, recvSize);
1101
                return;
1102
        }
1103

    
1104
        msg_h = (struct msg_header *) msgbuf;
1105

    
1106
        //verify minimum size
1107
        if (recvSize < sizeof(struct msg_header)) {
1108
          info("UDP packet too small, can't be an ML packet");
1109
          return;
1110
        }
1111

    
1112
        //TODO add more verifications
1113

    
1114
        bufptr += MSG_HEADER_SIZE + msg_h->len_mon_packet_hdr;
1115
        msg_size = recvSize - MSG_HEADER_SIZE - msg_h->len_mon_packet_hdr;
1116

    
1117

    
1118
        if(get_Recv_pkt_inf_cb != NULL) {
1119
                mon_pkt_inf msginfNow;
1120
                msginfNow.monitoringHeaderLen = msg_h->len_mon_packet_hdr;
1121
                msginfNow.monitoringHeader = msg_h->len_mon_packet_hdr ? &msgbuf[0] + MSG_HEADER_SIZE : NULL;
1122
                //TODO rethink this ...
1123
                if(msg_h->msg_type == ML_CON_MSG) {
1124
                        struct conn_msg *c_msg = (struct conn_msg *) bufptr;
1125
                        msginfNow.remote_socketID = &(c_msg->sock_id);
1126
                }
1127
                else if(connectbuf[msg_h->remote_con_id] == NULL) {
1128
                        error("ML: received pkg called with non existent connection\n");
1129
                        return;
1130
                } else
1131
                        msginfNow.remote_socketID = &(connectbuf[msg_h->remote_con_id]->external_socketID);
1132
                msginfNow.buffer = bufptr;
1133
                msginfNow.bufSize = recvSize;
1134
                msginfNow.msgtype = msg_h->msg_type;
1135
                msginfNow.ttl = ttl;
1136
                msginfNow.dataID = msg_h->msg_seq_num;
1137
                msginfNow.offset = msg_h->offset;
1138
                msginfNow.datasize = msg_h->msg_length;
1139
                gettimeofday(&msginfNow.arrival_time, NULL);
1140
                (get_Recv_pkt_inf_cb) ((void *) &msginfNow);
1141
        }
1142

    
1143

    
1144
        switch(msg_h->msg_type) {
1145
                case ML_CON_MSG:
1146
                        debug("ML: received conn pkg\n");
1147
                        recv_conn_msg(msg_h, bufptr, msg_size, &recv_addr);
1148
                        break;
1149
                default:
1150
                        if(msg_h->msg_type < 127) {
1151
                                debug("ML: received data pkg\n");
1152
                                recv_data_msg(msg_h, bufptr, msg_size);
1153
                                break;
1154
                        }
1155
                        debug("ML: unrecognised msg_type\n");
1156
                        break;
1157
        }
1158
}
1159

    
1160
/*
1161
 * compare the external IP address of two socketIDs
1162
 */
1163
int
1164
compare_external_address_socketIDs(socketID_handle sock1, socketID_handle sock2)
1165
{
1166
        if( sock1->external_addr.udpaddr.sin_addr.s_addr == sock2->external_addr.udpaddr.sin_addr.s_addr)
1167
                return 0;
1168
        return 1;
1169
}
1170

    
1171
void try_stun();
1172

    
1173
/*
1174
 * the timeout of the NAT traversal
1175
 */
1176
void nat_traversal_timeout(int fd, short event, void *arg)
1177
{
1178
        if (NAT_traversal == false) {
1179
                debug("ML: NAT traversal request re-send\n");
1180
                if(receive_SocketID_cb)
1181
                        (receive_SocketID_cb) (&local_socketID, 2);
1182
                try_stun();
1183
        }
1184
}
1185

    
1186
//return IP address, or INADDR_NONE if can't resolve
1187
unsigned long resolve(const char *ipaddr)
1188
{
1189
        struct hostent *h = gethostbyname(ipaddr);
1190
        if (!h) {
1191
                error("ML: Unable to resolve host name %s\n", ipaddr);
1192
                return INADDR_NONE;
1193
        }
1194
        unsigned long *addr = (unsigned long *) (h->h_addr);
1195
        return *addr;
1196
}
1197

    
1198

    
1199
/*
1200
 * returns the file descriptor, or <0 on error. The ipaddr can be a null
1201
 * pointer. Then all available ipaddr on the machine are choosen.
1202
 */
1203
int create_socket(const int port, const char *ipaddr)
1204
{
1205
        struct sockaddr_in udpaddr = {0};
1206
        udpaddr.sin_family = AF_INET;
1207
        if (ipaddr == NULL) {
1208
                /*
1209
                * try to guess the local IP address
1210
                */
1211
                const char *ipaddr_iface = mlAutodetectIPAddress();
1212
                if (ipaddr_iface) {
1213
                        udpaddr.sin_addr.s_addr = inet_addr(ipaddr_iface);
1214
                } else {
1215
                        udpaddr.sin_addr.s_addr = INADDR_ANY;
1216
                }
1217
        } else {
1218
                udpaddr.sin_addr.s_addr = inet_addr(ipaddr);
1219
        }
1220
        udpaddr.sin_port = htons(port);
1221

    
1222
        socketaddrgen udpgen;
1223
        memset(&udpgen,0,sizeof(socketaddrgen));        //this will be sent over the net, so set it to 0
1224
        udpgen.udpaddr = udpaddr;
1225
        local_socketID.internal_addr = udpgen;
1226

    
1227
        socketfd = createSocket(port, ipaddr);
1228
        if (socketfd < 0){
1229
                return socketfd;
1230
        }
1231

    
1232
        struct event *ev;
1233
        ev = event_new(base, socketfd, EV_READ | EV_PERSIST, recv_pkg, NULL);
1234

    
1235
        event_add(ev, NULL);
1236

    
1237
        try_stun();
1238

    
1239
        return socketfd;
1240
}
1241

    
1242
/*
1243
 * try to figure out external IP using STUN, if defined
1244
 */
1245
void try_stun()
1246
{
1247
        if (isStunDefined()) {
1248
                /*
1249
                * send the NAT traversal STUN request
1250
                */
1251
                 send_stun_request(socketfd, &stun_server);
1252

    
1253
                /*
1254
                * enter a NAT traversal timeout that takes care of retransmission
1255
                */
1256
                struct event *ev1;
1257
                struct timeval timeout_value_NAT_traversal = NAT_TRAVERSAL_TIMEOUT;
1258
                ev1 = evtimer_new(base, nat_traversal_timeout, NULL);
1259
                event_add(ev1, &timeout_value_NAT_traversal);
1260

    
1261
                NAT_traversal = false;
1262
        } else {
1263
                /*
1264
                * Assume we have accessibility and copy internal address to external one
1265
                */
1266
                local_socketID.external_addr = local_socketID.internal_addr;
1267
                NAT_traversal = true; // @TODO: this is not really NAT traversal, but a flag that init is over
1268
                // callback to the upper layer indicating that the socketID is now
1269
                // ready to use
1270
                if(receive_SocketID_cb)
1271
                        (receive_SocketID_cb) (&local_socketID, 0); //success
1272
        }
1273
}
1274

    
1275
/**************************** END OF INTERNAL ***********************/
1276

    
1277
/**************************** MONL functions *************************/
1278

    
1279
int mlInit(bool recv_data_cb,struct timeval timeout_value,const int port,const char *ipaddr,const int stun_port,const char *stun_ipaddr,receive_localsocketID_cb local_socketID_cb,void *arg){
1280

    
1281
        base = (struct event_base *) arg;
1282
        recv_data_callback = recv_data_cb;
1283
        mlSetRecvTimeout(timeout_value);
1284
        if (stun_ipaddr) {
1285
                 mlSetStunServer(stun_port, stun_ipaddr);
1286
        } else {
1287

    
1288
        }
1289
        register_recv_localsocketID_cb(local_socketID_cb);
1290
        return create_socket(port, ipaddr);
1291
}
1292

    
1293
/* register callbacks  */
1294
void mlRegisterGetRecvPktInf(get_recv_pkt_inf_cb recv_pkt_inf_cb){
1295

    
1296
        if (recv_pkt_inf_cb == NULL)
1297
                error("ML: Register get_recv_pkt_inf_cb failed: NULL ptr  \n");
1298
        else
1299
                get_Recv_pkt_inf_cb = recv_pkt_inf_cb;
1300

    
1301
}
1302

    
1303
void mlRegisterGetSendPktInf(get_send_pkt_inf_cb  send_pkt_inf_cb){
1304

    
1305
        if (send_pkt_inf_cb == NULL)
1306
                error("ML: Register get_send_pkt_inf_cb: NULL ptr  \n");
1307
        else
1308
                get_Send_pkt_inf_cb = send_pkt_inf_cb;
1309

    
1310
}
1311

    
1312

    
1313
void mlRegisterSetMonitoringHeaderPktCb(set_monitoring_header_pkt_cb monitoring_header_pkt_cb ){
1314

    
1315
        if (monitoring_header_pkt_cb == NULL)
1316
                error("ML: Register set_monitoring_header_pkt_cb: NULL ptr  \n");
1317
        else
1318
                set_Monitoring_header_pkt_cb = monitoring_header_pkt_cb;
1319

    
1320
}
1321

    
1322
void mlRegisterGetRecvDataInf(get_recv_data_inf_cb recv_data_inf_cb){
1323

    
1324
        if (recv_data_inf_cb == NULL)
1325
                error("ML: Register get_recv_data_inf_cb: NULL ptr  \n");
1326
        else
1327
                get_Recv_data_inf_cb = recv_data_inf_cb;
1328

    
1329
}
1330

    
1331
void mlRegisterGetSendDataInf(get_send_data_inf_cb  send_data_inf_cb){
1332

    
1333
        if (send_data_inf_cb == NULL)
1334
                error("ML: Register get_send_data_inf_cb: NULL ptr  \n");
1335
        else
1336
                get_Send_data_inf_cb = send_data_inf_cb;
1337

    
1338
}
1339

    
1340
void mlRegisterSetMonitoringHeaderDataCb(set_monitoring_header_data_cb monitoring_header_data_cb){
1341

    
1342
        if (monitoring_header_data_cb == NULL)
1343
                error("ML: Register set_monitoring_header_data_cb : NULL ptr  \n");
1344
        else
1345
        set_Monitoring_header_data_cb = monitoring_header_data_cb;
1346

    
1347
}
1348

    
1349
void mlSetRecvTimeout(struct timeval timeout_value){
1350

    
1351
        recv_timeout = timeout_value;
1352

    
1353
}
1354

    
1355
int mlGetStandardTTL(socketID_handle socketID,uint8_t *ttl){
1356

    
1357
        return getTTL(socketfd, ttl);
1358

    
1359
}
1360

    
1361
socketID_handle mlGetLocalSocketID(int *errorstatus){
1362

    
1363
        if (NAT_traversal == false) {
1364
                *errorstatus = 2;
1365
                return NULL;
1366
        }
1367

    
1368
        *errorstatus = 0;
1369
        return &local_socketID;
1370

    
1371
}
1372

    
1373

    
1374
/**************************** END of MONL functions *************************/
1375

    
1376
/**************************** GENERAL functions *************************/
1377

    
1378
void mlRegisterRecvConnectionCb(receive_connection_cb recv_conn_cb){
1379

    
1380
        if (recv_conn_cb == NULL)
1381
                error("ML: Register receive_connection_cb: NULL ptr  \n");
1382
        else
1383
                receive_Connection_cb = recv_conn_cb;
1384

    
1385
}
1386

    
1387
void mlRegisterErrorConnectionCb(connection_failed_cb conn_failed){
1388

    
1389
        if (conn_failed == NULL)
1390
                error("ML: Register connection_failed_cb: NULL ptr  \n");
1391
        else
1392
        failed_Connection_cb = conn_failed;
1393

    
1394
}
1395

    
1396
void mlRegisterRecvDataCb(receive_data_cb data_cb,unsigned char msgtype){
1397

    
1398
    if (msgtype > 126) {
1399

    
1400
            error
1401
            ("ML: Could not register recv_data callback. Msgtype is greater then 126 \n");
1402

    
1403
    }
1404

    
1405
    if (data_cb == NULL) {
1406

    
1407
            error("ML: Register receive data callback: NUll ptr \n ");
1408

    
1409
    } else {
1410

    
1411
        recvcbbuf[msgtype] = data_cb;
1412

    
1413
    }
1414

    
1415
}
1416

    
1417
void mlCloseSocket(socketID_handle socketID){
1418

    
1419
        free(socketID);
1420

    
1421
}
1422

    
1423
void keepalive_fn(evutil_socket_t fd, short what, void *arg) {
1424
        socketID_handle peer = arg;
1425

    
1426
        int con_id = mlConnectionExist(peer, false);
1427
        if (con_id < 0 || connectbuf[con_id]->defaultSendParams.keepalive <= 0) {
1428
                /* Connection fell from under us or keepalive was disabled */
1429
                free(arg);
1430
                return;
1431
        }
1432

    
1433
        /* do what we gotta do */
1434
        if ( connectbuf[con_id]->status == READY) {
1435
                char keepaliveMsg[32] = "";
1436
                sprintf(keepaliveMsg, "KEEPALIVE %d", connectbuf[con_id]->keepalive_seq++);
1437
                send_msg(con_id, MSG_TYPE_ML_KEEPALIVE, keepaliveMsg, 1 + strlen(keepaliveMsg), false, 
1438
                        &(connectbuf[con_id]->defaultSendParams));
1439
        }
1440

    
1441
        /* re-schedule */
1442
        struct timeval t = { 0,0 };
1443
        t.tv_sec = connectbuf[con_id]->defaultSendParams.keepalive;
1444
        if (connectbuf[con_id]->defaultSendParams.keepalive) 
1445
                event_base_once(base, -1, EV_TIMEOUT, keepalive_fn, peer, &t);
1446
}
1447

    
1448
void setupKeepalive(int conn_id) {
1449
        /* Save the peer's address for us */
1450
        socketID_handle peer = malloc(sizeof(socket_ID));
1451
        memcpy(peer, &connectbuf[conn_id]->external_socketID, sizeof(socket_ID));
1452

    
1453
        struct timeval t = { 0,0 };
1454
        t.tv_sec = connectbuf[conn_id]->defaultSendParams.keepalive;
1455

    
1456
        if (connectbuf[conn_id]->defaultSendParams.keepalive) 
1457
                event_base_once(base, -1, EV_TIMEOUT, keepalive_fn, peer, &t);
1458
}
1459

    
1460
/* connection functions */
1461
int mlOpenConnection(socketID_handle external_socketID,receive_connection_cb connection_cb,void *arg, const send_params defaultSendParams){
1462

    
1463
        int con_id;
1464
        if (external_socketID == NULL) {
1465
                error("ML: cannot open connection: one of the socketIDs is NULL\n");
1466
                return -1;
1467
        }
1468
        if (NAT_traversal == false) {
1469
                error("ML: cannot open connection: NAT traversal for socketID still in progress\n");
1470
                return -1;
1471
        }
1472
        if (connection_cb == NULL) {
1473
                error("ML: cannot open connection: connection_cb is NULL\n");
1474
                return -1;
1475
        }
1476

    
1477
        // check if that connection already exist
1478

    
1479
        con_id = mlConnectionExist(external_socketID, false);
1480
        if (con_id >= 0) {
1481
                // overwrite defaultSendParams
1482
                bool newKeepalive = 
1483
                        connectbuf[con_id]->defaultSendParams.keepalive == 0 && defaultSendParams.keepalive != 0;
1484
                connectbuf[con_id]->defaultSendParams = defaultSendParams;
1485
                if (newKeepalive) setupKeepalive(con_id);
1486
                // if so check if it is ready to use
1487
                if (connectbuf[con_id]->status == READY) {
1488
                                // if so use the callback immediately
1489
                                (connection_cb) (con_id, arg);
1490

    
1491
                // otherwise just write the connection cb and the arg pointer
1492
                // into the connection struct
1493
                } else {
1494
                        struct receive_connection_cb_list *temp;
1495
                        temp = malloc(sizeof(struct receive_connection_cb_list));
1496
                        temp->next = NULL;
1497
                        temp->connection_cb = connection_cb;
1498
                        temp->arg = arg;
1499
                        if(connectbuf[con_id]->connection_last != NULL) {
1500
                                connectbuf[con_id]->connection_last->next = temp;
1501
                                connectbuf[con_id]->connection_last = temp;
1502
                        } else
1503
                                connectbuf[con_id]->connection_last = connectbuf[con_id]->connection_head = temp;
1504
                }
1505
                return con_id;
1506
        }
1507
        // make entry in connection_establishment array
1508
        for (con_id = 0; con_id < CONNECTBUFSIZE; con_id++) {
1509
                if (connectbuf[con_id] == NULL) {
1510
                        connectbuf[con_id] = (connect_data *) malloc(sizeof(connect_data));
1511
                        memset(connectbuf[con_id],0,sizeof(connect_data));
1512
                        connectbuf[con_id]->starttime = time(NULL);
1513
                        memcpy(&connectbuf[con_id]->external_socketID, external_socketID, sizeof(socket_ID));
1514
                        connectbuf[con_id]->pmtusize = DSLSLIM;
1515
                        connectbuf[con_id]->timeout_event = NULL;
1516
                        connectbuf[con_id]->status = INVITE;
1517
                        connectbuf[con_id]->seqnr = 0;
1518
                        connectbuf[con_id]->internal_connect = !compare_external_address_socketIDs(external_socketID, &local_socketID);
1519
                        connectbuf[con_id]->connectionID = con_id;
1520

    
1521
                        connectbuf[con_id]->connection_head = connectbuf[con_id]->connection_last = malloc(sizeof(struct receive_connection_cb_list));
1522
                        connectbuf[con_id]->connection_last->next = NULL;
1523
                        connectbuf[con_id]->connection_last->connection_cb = connection_cb;
1524
                        connectbuf[con_id]->connection_last->arg = arg;
1525
                        connectbuf[con_id]->external_connectionID = -1;
1526

    
1527
                        connectbuf[con_id]->defaultSendParams = defaultSendParams;
1528
                        if (defaultSendParams.keepalive) setupKeepalive(con_id);
1529
                        break;
1530
                }
1531
        } //end of for
1532

    
1533
        if (con_id == CONNECTBUFSIZE) {
1534
                error("ML: Could not open connection: connection buffer full\n");
1535
                return -1;
1536
        }
1537

    
1538
        // create and send a connection message
1539
        info("ML:Sending INVITE to %s (lconn:%d)\n",conid_to_string(con_id), con_id);
1540
        send_conn_msg_with_pmtu_discovery(con_id, connectbuf[con_id]->pmtusize, INVITE);
1541

    
1542
        return con_id;
1543

    
1544
}
1545

    
1546
void mlCloseConnection(const int connectionID){
1547

    
1548
        // remove it from the connection array
1549
        if(connectbuf[connectionID]) {
1550
                if(connectbuf[connectionID]->ctrl_msg_buf) {
1551
                        free(connectbuf[connectionID]->ctrl_msg_buf);
1552
                }
1553
                // remove related events
1554
                if (connectbuf[connectionID]->timeout_event) {
1555
                        event_del(connectbuf[connectionID]->timeout_event);
1556
                        event_free(connectbuf[connectionID]->timeout_event);
1557
                        connectbuf[connectionID]->timeout_event = NULL;
1558
                }
1559
                free(connectbuf[connectionID]);
1560
                connectbuf[connectionID] = NULL;
1561
        }
1562

    
1563
}
1564

    
1565
void mlSendData(const int connectionID,char *sendbuf,int bufsize,unsigned char msgtype,send_params *sParams){
1566

    
1567
        if (connectionID < 0) {
1568
                error("ML: send data failed: connectionID does not exist\n");
1569
                return;
1570
        }
1571

    
1572
        if (connectbuf[connectionID] == NULL) {
1573
                error("ML: send data failed: connectionID does not exist\n");
1574
                return;
1575
        }
1576
        if (connectbuf[connectionID]->status != READY) {
1577
            error("ML: send data failed: connection is not active\n");
1578
            return;
1579
        }
1580

    
1581
        if (sParams == NULL) {
1582
                sParams = &(connectbuf[connectionID]->defaultSendParams);
1583
        }
1584

    
1585
        send_msg(connectionID, msgtype, sendbuf, bufsize, false, sParams);
1586

    
1587
}
1588

    
1589
/* transmit data functions  */
1590
int mlSendAllData(const int connectionID,send_all_data_container *container,int nr_entries,unsigned char msgtype,send_params *sParams){
1591

    
1592
    if (nr_entries < 1 || nr_entries > 5) {
1593

    
1594
        error
1595
            ("ML : sendALlData : nr_enties is not between 1 and 5 \n ");
1596
        return 0;
1597

    
1598
    } else {
1599

    
1600
        if (nr_entries == 1) {
1601

    
1602
                mlSendData(connectionID, container->buffer_1,
1603
                      container->length_1, msgtype, sParams);
1604

    
1605
            return 1;
1606

    
1607
        } else if (nr_entries == 2) {
1608

    
1609
            int buflen = container->length_1 + container->length_2;
1610
            char buf[buflen];
1611
            memcpy(buf, container->buffer_1, container->length_1);
1612
            memcpy(&buf[container->length_1], container->buffer_2,
1613
                   container->length_2);
1614
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1615

    
1616
            return 1;
1617

    
1618
        } else if (nr_entries == 3) {
1619

    
1620
            int buflen =
1621
                container->length_1 + container->length_2 +
1622
                container->length_3;
1623
            char buf[buflen];
1624
            memcpy(buf, container->buffer_1, container->length_1);
1625
            memcpy(&buf[container->length_1], container->buffer_2,
1626
                   container->length_2);
1627
            memcpy(&buf[container->length_2], container->buffer_3,
1628
                   container->length_3);
1629
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1630

    
1631

    
1632
            return 1;
1633

    
1634
        } else if (nr_entries == 4) {
1635

    
1636
            int buflen =
1637
                container->length_1 + container->length_2 +
1638
                container->length_3 + container->length_4;
1639
            char buf[buflen];
1640
            memcpy(buf, container->buffer_1, container->length_1);
1641
            memcpy(&buf[container->length_1], container->buffer_2,
1642
                   container->length_2);
1643
            memcpy(&buf[container->length_2], container->buffer_3,
1644
                   container->length_3);
1645
            memcpy(&buf[container->length_3], container->buffer_4,
1646
                   container->length_4);
1647
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1648

    
1649
            return 1;
1650

    
1651
        } else {
1652

    
1653
            int buflen =
1654
                container->length_1 + container->length_2 +
1655
                container->length_3 + container->length_4 +
1656
                container->length_5;
1657
            char buf[buflen];
1658
            memcpy(buf, container->buffer_1, container->length_1);
1659
            memcpy(&buf[container->length_1], container->buffer_2,
1660
                   container->length_2);
1661
            memcpy(&buf[container->length_2], container->buffer_3,
1662
                   container->length_3);
1663
            memcpy(&buf[container->length_3], container->buffer_4,
1664
                   container->length_4);
1665
            memcpy(&buf[container->length_4], container->buffer_5,
1666
                   container->length_5);
1667
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1668

    
1669
            return 1;
1670
        }
1671

    
1672
    }
1673

    
1674
}
1675

    
1676
int mlRecvData(const int connectionID,char *recvbuf,int *bufsize,recv_params *rParams){
1677

    
1678
        //TODO yet to be converted
1679
        return 0;
1680
#if 0
1681
        if (rParams == NULL) {
1682
                error("ML: recv_data failed: recv_params is a NULL ptr\n");
1683
                return 0;
1684
    } else {
1685

1686
        info("ML: recv data called \n");
1687

1688
        int i = 0;
1689
        int returnValue = 0;
1690
        double timeout = (double) recv_timeout.tv_sec;
1691
        time_t endtime = time(NULL);
1692

1693
        for (i = 0; i < RECVDATABUFSIZE; i++) {
1694

1695
            if (recvdatabuf[i] != NULL) {
1696

1697
                if (recvdatabuf[i]->connectionID == connectionID) {
1698

1699
                    info("ML: recv data has entry  \n");
1700

1701
                    double timepass = difftime(endtime, recvdatabuf[i]->starttime);
1702

1703
                    // check if the specified connection has data and it
1704
                    // is complete
1705
                    // check the data seqnr
1706
                    // if(connectionID == recvdatabuf[i]->connectionID &&
1707
                    // 1 == recvdatabuf[i]->status){
1708

1709
                    if (1 == recvdatabuf[i]->status) {
1710

1711
                        // info("transmissionHandler: recv_data set is
1712
                        // complete \n" );
1713

1714
                        // debug("debud \n");
1715

1716
                        // exchange the pointers
1717
                        int buffersize = 0;
1718
                        buffersize = recvdatabuf[i]->bufsize;
1719
                        *bufsize = buffersize;
1720
                        // recvbuf = recvdatabuf[i]->recvbuf;
1721

1722
                        // info("buffersize %d \n",buffersize);
1723
                        memcpy(recvbuf, recvdatabuf[i]->recvbuf,
1724
                               buffersize);
1725
                        // debug(" recvbuf %s \n",recvbuf );
1726

1727
//                         double nrMissFrags =
1728
//                             (double) recvdatabuf[i]->nrFragments /
1729
//                             (double) recvdatabuf[i]->recvFragments;
1730
//                         int nrMissingFragments = (int) ceil(nrMissFrags);
1731

1732
//                        rParams->nrMissingFragments = nrMissingFragments;
1733
//                         rParams->nrFragments = recvdatabuf[i]->nrFragments;
1734
                        rParams->msgtype = recvdatabuf[i]->msgtype;
1735
                        rParams->connectionID =
1736
                            recvdatabuf[i]->connectionID;
1737

1738
                        // break from the loop
1739
                        // debug(" recvbuf %s \n ",recvbuf);
1740

1741
                        // double nrMissFrags =
1742
                        // (double)recvdatabuf[i]->nrFragments /
1743
                        // (double)recvdatabuf[i]->recvFragments;
1744
                        // int nrMissingFragments =
1745
                        // (int)ceil(nrMissFrags);
1746

1747
                        if(get_Recv_data_inf_cb != NULL) {
1748
                                mon_data_inf recv_data_inf;
1749

1750
                                recv_data_inf.remote_socketID = &(connectbuf[connectionID]->external_socketID);
1751
                                recv_data_inf.buffer = recvdatabuf[i]->recvbuf;
1752
                                recv_data_inf.bufSize = recvdatabuf[i]->bufsize;
1753
                                recv_data_inf.msgtype = recvdatabuf[i]->msgtype;
1754
//                                 recv_data_inf.monitoringHeaderType = recvdatabuf[i]->monitoringHeaderType;
1755
//                                 recv_data_inf.monitoringDataHeader = recvdatabuf[i]->monitoringDataHeader;
1756
                                gettimeofday(&recv_data_inf.arrival_time, NULL);
1757
                                recv_data_inf.firstPacketArrived = recvdatabuf[i]->firstPacketArrived;
1758
                                recv_data_inf.nrMissingFragments = nrMissingFragments;
1759
                                recv_data_inf.nrFragments = recvdatabuf[i]->nrFragments;
1760
                                recv_data_inf.priority = false;
1761
                                recv_data_inf.padding = false;
1762
                                recv_data_inf.confirmation = false;
1763
                                recv_data_inf.reliable = false;
1764

1765
                                // send data recv callback to monitoring module
1766

1767
                                (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
1768
                        }
1769

1770

1771
                        // free the allocated memory
1772
                        free(recvdatabuf[i]);
1773
                        recvdatabuf[i] = NULL;
1774

1775
                        returnValue = 1;
1776
                        break;
1777

1778
                    }
1779

1780
                    if (recvdatabuf[i] != NULL) {
1781

1782
                        if (timepass > timeout) {
1783

1784
                            info("ML: recv_data timeout called  \n");
1785

1786
                            // some data about the missing chunks should
1787
                            // be added here
1788
                            // exchange the pointers
1789
                            int buffersize = 0;
1790
                            buffersize = recvdatabuf[i]->bufsize;
1791
                            *bufsize = buffersize;
1792
                            // recvbuf = recvdatabuf[i]->recvbuf;
1793

1794
                            double nrMissFrags =
1795
                                (double) recvdatabuf[i]->nrFragments /
1796
                                (double) recvdatabuf[i]->recvFragments;
1797
                            int nrMissingFragments =
1798
                                (int) ceil(nrMissFrags);
1799

1800
                            // debug(" recvbuf %s \n",recvbuf );
1801

1802
                            memcpy(recvbuf, recvdatabuf[i]->recvbuf,
1803
                                   buffersize);
1804

1805
                            rParams->nrMissingFragments =
1806
                                nrMissingFragments;
1807
                            rParams->nrFragments =
1808
                                recvdatabuf[i]->nrFragments;
1809
                            rParams->msgtype = recvdatabuf[i]->msgtype;
1810
                            rParams->connectionID =
1811
                                recvdatabuf[i]->connectionID;
1812

1813
                                if(get_Recv_data_inf_cb != NULL) {
1814
                                        mon_data_inf recv_data_inf;
1815

1816
                                        recv_data_inf.remote_socketID = &(connectbuf[connectionID]->external_socketID);
1817
                                        recv_data_inf.buffer = recvdatabuf[i]->recvbuf;
1818
                                        recv_data_inf.bufSize = recvdatabuf[i]->bufsize;
1819
                                        recv_data_inf.msgtype = recvdatabuf[i]->msgtype;
1820
                                        recv_data_inf.monitoringHeaderType = recvdatabuf[i]->monitoringHeaderType;
1821
                                        recv_data_inf.monitoringDataHeader = recvdatabuf[i]->monitoringDataHeader;
1822
                                        gettimeofday(&recv_data_inf.arrival_time, NULL);
1823
                                        recv_data_inf.firstPacketArrived = recvdatabuf[i]->firstPacketArrived;
1824
                                        recv_data_inf.nrMissingFragments = nrMissingFragments;
1825
                                        recv_data_inf.nrFragments = recvdatabuf[i]->nrFragments;
1826
                                        recv_data_inf.priority = false;
1827
                                        recv_data_inf.padding = false;
1828
                                        recv_data_inf.confirmation = false;
1829
                                        recv_data_inf.reliable = false;
1830

1831
                                        // send data recv callback to monitoring module
1832

1833
                                        (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
1834
                                }
1835

1836
                            // free the allocated memory
1837
                            free(recvdatabuf[i]);
1838
                            recvdatabuf[i] = NULL;
1839

1840
                            returnValue = 1;
1841
                            break;
1842

1843
                        }
1844
                    }
1845

1846
                }
1847

1848
            }
1849
            // debug("2 recvbuf %s \n ",recvbuf);
1850
        }
1851
        return returnValue;
1852
    }
1853
#endif
1854

    
1855
}
1856

    
1857
int mlSocketIDToString(socketID_handle socketID,char* socketID_string, size_t len){
1858

    
1859
        char internal_addr[INET_ADDRSTRLEN];
1860
        char external_addr[INET_ADDRSTRLEN];
1861
        inet_ntop(AF_INET, &(socketID->internal_addr.udpaddr.sin_addr.s_addr), internal_addr, INET_ADDRSTRLEN);
1862
        inet_ntop(AF_INET, &(socketID->external_addr.udpaddr.sin_addr.s_addr), external_addr, INET_ADDRSTRLEN);
1863

    
1864
        snprintf(socketID_string,len,"%s:%d-%s:%d", internal_addr, ntohs(socketID->internal_addr.udpaddr.sin_port),
1865
                external_addr,        ntohs(socketID->external_addr.udpaddr.sin_port));
1866
        return 0;
1867

    
1868
}
1869

    
1870
int mlStringToSocketID(const char* socketID_string, socketID_handle socketID){
1871

    
1872
        //@TODO add checks against malformed string
1873
        char external_addr[INET_ADDRSTRLEN];
1874
        int external_port;
1875
        char internal_addr[INET_ADDRSTRLEN];
1876
        int internal_port;
1877

    
1878
        char *pch;
1879
        char *s = strdup(socketID_string);
1880

    
1881
        //replace ':' with a blank
1882
        pch=strchr(s,':');
1883
        while (pch!=NULL){
1884
                                *pch = ' ';
1885
                pch=strchr(pch+1,':');
1886
        }
1887
        pch=strchr(s,'-');
1888
        if(pch) *pch = ' ';
1889

    
1890
        sscanf(s,"%s %d %s %d", internal_addr, &internal_port,
1891
                external_addr, &external_port);
1892

    
1893
        //set structure to 0, we initialize each byte, since it will be sent on the net later
1894
        memset(socketID, 0, sizeof(struct _socket_ID));
1895

    
1896
        if(inet_pton(AF_INET, internal_addr, &(socketID->internal_addr.udpaddr.sin_addr)) == 0)
1897
                return EINVAL;
1898
        socketID->internal_addr.udpaddr.sin_family = AF_INET;
1899
        socketID->internal_addr.udpaddr.sin_port = htons(internal_port);
1900

    
1901

    
1902
        if(inet_pton(AF_INET, external_addr, &(socketID->external_addr.udpaddr.sin_addr)) ==0)
1903
                return EINVAL;
1904
        socketID->external_addr.udpaddr.sin_family = AF_INET;
1905
        socketID->external_addr.udpaddr.sin_port = htons(external_port);
1906

    
1907
        free(s);
1908
        return 0;
1909

    
1910
}
1911

    
1912
int mlGetConnectionStatus(int connectionID){
1913

    
1914
        if(connectbuf[connectionID])
1915
                return connectbuf[connectionID]->status == READY;
1916
        return -1;
1917
    
1918
}
1919

    
1920

    
1921
int mlConnectionExist(socketID_handle socketID, bool ready){
1922

    
1923
    /*
1924
     * check if another connection for the external connectionID exist
1925
     * that was established \ within the last 2 seconds
1926
     */
1927
        int i;
1928
        for (i = 0; i < CONNECTBUFSIZE; i++)
1929
                if (connectbuf[i] != NULL)
1930
                        if (mlCompareSocketIDs(&(connectbuf[i]->external_socketID), socketID) == 0) {
1931
                                if (ready) return (connectbuf[i]->status == READY ? i : -1);;
1932
                                return i;
1933
                                }
1934

    
1935
    return -1;
1936

    
1937
}
1938

    
1939
//Added by Robert Birke as comodity functions
1940

    
1941
//int mlPrintSocketID(socketID_handle socketID) {
1942
//        char str[SOCKETID_STRING_SIZE];
1943
//        mlSocketIDToString(socketID, str, sizeof(str));
1944
//        printf(stderr,"int->%s<-ext\n",str);
1945
//}
1946

    
1947
/*
1948
 * hash code of a socketID
1949
 * TODO might think of a better way
1950
 */
1951
int mlHashSocketID(socketID_handle sock) {
1952
    return sock->internal_addr.udpaddr.sin_port +
1953
                          sock->external_addr.udpaddr.sin_port;
1954
}
1955

    
1956
int mlCompareSocketIDs(socketID_handle sock1, socketID_handle sock2) {
1957
        /*
1958
        * compare internal addr
1959
        */
1960
        if(sock1 == NULL || sock2 == NULL)
1961
                return 1;
1962

    
1963
        if (sock1->internal_addr.udpaddr.sin_addr.s_addr !=
1964
            sock2->internal_addr.udpaddr.sin_addr.s_addr)
1965
                        return 1;
1966

    
1967
        if (sock1->internal_addr.udpaddr.sin_port !=
1968
                 sock2->internal_addr.udpaddr.sin_port)
1969
                        return 1;
1970

    
1971
        /*
1972
        * compare external addr
1973
        */
1974
        if (sock1->external_addr.udpaddr.sin_addr.s_addr !=
1975
            sock2->external_addr.udpaddr.sin_addr.s_addr)
1976
                        return 1;
1977

    
1978
        if (sock1->external_addr.udpaddr.sin_port !=
1979
                 sock2->external_addr.udpaddr.sin_port)
1980
                        return 1;
1981

    
1982
        return 0;
1983
}
1984

    
1985
int mlCompareSocketIDsByPort(socketID_handle sock1, socketID_handle sock2)
1986
{
1987
        if(sock1 == NULL || sock2 == NULL)
1988
                return 1;
1989
 
1990
        if (sock1->internal_addr.udpaddr.sin_port !=
1991
                 sock2->internal_addr.udpaddr.sin_port)
1992
                        return 1;
1993

    
1994
        if (sock1->external_addr.udpaddr.sin_port !=
1995
                 sock2->external_addr.udpaddr.sin_port)
1996
                        return 1;
1997
        return 0;
1998
}
1999

    
2000
int mlGetPathMTU(int ConnectionId) {
2001
        if(ConnectionId < 0 || ConnectionId >= CONNECTBUFSIZE)
2002
                return -1;
2003
        if (connectbuf[ConnectionId] != NULL)
2004
                return connectbuf[ConnectionId]->pmtusize;
2005
        return -1;
2006
}
2007

    
2008
/**************************** END of GENERAL functions *************************/
2009

    
2010
/**************************** NAT functions *************************/
2011

    
2012
/* setter  */
2013
void mlSetStunServer(const int port,const char *ipaddr){
2014

    
2015
        stun_server.sin_family = AF_INET;
2016
        if (ipaddr == NULL)
2017
                stun_server.sin_addr.s_addr = htonl(INADDR_NONE);
2018
        else
2019
                stun_server.sin_addr.s_addr = resolve(ipaddr);
2020
        stun_server.sin_port = htons(port);
2021

    
2022
}
2023

    
2024
int mlGetExternalIP(char* external_addr){
2025

    
2026
        socketaddrgen udpgen;
2027
        struct sockaddr_in udpaddr;
2028

    
2029
        udpgen = local_socketID.external_addr;
2030
        udpaddr = udpgen.udpaddr;
2031

    
2032
        inet_ntop(AF_INET, &(udpaddr.sin_addr), external_addr,
2033
                        INET_ADDRSTRLEN);
2034

    
2035
        if (external_addr == NULL) {
2036

    
2037
        return -1;
2038

    
2039
        } else {
2040

    
2041
        return 0;
2042

    
2043
        }
2044

    
2045
}
2046

    
2047
/**************************** END of NAT functions *************************/