Statistics
| Branch: | Revision:

ml / ml.c @ 9f95713e

History | View | Annotate | Download (57.5 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
void register_recv_localsocketID_cb(receive_localsocketID_cb local_socketID_cb)
183
{
184
        if (local_socketID_cb == NULL)
185
                error("ML : Register receive_localsocketID_cb: NULL ptr \n");
186
        else
187
        receive_SocketID_cb = local_socketID_cb;
188
}
189

    
190

    
191
//void keep_connection_alive(const int connectionID)
192
//{
193
//
194
//    // to be done with the NAT traversal
195
//    // send a message over the wire
196
//    printf("\n");
197
//
198
//}
199

    
200
void unsetStunServer()
201
{
202
        stun_server.sin_addr.s_addr = 0;
203
}
204

    
205
bool isStunDefined()
206
{
207
        return stun_server.sin_addr.s_addr;
208
}
209

    
210
void send_msg(int con_id, int msg_type, char* msg, int msg_len, bool truncable, send_params * sParams) {
211
        socketaddrgen udpgen;
212
        bool retry;
213
        int pkt_len, offset;
214
        struct iovec iov[4];
215

    
216
        char h_pkt[MON_HEADER_SPACE];
217
        char h_data[MON_HEADER_SPACE];
218

    
219
        struct msg_header msg_h;
220

    
221
        char str[1000];
222
        mlSocketIDToString(&connectbuf[con_id]->external_socketID,str,999);
223
        debug("ML: send_msg to conID:%d extID:%d, %s\n",con_id,connectbuf[con_id]->external_connectionID,str);
224

    
225
        iov[0].iov_base = &msg_h;
226
        iov[0].iov_len = MSG_HEADER_SIZE;
227

    
228
        msg_h.local_con_id = con_id;
229
        msg_h.remote_con_id = connectbuf[con_id]->external_connectionID;
230
        msg_h.msg_type = msg_type;
231
        msg_h.msg_seq_num = connectbuf[con_id]->seqnr++;
232

    
233

    
234
        iov[1].iov_len = iov[2].iov_len = 0;
235
        iov[1].iov_base = h_pkt;
236
        iov[2].iov_base = h_data;
237

    
238

    
239
        if (connectbuf[con_id]->internal_connect)
240
                udpgen = connectbuf[con_id]->external_socketID.internal_addr;
241
        else
242
                udpgen = connectbuf[con_id]->external_socketID.external_addr;
243

    
244
        do{
245
                offset = 0;
246
                retry = false;
247
                // Monitoring layer hook
248
                if(set_Monitoring_header_data_cb != NULL) {
249
                        iov[2].iov_len = ((set_Monitoring_header_data_cb) (&(connectbuf[con_id]->external_socketID), msg_type));
250
                }
251
                msg_h.len_mon_data_hdr = iov[2].iov_len;
252

    
253
                if(get_Send_data_inf_cb != NULL && iov[2].iov_len != 0) {
254
                        mon_data_inf sd_data_inf;
255

    
256
                        sd_data_inf.remote_socketID = &(connectbuf[con_id]->external_socketID);
257
                        sd_data_inf.buffer = msg;
258
                        sd_data_inf.bufSize = msg_len;
259
                        sd_data_inf.msgtype = msg_type;
260
                        sd_data_inf.monitoringDataHeader = iov[2].iov_base;
261
                        sd_data_inf.monitoringDataHeaderLen = iov[2].iov_len;
262
                        sd_data_inf.priority = sParams->priority;
263
                        sd_data_inf.padding = sParams->padding;
264
                        sd_data_inf.confirmation = sParams->confirmation;
265
                        sd_data_inf.reliable = sParams->reliable;
266
                        memset(&sd_data_inf.arrival_time, 0, sizeof(struct timeval));
267

    
268
                        (get_Send_data_inf_cb) ((void *) &sd_data_inf);
269
                }
270

    
271
                do {
272
                        if(set_Monitoring_header_pkt_cb != NULL) {
273
                                iov[1].iov_len = (set_Monitoring_header_pkt_cb) (&(connectbuf[con_id]->external_socketID), msg_type);
274
                        }
275
                        pkt_len = min(connectbuf[con_id]->pmtusize - iov[2].iov_len - iov[1].iov_len - iov[0].iov_len, msg_len - offset) ;
276

    
277
                        iov[3].iov_len = pkt_len;
278
                        iov[3].iov_base = msg + offset;
279

    
280
                        //fill header
281
                        msg_h.len_mon_packet_hdr = iov[1].iov_len;
282
                        msg_h.offset = offset;
283
                        msg_h.msg_length = truncable ? pkt_len : msg_len;
284

    
285
                        //monitoring layer hook
286
                        if(get_Send_pkt_inf_cb != NULL && iov[1].iov_len) {
287
                                mon_pkt_inf pkt_info;
288

    
289
                                pkt_info.remote_socketID = &(connectbuf[con_id]->external_socketID);
290
                                pkt_info.buffer = msg + offset;
291
                                pkt_info.bufSize = pkt_len;
292
                                pkt_info.msgtype = msg_type;
293
                                pkt_info.dataID = connectbuf[con_id]->seqnr;
294
                                pkt_info.offset = offset;
295
                                pkt_info.datasize = msg_len;
296
                                pkt_info.monitoringHeaderLen = iov[1].iov_len;
297
                                pkt_info.monitoringHeader = iov[1].iov_base;
298
                                pkt_info.ttl = -1;
299
                                memset(&(pkt_info.arrival_time),0,sizeof(struct timeval));
300

    
301
                                (get_Send_pkt_inf_cb) ((void *) &pkt_info);
302
                        }
303

    
304
                        debug("ML: sending packet with rconID:%d lconID:%d\n",msg_h.remote_con_id,msg_h.local_con_id);
305
                        switch(sendPacket(socketfd, iov, 4, &udpgen.udpaddr)) {
306
                                case MSGLEN:
307
                                        info("ML: sending message failed, reducing MTU from %d to %d (conID:%d lconID:%d msgsize:%d offset:%d)\n", connectbuf[con_id]->pmtusize, pmtu_decrement(connectbuf[con_id]->pmtusize), msg_h.remote_con_id, msg_h.local_con_id, msg_len, offset);
308
                                        connectbuf[con_id]->pmtusize = pmtu_decrement(connectbuf[con_id]->pmtusize);
309
                                        connectbuf[con_id]->delay = true;
310
                                        retry = true;
311
                                        offset = msg_len + msg_h.len_mon_data_hdr; // exit the while
312
                                        break;
313
                                case FAILURE:
314
                                        info("ML: sending message failed (conID:%d lconID:%d msgsize:%d offset:%d)\n", msg_h.remote_con_id, msg_h.local_con_id, msg_len, offset);
315
                                        offset = msg_len + msg_h.len_mon_data_hdr; // exit the while
316
                                        break;
317
                                case OK:
318
                                        //update
319
                                        offset += pkt_len + iov[2].iov_len;
320
                                        //transmit data header only in the first packet
321
                                        iov[2].iov_len = 0;
322
                                        break;
323
                        }
324
                } while(offset != msg_len + msg_h.len_mon_data_hdr && !truncable);
325
        } while(retry);
326
}
327

    
328
void pmtu_timeout_cb(int fd, short event, void *arg);
329

    
330
void reschedule_conn_msg(int con_id)
331
{
332
        if (connectbuf[con_id]->timeout_event) {
333
                /* delete old timout */        
334
                event_del(connectbuf[con_id]->timeout_event);
335
                event_free(connectbuf[con_id]->timeout_event);
336
        }
337
        connectbuf[con_id]->timeout_event = event_new(base, -1, EV_TIMEOUT, &pmtu_timeout_cb, (void *) (long)con_id);
338
        evtimer_add(connectbuf[con_id]->timeout_event, &connectbuf[con_id]->timeout_value);
339
}
340

    
341
void send_conn_msg(int con_id, int buf_size, int command_type)
342
{
343
        if (buf_size < sizeof(struct conn_msg)) {
344
                error("ML: requested connection message size is too small\n");
345
                return;
346
        }
347

    
348
        if(connectbuf[con_id]->ctrl_msg_buf == NULL) {
349
                connectbuf[con_id]->ctrl_msg_buf = malloc(buf_size);
350
                memset(connectbuf[con_id]->ctrl_msg_buf, 0, buf_size);
351
        }
352

    
353
        if(connectbuf[con_id]->ctrl_msg_buf == NULL) {
354
                error("ML: can not allocate memory for connection message\n");
355
                return;
356
        }
357

    
358
        struct conn_msg *msg_header = (struct conn_msg*) connectbuf[con_id]->ctrl_msg_buf;
359

    
360
        msg_header->comand_type = command_type;
361
        msg_header->pmtu_size = connectbuf[con_id]->pmtusize;
362

    
363
        memcpy(&(msg_header->sock_id), loc_socketID, sizeof(socket_ID));
364

    
365
        send_msg(con_id, ML_CON_MSG, connectbuf[con_id]->ctrl_msg_buf, buf_size, true, &(connectbuf[con_id]->defaultSendParams));
366
}
367

    
368
void send_conn_msg_with_pmtu_discovery(int con_id, int buf_size, int command_type)
369
{
370
        struct timeval tout = PMTU_TIMEOUT;
371
        connectbuf[con_id]->timeout_value = tout;
372
        connectbuf[con_id]->trials = 1;
373
        send_conn_msg(con_id, buf_size, command_type);
374
        reschedule_conn_msg(con_id);
375
}
376

    
377
void resend_conn_msg(int con_id)
378
{
379
        connectbuf[con_id]->trials++;
380
        send_conn_msg(con_id, connectbuf[con_id]->pmtusize, connectbuf[con_id]->status);
381
        reschedule_conn_msg(con_id);
382
}
383

    
384
void
385
recv_conn_msg(struct msg_header *msg_h, char *msgbuf, int bufsize)
386
{
387
        struct conn_msg *con_msg;
388
        int free_con_id, con_id;
389

    
390
        time_t now = time(NULL);
391
        double timediff = 0.0;
392
        char str[1000];
393

    
394
        // Monitoring layer hook
395
        if(get_Recv_data_inf_cb != NULL && msg_h->len_mon_data_hdr != 0) {
396
                // update pointer to the real data
397
                msgbuf += msg_h->len_mon_data_hdr;
398
                bufsize -= msg_h->len_mon_data_hdr;
399
                con_msg = (struct conn_msg *)msgbuf;
400

    
401
                mon_data_inf recv_data_inf;
402
                recv_data_inf.remote_socketID = &(con_msg->sock_id);
403
                recv_data_inf.buffer = msgbuf;
404
                recv_data_inf.bufSize = bufsize;
405
                recv_data_inf.msgtype = msg_h->msg_type;
406
                recv_data_inf.monitoringDataHeaderLen = msg_h->len_mon_data_hdr;
407
                recv_data_inf.monitoringDataHeader = msg_h->len_mon_data_hdr ? msgbuf : NULL;
408
                gettimeofday(&recv_data_inf.arrival_time, NULL);
409
                recv_data_inf.firstPacketArrived = true;
410
                recv_data_inf.recvFragments = 1;
411
                recv_data_inf.priority = false;
412
                recv_data_inf.padding = false;
413
                recv_data_inf.confirmation = false;
414
                recv_data_inf.reliable = false;
415

    
416
                // send data recv callback to monitoring module
417
                (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
418
        } else {
419
                con_msg = (struct conn_msg *) msgbuf;
420
        }
421

    
422
        //decode sock_id for debug messages
423
        mlSocketIDToString(&con_msg->sock_id,str,999);
424

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

    
454
                        if (con_id == CONNECTBUFSIZE) {
455
                                // create an entry in the connecttrybuf
456
                                if(free_con_id == -1) {
457
                                        error("ML: no new connect_buf available\n");
458
                                        return;
459
                                }
460
                                connectbuf[free_con_id] = (connect_data *) malloc(sizeof(connect_data));
461
                                memset(connectbuf[free_con_id],0,sizeof(connect_data));
462
                                connectbuf[free_con_id]->connection_head = connectbuf[free_con_id]->connection_last = NULL;
463
                                connectbuf[free_con_id]->starttime = time(NULL);
464
                                memcpy(&(connectbuf[free_con_id]->external_socketID), &(con_msg->sock_id), sizeof(socket_ID));
465
                                connectbuf[free_con_id]->pmtusize = con_msg->pmtu_size;        // bootstrap pmtu from the other's size. Not strictly needed, but a good hint
466
                                connectbuf[free_con_id]->external_connectionID = msg_h->local_con_id;
467
                                connectbuf[free_con_id]->internal_connect =
468
                                        !compare_external_address_socketIDs(&(con_msg->sock_id), loc_socketID);
469
                                con_id = free_con_id;
470
                        }
471

    
472
                        //if(connectbuf[con_id]->status <= CONNECT) { //TODO: anwer anyway. Why the outher would invite otherwise?
473
                                //update status and send back answer
474
                                connectbuf[con_id]->status = CONNECT;
475
                                send_conn_msg_with_pmtu_discovery(con_id, con_msg->pmtu_size, CONNECT);
476
                        //}
477
                        break;
478
                case CONNECT:
479
                        info("ML: received CONNECT from %s\n",str);
480

    
481
                        if(msg_h->remote_con_id != -1 && connectbuf[msg_h->remote_con_id] == NULL) {
482
                                error("ML: received CONNECT for inexistent connection rconID:%d\n",msg_h->remote_con_id);
483
                                return;
484
                        }
485

    
486
                        /*
487
                        * check if the connection status is not already 1 or 2
488
                        */
489
                        if (connectbuf[msg_h->remote_con_id]->status == INVITE) {
490
                                // set the external connectionID
491
                                connectbuf[msg_h->remote_con_id]->external_connectionID = msg_h->local_con_id;
492
                                // change status con_msg the connection_data
493
                                connectbuf[msg_h->remote_con_id]->status = READY;
494
                                // change pmtusize in the connection_data: not needed. receiving a CONNECT means our INVITE went through. So why change pmtu?
495
                                //connectbuf[msg_h->remote_con_id]->pmtusize = con_msg->pmtu_size;
496

    
497
                                // send the READY
498
                                send_conn_msg_with_pmtu_discovery(msg_h->remote_con_id, con_msg->pmtu_size, READY);
499

    
500
                                if (receive_Connection_cb != NULL)
501
                                        (receive_Connection_cb) (msg_h->remote_con_id, NULL);
502

    
503
                                // call all registered callbacks
504
                                while(connectbuf[msg_h->remote_con_id]->connection_head != NULL) {
505
                                        struct receive_connection_cb_list *temp;
506
                                        temp = connectbuf[msg_h->remote_con_id]->connection_head;
507
                                        (temp->connection_cb) (msg_h->remote_con_id, temp->arg);
508
                                        connectbuf[msg_h->remote_con_id]->connection_head = temp->next;
509
                                        free(temp);
510
                                }
511
                                connectbuf[msg_h->remote_con_id]->connection_head =
512
                                        connectbuf[msg_h->remote_con_id]->connection_last = NULL;
513
                        } else {
514
                                // send the READY
515
                                send_conn_msg_with_pmtu_discovery(msg_h->remote_con_id, con_msg->pmtu_size, READY);
516
                        }
517

    
518
                        debug("ML: active connection established\n");
519
                        break;
520

    
521
                        /*
522
                        * if READY: find the entry in the connection array set the
523
                        * connection active change the pmtu size
524
                        */
525
                case READY:
526
                        info("ML: received READY from %s\n",str);
527
                        if(connectbuf[msg_h->remote_con_id] == NULL) {
528
                                error("ML: received READY for inexistent connection\n");
529
                                return;
530
                        }
531
                        /*
532
                        * checks if the connection is not already established
533
                        */
534
                        if (connectbuf[msg_h->remote_con_id]->status == CONNECT) {
535
                                // change status of the connection
536
                                connectbuf[msg_h->remote_con_id]->status = READY;
537
                                // change pmtusize: not needed. pmtu doesn't have to be symmetric
538
                                //connectbuf[msg_h->remote_con_id]->pmtusize = con_msg->pmtu_size;
539

    
540
                                if (receive_Connection_cb != NULL)
541
                                        (receive_Connection_cb) (msg_h->remote_con_id, NULL);
542

    
543
                                while(connectbuf[msg_h->remote_con_id]->connection_head != NULL) {
544
                                        struct receive_connection_cb_list *temp;
545
                                        temp = connectbuf[msg_h->remote_con_id]->connection_head;
546
                                        (temp->connection_cb) (msg_h->remote_con_id, temp->arg);
547
                                        connectbuf[msg_h->remote_con_id]->connection_head = temp->next;
548
                                        free(temp);
549
                                }
550
                                connectbuf[msg_h->remote_con_id]->connection_head =
551
                                        connectbuf[msg_h->remote_con_id]->connection_last = NULL;
552
                                debug("ML: passive connection established\n");
553
                        }
554
                        break;
555
        }
556
}
557

    
558
void recv_stun_msg(char *msgbuf, int recvSize)
559
{
560
        /*
561
        * create empty stun message struct
562
        */
563
        StunMessage resp;
564
        memset(&resp, 0, sizeof(StunMessage));
565
        /*
566
        * parse the message
567
        */
568
        int returnValue = 0;
569
        returnValue = recv_stun_message(msgbuf, recvSize, &resp);
570

    
571
        if (returnValue == 0) {
572
                /*
573
                * read the reflexive Address into the local_socketID
574
                */
575
                struct sockaddr_in reflexiveAddr;
576
                reflexiveAddr.sin_family = AF_INET;
577
                reflexiveAddr.sin_addr.s_addr = htonl(resp.mappedAddress.ipv4.addr);
578
                reflexiveAddr.sin_port = htons(resp.mappedAddress.ipv4.port);
579
                socketaddrgen reflexiveAddres;
580
                reflexiveAddres.udpaddr = reflexiveAddr;
581
                local_socketID.external_addr = reflexiveAddres;
582
                NAT_traversal = true;
583
                // callback to the upper layer indicating that the socketID is now
584
                // ready to use
585
                (receive_SocketID_cb) (&local_socketID, 0);
586
        }
587
}
588

    
589
//done
590
void recv_timeout_cb(int fd, short event, void *arg)
591
{
592
        int recv_id = (long) arg;
593
        debug("ML: recv_timeout_cb called. Timeout for id:%d\n",recv_id);
594

    
595
        if (recvdatabuf[recv_id] == NULL) {
596
                return;
597
        }
598

    
599

    
600
/*        if(recvdatabuf[recv_id]->status == ACTIVE) {
601
                //TODO make timeout at least a DEFINE
602
                struct timeval timeout = { 4, 0 };
603
                recvdatabuf[recv_id]->status = INACTIVE;
604
                event_base_once(base, -1, EV_TIMEOUT, recv_timeout_cb,
605
                        arg, &timeout);
606
                return;
607
        }
608
*/
609

    
610
        if(recvdatabuf[recv_id]->status == ACTIVE) {
611
                // Monitoring layer hook
612
                if(get_Recv_data_inf_cb != NULL) {
613
                        mon_data_inf recv_data_inf;
614

    
615
                        recv_data_inf.remote_socketID =
616
                                        &(connectbuf[recvdatabuf[recv_id]->connectionID]->external_socketID);
617
                        recv_data_inf.buffer = recvdatabuf[recv_id]->recvbuf;
618
                        recv_data_inf.bufSize = recvdatabuf[recv_id]->bufsize;
619
                        recv_data_inf.msgtype = recvdatabuf[recv_id]->msgtype;
620
                        recv_data_inf.monitoringDataHeaderLen = recvdatabuf[recv_id]->monitoringDataHeaderLen;
621
                        recv_data_inf.monitoringDataHeader = recvdatabuf[recv_id]->monitoringDataHeaderLen ?
622
                                recvdatabuf[recv_id]->recvbuf : NULL;
623
                        gettimeofday(&recv_data_inf.arrival_time, NULL);
624
                        recv_data_inf.firstPacketArrived = recvdatabuf[recv_id]->firstPacketArrived;
625
                        recv_data_inf.recvFragments = recvdatabuf[recv_id]->recvFragments;
626
                        recv_data_inf.priority = false;
627
                        recv_data_inf.padding = false;
628
                        recv_data_inf.confirmation = false;
629
                        recv_data_inf.reliable = false;
630

    
631
                        // send data recv callback to monitoring module
632

    
633
                        (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
634
                }
635

    
636
                // Get the right callback
637
                receive_data_cb receive_data_callback = recvcbbuf[recvdatabuf[recv_id]->msgtype];
638

    
639
                recv_params rParams;
640

    
641
                rParams.nrMissingBytes = recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->arrivedBytes;
642
                rParams.recvFragments = recvdatabuf[recv_id]->recvFragments;
643
                rParams.msgtype = recvdatabuf[recv_id]->msgtype;
644
                rParams.connectionID = recvdatabuf[recv_id]->connectionID;
645
                rParams.remote_socketID =
646
                        &(connectbuf[recvdatabuf[recv_id]->connectionID]->external_socketID);
647
                rParams.firstPacketArrived = recvdatabuf[recv_id]->firstPacketArrived;
648

    
649
                (receive_data_callback) (recvdatabuf[recv_id]->recvbuf + recvdatabuf[recv_id]->monitoringDataHeaderLen, recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->monitoringDataHeaderLen,
650
                        recvdatabuf[recv_id]->msgtype, &rParams);
651

    
652
                //clean up
653
                free(recvdatabuf[recv_id]->recvbuf);
654
                free(recvdatabuf[recv_id]);
655
                recvdatabuf[recv_id] = NULL;
656
        }
657
}
658

    
659
// process a single recv data message
660
void recv_data_msg(struct msg_header *msg_h, char *msgbuf, int bufsize)
661
{
662
        debug("ML: received packet of size %d with rconID:%d lconID:%d\n",bufsize,msg_h->remote_con_id,msg_h->local_con_id);
663

    
664
        int recv_id, free_recv_id = -1;
665

    
666
        if(connectbuf[msg_h->remote_con_id] == NULL) {
667
                debug("ML: Received a message not related to any opened connection!\n");
668
                return;
669
        }
670

    
671
        // check if a recv_data exist and enter data
672
        for (recv_id = 0; recv_id < RECVDATABUFSIZE; recv_id++)
673
                if (recvdatabuf[recv_id] != NULL) {
674
                        if (msg_h->remote_con_id == recvdatabuf[recv_id]->connectionID &&
675
                                        msg_h->msg_seq_num == recvdatabuf[recv_id]->seqnr)
676
                                                break;
677
                } else
678
                        if(free_recv_id == -1)
679
                                free_recv_id = recv_id;
680

    
681

    
682
        if(recv_id == RECVDATABUFSIZE) {
683
                //no recv_data found: create one
684
                recv_id = free_recv_id;
685
                recvdatabuf[recv_id] = (recvdata *) malloc(sizeof(recvdata));
686
                memset(recvdatabuf[recv_id], 0, sizeof(recvdata));
687
                recvdatabuf[recv_id]->connectionID = msg_h->remote_con_id;
688
                recvdatabuf[recv_id]->seqnr = msg_h->msg_seq_num;
689
                recvdatabuf[recv_id]->monitoringDataHeaderLen = msg_h->len_mon_data_hdr;
690
                recvdatabuf[recv_id]->bufsize = msg_h->msg_length + msg_h->len_mon_data_hdr;
691
                recvdatabuf[recv_id]->recvbuf = (char *) malloc(recvdatabuf[recv_id]->bufsize);
692
                /*
693
                * read the timeout data and set it
694
                */
695
                recvdatabuf[recv_id]->timeout_value = recv_timeout;
696
                recvdatabuf[recv_id]->timeout_event = NULL;
697
                recvdatabuf[recv_id]->recvID = recv_id;
698
                recvdatabuf[recv_id]->starttime = time(NULL);
699
                recvdatabuf[recv_id]->msgtype = msg_h->msg_type;
700

    
701
                // fill the buffer with zeros
702
                memset(recvdatabuf[recv_id]->recvbuf, 0, msg_h->msg_length);
703
                debug(" new @ id:%d\n",recv_id);
704
        } else {        //message structure already exists, no need to create new
705
                debug(" found @ id:%d\n",recv_id);
706
        }
707

    
708
        if (msg_h->offset == 0)
709
                recvdatabuf[recv_id]->firstPacketArrived = 1;
710

    
711

    
712
        // increment fragmentnr
713
        recvdatabuf[recv_id]->recvFragments++;
714
        // increment the arrivedBytes
715
        recvdatabuf[recv_id]->arrivedBytes += bufsize;
716

    
717
        // enter the data into the buffer
718
        memcpy(recvdatabuf[recv_id]->recvbuf + msg_h->offset, msgbuf, bufsize);
719

    
720
        //TODO very basic checkif all fragments arrived: has to be reviewed
721
        if(recvdatabuf[recv_id]->arrivedBytes == recvdatabuf[recv_id]->bufsize)
722
                recvdatabuf[recv_id]->status = COMPLETE; //buffer full -> msg completly arrived
723
        else
724
                recvdatabuf[recv_id]->status = ACTIVE;
725

    
726
        if (recv_data_callback) {
727
                if(recvdatabuf[recv_id]->status == COMPLETE) {
728
                        // Monitoring layer hook
729
                        if(get_Recv_data_inf_cb != NULL) {
730
                                mon_data_inf recv_data_inf;
731

    
732
                                recv_data_inf.remote_socketID =
733
                                         &(connectbuf[recvdatabuf[recv_id]->connectionID]->external_socketID);
734
                                recv_data_inf.buffer = recvdatabuf[recv_id]->recvbuf;
735
                                recv_data_inf.bufSize = recvdatabuf[recv_id]->bufsize;
736
                                recv_data_inf.msgtype = recvdatabuf[recv_id]->msgtype;
737
                                recv_data_inf.monitoringDataHeaderLen = recvdatabuf[recv_id]->monitoringDataHeaderLen;
738
                                recv_data_inf.monitoringDataHeader = recvdatabuf[recv_id]->monitoringDataHeaderLen ?
739
                                        recvdatabuf[recv_id]->recvbuf : NULL;
740
                                gettimeofday(&recv_data_inf.arrival_time, NULL);
741
                                recv_data_inf.firstPacketArrived = recvdatabuf[recv_id]->firstPacketArrived;
742
                                recv_data_inf.recvFragments = recvdatabuf[recv_id]->recvFragments;
743
                                recv_data_inf.priority = false;
744
                                recv_data_inf.padding = false;
745
                                recv_data_inf.confirmation = false;
746
                                recv_data_inf.reliable = false;
747

    
748
                                // send data recv callback to monitoring module
749

    
750
                                (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
751
                        }
752

    
753
                        // Get the right callback
754
                        receive_data_cb receive_data_callback = recvcbbuf[msg_h->msg_type];
755
                        if (receive_data_callback) {
756

    
757
                                recv_params rParams;
758

    
759
                                rParams.nrMissingBytes = recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->arrivedBytes;
760
                                rParams.recvFragments = recvdatabuf[recv_id]->recvFragments;
761
                                rParams.msgtype = recvdatabuf[recv_id]->msgtype;
762
                                rParams.connectionID = recvdatabuf[recv_id]->connectionID;
763
                                rParams.remote_socketID =
764
                                        &(connectbuf[recvdatabuf[recv_id]->connectionID]->external_socketID);
765

    
766
                                char str[1000];
767
                                mlSocketIDToString(rParams.remote_socketID,str,999);
768
                                debug("ML: received message from conID:%d, %s\n",recvdatabuf[recv_id]->connectionID,str);
769
                                rParams.firstPacketArrived = recvdatabuf[recv_id]->firstPacketArrived;
770

    
771
                                (receive_data_callback) (recvdatabuf[recv_id]->recvbuf + recvdatabuf[recv_id]->monitoringDataHeaderLen, recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->monitoringDataHeaderLen,
772
                                        recvdatabuf[recv_id]->msgtype, (void *) &rParams);
773
                        } else {
774
                            warn("ML: callback not initialized for this message type: %d!\n",msg_h->msg_type);
775
                        }
776

    
777
                        //clean up
778
                        if (recvdatabuf[recv_id]->timeout_event) {
779
                                int ret;
780
                                debug("ML: freeing timeout for %d",recv_id);
781
                                ret = event_del(recvdatabuf[recv_id]->timeout_event);
782
                                event_free(recvdatabuf[recv_id]->timeout_event);
783
                                debug(" ret: %d\n",ret);
784
                        } else {
785
                                debug("ML: received in 1 packet\n",recv_id);
786
                        }
787
                        free(recvdatabuf[recv_id]->recvbuf);
788
                        free(recvdatabuf[recv_id]);
789
                        recvdatabuf[recv_id] = NULL;
790
                } else { // not COMPLETE
791
                        if (!recvdatabuf[recv_id]->timeout_event) {
792
                                //start time out
793
                                //TODO make timeout at least a DEFINE
794
                                recvdatabuf[recv_id]->timeout_event = event_new(base, -1, EV_TIMEOUT, &recv_timeout_cb, (void *) (long)recv_id);
795
                                evtimer_add(recvdatabuf[recv_id]->timeout_event, &recv_timeout);
796
                        }
797
                }
798
        }
799
}
800

    
801
//done
802
void pmtu_timeout_cb(int fd, short event, void *arg)
803
{
804

    
805
        int con_id = (long) arg;
806
        pmtu new_pmtusize;
807
        struct timeval timeout;
808

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

    
811
        if(connectbuf[con_id] == NULL) {
812
                error("ML: pmtu timeout called on non existing con_id\n");
813
                return;
814
        }
815

    
816
        if(connectbuf[con_id]->status == READY) {
817
                // nothing to do anymore
818
                event_del(connectbuf[con_id]->timeout_event);
819
                event_free(connectbuf[con_id]->timeout_event);
820
                return;
821
        }
822

    
823
        info("ML: pmtu timeout while connecting(lcon:%d status:%d)\n",con_id, connectbuf[con_id]->status);
824

    
825
        timeout = connectbuf[con_id]->timeout_value;
826

    
827
        if(connectbuf[con_id]->delay || connectbuf[con_id]->trials == MAX_TRIALS - 1) {
828
                double delay = timeout.tv_sec + timeout.tv_usec / 1000000.0;
829
                delay = delay * 2;
830
                info("\tML: increasing pmtu timeout to %f sec\n", delay);
831
                timeout.tv_sec = floor(delay);
832
                timeout.tv_usec = fmod(delay, 1.0) * 1000000.0;
833
                if(connectbuf[con_id]->delay) {
834
                        connectbuf[con_id]->delay = false;
835
                        reschedule_conn_msg(con_id);
836
                }
837
        }
838

    
839
        if(connectbuf[con_id]->trials == MAX_TRIALS) {
840
                // decrement the pmtu size
841
                struct timeval tout = PMTU_TIMEOUT;
842
                info("\tML: decreasing pmtu timeout from %d to %d", connectbuf[con_id]->pmtusize, pmtu_decrement(connectbuf[con_id]->pmtusize));
843
                connectbuf[con_id]->pmtusize = pmtu_decrement(connectbuf[con_id]->pmtusize);
844
                connectbuf[con_id]->timeout_value = tout; 
845
                connectbuf[con_id]->trials = 0;
846
        }
847

    
848
        //error in PMTU discovery?
849
        if (connectbuf[con_id]->pmtusize == ERROR) {
850
                if (connectbuf[con_id]->internal_connect == true) {
851
                        //as of now we tried directly connecting, now let's try trough the NAT
852
                        connectbuf[con_id]->internal_connect = false;
853
                        connectbuf[con_id]->pmtusize = MAX;
854
                } else {
855
                        //nothing to do we have to give up
856
                        error("ML: Could not create connection with connectionID %i!\n",con_id);
857
                        // envoke the callback for failed connection establishment
858
                        if(failed_Connection_cb != NULL)
859
                                (failed_Connection_cb) (con_id, NULL);
860
                        // delete the connection entry
861
                        mlCloseConnection(con_id);
862
                        return;
863
                }
864
        }
865

    
866
        //retry with new pmtu size
867
        connectbuf[con_id]->trials++;
868
        resend_conn_msg(con_id);
869
}
870

    
871

    
872
int schedule_pmtu_timeout(int con_id)
873
{
874
        if (! connectbuf[con_id]->timeout_event) {
875
                struct timeval tout = PMTU_TIMEOUT;
876
                connectbuf[con_id]->timeout_value = tout;
877
                connectbuf[con_id]->trials = 1;
878
                connectbuf[con_id]->timeout_event = event_new(base, -1, EV_TIMEOUT, &pmtu_timeout_cb, (void *) (long)con_id);
879
                evtimer_add(connectbuf[con_id]->timeout_event, &connectbuf[con_id]->timeout_value);
880
        }
881
}
882

    
883
/*
884
 * decrements the mtu size
885
 */
886
pmtu pmtu_decrement(pmtu pmtusize)
887
{
888
        pmtu pmtu_return_size;
889
        switch(pmtusize) {
890
        case MAX:
891
                return DSL;
892
        case DSL:
893
                return DSLMEDIUM;
894
        case DSLMEDIUM:
895
                return DSLSLIM;
896
        case DSLSLIM:
897
                return BELOWDSL;
898
        case BELOWDSL:
899
                return MIN;
900
        default:
901
                return ERROR;
902
        }
903
}
904

    
905
// called when an ICMP pmtu error message (type 3, code 4) is received
906
void pmtu_error_cb_th(char *msg, int msglen)
907
{
908
        debug("ML: pmtu_error callback called msg_size: %d\n",msglen);
909
        //TODO debug
910
        return;
911

    
912
    char *msgbufptr = NULL;
913
    int msgtype;
914
    int connectionID;
915
    pmtu pmtusize;
916
    pmtu new_pmtusize;
917
    int dead = 0;
918

    
919
    // check the packettype
920
    msgbufptr = &msg[0];
921

    
922
    // check the msgtype
923
    msgbufptr = &msg[1];
924
    memcpy(&msgtype, msgbufptr, 4);
925

    
926
    if (msgtype == 0) {
927

    
928
        // get the connectionID
929
        msgbufptr = &msg[5];
930
        memcpy(&connectionID, msgbufptr, 4);
931

    
932
        int msgtype_c = connectbuf[connectionID]->status;
933
//        pmtusize = connectbuf[connectionID]->pmtutrysize;
934

    
935
        if (msgtype_c != msgtype) {
936
            dead = 1;
937
        }
938

    
939

    
940
    } else if (msgtype == 1) {
941

    
942
        // read the connectionID
943
        msgbufptr = &msg[9];
944
        memcpy(&connectionID, msgbufptr, 4);
945

    
946
        int msgtype_c = connectbuf[connectionID]->status;
947
//        pmtusize = connectbuf[connectionID]->pmtutrysize;
948

    
949
        if (msgtype_c != msgtype) {
950
            dead = 1;
951
        }
952

    
953
    }
954
    // decrement the pmtu size
955
    new_pmtusize = pmtu_decrement(pmtusize);
956

    
957
//    connectbuf[connectionID]->pmtutrysize = new_pmtusize;
958

    
959
    if (new_pmtusize == ERROR) {
960
                error("ML:  Could not create connection with connectionID %i !\n",
961
                        connectionID);
962

    
963
                if(failed_Connection_cb != NULL)
964
                        (failed_Connection_cb) (connectionID, NULL);
965
                // set the message type to a non existent message
966
                msgtype = 2;
967
                // delete the connection entry
968
                 mlCloseConnection(connectionID);
969
        }
970

    
971
    if (msgtype == 0 && dead != 1) {
972

    
973
        // stop the timeout event
974
        // timeout_del(connectbuf[connectionID]->timeout);
975
        /*
976
         * libevent2
977
         */
978

    
979
        // event_del(connectbuf[connectionID]->timeout);
980

    
981

    
982
        // create and send a connection message
983
//         create_conn_msg(new_pmtusize, connectionID,
984
//                         &local_socketID, INVITE);
985

    
986
//        send_conn_msg(connectionID, new_pmtusize);
987

    
988
        // set a timeout event for the pmtu discovery
989
        // timeout_set(connectbuf[connectionID]->timeout,pmtu_timeout_cb,(void
990
        // *)&connectionID);
991

    
992
        // timeout_add(connectbuf[connectionID]->timeout,&connectbuf[connectionID]->timeout_value);
993

    
994
        /*
995
         * libevent2
996
         */
997

    
998
        struct event *ev;
999
        ev = evtimer_new(base, pmtu_timeout_cb,
1000
                         (void *) connectbuf[connectionID]);
1001

    
1002
        // connectbuf[connectionID]->timeout = ev;
1003

    
1004
        event_add(ev, &connectbuf[connectionID]->timeout_value);
1005

    
1006
    } else if (msgtype == 1 && dead != 1) {
1007

    
1008
        // stop the timeout event
1009
        // timeout_del(connectbuf[connectionID]->timeout);
1010

    
1011
        /*
1012
         * libevent2
1013
         */
1014
        // info("still here 11 \n");
1015
        // printf("ev %d \n",connectbuf[connectionID]->timeout);
1016
        // event_del(connectbuf[connectionID]->timeout );
1017
        // evtimer_del(connectbuf[connectionID]->timeout );
1018

    
1019

    
1020
//         // create and send a connection message
1021
//         create_conn_msg(new_pmtusize,
1022
//                         connectbuf[connectionID]->connectionID,
1023
//                         NULL, CONNECT);
1024

    
1025
        //send_conn_msg(connectionID, new_pmtusize);
1026

    
1027
        // set a timeout event for the pmtu discovery
1028
        // timeout_set(connectbuf[connectionID]->timeout,pmtu_timeout_cb,(void
1029
        // *)&connectionID);
1030
        // timeout_add(connectbuf[connectionID]->timeout,&connectbuf[connectionID]->timeout_value);
1031

    
1032
        /*
1033
         * libevent2
1034
         */
1035
        // struct event *ev;
1036
        // ev = evtimer_new(base,pmtu_timeout_cb, (void
1037
        // *)connectbuf[connectionID]);
1038
        // connectbuf[connectionID]->timeout = ev;
1039
        // event_add(ev,&connectbuf[connectionID]->timeout_value);
1040

    
1041
    }
1042
}
1043

    
1044
/*
1045
 * what to do once a packet arrived if it is a conn packet send it to
1046
 * recv_conn handler if it is a data packet send it to the recv_data
1047
 * handler
1048
 */
1049

    
1050
//done --
1051
void recv_pkg(int fd, short event, void *arg)
1052
{
1053
        debug("ML: recv_pkg called\n");
1054

    
1055
        struct msg_header *msg_h;
1056
        char msgbuf[MAX];
1057
        pmtu recvSize = MAX;
1058
        char *bufptr = msgbuf;
1059
        int ttl;
1060
        struct sockaddr_in recv_addr;
1061
        int msg_size;
1062

    
1063
        recvPacket(fd, msgbuf, &recvSize, &recv_addr, pmtu_error_cb_th, &ttl);
1064

    
1065

    
1066
        // check if it is not just an ERROR message
1067
        if(recvSize < 0)
1068
                return;
1069

    
1070
        // @TODO check if this simplistic STUN message recognition really always works, probably not
1071
        unsigned short stun_bind_response = 0x0101;
1072
        unsigned short * msgspot = (unsigned short *) msgbuf;
1073
        if (*msgspot == stun_bind_response) {
1074
                debug("ML: recv_pkg: parse stun message called\n");
1075
                recv_stun_msg(msgbuf, recvSize);
1076
                return;
1077
        }
1078

    
1079
        msg_h = (struct msg_header *) msgbuf;
1080
        bufptr += MSG_HEADER_SIZE + msg_h->len_mon_packet_hdr;
1081
        msg_size = recvSize - MSG_HEADER_SIZE - msg_h->len_mon_packet_hdr;
1082

    
1083

    
1084
        if(get_Recv_pkt_inf_cb != NULL && msg_h->len_mon_packet_hdr != 0) {
1085
                mon_pkt_inf msginfNow;
1086
                msginfNow.monitoringHeaderLen = msg_h->len_mon_packet_hdr;
1087
                msginfNow.monitoringHeader = msg_h->len_mon_packet_hdr ? &msgbuf[0] + MSG_HEADER_SIZE : NULL;
1088
                //TODO rethink this ...
1089
                if(msg_h->msg_type == ML_CON_MSG) {
1090
                        struct conn_msg *c_msg = (struct conn_msg *) bufptr;
1091
                        msginfNow.remote_socketID = &(c_msg->sock_id);
1092
                }
1093
                else if(connectbuf[msg_h->remote_con_id] == NULL) {
1094
                        error("ML: received pkg called with non existent connection\n");
1095
                        return;
1096
                } else
1097
                        msginfNow.remote_socketID = &(connectbuf[msg_h->remote_con_id]->external_socketID);
1098
                msginfNow.buffer = bufptr;
1099
                msginfNow.bufSize = recvSize;
1100
                msginfNow.msgtype = msg_h->msg_type;
1101
                msginfNow.ttl = ttl;
1102
                msginfNow.dataID = msg_h->msg_seq_num;
1103
                msginfNow.offset = msg_h->offset;
1104
                msginfNow.datasize = msg_h->msg_length;
1105
                gettimeofday(&msginfNow.arrival_time, NULL);
1106
                (get_Recv_pkt_inf_cb) ((void *) &msginfNow);
1107
        }
1108

    
1109

    
1110
        switch(msg_h->msg_type) {
1111
                case ML_CON_MSG:
1112
                        debug("ML: received conn pkg\n");
1113
                        recv_conn_msg(msg_h, bufptr, msg_size);
1114
                        break;
1115
                default:
1116
                        if(msg_h->msg_type < 127) {
1117
                                debug("ML: received data pkg\n");
1118
                                recv_data_msg(msg_h, bufptr, msg_size);
1119
                                break;
1120
                        }
1121
                        debug("ML: unrecognised msg_type\n");
1122
                        break;
1123
        }
1124
}
1125

    
1126
/*
1127
 * compare the external IP address of two socketIDs
1128
 */
1129
int
1130
compare_external_address_socketIDs(socketID_handle sock1, socketID_handle sock2)
1131
{
1132
        if( sock1->external_addr.udpaddr.sin_addr.s_addr == sock2->external_addr.udpaddr.sin_addr.s_addr)
1133
                return 0;
1134
        return 1;
1135
}
1136

    
1137
void try_stun();
1138

    
1139
/*
1140
 * the timeout of the NAT traversal
1141
 */
1142
void nat_traversal_timeout(int fd, short event, void *arg)
1143
{
1144
        if (NAT_traversal == false) {
1145
                debug("ML: NAT traversal request re-send\n");
1146
                if(receive_SocketID_cb)
1147
                        (receive_SocketID_cb) (&local_socketID, 2);
1148
                try_stun();
1149
        }
1150
}
1151

    
1152
unsigned long resolve(const char *ipaddr)
1153
{
1154
        struct hostent *h = gethostbyname(ipaddr);
1155
        if (!h) {
1156
                error("ML: Unable to resolve host name %s\n", ipaddr);
1157
        exit(-1);
1158
    }
1159
    unsigned long *addr = (unsigned long *) (h->h_addr);
1160
    return *addr;
1161
}
1162

    
1163

    
1164
/*
1165
 * returns a handle to the socketID struct the ipaddr can be a null
1166
 * pointer. Then all available ipaddr on the machine are choosen.
1167
 */
1168
void create_socket(const int port, const char *ipaddr)
1169
{
1170
        struct sockaddr_in udpaddr;
1171
        udpaddr.sin_family = AF_INET;
1172
        if (ipaddr == NULL) {
1173
                /*
1174
                * try to guess the local IP address
1175
                */
1176
                const char *ipaddr_iface = mlAutodetectIPAddress();
1177
                if (ipaddr_iface) {
1178
                        udpaddr.sin_addr.s_addr = inet_addr(ipaddr_iface);
1179
                } else {
1180
                        udpaddr.sin_addr.s_addr = INADDR_ANY;
1181
                }
1182
        } else {
1183
                udpaddr.sin_addr.s_addr = inet_addr(ipaddr);
1184
        }
1185
        udpaddr.sin_port = htons(port);
1186

    
1187
        socketaddrgen udpgen;
1188
        memset(&udpgen,0,sizeof(socketaddrgen));        //this will be sent over the net, so set it to 0
1189
        udpgen.udpaddr = udpaddr;
1190
        local_socketID.internal_addr = udpgen;
1191

    
1192
        socketfd = createSocket(port, ipaddr);
1193

    
1194
        struct event *ev;
1195
        ev = event_new(base, socketfd, EV_READ | EV_PERSIST, recv_pkg, NULL);
1196

    
1197
        event_add(ev, NULL);
1198

    
1199
        try_stun();
1200
}
1201

    
1202
/*
1203
 * try to figure out external IP using STUN, if defined
1204
 */
1205
void try_stun()
1206
{
1207
        if (isStunDefined()) {
1208
                /*
1209
                * send the NAT traversal STUN request
1210
                */
1211
                 send_stun_request(socketfd, &stun_server);
1212

    
1213
                /*
1214
                * enter a NAT traversal timeout that takes care of retransmission
1215
                */
1216
                struct event *ev1;
1217
                struct timeval timeout_value_NAT_traversal = NAT_TRAVERSAL_TIMEOUT;
1218
                ev1 = evtimer_new(base, nat_traversal_timeout, NULL);
1219
                event_add(ev1, &timeout_value_NAT_traversal);
1220

    
1221
                NAT_traversal = false;
1222
        } else {
1223
                /*
1224
                * Assume we have accessibility and copy internal address to external one
1225
                */
1226
                local_socketID.external_addr = local_socketID.internal_addr;
1227
                NAT_traversal = true; // @TODO: this is not really NAT traversal, but a flag that init is over
1228
                // callback to the upper layer indicating that the socketID is now
1229
                // ready to use
1230
                if(receive_SocketID_cb)
1231
                        (receive_SocketID_cb) (&local_socketID, 0); //success
1232
        }
1233
}
1234

    
1235
/**************************** END OF INTERNAL ***********************/
1236

    
1237
/**************************** MONL functions *************************/
1238

    
1239
void 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){
1240

    
1241
        base = (struct event_base *) arg;
1242
        recv_data_callback = recv_data_cb;
1243
        mlSetRecvTimeout(timeout_value);
1244
        if (stun_ipaddr) {
1245
                 mlSetStunServer(stun_port, stun_ipaddr);
1246
        } else {
1247

    
1248
        }
1249
        register_recv_localsocketID_cb(local_socketID_cb);
1250
        create_socket(port, ipaddr);
1251

    
1252
}
1253

    
1254
/* register callbacks  */
1255
void mlRegisterGetRecvPktInf(get_recv_pkt_inf_cb recv_pkt_inf_cb){
1256

    
1257
        if (recv_pkt_inf_cb == NULL)
1258
                error("ML: Register get_recv_pkt_inf_cb failed: NULL ptr  \n");
1259
        else
1260
                get_Recv_pkt_inf_cb = recv_pkt_inf_cb;
1261

    
1262
}
1263

    
1264
void mlRegisterGetSendPktInf(get_send_pkt_inf_cb  send_pkt_inf_cb){
1265

    
1266
        if (send_pkt_inf_cb == NULL)
1267
                error("ML: Register get_send_pkt_inf_cb: NULL ptr  \n");
1268
        else
1269
                get_Send_pkt_inf_cb = send_pkt_inf_cb;
1270

    
1271
}
1272

    
1273

    
1274
void mlRegisterSetMonitoringHeaderPktCb(set_monitoring_header_pkt_cb monitoring_header_pkt_cb ){
1275

    
1276
        if (monitoring_header_pkt_cb == NULL)
1277
                error("ML: Register set_monitoring_header_pkt_cb: NULL ptr  \n");
1278
        else
1279
                set_Monitoring_header_pkt_cb = monitoring_header_pkt_cb;
1280

    
1281
}
1282

    
1283
void mlRegisterGetRecvDataInf(get_recv_data_inf_cb recv_data_inf_cb){
1284

    
1285
        if (recv_data_inf_cb == NULL)
1286
                error("ML: Register get_recv_data_inf_cb: NULL ptr  \n");
1287
        else
1288
                get_Recv_data_inf_cb = recv_data_inf_cb;
1289

    
1290
}
1291

    
1292
void mlRegisterGetSendDataInf(get_send_data_inf_cb  send_data_inf_cb){
1293

    
1294
        if (send_data_inf_cb == NULL)
1295
                error("ML: Register get_send_data_inf_cb: NULL ptr  \n");
1296
        else
1297
                get_Send_data_inf_cb = send_data_inf_cb;
1298

    
1299
}
1300

    
1301
void mlRegisterSetMonitoringHeaderDataCb(set_monitoring_header_data_cb monitoring_header_data_cb){
1302

    
1303
        if (monitoring_header_data_cb == NULL)
1304
                error("ML: Register set_monitoring_header_data_cb : NULL ptr  \n");
1305
        else
1306
        set_Monitoring_header_data_cb = monitoring_header_data_cb;
1307

    
1308
}
1309

    
1310
void mlSetRecvTimeout(struct timeval timeout_value){
1311

    
1312
        recv_timeout = timeout_value;
1313

    
1314
}
1315

    
1316
int mlGetStandardTTL(socketID_handle socketID,uint8_t *ttl){
1317

    
1318
        return getTTL(socketfd, ttl);
1319

    
1320
}
1321

    
1322
socketID_handle mlGetLocalSocketID(int *errorstatus){
1323

    
1324
        if (NAT_traversal == false) {
1325
                *errorstatus = 2;
1326
                return NULL;
1327
        }
1328

    
1329
        *errorstatus = 0;
1330
        return &local_socketID;
1331

    
1332
}
1333

    
1334

    
1335
/**************************** END of MONL functions *************************/
1336

    
1337
/**************************** GENERAL functions *************************/
1338

    
1339
void mlRegisterRecvConnectionCb(receive_connection_cb recv_conn_cb){
1340

    
1341
        if (recv_conn_cb == NULL)
1342
                error("ML: Register receive_connection_cb: NULL ptr  \n");
1343
        else
1344
                receive_Connection_cb = recv_conn_cb;
1345

    
1346
}
1347

    
1348
void mlRegisterErrorConnectionCb(connection_failed_cb conn_failed){
1349

    
1350
        if (conn_failed == NULL)
1351
                error("ML: Register connection_failed_cb: NULL ptr  \n");
1352
        else
1353
        failed_Connection_cb = conn_failed;
1354

    
1355
}
1356

    
1357
void mlRegisterRecvDataCb(receive_data_cb data_cb,unsigned char msgtype){
1358

    
1359
    if (msgtype > 126) {
1360

    
1361
            error
1362
            ("ML: Could not register recv_data callback. Msgtype is greater then 126 \n");
1363

    
1364
    }
1365

    
1366
    if (data_cb == NULL) {
1367

    
1368
            error("ML: Register receive data callback: NUll ptr \n ");
1369

    
1370
    } else {
1371

    
1372
        recvcbbuf[msgtype] = data_cb;
1373

    
1374
    }
1375

    
1376
}
1377

    
1378
void mlCloseSocket(socketID_handle socketID){
1379

    
1380
        free(socketID);
1381

    
1382
}
1383

    
1384
void keepalive_fn(evutil_socket_t fd, short what, void *arg) {
1385
        socketID_handle peer = arg;
1386

    
1387
        int con_id = mlConnectionExist(peer, false);
1388
        if (con_id < 0 || connectbuf[con_id]->defaultSendParams.keepalive <= 0) {
1389
                /* Connection fell from under us or keepalive was disabled */
1390
                free(arg);
1391
                return;
1392
        }
1393

    
1394
        /* do what we gotta do */
1395
        if ( connectbuf[con_id]->status == READY) {
1396
                char keepaliveMsg[32] = "";
1397
                sprintf(keepaliveMsg, "KEEPALIVE %d", connectbuf[con_id]->keepalive_seq++);
1398
                send_msg(con_id, MSG_TYPE_ML_KEEPALIVE, keepaliveMsg, 1 + strlen(keepaliveMsg), false, 
1399
                        &(connectbuf[con_id]->defaultSendParams));
1400
        }
1401

    
1402
        /* re-schedule */
1403
        struct timeval t = { 0,0 };
1404
        t.tv_sec = connectbuf[con_id]->defaultSendParams.keepalive;
1405
        if (connectbuf[con_id]->defaultSendParams.keepalive) 
1406
                event_base_once(base, -1, EV_TIMEOUT, keepalive_fn, peer, &t);
1407
}
1408

    
1409
void setupKeepalive(int conn_id) {
1410
        /* Save the peer's address for us */
1411
        socketID_handle peer = malloc(sizeof(socket_ID));
1412
        memcpy(peer, &connectbuf[conn_id]->external_socketID, sizeof(socket_ID));
1413

    
1414
        struct timeval t = { 0,0 };
1415
        t.tv_sec = connectbuf[conn_id]->defaultSendParams.keepalive;
1416

    
1417
        if (connectbuf[conn_id]->defaultSendParams.keepalive) 
1418
                event_base_once(base, -1, EV_TIMEOUT, keepalive_fn, peer, &t);
1419
}
1420

    
1421
/* connection functions */
1422
int mlOpenConnection(socketID_handle external_socketID,receive_connection_cb connection_cb,void *arg, const send_params defaultSendParams){
1423

    
1424
        int con_id;
1425
        if (external_socketID == NULL) {
1426
                error("ML: cannot open connection: one of the socketIDs is NULL\n");
1427
                return -1;
1428
        }
1429
        if (NAT_traversal == false) {
1430
                error("ML: cannot open connection: NAT traversal for socketID still in progress\n");
1431
                return -1;
1432
        }
1433
        if (connection_cb == NULL) {
1434
                error("ML: cannot open connection: connection_cb is NULL\n");
1435
                return -1;
1436
        }
1437

    
1438
        // check if that connection already exist
1439

    
1440
        con_id = mlConnectionExist(external_socketID, false);
1441
        if (con_id >= 0) {
1442
                // overwrite defaultSendParams
1443
                bool newKeepalive = 
1444
                        connectbuf[con_id]->defaultSendParams.keepalive == 0 && defaultSendParams.keepalive != 0;
1445
                connectbuf[con_id]->defaultSendParams = defaultSendParams;
1446
                if (newKeepalive) setupKeepalive(con_id);
1447
                // if so check if it is ready to use
1448
                if (connectbuf[con_id]->status == READY) {
1449
                                // if so use the callback immediately
1450
                                (connection_cb) (con_id, arg);
1451

    
1452
                // otherwise just write the connection cb and the arg pointer
1453
                // into the connection struct
1454
                } else {
1455
                        struct receive_connection_cb_list *temp;
1456
                        temp = malloc(sizeof(struct receive_connection_cb_list));
1457
                        temp->next = NULL;
1458
                        temp->connection_cb = connection_cb;
1459
                        temp->arg = arg;
1460
                        if(connectbuf[con_id]->connection_last != NULL) {
1461
                                connectbuf[con_id]->connection_last->next = temp;
1462
                                connectbuf[con_id]->connection_last = temp;
1463
                        } else
1464
                                connectbuf[con_id]->connection_last = connectbuf[con_id]->connection_head = temp;
1465
                }
1466
                return con_id;
1467
        }
1468
        // make entry in connection_establishment array
1469
        for (con_id = 0; con_id < CONNECTBUFSIZE; con_id++) {
1470
                if (connectbuf[con_id] == NULL) {
1471
                        connectbuf[con_id] = (connect_data *) malloc(sizeof(connect_data));
1472
                        memset(connectbuf[con_id],0,sizeof(connect_data));
1473
                        connectbuf[con_id]->starttime = time(NULL);
1474
                        memcpy(&connectbuf[con_id]->external_socketID, external_socketID, sizeof(socket_ID));
1475
                        connectbuf[con_id]->pmtusize = DSLSLIM;
1476
                        connectbuf[con_id]->status = INVITE;
1477
                        connectbuf[con_id]->seqnr = 0;
1478
                        connectbuf[con_id]->internal_connect = !compare_external_address_socketIDs(external_socketID, &local_socketID);
1479
                        connectbuf[con_id]->connectionID = con_id;
1480

    
1481
                        connectbuf[con_id]->connection_head = connectbuf[con_id]->connection_last = malloc(sizeof(struct receive_connection_cb_list));
1482
                        connectbuf[con_id]->connection_last->next = NULL;
1483
                        connectbuf[con_id]->connection_last->connection_cb = connection_cb;
1484
                        connectbuf[con_id]->connection_last->arg = arg;
1485
                        connectbuf[con_id]->external_connectionID = -1;
1486

    
1487
                        connectbuf[con_id]->defaultSendParams = defaultSendParams;
1488
                        if (defaultSendParams.keepalive) setupKeepalive(con_id);
1489
                        break;
1490
                }
1491
        } //end of for
1492

    
1493
        if (con_id == CONNECTBUFSIZE) {
1494
                error("ML: Could not open connection: connection buffer full\n");
1495
                return -1;
1496
        }
1497

    
1498
        // create and send a connection message
1499
        send_conn_msg_with_pmtu_discovery(con_id, MAX, INVITE);
1500

    
1501
        return con_id;
1502

    
1503
}
1504

    
1505
void mlCloseConnection(const int connectionID){
1506

    
1507
        // remove it from the connection array
1508
        if(connectbuf[connectionID]) {
1509
                if(connectbuf[connectionID]->ctrl_msg_buf) {
1510
                        free(connectbuf[connectionID]->ctrl_msg_buf);
1511
                }
1512
                // remove related events
1513
                if (connectbuf[connectionID]->timeout_event) {
1514
                        event_del(connectbuf[connectionID]->timeout_event);
1515
                        event_free(connectbuf[connectionID]->timeout_event);
1516
                }
1517
                free(connectbuf[connectionID]);
1518
                connectbuf[connectionID] = NULL;
1519
        }
1520

    
1521
}
1522

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

    
1525
        if (connectionID < 0) {
1526
                error("ML: send data failed: connectionID does not exist\n");
1527
                return;
1528
        }
1529

    
1530
        if (connectbuf[connectionID] == NULL) {
1531
                error("ML: send data failed: connectionID does not exist\n");
1532
                return;
1533
        }
1534
        if (connectbuf[connectionID]->status != READY) {
1535
            error("ML: send data failed: connection is not active\n");
1536
            return;
1537
        }
1538

    
1539
        if (sParams == NULL) {
1540
                sParams = &(connectbuf[connectionID]->defaultSendParams);
1541
        }
1542

    
1543
        send_msg(connectionID, msgtype, sendbuf, bufsize, false, sParams);
1544

    
1545
}
1546

    
1547
/* transmit data functions  */
1548
int mlSendAllData(const int connectionID,send_all_data_container *container,int nr_entries,unsigned char msgtype,send_params *sParams){
1549

    
1550
    if (nr_entries < 1 || nr_entries > 5) {
1551

    
1552
        error
1553
            ("ML : sendALlData : nr_enties is not between 1 and 5 \n ");
1554
        return 0;
1555

    
1556
    } else {
1557

    
1558
        if (nr_entries == 1) {
1559

    
1560
                mlSendData(connectionID, container->buffer_1,
1561
                      container->length_1, msgtype, sParams);
1562

    
1563
            return 1;
1564

    
1565
        } else if (nr_entries == 2) {
1566

    
1567
            int buflen = container->length_1 + container->length_2;
1568
            char buf[buflen];
1569
            memcpy(buf, container->buffer_1, container->length_1);
1570
            memcpy(&buf[container->length_1], container->buffer_2,
1571
                   container->length_2);
1572
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1573

    
1574
            return 1;
1575

    
1576
        } else if (nr_entries == 3) {
1577

    
1578
            int buflen =
1579
                container->length_1 + container->length_2 +
1580
                container->length_3;
1581
            char buf[buflen];
1582
            memcpy(buf, container->buffer_1, container->length_1);
1583
            memcpy(&buf[container->length_1], container->buffer_2,
1584
                   container->length_2);
1585
            memcpy(&buf[container->length_2], container->buffer_3,
1586
                   container->length_3);
1587
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1588

    
1589

    
1590
            return 1;
1591

    
1592
        } else if (nr_entries == 4) {
1593

    
1594
            int buflen =
1595
                container->length_1 + container->length_2 +
1596
                container->length_3 + container->length_4;
1597
            char buf[buflen];
1598
            memcpy(buf, container->buffer_1, container->length_1);
1599
            memcpy(&buf[container->length_1], container->buffer_2,
1600
                   container->length_2);
1601
            memcpy(&buf[container->length_2], container->buffer_3,
1602
                   container->length_3);
1603
            memcpy(&buf[container->length_3], container->buffer_4,
1604
                   container->length_4);
1605
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1606

    
1607
            return 1;
1608

    
1609
        } else {
1610

    
1611
            int buflen =
1612
                container->length_1 + container->length_2 +
1613
                container->length_3 + container->length_4 +
1614
                container->length_5;
1615
            char buf[buflen];
1616
            memcpy(buf, container->buffer_1, container->length_1);
1617
            memcpy(&buf[container->length_1], container->buffer_2,
1618
                   container->length_2);
1619
            memcpy(&buf[container->length_2], container->buffer_3,
1620
                   container->length_3);
1621
            memcpy(&buf[container->length_3], container->buffer_4,
1622
                   container->length_4);
1623
            memcpy(&buf[container->length_4], container->buffer_5,
1624
                   container->length_5);
1625
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1626

    
1627
            return 1;
1628
        }
1629

    
1630
    }
1631

    
1632
}
1633

    
1634
int mlRecvData(const int connectionID,char *recvbuf,int *bufsize,recv_params *rParams){
1635

    
1636
        //TODO yet to be converted
1637
        return 0;
1638
#if 0
1639
        if (rParams == NULL) {
1640
                error("ML: recv_data failed: recv_params is a NULL ptr\n");
1641
                return 0;
1642
    } else {
1643

1644
        info("ML: recv data called \n");
1645

1646
        int i = 0;
1647
        int returnValue = 0;
1648
        double timeout = (double) recv_timeout.tv_sec;
1649
        time_t endtime = time(NULL);
1650

1651
        for (i = 0; i < RECVDATABUFSIZE; i++) {
1652

1653
            if (recvdatabuf[i] != NULL) {
1654

1655
                if (recvdatabuf[i]->connectionID == connectionID) {
1656

1657
                    info("ML: recv data has entry  \n");
1658

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

1661
                    // check if the specified connection has data and it
1662
                    // is complete
1663
                    // check the data seqnr
1664
                    // if(connectionID == recvdatabuf[i]->connectionID &&
1665
                    // 1 == recvdatabuf[i]->status){
1666

1667
                    if (1 == recvdatabuf[i]->status) {
1668

1669
                        // info("transmissionHandler: recv_data set is
1670
                        // complete \n" );
1671

1672
                        // debug("debud \n");
1673

1674
                        // exchange the pointers
1675
                        int buffersize = 0;
1676
                        buffersize = recvdatabuf[i]->bufsize;
1677
                        *bufsize = buffersize;
1678
                        // recvbuf = recvdatabuf[i]->recvbuf;
1679

1680
                        // info("buffersize %d \n",buffersize);
1681
                        memcpy(recvbuf, recvdatabuf[i]->recvbuf,
1682
                               buffersize);
1683
                        // debug(" recvbuf %s \n",recvbuf );
1684

1685
//                         double nrMissFrags =
1686
//                             (double) recvdatabuf[i]->nrFragments /
1687
//                             (double) recvdatabuf[i]->recvFragments;
1688
//                         int nrMissingFragments = (int) ceil(nrMissFrags);
1689

1690
//                        rParams->nrMissingFragments = nrMissingFragments;
1691
//                         rParams->nrFragments = recvdatabuf[i]->nrFragments;
1692
                        rParams->msgtype = recvdatabuf[i]->msgtype;
1693
                        rParams->connectionID =
1694
                            recvdatabuf[i]->connectionID;
1695

1696
                        // break from the loop
1697
                        // debug(" recvbuf %s \n ",recvbuf);
1698

1699
                        // double nrMissFrags =
1700
                        // (double)recvdatabuf[i]->nrFragments /
1701
                        // (double)recvdatabuf[i]->recvFragments;
1702
                        // int nrMissingFragments =
1703
                        // (int)ceil(nrMissFrags);
1704

1705
                        if(get_Recv_data_inf_cb != NULL) {
1706
                                mon_data_inf recv_data_inf;
1707

1708
                                recv_data_inf.remote_socketID = &(connectbuf[connectionID]->external_socketID);
1709
                                recv_data_inf.buffer = recvdatabuf[i]->recvbuf;
1710
                                recv_data_inf.bufSize = recvdatabuf[i]->bufsize;
1711
                                recv_data_inf.msgtype = recvdatabuf[i]->msgtype;
1712
//                                 recv_data_inf.monitoringHeaderType = recvdatabuf[i]->monitoringHeaderType;
1713
//                                 recv_data_inf.monitoringDataHeader = recvdatabuf[i]->monitoringDataHeader;
1714
                                gettimeofday(&recv_data_inf.arrival_time, NULL);
1715
                                recv_data_inf.firstPacketArrived = recvdatabuf[i]->firstPacketArrived;
1716
                                recv_data_inf.nrMissingFragments = nrMissingFragments;
1717
                                recv_data_inf.nrFragments = recvdatabuf[i]->nrFragments;
1718
                                recv_data_inf.priority = false;
1719
                                recv_data_inf.padding = false;
1720
                                recv_data_inf.confirmation = false;
1721
                                recv_data_inf.reliable = false;
1722

1723
                                // send data recv callback to monitoring module
1724

1725
                                (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
1726
                        }
1727

1728

1729
                        // free the allocated memory
1730
                        free(recvdatabuf[i]);
1731
                        recvdatabuf[i] = NULL;
1732

1733
                        returnValue = 1;
1734
                        break;
1735

1736
                    }
1737

1738
                    if (recvdatabuf[i] != NULL) {
1739

1740
                        if (timepass > timeout) {
1741

1742
                            info("ML: recv_data timeout called  \n");
1743

1744
                            // some data about the missing chunks should
1745
                            // be added here
1746
                            // exchange the pointers
1747
                            int buffersize = 0;
1748
                            buffersize = recvdatabuf[i]->bufsize;
1749
                            *bufsize = buffersize;
1750
                            // recvbuf = recvdatabuf[i]->recvbuf;
1751

1752
                            double nrMissFrags =
1753
                                (double) recvdatabuf[i]->nrFragments /
1754
                                (double) recvdatabuf[i]->recvFragments;
1755
                            int nrMissingFragments =
1756
                                (int) ceil(nrMissFrags);
1757

1758
                            // debug(" recvbuf %s \n",recvbuf );
1759

1760
                            memcpy(recvbuf, recvdatabuf[i]->recvbuf,
1761
                                   buffersize);
1762

1763
                            rParams->nrMissingFragments =
1764
                                nrMissingFragments;
1765
                            rParams->nrFragments =
1766
                                recvdatabuf[i]->nrFragments;
1767
                            rParams->msgtype = recvdatabuf[i]->msgtype;
1768
                            rParams->connectionID =
1769
                                recvdatabuf[i]->connectionID;
1770

1771
                                if(get_Recv_data_inf_cb != NULL) {
1772
                                        mon_data_inf recv_data_inf;
1773

1774
                                        recv_data_inf.remote_socketID = &(connectbuf[connectionID]->external_socketID);
1775
                                        recv_data_inf.buffer = recvdatabuf[i]->recvbuf;
1776
                                        recv_data_inf.bufSize = recvdatabuf[i]->bufsize;
1777
                                        recv_data_inf.msgtype = recvdatabuf[i]->msgtype;
1778
                                        recv_data_inf.monitoringHeaderType = recvdatabuf[i]->monitoringHeaderType;
1779
                                        recv_data_inf.monitoringDataHeader = recvdatabuf[i]->monitoringDataHeader;
1780
                                        gettimeofday(&recv_data_inf.arrival_time, NULL);
1781
                                        recv_data_inf.firstPacketArrived = recvdatabuf[i]->firstPacketArrived;
1782
                                        recv_data_inf.nrMissingFragments = nrMissingFragments;
1783
                                        recv_data_inf.nrFragments = recvdatabuf[i]->nrFragments;
1784
                                        recv_data_inf.priority = false;
1785
                                        recv_data_inf.padding = false;
1786
                                        recv_data_inf.confirmation = false;
1787
                                        recv_data_inf.reliable = false;
1788

1789
                                        // send data recv callback to monitoring module
1790

1791
                                        (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
1792
                                }
1793

1794
                            // free the allocated memory
1795
                            free(recvdatabuf[i]);
1796
                            recvdatabuf[i] = NULL;
1797

1798
                            returnValue = 1;
1799
                            break;
1800

1801
                        }
1802
                    }
1803

1804
                }
1805

1806
            }
1807
            // debug("2 recvbuf %s \n ",recvbuf);
1808
        }
1809
        return returnValue;
1810
    }
1811
#endif
1812

    
1813
}
1814

    
1815
int mlSocketIDToString(socketID_handle socketID,char* socketID_string, size_t len){
1816

    
1817
        char internal_addr[INET_ADDRSTRLEN];
1818
        char external_addr[INET_ADDRSTRLEN];
1819
        inet_ntop(AF_INET, &(socketID->internal_addr.udpaddr.sin_addr.s_addr), internal_addr, INET_ADDRSTRLEN);
1820
        inet_ntop(AF_INET, &(socketID->external_addr.udpaddr.sin_addr.s_addr), external_addr, INET_ADDRSTRLEN);
1821

    
1822
        snprintf(socketID_string,len,"%s:%d-%s:%d", internal_addr, ntohs(socketID->internal_addr.udpaddr.sin_port),
1823
                external_addr,        ntohs(socketID->external_addr.udpaddr.sin_port));
1824
        return 0;
1825

    
1826
}
1827

    
1828
int mlStringToSocketID(const char* socketID_string, socketID_handle socketID){
1829

    
1830
        //@TODO add checks against malformed string
1831
        char external_addr[INET_ADDRSTRLEN];
1832
        int external_port;
1833
        char internal_addr[INET_ADDRSTRLEN];
1834
        int internal_port;
1835

    
1836
        char *pch;
1837
        char *s = strdup(socketID_string);
1838

    
1839
        //replace ':' with a blank
1840
        pch=strchr(s,':');
1841
        while (pch!=NULL){
1842
                                *pch = ' ';
1843
                pch=strchr(pch+1,':');
1844
        }
1845
        pch=strchr(s,'-');
1846
        if(pch) *pch = ' ';
1847

    
1848
        sscanf(s,"%s %d %s %d", internal_addr, &internal_port,
1849
                external_addr, &external_port);
1850

    
1851
        if(inet_pton(AF_INET, internal_addr, &(socketID->internal_addr.udpaddr.sin_addr)) == 0)
1852
                return EINVAL;
1853
        socketID->internal_addr.udpaddr.sin_family = AF_INET;
1854
        socketID->internal_addr.udpaddr.sin_port = htons(internal_port);
1855

    
1856

    
1857
        if(inet_pton(AF_INET, external_addr, &(socketID->external_addr.udpaddr.sin_addr)) ==0)
1858
                return EINVAL;
1859
        socketID->external_addr.udpaddr.sin_family = AF_INET;
1860
        socketID->external_addr.udpaddr.sin_port = htons(external_port);
1861

    
1862
        free(s);
1863
        return 0;
1864

    
1865
}
1866

    
1867
int mlGetConnectionStatus(int connectionID){
1868

    
1869
        if(connectbuf[connectionID])
1870
                return connectbuf[connectionID]->status == READY;
1871
        return -1;
1872
    
1873
}
1874

    
1875

    
1876
int mlConnectionExist(socketID_handle socketID, bool ready){
1877

    
1878
    /*
1879
     * check if another connection for the external connectionID exist
1880
     * that was established \ within the last 2 seconds
1881
     */
1882
        int i;
1883
        for (i = 0; i < CONNECTBUFSIZE; i++)
1884
                if (connectbuf[i] != NULL)
1885
                        if (mlCompareSocketIDs(&(connectbuf[i]->external_socketID), socketID) == 0) {
1886
                                if (ready) return (connectbuf[i]->status == READY ? i : -1);;
1887
                                return i;
1888
                                }
1889

    
1890
    return -1;
1891

    
1892
}
1893

    
1894
//Added by Robert Birke as comodity functions
1895

    
1896
//int mlPrintSocketID(socketID_handle socketID) {
1897
//        char str[SOCKETID_STRING_SIZE];
1898
//        mlSocketIDToString(socketID, str, sizeof(str));
1899
//        printf(stderr,"int->%s<-ext\n",str);
1900
//}
1901

    
1902
/*
1903
 * hash code of a socketID
1904
 * TODO might think of a better way
1905
 */
1906
int mlHashSocketID(socketID_handle sock) {
1907
    return sock->internal_addr.udpaddr.sin_port +
1908
                          sock->external_addr.udpaddr.sin_port;
1909
}
1910

    
1911
int mlCompareSocketIDs(socketID_handle sock1, socketID_handle sock2) {
1912
        /*
1913
        * compare internal addr
1914
        */
1915
        if (sock1->internal_addr.udpaddr.sin_addr.s_addr !=
1916
            sock2->internal_addr.udpaddr.sin_addr.s_addr)
1917
                        return 1;
1918

    
1919
        if (sock1->internal_addr.udpaddr.sin_port !=
1920
                 sock2->internal_addr.udpaddr.sin_port)
1921
                        return 1;
1922

    
1923
        /*
1924
        * compare external addr
1925
        */
1926
        if (sock1->external_addr.udpaddr.sin_addr.s_addr !=
1927
            sock2->external_addr.udpaddr.sin_addr.s_addr)
1928
                        return 1;
1929

    
1930
        if (sock1->external_addr.udpaddr.sin_port !=
1931
                 sock2->external_addr.udpaddr.sin_port)
1932
                        return 1;
1933

    
1934
        return 0;
1935
}
1936

    
1937
int mlCompareSocketIDsByPort(socketID_handle sock1, socketID_handle sock2)
1938
{ 
1939
        if (sock1->internal_addr.udpaddr.sin_port !=
1940
                 sock2->internal_addr.udpaddr.sin_port)
1941
                        return 1;
1942

    
1943
        if (sock1->external_addr.udpaddr.sin_port !=
1944
                 sock2->external_addr.udpaddr.sin_port)
1945
                        return 1;
1946
        return 0;
1947
}
1948

    
1949
int mlGetPathMTU(int ConnectionId) {
1950
        if(ConnectionId < 0 || ConnectionId >= CONNECTBUFSIZE)
1951
                return -1;
1952
        if (connectbuf[ConnectionId] != NULL)
1953
                return connectbuf[ConnectionId]->pmtusize;
1954
        return -1;
1955
}
1956

    
1957
/**************************** END of GENERAL functions *************************/
1958

    
1959
/**************************** NAT functions *************************/
1960

    
1961
/* setter  */
1962
void mlSetStunServer(const int port,const char *ipaddr){
1963

    
1964
        stun_server.sin_family = AF_INET;
1965
        if (ipaddr == NULL)
1966
                stun_server.sin_addr.s_addr = htonl(INADDR_ANY);
1967
        else
1968
                stun_server.sin_addr.s_addr = resolve(ipaddr);
1969
        stun_server.sin_port = htons(port);
1970

    
1971
}
1972

    
1973
int mlGetExternalIP(char* external_addr){
1974

    
1975
        socketaddrgen udpgen;
1976
        struct sockaddr_in udpaddr;
1977

    
1978
        udpgen = local_socketID.external_addr;
1979
        udpaddr = udpgen.udpaddr;
1980

    
1981
        inet_ntop(AF_INET, &(udpaddr.sin_addr), external_addr,
1982
                        INET_ADDRSTRLEN);
1983

    
1984
        if (external_addr == NULL) {
1985

    
1986
        return -1;
1987

    
1988
        } else {
1989

    
1990
        return 0;
1991

    
1992
        }
1993

    
1994
}
1995

    
1996
/**************************** END of NAT functions *************************/