Statistics
| Branch: | Revision:

ml / ml.c @ 9ac85ab6

History | View | Annotate | Download (59.4 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
#include <netinet/in.h>
37
#include <sys/socket.h>
38
#include <fcntl.h>
39
#include <event2/event.h>
40
#include <stdlib.h>
41
#include <unistd.h>
42
#include <stdio.h>
43
#include <stddef.h>
44
#include <stdint.h>
45
#include <string.h>
46
#include <sys/types.h>
47
#include <arpa/inet.h>
48
#include <netdb.h>
49
#include <errno.h>
50
#include <time.h>
51
#include <math.h>
52
#include "msg_types.h"
53
#include "util/udpSocket.h"
54
#include "util/stun.h"
55
#include "transmissionHandler.h"
56

    
57
#define LOG_MODULE "[ml] "
58
#include "ml_log.h"
59

    
60
/**************************** START OF INTERNALS ***********************/
61

    
62
/*
63
 * a pointer to a libevent instance
64
 */
65
struct event_base *base;
66

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

    
80

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

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

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

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

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

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

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

    
119
/*
120
 * stun server address
121
 */
122
struct sockaddr_in stun_server;
123

    
124
/*
125
 * receive timeout
126
 */
127
static struct timeval recv_timeout = RECV_TIMEOUT_DEFAULT;
128

    
129
/*
130
 * boolean NAT traversal successful if true
131
 */
132
boolean NAT_traversal;
133

    
134
/*
135
 * file descriptor for local socket
136
 */
137
evutil_socket_t socketfd;
138

    
139
/*
140
 * local socketID
141
 */
142
socket_ID local_socketID;
143

    
144
socketID_handle loc_socketID = &local_socketID;
145

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

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

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

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

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

    
200

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

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

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

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

    
226
        char h_pkt[MON_PKT_HEADER_SPACE];
227
        char h_data[MON_DATA_HEADER_SPACE];
228

    
229
        struct msg_header msg_h;
230

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

    
233
        iov[0].iov_base = &msg_h;
234
        iov[0].iov_len = MSG_HEADER_SIZE;
235

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

    
241

    
242
        iov[1].iov_len = iov[2].iov_len = 0;
243
        iov[1].iov_base = h_pkt;
244
        iov[2].iov_base = h_data;
245

    
246

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

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

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

    
264
                        memset(h_data, 0, MON_DATA_HEADER_SPACE);
265

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

    
278
                        (get_Send_data_inf_cb) ((void *) &sd_data_inf);
279
                }
280

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

    
287
                        iov[3].iov_len = pkt_len;
288
                        iov[3].iov_base = msg + offset;
289

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

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

    
299
                                memset(h_pkt,0,MON_PKT_HEADER_SPACE);
300

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

    
313
                                (get_Send_pkt_inf_cb) ((void *) &pkt_info);
314
                        }
315

    
316
                        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);
317
                        switch(sendPacket(socketfd, iov, 4, &udpgen.udpaddr)) {
318
                                case MSGLEN:
319
                                        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);
320
                                        // TODO: pmtu decremented here, but not in the "truncable" packet. That is currently resent without changing the claimed pmtu. Might need to be changed.
321
                                        connectbuf[con_id]->pmtusize = pmtu_decrement(connectbuf[con_id]->pmtusize);
322
                                        if (connectbuf[con_id]->pmtusize > 0) {
323
                                                connectbuf[con_id]->delay = true;
324
                                                retry = true;
325
                                        }
326
                                        offset = msg_len; // exit the while
327
                                        break;
328
                                case FAILURE:
329
                                        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);
330
                                        offset = msg_len; // exit the while
331
                                        break;
332
                                case OK:
333
                                        //update
334
                                        offset += pkt_len;
335
                                        //transmit data header only in the first packet
336
                                        iov[2].iov_len = 0;
337
                                        break;
338
                        }
339
                } while(offset != msg_len && !truncable);
340
        } while(retry);
341
}
342

    
343
void pmtu_timeout_cb(int fd, short event, void *arg);
344

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

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

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

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

    
373
        struct conn_msg *msg_header = (struct conn_msg*) connectbuf[con_id]->ctrl_msg_buf;
374

    
375
        msg_header->comand_type = command_type;
376
        msg_header->pmtu_size = connectbuf[con_id]->pmtusize;
377

    
378
        memcpy(&(msg_header->sock_id), loc_socketID, sizeof(socket_ID));
379

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

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

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

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

    
405
        time_t now = time(NULL);
406
        double timediff = 0.0;
407
        char str[1000];
408
        
409
        msgbuf += msg_h->len_mon_data_hdr;
410
        msg_size -= msg_h->len_mon_data_hdr;
411
        con_msg = (struct conn_msg *)msgbuf;
412
        
413
        // Monitoring layer hook
414
        if(get_Recv_data_inf_cb != NULL) {
415
                // update pointer to the real data
416
                mon_data_inf recv_data_inf;
417
                recv_data_inf.remote_socketID = &(con_msg->sock_id);
418
                recv_data_inf.buffer = msgbuf;
419
                recv_data_inf.bufSize = msg_size;
420
                recv_data_inf.msgtype = msg_h->msg_type;
421
                recv_data_inf.monitoringDataHeaderLen = msg_h->len_mon_data_hdr;
422
                recv_data_inf.monitoringDataHeader = msg_h->len_mon_data_hdr ? msgbuf : NULL;
423
                gettimeofday(&recv_data_inf.arrival_time, NULL);
424
                recv_data_inf.firstPacketArrived = true;
425
                recv_data_inf.recvFragments = 1;
426
                recv_data_inf.priority = false;
427
                recv_data_inf.padding = false;
428
                recv_data_inf.confirmation = false;
429
                recv_data_inf.reliable = false;
430

    
431
                // send data recv callback to monitoring module
432
                (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
433
        }
434

    
435
        //decode sock_id for debug messages
436
        mlSocketIDToString(&con_msg->sock_id,str,999);
437

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
613

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

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

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

    
645
                        // send data recv callback to monitoring module
646

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

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

    
653
                recv_params rParams;
654

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

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

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

    
678
// process a single recv data message
679
void recv_data_msg(struct msg_header *msg_h, char *msgbuf, int bufsize)
680
{
681
        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);
682

    
683
        int recv_id, free_recv_id = -1;
684

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

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

    
700

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

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

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

    
734

    
735
        // increment fragmentnr
736
        recvdatabuf[recv_id]->recvFragments++;
737
        // increment the arrivedBytes
738
        recvdatabuf[recv_id]->arrivedBytes += bufsize;
739

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

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

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

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

    
771
                                // send data recv callback to monitoring module
772

    
773
                                (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
774
                        }
775

    
776
                        // Get the right callback
777
                        receive_data_cb receive_data_callback = recvcbbuf[msg_h->msg_type];
778
                        if (receive_data_callback) {
779

    
780
                                recv_params rParams;
781

    
782
                                rParams.nrMissingBytes = recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->arrivedBytes;
783
                                rParams.recvFragments = recvdatabuf[recv_id]->recvFragments;
784
                                rParams.msgtype = recvdatabuf[recv_id]->msgtype;
785
                                rParams.connectionID = recvdatabuf[recv_id]->connectionID;
786
                                rParams.remote_socketID =
787
                                        &(connectbuf[recvdatabuf[recv_id]->connectionID]->external_socketID);
788

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

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

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

    
823
//done
824
void pmtu_timeout_cb(int fd, short event, void *arg)
825
{
826

    
827
        int con_id = (long) arg;
828
        pmtu new_pmtusize;
829

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

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

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

    
845
        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);
846

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

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

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

    
886
        //retry
887
        resend_conn_msg(con_id);
888
}
889

    
890

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

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

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

    
934
    char *msgbufptr = NULL;
935
    int msgtype;
936
    int connectionID;
937
    pmtu pmtusize;
938
    pmtu new_pmtusize;
939
    int dead = 0;
940

    
941
    // check the packettype
942
    msgbufptr = &msg[0];
943

    
944
    // check the msgtype
945
    msgbufptr = &msg[1];
946
    memcpy(&msgtype, msgbufptr, 4);
947

    
948
    if (msgtype == 0) {
949

    
950
        // get the connectionID
951
        msgbufptr = &msg[5];
952
        memcpy(&connectionID, msgbufptr, 4);
953

    
954
        int msgtype_c = connectbuf[connectionID]->status;
955
//        pmtusize = connectbuf[connectionID]->pmtutrysize;
956

    
957
        if (msgtype_c != msgtype) {
958
            dead = 1;
959
        }
960

    
961

    
962
    } else if (msgtype == 1) {
963

    
964
        // read the connectionID
965
        msgbufptr = &msg[9];
966
        memcpy(&connectionID, msgbufptr, 4);
967

    
968
        int msgtype_c = connectbuf[connectionID]->status;
969
//        pmtusize = connectbuf[connectionID]->pmtutrysize;
970

    
971
        if (msgtype_c != msgtype) {
972
            dead = 1;
973
        }
974

    
975
    }
976
    // decrement the pmtu size
977
    new_pmtusize = pmtu_decrement(pmtusize);
978

    
979
//    connectbuf[connectionID]->pmtutrysize = new_pmtusize;
980

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

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

    
993
    if (msgtype == 0 && dead != 1) {
994

    
995
        // stop the timeout event
996
        // timeout_del(connectbuf[connectionID]->timeout);
997
        /*
998
         * libevent2
999
         */
1000

    
1001
        // event_del(connectbuf[connectionID]->timeout);
1002

    
1003

    
1004
        // create and send a connection message
1005
//         create_conn_msg(new_pmtusize, connectionID,
1006
//                         &local_socketID, INVITE);
1007

    
1008
//        send_conn_msg(connectionID, new_pmtusize);
1009

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

    
1014
        // timeout_add(connectbuf[connectionID]->timeout,&connectbuf[connectionID]->timeout_value);
1015

    
1016
        /*
1017
         * libevent2
1018
         */
1019

    
1020
        struct event *ev;
1021
        ev = evtimer_new(base, pmtu_timeout_cb,
1022
                         (void *) connectbuf[connectionID]);
1023

    
1024
        // connectbuf[connectionID]->timeout = ev;
1025

    
1026
        event_add(ev, &connectbuf[connectionID]->timeout_value);
1027

    
1028
    } else if (msgtype == 1 && dead != 1) {
1029

    
1030
        // stop the timeout event
1031
        // timeout_del(connectbuf[connectionID]->timeout);
1032

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

    
1041

    
1042
//         // create and send a connection message
1043
//         create_conn_msg(new_pmtusize,
1044
//                         connectbuf[connectionID]->connectionID,
1045
//                         NULL, CONNECT);
1046

    
1047
        //send_conn_msg(connectionID, new_pmtusize);
1048

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

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

    
1063
    }
1064
}
1065

    
1066
/*
1067
 * what to do once a packet arrived if it is a conn packet send it to
1068
 * recv_conn handler if it is a data packet send it to the recv_data
1069
 * handler
1070
 */
1071

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

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

    
1085
        recvPacket(fd, msgbuf, &recvSize, &recv_addr, pmtu_error_cb_th, &ttl);
1086

    
1087

    
1088
        // check if it is not just an ERROR message
1089
        if(recvSize < 0)
1090
                return;
1091

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

    
1101
        msg_h = (struct msg_header *) msgbuf;
1102
        bufptr += MSG_HEADER_SIZE + msg_h->len_mon_packet_hdr;
1103
        msg_size = recvSize - MSG_HEADER_SIZE - msg_h->len_mon_packet_hdr;
1104

    
1105

    
1106
        if(get_Recv_pkt_inf_cb != NULL) {
1107
                mon_pkt_inf msginfNow;
1108
                msginfNow.monitoringHeaderLen = msg_h->len_mon_packet_hdr;
1109
                msginfNow.monitoringHeader = msg_h->len_mon_packet_hdr ? &msgbuf[0] + MSG_HEADER_SIZE : NULL;
1110
                //TODO rethink this ...
1111
                if(msg_h->msg_type == ML_CON_MSG) {
1112
                        struct conn_msg *c_msg = (struct conn_msg *) bufptr;
1113
                        msginfNow.remote_socketID = &(c_msg->sock_id);
1114
                }
1115
                else if(connectbuf[msg_h->remote_con_id] == NULL) {
1116
                        error("ML: received pkg called with non existent connection\n");
1117
                        return;
1118
                } else
1119
                        msginfNow.remote_socketID = &(connectbuf[msg_h->remote_con_id]->external_socketID);
1120
                msginfNow.buffer = bufptr;
1121
                msginfNow.bufSize = recvSize;
1122
                msginfNow.msgtype = msg_h->msg_type;
1123
                msginfNow.ttl = ttl;
1124
                msginfNow.dataID = msg_h->msg_seq_num;
1125
                msginfNow.offset = msg_h->offset;
1126
                msginfNow.datasize = msg_h->msg_length;
1127
                gettimeofday(&msginfNow.arrival_time, NULL);
1128
                (get_Recv_pkt_inf_cb) ((void *) &msginfNow);
1129
        }
1130

    
1131

    
1132
        switch(msg_h->msg_type) {
1133
                case ML_CON_MSG:
1134
                        debug("ML: received conn pkg\n");
1135
                        recv_conn_msg(msg_h, bufptr, msg_size);
1136
                        break;
1137
                default:
1138
                        if(msg_h->msg_type < 127) {
1139
                                debug("ML: received data pkg\n");
1140
                                recv_data_msg(msg_h, bufptr, msg_size);
1141
                                break;
1142
                        }
1143
                        debug("ML: unrecognised msg_type\n");
1144
                        break;
1145
        }
1146
}
1147

    
1148
/*
1149
 * compare the external IP address of two socketIDs
1150
 */
1151
int
1152
compare_external_address_socketIDs(socketID_handle sock1, socketID_handle sock2)
1153
{
1154
        if( sock1->external_addr.udpaddr.sin_addr.s_addr == sock2->external_addr.udpaddr.sin_addr.s_addr)
1155
                return 0;
1156
        return 1;
1157
}
1158

    
1159
void try_stun();
1160

    
1161
/*
1162
 * the timeout of the NAT traversal
1163
 */
1164
void nat_traversal_timeout(int fd, short event, void *arg)
1165
{
1166
        if (NAT_traversal == false) {
1167
                debug("ML: NAT traversal request re-send\n");
1168
                if(receive_SocketID_cb)
1169
                        (receive_SocketID_cb) (&local_socketID, 2);
1170
                try_stun();
1171
        }
1172
}
1173

    
1174
//return IP address, or INADDR_NONE if can't resolve
1175
unsigned long resolve(const char *ipaddr)
1176
{
1177
        struct hostent *h = gethostbyname(ipaddr);
1178
        if (!h) {
1179
                error("ML: Unable to resolve host name %s\n", ipaddr);
1180
                return INADDR_NONE;
1181
        }
1182
        unsigned long *addr = (unsigned long *) (h->h_addr);
1183
        return *addr;
1184
}
1185

    
1186

    
1187
/*
1188
 * returns the file descriptor, or <0 on error. The ipaddr can be a null
1189
 * pointer. Then all available ipaddr on the machine are choosen.
1190
 */
1191
int create_socket(const int port, const char *ipaddr)
1192
{
1193
        struct sockaddr_in udpaddr = {0};
1194
        udpaddr.sin_family = AF_INET;
1195
        if (ipaddr == NULL) {
1196
                /*
1197
                * try to guess the local IP address
1198
                */
1199
                const char *ipaddr_iface = mlAutodetectIPAddress();
1200
                if (ipaddr_iface) {
1201
                        udpaddr.sin_addr.s_addr = inet_addr(ipaddr_iface);
1202
                } else {
1203
                        udpaddr.sin_addr.s_addr = INADDR_ANY;
1204
                }
1205
        } else {
1206
                udpaddr.sin_addr.s_addr = inet_addr(ipaddr);
1207
        }
1208
        udpaddr.sin_port = htons(port);
1209

    
1210
        socketaddrgen udpgen;
1211
        memset(&udpgen,0,sizeof(socketaddrgen));        //this will be sent over the net, so set it to 0
1212
        udpgen.udpaddr = udpaddr;
1213
        local_socketID.internal_addr = udpgen;
1214

    
1215
        socketfd = createSocket(port, ipaddr);
1216
        if (socketfd < 0){
1217
                return socketfd;
1218
        }
1219

    
1220
        struct event *ev;
1221
        ev = event_new(base, socketfd, EV_READ | EV_PERSIST, recv_pkg, NULL);
1222

    
1223
        event_add(ev, NULL);
1224

    
1225
        try_stun();
1226

    
1227
        return socketfd;
1228
}
1229

    
1230
/*
1231
 * try to figure out external IP using STUN, if defined
1232
 */
1233
void try_stun()
1234
{
1235
        if (isStunDefined()) {
1236
                /*
1237
                * send the NAT traversal STUN request
1238
                */
1239
                 send_stun_request(socketfd, &stun_server);
1240

    
1241
                /*
1242
                * enter a NAT traversal timeout that takes care of retransmission
1243
                */
1244
                struct event *ev1;
1245
                struct timeval timeout_value_NAT_traversal = NAT_TRAVERSAL_TIMEOUT;
1246
                ev1 = evtimer_new(base, nat_traversal_timeout, NULL);
1247
                event_add(ev1, &timeout_value_NAT_traversal);
1248

    
1249
                NAT_traversal = false;
1250
        } else {
1251
                /*
1252
                * Assume we have accessibility and copy internal address to external one
1253
                */
1254
                local_socketID.external_addr = local_socketID.internal_addr;
1255
                NAT_traversal = true; // @TODO: this is not really NAT traversal, but a flag that init is over
1256
                // callback to the upper layer indicating that the socketID is now
1257
                // ready to use
1258
                if(receive_SocketID_cb)
1259
                        (receive_SocketID_cb) (&local_socketID, 0); //success
1260
        }
1261
}
1262

    
1263
/**************************** END OF INTERNAL ***********************/
1264

    
1265
/**************************** MONL functions *************************/
1266

    
1267
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){
1268

    
1269
        base = (struct event_base *) arg;
1270
        recv_data_callback = recv_data_cb;
1271
        mlSetRecvTimeout(timeout_value);
1272
        if (stun_ipaddr) {
1273
                 mlSetStunServer(stun_port, stun_ipaddr);
1274
        } else {
1275

    
1276
        }
1277
        register_recv_localsocketID_cb(local_socketID_cb);
1278
        return create_socket(port, ipaddr);
1279
}
1280

    
1281
/* register callbacks  */
1282
void mlRegisterGetRecvPktInf(get_recv_pkt_inf_cb recv_pkt_inf_cb){
1283

    
1284
        if (recv_pkt_inf_cb == NULL)
1285
                error("ML: Register get_recv_pkt_inf_cb failed: NULL ptr  \n");
1286
        else
1287
                get_Recv_pkt_inf_cb = recv_pkt_inf_cb;
1288

    
1289
}
1290

    
1291
void mlRegisterGetSendPktInf(get_send_pkt_inf_cb  send_pkt_inf_cb){
1292

    
1293
        if (send_pkt_inf_cb == NULL)
1294
                error("ML: Register get_send_pkt_inf_cb: NULL ptr  \n");
1295
        else
1296
                get_Send_pkt_inf_cb = send_pkt_inf_cb;
1297

    
1298
}
1299

    
1300

    
1301
void mlRegisterSetMonitoringHeaderPktCb(set_monitoring_header_pkt_cb monitoring_header_pkt_cb ){
1302

    
1303
        if (monitoring_header_pkt_cb == NULL)
1304
                error("ML: Register set_monitoring_header_pkt_cb: NULL ptr  \n");
1305
        else
1306
                set_Monitoring_header_pkt_cb = monitoring_header_pkt_cb;
1307

    
1308
}
1309

    
1310
void mlRegisterGetRecvDataInf(get_recv_data_inf_cb recv_data_inf_cb){
1311

    
1312
        if (recv_data_inf_cb == NULL)
1313
                error("ML: Register get_recv_data_inf_cb: NULL ptr  \n");
1314
        else
1315
                get_Recv_data_inf_cb = recv_data_inf_cb;
1316

    
1317
}
1318

    
1319
void mlRegisterGetSendDataInf(get_send_data_inf_cb  send_data_inf_cb){
1320

    
1321
        if (send_data_inf_cb == NULL)
1322
                error("ML: Register get_send_data_inf_cb: NULL ptr  \n");
1323
        else
1324
                get_Send_data_inf_cb = send_data_inf_cb;
1325

    
1326
}
1327

    
1328
void mlRegisterSetMonitoringHeaderDataCb(set_monitoring_header_data_cb monitoring_header_data_cb){
1329

    
1330
        if (monitoring_header_data_cb == NULL)
1331
                error("ML: Register set_monitoring_header_data_cb : NULL ptr  \n");
1332
        else
1333
        set_Monitoring_header_data_cb = monitoring_header_data_cb;
1334

    
1335
}
1336

    
1337
void mlSetRecvTimeout(struct timeval timeout_value){
1338

    
1339
        recv_timeout = timeout_value;
1340

    
1341
}
1342

    
1343
int mlGetStandardTTL(socketID_handle socketID,uint8_t *ttl){
1344

    
1345
        return getTTL(socketfd, ttl);
1346

    
1347
}
1348

    
1349
socketID_handle mlGetLocalSocketID(int *errorstatus){
1350

    
1351
        if (NAT_traversal == false) {
1352
                *errorstatus = 2;
1353
                return NULL;
1354
        }
1355

    
1356
        *errorstatus = 0;
1357
        return &local_socketID;
1358

    
1359
}
1360

    
1361

    
1362
/**************************** END of MONL functions *************************/
1363

    
1364
/**************************** GENERAL functions *************************/
1365

    
1366
void mlRegisterRecvConnectionCb(receive_connection_cb recv_conn_cb){
1367

    
1368
        if (recv_conn_cb == NULL)
1369
                error("ML: Register receive_connection_cb: NULL ptr  \n");
1370
        else
1371
                receive_Connection_cb = recv_conn_cb;
1372

    
1373
}
1374

    
1375
void mlRegisterErrorConnectionCb(connection_failed_cb conn_failed){
1376

    
1377
        if (conn_failed == NULL)
1378
                error("ML: Register connection_failed_cb: NULL ptr  \n");
1379
        else
1380
        failed_Connection_cb = conn_failed;
1381

    
1382
}
1383

    
1384
void mlRegisterRecvDataCb(receive_data_cb data_cb,unsigned char msgtype){
1385

    
1386
    if (msgtype > 126) {
1387

    
1388
            error
1389
            ("ML: Could not register recv_data callback. Msgtype is greater then 126 \n");
1390

    
1391
    }
1392

    
1393
    if (data_cb == NULL) {
1394

    
1395
            error("ML: Register receive data callback: NUll ptr \n ");
1396

    
1397
    } else {
1398

    
1399
        recvcbbuf[msgtype] = data_cb;
1400

    
1401
    }
1402

    
1403
}
1404

    
1405
void mlCloseSocket(socketID_handle socketID){
1406

    
1407
        free(socketID);
1408

    
1409
}
1410

    
1411
void keepalive_fn(evutil_socket_t fd, short what, void *arg) {
1412
        socketID_handle peer = arg;
1413

    
1414
        int con_id = mlConnectionExist(peer, false);
1415
        if (con_id < 0 || connectbuf[con_id]->defaultSendParams.keepalive <= 0) {
1416
                /* Connection fell from under us or keepalive was disabled */
1417
                free(arg);
1418
                return;
1419
        }
1420

    
1421
        /* do what we gotta do */
1422
        if ( connectbuf[con_id]->status == READY) {
1423
                char keepaliveMsg[32] = "";
1424
                sprintf(keepaliveMsg, "KEEPALIVE %d", connectbuf[con_id]->keepalive_seq++);
1425
                send_msg(con_id, MSG_TYPE_ML_KEEPALIVE, keepaliveMsg, 1 + strlen(keepaliveMsg), false, 
1426
                        &(connectbuf[con_id]->defaultSendParams));
1427
        }
1428

    
1429
        /* re-schedule */
1430
        struct timeval t = { 0,0 };
1431
        t.tv_sec = connectbuf[con_id]->defaultSendParams.keepalive;
1432
        if (connectbuf[con_id]->defaultSendParams.keepalive) 
1433
                event_base_once(base, -1, EV_TIMEOUT, keepalive_fn, peer, &t);
1434
}
1435

    
1436
void setupKeepalive(int conn_id) {
1437
        /* Save the peer's address for us */
1438
        socketID_handle peer = malloc(sizeof(socket_ID));
1439
        memcpy(peer, &connectbuf[conn_id]->external_socketID, sizeof(socket_ID));
1440

    
1441
        struct timeval t = { 0,0 };
1442
        t.tv_sec = connectbuf[conn_id]->defaultSendParams.keepalive;
1443

    
1444
        if (connectbuf[conn_id]->defaultSendParams.keepalive) 
1445
                event_base_once(base, -1, EV_TIMEOUT, keepalive_fn, peer, &t);
1446
}
1447

    
1448
/* connection functions */
1449
int mlOpenConnection(socketID_handle external_socketID,receive_connection_cb connection_cb,void *arg, const send_params defaultSendParams){
1450

    
1451
        int con_id;
1452
        if (external_socketID == NULL) {
1453
                error("ML: cannot open connection: one of the socketIDs is NULL\n");
1454
                return -1;
1455
        }
1456
        if (NAT_traversal == false) {
1457
                error("ML: cannot open connection: NAT traversal for socketID still in progress\n");
1458
                return -1;
1459
        }
1460
        if (connection_cb == NULL) {
1461
                error("ML: cannot open connection: connection_cb is NULL\n");
1462
                return -1;
1463
        }
1464

    
1465
        // check if that connection already exist
1466

    
1467
        con_id = mlConnectionExist(external_socketID, false);
1468
        if (con_id >= 0) {
1469
                // overwrite defaultSendParams
1470
                bool newKeepalive = 
1471
                        connectbuf[con_id]->defaultSendParams.keepalive == 0 && defaultSendParams.keepalive != 0;
1472
                connectbuf[con_id]->defaultSendParams = defaultSendParams;
1473
                if (newKeepalive) setupKeepalive(con_id);
1474
                // if so check if it is ready to use
1475
                if (connectbuf[con_id]->status == READY) {
1476
                                // if so use the callback immediately
1477
                                (connection_cb) (con_id, arg);
1478

    
1479
                // otherwise just write the connection cb and the arg pointer
1480
                // into the connection struct
1481
                } else {
1482
                        struct receive_connection_cb_list *temp;
1483
                        temp = malloc(sizeof(struct receive_connection_cb_list));
1484
                        temp->next = NULL;
1485
                        temp->connection_cb = connection_cb;
1486
                        temp->arg = arg;
1487
                        if(connectbuf[con_id]->connection_last != NULL) {
1488
                                connectbuf[con_id]->connection_last->next = temp;
1489
                                connectbuf[con_id]->connection_last = temp;
1490
                        } else
1491
                                connectbuf[con_id]->connection_last = connectbuf[con_id]->connection_head = temp;
1492
                }
1493
                return con_id;
1494
        }
1495
        // make entry in connection_establishment array
1496
        for (con_id = 0; con_id < CONNECTBUFSIZE; con_id++) {
1497
                if (connectbuf[con_id] == NULL) {
1498
                        connectbuf[con_id] = (connect_data *) malloc(sizeof(connect_data));
1499
                        memset(connectbuf[con_id],0,sizeof(connect_data));
1500
                        connectbuf[con_id]->starttime = time(NULL);
1501
                        memcpy(&connectbuf[con_id]->external_socketID, external_socketID, sizeof(socket_ID));
1502
                        connectbuf[con_id]->pmtusize = DSLSLIM;
1503
                        connectbuf[con_id]->timeout_event = NULL;
1504
                        connectbuf[con_id]->status = INVITE;
1505
                        connectbuf[con_id]->seqnr = 0;
1506
                        connectbuf[con_id]->internal_connect = !compare_external_address_socketIDs(external_socketID, &local_socketID);
1507
                        connectbuf[con_id]->connectionID = con_id;
1508

    
1509
                        connectbuf[con_id]->connection_head = connectbuf[con_id]->connection_last = malloc(sizeof(struct receive_connection_cb_list));
1510
                        connectbuf[con_id]->connection_last->next = NULL;
1511
                        connectbuf[con_id]->connection_last->connection_cb = connection_cb;
1512
                        connectbuf[con_id]->connection_last->arg = arg;
1513
                        connectbuf[con_id]->external_connectionID = -1;
1514

    
1515
                        connectbuf[con_id]->defaultSendParams = defaultSendParams;
1516
                        if (defaultSendParams.keepalive) setupKeepalive(con_id);
1517
                        break;
1518
                }
1519
        } //end of for
1520

    
1521
        if (con_id == CONNECTBUFSIZE) {
1522
                error("ML: Could not open connection: connection buffer full\n");
1523
                return -1;
1524
        }
1525

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

    
1530
        return con_id;
1531

    
1532
}
1533

    
1534
void mlCloseConnection(const int connectionID){
1535

    
1536
        // remove it from the connection array
1537
        if(connectbuf[connectionID]) {
1538
                if(connectbuf[connectionID]->ctrl_msg_buf) {
1539
                        free(connectbuf[connectionID]->ctrl_msg_buf);
1540
                }
1541
                // remove related events
1542
                if (connectbuf[connectionID]->timeout_event) {
1543
                        event_del(connectbuf[connectionID]->timeout_event);
1544
                        event_free(connectbuf[connectionID]->timeout_event);
1545
                        connectbuf[connectionID]->timeout_event = NULL;
1546
                }
1547
                free(connectbuf[connectionID]);
1548
                connectbuf[connectionID] = NULL;
1549
        }
1550

    
1551
}
1552

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

    
1555
        if (connectionID < 0) {
1556
                error("ML: send data failed: connectionID does not exist\n");
1557
                return;
1558
        }
1559

    
1560
        if (connectbuf[connectionID] == NULL) {
1561
                error("ML: send data failed: connectionID does not exist\n");
1562
                return;
1563
        }
1564
        if (connectbuf[connectionID]->status != READY) {
1565
            error("ML: send data failed: connection is not active\n");
1566
            return;
1567
        }
1568

    
1569
        if (sParams == NULL) {
1570
                sParams = &(connectbuf[connectionID]->defaultSendParams);
1571
        }
1572

    
1573
        send_msg(connectionID, msgtype, sendbuf, bufsize, false, sParams);
1574

    
1575
}
1576

    
1577
/* transmit data functions  */
1578
int mlSendAllData(const int connectionID,send_all_data_container *container,int nr_entries,unsigned char msgtype,send_params *sParams){
1579

    
1580
    if (nr_entries < 1 || nr_entries > 5) {
1581

    
1582
        error
1583
            ("ML : sendALlData : nr_enties is not between 1 and 5 \n ");
1584
        return 0;
1585

    
1586
    } else {
1587

    
1588
        if (nr_entries == 1) {
1589

    
1590
                mlSendData(connectionID, container->buffer_1,
1591
                      container->length_1, msgtype, sParams);
1592

    
1593
            return 1;
1594

    
1595
        } else if (nr_entries == 2) {
1596

    
1597
            int buflen = container->length_1 + container->length_2;
1598
            char buf[buflen];
1599
            memcpy(buf, container->buffer_1, container->length_1);
1600
            memcpy(&buf[container->length_1], container->buffer_2,
1601
                   container->length_2);
1602
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1603

    
1604
            return 1;
1605

    
1606
        } else if (nr_entries == 3) {
1607

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

    
1619

    
1620
            return 1;
1621

    
1622
        } else if (nr_entries == 4) {
1623

    
1624
            int buflen =
1625
                container->length_1 + container->length_2 +
1626
                container->length_3 + container->length_4;
1627
            char buf[buflen];
1628
            memcpy(buf, container->buffer_1, container->length_1);
1629
            memcpy(&buf[container->length_1], container->buffer_2,
1630
                   container->length_2);
1631
            memcpy(&buf[container->length_2], container->buffer_3,
1632
                   container->length_3);
1633
            memcpy(&buf[container->length_3], container->buffer_4,
1634
                   container->length_4);
1635
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1636

    
1637
            return 1;
1638

    
1639
        } else {
1640

    
1641
            int buflen =
1642
                container->length_1 + container->length_2 +
1643
                container->length_3 + container->length_4 +
1644
                container->length_5;
1645
            char buf[buflen];
1646
            memcpy(buf, container->buffer_1, container->length_1);
1647
            memcpy(&buf[container->length_1], container->buffer_2,
1648
                   container->length_2);
1649
            memcpy(&buf[container->length_2], container->buffer_3,
1650
                   container->length_3);
1651
            memcpy(&buf[container->length_3], container->buffer_4,
1652
                   container->length_4);
1653
            memcpy(&buf[container->length_4], container->buffer_5,
1654
                   container->length_5);
1655
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1656

    
1657
            return 1;
1658
        }
1659

    
1660
    }
1661

    
1662
}
1663

    
1664
int mlRecvData(const int connectionID,char *recvbuf,int *bufsize,recv_params *rParams){
1665

    
1666
        //TODO yet to be converted
1667
        return 0;
1668
#if 0
1669
        if (rParams == NULL) {
1670
                error("ML: recv_data failed: recv_params is a NULL ptr\n");
1671
                return 0;
1672
    } else {
1673

1674
        info("ML: recv data called \n");
1675

1676
        int i = 0;
1677
        int returnValue = 0;
1678
        double timeout = (double) recv_timeout.tv_sec;
1679
        time_t endtime = time(NULL);
1680

1681
        for (i = 0; i < RECVDATABUFSIZE; i++) {
1682

1683
            if (recvdatabuf[i] != NULL) {
1684

1685
                if (recvdatabuf[i]->connectionID == connectionID) {
1686

1687
                    info("ML: recv data has entry  \n");
1688

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

1691
                    // check if the specified connection has data and it
1692
                    // is complete
1693
                    // check the data seqnr
1694
                    // if(connectionID == recvdatabuf[i]->connectionID &&
1695
                    // 1 == recvdatabuf[i]->status){
1696

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

1699
                        // info("transmissionHandler: recv_data set is
1700
                        // complete \n" );
1701

1702
                        // debug("debud \n");
1703

1704
                        // exchange the pointers
1705
                        int buffersize = 0;
1706
                        buffersize = recvdatabuf[i]->bufsize;
1707
                        *bufsize = buffersize;
1708
                        // recvbuf = recvdatabuf[i]->recvbuf;
1709

1710
                        // info("buffersize %d \n",buffersize);
1711
                        memcpy(recvbuf, recvdatabuf[i]->recvbuf,
1712
                               buffersize);
1713
                        // debug(" recvbuf %s \n",recvbuf );
1714

1715
//                         double nrMissFrags =
1716
//                             (double) recvdatabuf[i]->nrFragments /
1717
//                             (double) recvdatabuf[i]->recvFragments;
1718
//                         int nrMissingFragments = (int) ceil(nrMissFrags);
1719

1720
//                        rParams->nrMissingFragments = nrMissingFragments;
1721
//                         rParams->nrFragments = recvdatabuf[i]->nrFragments;
1722
                        rParams->msgtype = recvdatabuf[i]->msgtype;
1723
                        rParams->connectionID =
1724
                            recvdatabuf[i]->connectionID;
1725

1726
                        // break from the loop
1727
                        // debug(" recvbuf %s \n ",recvbuf);
1728

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

1735
                        if(get_Recv_data_inf_cb != NULL) {
1736
                                mon_data_inf recv_data_inf;
1737

1738
                                recv_data_inf.remote_socketID = &(connectbuf[connectionID]->external_socketID);
1739
                                recv_data_inf.buffer = recvdatabuf[i]->recvbuf;
1740
                                recv_data_inf.bufSize = recvdatabuf[i]->bufsize;
1741
                                recv_data_inf.msgtype = recvdatabuf[i]->msgtype;
1742
//                                 recv_data_inf.monitoringHeaderType = recvdatabuf[i]->monitoringHeaderType;
1743
//                                 recv_data_inf.monitoringDataHeader = recvdatabuf[i]->monitoringDataHeader;
1744
                                gettimeofday(&recv_data_inf.arrival_time, NULL);
1745
                                recv_data_inf.firstPacketArrived = recvdatabuf[i]->firstPacketArrived;
1746
                                recv_data_inf.nrMissingFragments = nrMissingFragments;
1747
                                recv_data_inf.nrFragments = recvdatabuf[i]->nrFragments;
1748
                                recv_data_inf.priority = false;
1749
                                recv_data_inf.padding = false;
1750
                                recv_data_inf.confirmation = false;
1751
                                recv_data_inf.reliable = false;
1752

1753
                                // send data recv callback to monitoring module
1754

1755
                                (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
1756
                        }
1757

1758

1759
                        // free the allocated memory
1760
                        free(recvdatabuf[i]);
1761
                        recvdatabuf[i] = NULL;
1762

1763
                        returnValue = 1;
1764
                        break;
1765

1766
                    }
1767

1768
                    if (recvdatabuf[i] != NULL) {
1769

1770
                        if (timepass > timeout) {
1771

1772
                            info("ML: recv_data timeout called  \n");
1773

1774
                            // some data about the missing chunks should
1775
                            // be added here
1776
                            // exchange the pointers
1777
                            int buffersize = 0;
1778
                            buffersize = recvdatabuf[i]->bufsize;
1779
                            *bufsize = buffersize;
1780
                            // recvbuf = recvdatabuf[i]->recvbuf;
1781

1782
                            double nrMissFrags =
1783
                                (double) recvdatabuf[i]->nrFragments /
1784
                                (double) recvdatabuf[i]->recvFragments;
1785
                            int nrMissingFragments =
1786
                                (int) ceil(nrMissFrags);
1787

1788
                            // debug(" recvbuf %s \n",recvbuf );
1789

1790
                            memcpy(recvbuf, recvdatabuf[i]->recvbuf,
1791
                                   buffersize);
1792

1793
                            rParams->nrMissingFragments =
1794
                                nrMissingFragments;
1795
                            rParams->nrFragments =
1796
                                recvdatabuf[i]->nrFragments;
1797
                            rParams->msgtype = recvdatabuf[i]->msgtype;
1798
                            rParams->connectionID =
1799
                                recvdatabuf[i]->connectionID;
1800

1801
                                if(get_Recv_data_inf_cb != NULL) {
1802
                                        mon_data_inf recv_data_inf;
1803

1804
                                        recv_data_inf.remote_socketID = &(connectbuf[connectionID]->external_socketID);
1805
                                        recv_data_inf.buffer = recvdatabuf[i]->recvbuf;
1806
                                        recv_data_inf.bufSize = recvdatabuf[i]->bufsize;
1807
                                        recv_data_inf.msgtype = recvdatabuf[i]->msgtype;
1808
                                        recv_data_inf.monitoringHeaderType = recvdatabuf[i]->monitoringHeaderType;
1809
                                        recv_data_inf.monitoringDataHeader = recvdatabuf[i]->monitoringDataHeader;
1810
                                        gettimeofday(&recv_data_inf.arrival_time, NULL);
1811
                                        recv_data_inf.firstPacketArrived = recvdatabuf[i]->firstPacketArrived;
1812
                                        recv_data_inf.nrMissingFragments = nrMissingFragments;
1813
                                        recv_data_inf.nrFragments = recvdatabuf[i]->nrFragments;
1814
                                        recv_data_inf.priority = false;
1815
                                        recv_data_inf.padding = false;
1816
                                        recv_data_inf.confirmation = false;
1817
                                        recv_data_inf.reliable = false;
1818

1819
                                        // send data recv callback to monitoring module
1820

1821
                                        (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
1822
                                }
1823

1824
                            // free the allocated memory
1825
                            free(recvdatabuf[i]);
1826
                            recvdatabuf[i] = NULL;
1827

1828
                            returnValue = 1;
1829
                            break;
1830

1831
                        }
1832
                    }
1833

1834
                }
1835

1836
            }
1837
            // debug("2 recvbuf %s \n ",recvbuf);
1838
        }
1839
        return returnValue;
1840
    }
1841
#endif
1842

    
1843
}
1844

    
1845
int mlSocketIDToString(socketID_handle socketID,char* socketID_string, size_t len){
1846

    
1847
        char internal_addr[INET_ADDRSTRLEN];
1848
        char external_addr[INET_ADDRSTRLEN];
1849
        inet_ntop(AF_INET, &(socketID->internal_addr.udpaddr.sin_addr.s_addr), internal_addr, INET_ADDRSTRLEN);
1850
        inet_ntop(AF_INET, &(socketID->external_addr.udpaddr.sin_addr.s_addr), external_addr, INET_ADDRSTRLEN);
1851

    
1852
        snprintf(socketID_string,len,"%s:%d-%s:%d", internal_addr, ntohs(socketID->internal_addr.udpaddr.sin_port),
1853
                external_addr,        ntohs(socketID->external_addr.udpaddr.sin_port));
1854
        return 0;
1855

    
1856
}
1857

    
1858
int mlStringToSocketID(const char* socketID_string, socketID_handle socketID){
1859

    
1860
        //@TODO add checks against malformed string
1861
        char external_addr[INET_ADDRSTRLEN];
1862
        int external_port;
1863
        char internal_addr[INET_ADDRSTRLEN];
1864
        int internal_port;
1865

    
1866
        char *pch;
1867
        char *s = strdup(socketID_string);
1868

    
1869
        //replace ':' with a blank
1870
        pch=strchr(s,':');
1871
        while (pch!=NULL){
1872
                                *pch = ' ';
1873
                pch=strchr(pch+1,':');
1874
        }
1875
        pch=strchr(s,'-');
1876
        if(pch) *pch = ' ';
1877

    
1878
        sscanf(s,"%s %d %s %d", internal_addr, &internal_port,
1879
                external_addr, &external_port);
1880

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

    
1884
        if(inet_pton(AF_INET, internal_addr, &(socketID->internal_addr.udpaddr.sin_addr)) == 0)
1885
                return EINVAL;
1886
        socketID->internal_addr.udpaddr.sin_family = AF_INET;
1887
        socketID->internal_addr.udpaddr.sin_port = htons(internal_port);
1888

    
1889

    
1890
        if(inet_pton(AF_INET, external_addr, &(socketID->external_addr.udpaddr.sin_addr)) ==0)
1891
                return EINVAL;
1892
        socketID->external_addr.udpaddr.sin_family = AF_INET;
1893
        socketID->external_addr.udpaddr.sin_port = htons(external_port);
1894

    
1895
        free(s);
1896
        return 0;
1897

    
1898
}
1899

    
1900
int mlGetConnectionStatus(int connectionID){
1901

    
1902
        if(connectbuf[connectionID])
1903
                return connectbuf[connectionID]->status == READY;
1904
        return -1;
1905
    
1906
}
1907

    
1908

    
1909
int mlConnectionExist(socketID_handle socketID, bool ready){
1910

    
1911
    /*
1912
     * check if another connection for the external connectionID exist
1913
     * that was established \ within the last 2 seconds
1914
     */
1915
        int i;
1916
        for (i = 0; i < CONNECTBUFSIZE; i++)
1917
                if (connectbuf[i] != NULL)
1918
                        if (mlCompareSocketIDs(&(connectbuf[i]->external_socketID), socketID) == 0) {
1919
                                if (ready) return (connectbuf[i]->status == READY ? i : -1);;
1920
                                return i;
1921
                                }
1922

    
1923
    return -1;
1924

    
1925
}
1926

    
1927
//Added by Robert Birke as comodity functions
1928

    
1929
//int mlPrintSocketID(socketID_handle socketID) {
1930
//        char str[SOCKETID_STRING_SIZE];
1931
//        mlSocketIDToString(socketID, str, sizeof(str));
1932
//        printf(stderr,"int->%s<-ext\n",str);
1933
//}
1934

    
1935
/*
1936
 * hash code of a socketID
1937
 * TODO might think of a better way
1938
 */
1939
int mlHashSocketID(socketID_handle sock) {
1940
    return sock->internal_addr.udpaddr.sin_port +
1941
                          sock->external_addr.udpaddr.sin_port;
1942
}
1943

    
1944
int mlCompareSocketIDs(socketID_handle sock1, socketID_handle sock2) {
1945
        /*
1946
        * compare internal addr
1947
        */
1948
        if (sock1->internal_addr.udpaddr.sin_addr.s_addr !=
1949
            sock2->internal_addr.udpaddr.sin_addr.s_addr)
1950
                        return 1;
1951

    
1952
        if (sock1->internal_addr.udpaddr.sin_port !=
1953
                 sock2->internal_addr.udpaddr.sin_port)
1954
                        return 1;
1955

    
1956
        /*
1957
        * compare external addr
1958
        */
1959
        if (sock1->external_addr.udpaddr.sin_addr.s_addr !=
1960
            sock2->external_addr.udpaddr.sin_addr.s_addr)
1961
                        return 1;
1962

    
1963
        if (sock1->external_addr.udpaddr.sin_port !=
1964
                 sock2->external_addr.udpaddr.sin_port)
1965
                        return 1;
1966

    
1967
        return 0;
1968
}
1969

    
1970
int mlCompareSocketIDsByPort(socketID_handle sock1, socketID_handle sock2)
1971
{ 
1972
        if (sock1->internal_addr.udpaddr.sin_port !=
1973
                 sock2->internal_addr.udpaddr.sin_port)
1974
                        return 1;
1975

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

    
1982
int mlGetPathMTU(int ConnectionId) {
1983
        if(ConnectionId < 0 || ConnectionId >= CONNECTBUFSIZE)
1984
                return -1;
1985
        if (connectbuf[ConnectionId] != NULL)
1986
                return connectbuf[ConnectionId]->pmtusize;
1987
        return -1;
1988
}
1989

    
1990
/**************************** END of GENERAL functions *************************/
1991

    
1992
/**************************** NAT functions *************************/
1993

    
1994
/* setter  */
1995
void mlSetStunServer(const int port,const char *ipaddr){
1996

    
1997
        stun_server.sin_family = AF_INET;
1998
        if (ipaddr == NULL)
1999
                stun_server.sin_addr.s_addr = htonl(INADDR_NONE);
2000
        else
2001
                stun_server.sin_addr.s_addr = resolve(ipaddr);
2002
        stun_server.sin_port = htons(port);
2003

    
2004
}
2005

    
2006
int mlGetExternalIP(char* external_addr){
2007

    
2008
        socketaddrgen udpgen;
2009
        struct sockaddr_in udpaddr;
2010

    
2011
        udpgen = local_socketID.external_addr;
2012
        udpaddr = udpgen.udpaddr;
2013

    
2014
        inet_ntop(AF_INET, &(udpaddr.sin_addr), external_addr,
2015
                        INET_ADDRSTRLEN);
2016

    
2017
        if (external_addr == NULL) {
2018

    
2019
        return -1;
2020

    
2021
        } else {
2022

    
2023
        return 0;
2024

    
2025
        }
2026

    
2027
}
2028

    
2029
/**************************** END of NAT functions *************************/