Statistics
| Branch: | Revision:

ml / ml.c @ 1f8ebe96

History | View | Annotate | Download (59.2 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_HEADER_SPACE];
227
        char h_data[MON_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
                        sd_data_inf.remote_socketID = &(connectbuf[con_id]->external_socketID);
265
                        sd_data_inf.buffer = msg;
266
                        sd_data_inf.bufSize = msg_len;
267
                        sd_data_inf.msgtype = msg_type;
268
                        sd_data_inf.monitoringDataHeader = iov[2].iov_base;
269
                        sd_data_inf.monitoringDataHeaderLen = iov[2].iov_len;
270
                        sd_data_inf.priority = sParams->priority;
271
                        sd_data_inf.padding = sParams->padding;
272
                        sd_data_inf.confirmation = sParams->confirmation;
273
                        sd_data_inf.reliable = sParams->reliable;
274
                        memset(&sd_data_inf.arrival_time, 0, sizeof(struct timeval));
275

    
276
                        (get_Send_data_inf_cb) ((void *) &sd_data_inf);
277
                }
278

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

    
285
                        iov[3].iov_len = pkt_len;
286
                        iov[3].iov_base = msg + offset;
287

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

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

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

    
309
                                (get_Send_pkt_inf_cb) ((void *) &pkt_info);
310
                        }
311

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

    
339
void pmtu_timeout_cb(int fd, short event, void *arg);
340

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

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

    
359
        if(connectbuf[con_id]->ctrl_msg_buf == NULL) {
360
                connectbuf[con_id]->ctrl_msg_buf = malloc(buf_size);
361
                memset(connectbuf[con_id]->ctrl_msg_buf, 0, buf_size);
362
        }
363

    
364
        if(connectbuf[con_id]->ctrl_msg_buf == NULL) {
365
                error("ML: can not allocate memory for connection message\n");
366
                return;
367
        }
368

    
369
        struct conn_msg *msg_header = (struct conn_msg*) connectbuf[con_id]->ctrl_msg_buf;
370

    
371
        msg_header->comand_type = command_type;
372
        msg_header->pmtu_size = connectbuf[con_id]->pmtusize;
373

    
374
        memcpy(&(msg_header->sock_id), loc_socketID, sizeof(socket_ID));
375

    
376
        send_msg(con_id, ML_CON_MSG, connectbuf[con_id]->ctrl_msg_buf, buf_size, true, &(connectbuf[con_id]->defaultSendParams));
377
}
378

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

    
388
void resend_conn_msg(int con_id)
389
{
390
        connectbuf[con_id]->trials++;
391
        send_conn_msg(con_id, connectbuf[con_id]->pmtusize, connectbuf[con_id]->status);
392
        reschedule_conn_msg(con_id);
393
}
394

    
395
void
396
recv_conn_msg(struct msg_header *msg_h, char *msgbuf, int msg_size)
397
{
398
        struct conn_msg *con_msg;
399
        int free_con_id, con_id;
400

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

    
427
                // send data recv callback to monitoring module
428
                (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
429
        }
430

    
431
        //decode sock_id for debug messages
432
        mlSocketIDToString(&con_msg->sock_id,str,999);
433

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

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

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

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

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

    
507
                                // send the READY
508
                                send_conn_msg_with_pmtu_discovery(msg_h->remote_con_id, con_msg->pmtu_size, READY);
509

    
510
                                if (receive_Connection_cb != NULL)
511
                                        (receive_Connection_cb) (msg_h->remote_con_id, NULL);
512

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

    
528
                        debug("ML: active connection established\n");
529
                        break;
530

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

    
550
                                if (receive_Connection_cb != NULL)
551
                                        (receive_Connection_cb) (msg_h->remote_con_id, NULL);
552

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

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

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

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

    
605
        if (recvdatabuf[recv_id] == NULL) {
606
                return;
607
        }
608

    
609

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

    
620
        if(recvdatabuf[recv_id]->status == ACTIVE) {
621
                // Monitoring layer hook
622
                if(get_Recv_data_inf_cb != NULL) {
623
                        mon_data_inf recv_data_inf;
624

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

    
641
                        // send data recv callback to monitoring module
642

    
643
                        (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
644
                }
645

    
646
                // Get the right callback
647
                receive_data_cb receive_data_callback = recvcbbuf[recvdatabuf[recv_id]->msgtype];
648

    
649
                recv_params rParams;
650

    
651
                rParams.nrMissingBytes = recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->arrivedBytes;
652
                rParams.recvFragments = recvdatabuf[recv_id]->recvFragments;
653
                rParams.msgtype = recvdatabuf[recv_id]->msgtype;
654
                rParams.connectionID = recvdatabuf[recv_id]->connectionID;
655
                rParams.remote_socketID =
656
                        &(connectbuf[recvdatabuf[recv_id]->connectionID]->external_socketID);
657
                rParams.firstPacketArrived = recvdatabuf[recv_id]->firstPacketArrived;
658

    
659
                (receive_data_callback) (recvdatabuf[recv_id]->recvbuf + recvdatabuf[recv_id]->monitoringDataHeaderLen, recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->monitoringDataHeaderLen,
660
                        recvdatabuf[recv_id]->msgtype, &rParams);
661

    
662
                //clean up
663
                if (recvdatabuf[recv_id]->timeout_event) {
664
                        event_del(recvdatabuf[recv_id]->timeout_event);
665
                        event_free(recvdatabuf[recv_id]->timeout_event);
666
                        recvdatabuf[recv_id]->timeout_event = NULL;
667
                }
668
                free(recvdatabuf[recv_id]->recvbuf);
669
                free(recvdatabuf[recv_id]);
670
                recvdatabuf[recv_id] = NULL;
671
        }
672
}
673

    
674
// process a single recv data message
675
void recv_data_msg(struct msg_header *msg_h, char *msgbuf, int bufsize)
676
{
677
        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);
678

    
679
        int recv_id, free_recv_id = -1;
680

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

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

    
696

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

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

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

    
730

    
731
        // increment fragmentnr
732
        recvdatabuf[recv_id]->recvFragments++;
733
        // increment the arrivedBytes
734
        recvdatabuf[recv_id]->arrivedBytes += bufsize;
735

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

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

    
745
        if (recv_data_callback) {
746
                if(recvdatabuf[recv_id]->status == COMPLETE) {
747
                        // Monitoring layer hook
748
                        if(get_Recv_data_inf_cb != NULL) {
749
                                mon_data_inf recv_data_inf;
750

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

    
767
                                // send data recv callback to monitoring module
768

    
769
                                (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
770
                        }
771

    
772
                        // Get the right callback
773
                        receive_data_cb receive_data_callback = recvcbbuf[msg_h->msg_type];
774
                        if (receive_data_callback) {
775

    
776
                                recv_params rParams;
777

    
778
                                rParams.nrMissingBytes = recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->arrivedBytes;
779
                                rParams.recvFragments = recvdatabuf[recv_id]->recvFragments;
780
                                rParams.msgtype = recvdatabuf[recv_id]->msgtype;
781
                                rParams.connectionID = recvdatabuf[recv_id]->connectionID;
782
                                rParams.remote_socketID =
783
                                        &(connectbuf[recvdatabuf[recv_id]->connectionID]->external_socketID);
784

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

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

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

    
819
//done
820
void pmtu_timeout_cb(int fd, short event, void *arg)
821
{
822

    
823
        int con_id = (long) arg;
824
        pmtu new_pmtusize;
825

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

    
828
        if(connectbuf[con_id] == NULL) {
829
                error("ML: pmtu timeout called on non existing con_id\n");
830
                return;
831
        }
832

    
833
        if(connectbuf[con_id]->status == READY) {
834
                // nothing to do anymore
835
                event_del(connectbuf[con_id]->timeout_event);
836
                event_free(connectbuf[con_id]->timeout_event);
837
                connectbuf[con_id]->timeout_event = NULL;
838
                return;
839
        }
840

    
841
        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);
842

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

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

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

    
882
        //retry
883
        resend_conn_msg(con_id);
884
}
885

    
886

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

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

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

    
930
    char *msgbufptr = NULL;
931
    int msgtype;
932
    int connectionID;
933
    pmtu pmtusize;
934
    pmtu new_pmtusize;
935
    int dead = 0;
936

    
937
    // check the packettype
938
    msgbufptr = &msg[0];
939

    
940
    // check the msgtype
941
    msgbufptr = &msg[1];
942
    memcpy(&msgtype, msgbufptr, 4);
943

    
944
    if (msgtype == 0) {
945

    
946
        // get the connectionID
947
        msgbufptr = &msg[5];
948
        memcpy(&connectionID, msgbufptr, 4);
949

    
950
        int msgtype_c = connectbuf[connectionID]->status;
951
//        pmtusize = connectbuf[connectionID]->pmtutrysize;
952

    
953
        if (msgtype_c != msgtype) {
954
            dead = 1;
955
        }
956

    
957

    
958
    } else if (msgtype == 1) {
959

    
960
        // read the connectionID
961
        msgbufptr = &msg[9];
962
        memcpy(&connectionID, msgbufptr, 4);
963

    
964
        int msgtype_c = connectbuf[connectionID]->status;
965
//        pmtusize = connectbuf[connectionID]->pmtutrysize;
966

    
967
        if (msgtype_c != msgtype) {
968
            dead = 1;
969
        }
970

    
971
    }
972
    // decrement the pmtu size
973
    new_pmtusize = pmtu_decrement(pmtusize);
974

    
975
//    connectbuf[connectionID]->pmtutrysize = new_pmtusize;
976

    
977
    if (new_pmtusize == ERROR) {
978
                error("ML:  Could not create connection with connectionID %i !\n",
979
                        connectionID);
980

    
981
                if(failed_Connection_cb != NULL)
982
                        (failed_Connection_cb) (connectionID, NULL);
983
                // set the message type to a non existent message
984
                msgtype = 2;
985
                // delete the connection entry
986
                 mlCloseConnection(connectionID);
987
        }
988

    
989
    if (msgtype == 0 && dead != 1) {
990

    
991
        // stop the timeout event
992
        // timeout_del(connectbuf[connectionID]->timeout);
993
        /*
994
         * libevent2
995
         */
996

    
997
        // event_del(connectbuf[connectionID]->timeout);
998

    
999

    
1000
        // create and send a connection message
1001
//         create_conn_msg(new_pmtusize, connectionID,
1002
//                         &local_socketID, INVITE);
1003

    
1004
//        send_conn_msg(connectionID, new_pmtusize);
1005

    
1006
        // set a timeout event for the pmtu discovery
1007
        // timeout_set(connectbuf[connectionID]->timeout,pmtu_timeout_cb,(void
1008
        // *)&connectionID);
1009

    
1010
        // timeout_add(connectbuf[connectionID]->timeout,&connectbuf[connectionID]->timeout_value);
1011

    
1012
        /*
1013
         * libevent2
1014
         */
1015

    
1016
        struct event *ev;
1017
        ev = evtimer_new(base, pmtu_timeout_cb,
1018
                         (void *) connectbuf[connectionID]);
1019

    
1020
        // connectbuf[connectionID]->timeout = ev;
1021

    
1022
        event_add(ev, &connectbuf[connectionID]->timeout_value);
1023

    
1024
    } else if (msgtype == 1 && dead != 1) {
1025

    
1026
        // stop the timeout event
1027
        // timeout_del(connectbuf[connectionID]->timeout);
1028

    
1029
        /*
1030
         * libevent2
1031
         */
1032
        // info("still here 11 \n");
1033
        // printf("ev %d \n",connectbuf[connectionID]->timeout);
1034
        // event_del(connectbuf[connectionID]->timeout );
1035
        // evtimer_del(connectbuf[connectionID]->timeout );
1036

    
1037

    
1038
//         // create and send a connection message
1039
//         create_conn_msg(new_pmtusize,
1040
//                         connectbuf[connectionID]->connectionID,
1041
//                         NULL, CONNECT);
1042

    
1043
        //send_conn_msg(connectionID, new_pmtusize);
1044

    
1045
        // set a timeout event for the pmtu discovery
1046
        // timeout_set(connectbuf[connectionID]->timeout,pmtu_timeout_cb,(void
1047
        // *)&connectionID);
1048
        // timeout_add(connectbuf[connectionID]->timeout,&connectbuf[connectionID]->timeout_value);
1049

    
1050
        /*
1051
         * libevent2
1052
         */
1053
        // struct event *ev;
1054
        // ev = evtimer_new(base,pmtu_timeout_cb, (void
1055
        // *)connectbuf[connectionID]);
1056
        // connectbuf[connectionID]->timeout = ev;
1057
        // event_add(ev,&connectbuf[connectionID]->timeout_value);
1058

    
1059
    }
1060
}
1061

    
1062
/*
1063
 * what to do once a packet arrived if it is a conn packet send it to
1064
 * recv_conn handler if it is a data packet send it to the recv_data
1065
 * handler
1066
 */
1067

    
1068
//done --
1069
void recv_pkg(int fd, short event, void *arg)
1070
{
1071
        debug("ML: recv_pkg called\n");
1072

    
1073
        struct msg_header *msg_h;
1074
        char msgbuf[MAX];
1075
        pmtu recvSize = MAX;
1076
        char *bufptr = msgbuf;
1077
        int ttl;
1078
        struct sockaddr_in recv_addr;
1079
        int msg_size;
1080

    
1081
        recvPacket(fd, msgbuf, &recvSize, &recv_addr, pmtu_error_cb_th, &ttl);
1082

    
1083

    
1084
        // check if it is not just an ERROR message
1085
        if(recvSize < 0)
1086
                return;
1087

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

    
1097
        msg_h = (struct msg_header *) msgbuf;
1098
        bufptr += MSG_HEADER_SIZE + msg_h->len_mon_packet_hdr;
1099
        msg_size = recvSize - MSG_HEADER_SIZE - msg_h->len_mon_packet_hdr;
1100

    
1101

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

    
1127

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

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

    
1155
void try_stun();
1156

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

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

    
1182

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

    
1206
        socketaddrgen udpgen;
1207
        memset(&udpgen,0,sizeof(socketaddrgen));        //this will be sent over the net, so set it to 0
1208
        udpgen.udpaddr = udpaddr;
1209
        local_socketID.internal_addr = udpgen;
1210

    
1211
        socketfd = createSocket(port, ipaddr);
1212
        if (socketfd < 0){
1213
                return socketfd;
1214
        }
1215

    
1216
        struct event *ev;
1217
        ev = event_new(base, socketfd, EV_READ | EV_PERSIST, recv_pkg, NULL);
1218

    
1219
        event_add(ev, NULL);
1220

    
1221
        try_stun();
1222

    
1223
        return socketfd;
1224
}
1225

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

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

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

    
1259
/**************************** END OF INTERNAL ***********************/
1260

    
1261
/**************************** MONL functions *************************/
1262

    
1263
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){
1264

    
1265
        base = (struct event_base *) arg;
1266
        recv_data_callback = recv_data_cb;
1267
        mlSetRecvTimeout(timeout_value);
1268
        if (stun_ipaddr) {
1269
                 mlSetStunServer(stun_port, stun_ipaddr);
1270
        } else {
1271

    
1272
        }
1273
        register_recv_localsocketID_cb(local_socketID_cb);
1274
        return create_socket(port, ipaddr);
1275
}
1276

    
1277
/* register callbacks  */
1278
void mlRegisterGetRecvPktInf(get_recv_pkt_inf_cb recv_pkt_inf_cb){
1279

    
1280
        if (recv_pkt_inf_cb == NULL)
1281
                error("ML: Register get_recv_pkt_inf_cb failed: NULL ptr  \n");
1282
        else
1283
                get_Recv_pkt_inf_cb = recv_pkt_inf_cb;
1284

    
1285
}
1286

    
1287
void mlRegisterGetSendPktInf(get_send_pkt_inf_cb  send_pkt_inf_cb){
1288

    
1289
        if (send_pkt_inf_cb == NULL)
1290
                error("ML: Register get_send_pkt_inf_cb: NULL ptr  \n");
1291
        else
1292
                get_Send_pkt_inf_cb = send_pkt_inf_cb;
1293

    
1294
}
1295

    
1296

    
1297
void mlRegisterSetMonitoringHeaderPktCb(set_monitoring_header_pkt_cb monitoring_header_pkt_cb ){
1298

    
1299
        if (monitoring_header_pkt_cb == NULL)
1300
                error("ML: Register set_monitoring_header_pkt_cb: NULL ptr  \n");
1301
        else
1302
                set_Monitoring_header_pkt_cb = monitoring_header_pkt_cb;
1303

    
1304
}
1305

    
1306
void mlRegisterGetRecvDataInf(get_recv_data_inf_cb recv_data_inf_cb){
1307

    
1308
        if (recv_data_inf_cb == NULL)
1309
                error("ML: Register get_recv_data_inf_cb: NULL ptr  \n");
1310
        else
1311
                get_Recv_data_inf_cb = recv_data_inf_cb;
1312

    
1313
}
1314

    
1315
void mlRegisterGetSendDataInf(get_send_data_inf_cb  send_data_inf_cb){
1316

    
1317
        if (send_data_inf_cb == NULL)
1318
                error("ML: Register get_send_data_inf_cb: NULL ptr  \n");
1319
        else
1320
                get_Send_data_inf_cb = send_data_inf_cb;
1321

    
1322
}
1323

    
1324
void mlRegisterSetMonitoringHeaderDataCb(set_monitoring_header_data_cb monitoring_header_data_cb){
1325

    
1326
        if (monitoring_header_data_cb == NULL)
1327
                error("ML: Register set_monitoring_header_data_cb : NULL ptr  \n");
1328
        else
1329
        set_Monitoring_header_data_cb = monitoring_header_data_cb;
1330

    
1331
}
1332

    
1333
void mlSetRecvTimeout(struct timeval timeout_value){
1334

    
1335
        recv_timeout = timeout_value;
1336

    
1337
}
1338

    
1339
int mlGetStandardTTL(socketID_handle socketID,uint8_t *ttl){
1340

    
1341
        return getTTL(socketfd, ttl);
1342

    
1343
}
1344

    
1345
socketID_handle mlGetLocalSocketID(int *errorstatus){
1346

    
1347
        if (NAT_traversal == false) {
1348
                *errorstatus = 2;
1349
                return NULL;
1350
        }
1351

    
1352
        *errorstatus = 0;
1353
        return &local_socketID;
1354

    
1355
}
1356

    
1357

    
1358
/**************************** END of MONL functions *************************/
1359

    
1360
/**************************** GENERAL functions *************************/
1361

    
1362
void mlRegisterRecvConnectionCb(receive_connection_cb recv_conn_cb){
1363

    
1364
        if (recv_conn_cb == NULL)
1365
                error("ML: Register receive_connection_cb: NULL ptr  \n");
1366
        else
1367
                receive_Connection_cb = recv_conn_cb;
1368

    
1369
}
1370

    
1371
void mlRegisterErrorConnectionCb(connection_failed_cb conn_failed){
1372

    
1373
        if (conn_failed == NULL)
1374
                error("ML: Register connection_failed_cb: NULL ptr  \n");
1375
        else
1376
        failed_Connection_cb = conn_failed;
1377

    
1378
}
1379

    
1380
void mlRegisterRecvDataCb(receive_data_cb data_cb,unsigned char msgtype){
1381

    
1382
    if (msgtype > 126) {
1383

    
1384
            error
1385
            ("ML: Could not register recv_data callback. Msgtype is greater then 126 \n");
1386

    
1387
    }
1388

    
1389
    if (data_cb == NULL) {
1390

    
1391
            error("ML: Register receive data callback: NUll ptr \n ");
1392

    
1393
    } else {
1394

    
1395
        recvcbbuf[msgtype] = data_cb;
1396

    
1397
    }
1398

    
1399
}
1400

    
1401
void mlCloseSocket(socketID_handle socketID){
1402

    
1403
        free(socketID);
1404

    
1405
}
1406

    
1407
void keepalive_fn(evutil_socket_t fd, short what, void *arg) {
1408
        socketID_handle peer = arg;
1409

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

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

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

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

    
1437
        struct timeval t = { 0,0 };
1438
        t.tv_sec = connectbuf[conn_id]->defaultSendParams.keepalive;
1439

    
1440
        if (connectbuf[conn_id]->defaultSendParams.keepalive) 
1441
                event_base_once(base, -1, EV_TIMEOUT, keepalive_fn, peer, &t);
1442
}
1443

    
1444
/* connection functions */
1445
int mlOpenConnection(socketID_handle external_socketID,receive_connection_cb connection_cb,void *arg, const send_params defaultSendParams){
1446

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

    
1461
        // check if that connection already exist
1462

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

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

    
1505
                        connectbuf[con_id]->connection_head = connectbuf[con_id]->connection_last = malloc(sizeof(struct receive_connection_cb_list));
1506
                        connectbuf[con_id]->connection_last->next = NULL;
1507
                        connectbuf[con_id]->connection_last->connection_cb = connection_cb;
1508
                        connectbuf[con_id]->connection_last->arg = arg;
1509
                        connectbuf[con_id]->external_connectionID = -1;
1510

    
1511
                        connectbuf[con_id]->defaultSendParams = defaultSendParams;
1512
                        if (defaultSendParams.keepalive) setupKeepalive(con_id);
1513
                        break;
1514
                }
1515
        } //end of for
1516

    
1517
        if (con_id == CONNECTBUFSIZE) {
1518
                error("ML: Could not open connection: connection buffer full\n");
1519
                return -1;
1520
        }
1521

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

    
1526
        return con_id;
1527

    
1528
}
1529

    
1530
void mlCloseConnection(const int connectionID){
1531

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

    
1547
}
1548

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

    
1551
        if (connectionID < 0) {
1552
                error("ML: send data failed: connectionID does not exist\n");
1553
                return;
1554
        }
1555

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

    
1565
        if (sParams == NULL) {
1566
                sParams = &(connectbuf[connectionID]->defaultSendParams);
1567
        }
1568

    
1569
        send_msg(connectionID, msgtype, sendbuf, bufsize, false, sParams);
1570

    
1571
}
1572

    
1573
/* transmit data functions  */
1574
int mlSendAllData(const int connectionID,send_all_data_container *container,int nr_entries,unsigned char msgtype,send_params *sParams){
1575

    
1576
    if (nr_entries < 1 || nr_entries > 5) {
1577

    
1578
        error
1579
            ("ML : sendALlData : nr_enties is not between 1 and 5 \n ");
1580
        return 0;
1581

    
1582
    } else {
1583

    
1584
        if (nr_entries == 1) {
1585

    
1586
                mlSendData(connectionID, container->buffer_1,
1587
                      container->length_1, msgtype, sParams);
1588

    
1589
            return 1;
1590

    
1591
        } else if (nr_entries == 2) {
1592

    
1593
            int buflen = container->length_1 + container->length_2;
1594
            char buf[buflen];
1595
            memcpy(buf, container->buffer_1, container->length_1);
1596
            memcpy(&buf[container->length_1], container->buffer_2,
1597
                   container->length_2);
1598
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1599

    
1600
            return 1;
1601

    
1602
        } else if (nr_entries == 3) {
1603

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

    
1615

    
1616
            return 1;
1617

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

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

    
1633
            return 1;
1634

    
1635
        } else {
1636

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

    
1653
            return 1;
1654
        }
1655

    
1656
    }
1657

    
1658
}
1659

    
1660
int mlRecvData(const int connectionID,char *recvbuf,int *bufsize,recv_params *rParams){
1661

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

1670
        info("ML: recv data called \n");
1671

1672
        int i = 0;
1673
        int returnValue = 0;
1674
        double timeout = (double) recv_timeout.tv_sec;
1675
        time_t endtime = time(NULL);
1676

1677
        for (i = 0; i < RECVDATABUFSIZE; i++) {
1678

1679
            if (recvdatabuf[i] != NULL) {
1680

1681
                if (recvdatabuf[i]->connectionID == connectionID) {
1682

1683
                    info("ML: recv data has entry  \n");
1684

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

1687
                    // check if the specified connection has data and it
1688
                    // is complete
1689
                    // check the data seqnr
1690
                    // if(connectionID == recvdatabuf[i]->connectionID &&
1691
                    // 1 == recvdatabuf[i]->status){
1692

1693
                    if (1 == recvdatabuf[i]->status) {
1694

1695
                        // info("transmissionHandler: recv_data set is
1696
                        // complete \n" );
1697

1698
                        // debug("debud \n");
1699

1700
                        // exchange the pointers
1701
                        int buffersize = 0;
1702
                        buffersize = recvdatabuf[i]->bufsize;
1703
                        *bufsize = buffersize;
1704
                        // recvbuf = recvdatabuf[i]->recvbuf;
1705

1706
                        // info("buffersize %d \n",buffersize);
1707
                        memcpy(recvbuf, recvdatabuf[i]->recvbuf,
1708
                               buffersize);
1709
                        // debug(" recvbuf %s \n",recvbuf );
1710

1711
//                         double nrMissFrags =
1712
//                             (double) recvdatabuf[i]->nrFragments /
1713
//                             (double) recvdatabuf[i]->recvFragments;
1714
//                         int nrMissingFragments = (int) ceil(nrMissFrags);
1715

1716
//                        rParams->nrMissingFragments = nrMissingFragments;
1717
//                         rParams->nrFragments = recvdatabuf[i]->nrFragments;
1718
                        rParams->msgtype = recvdatabuf[i]->msgtype;
1719
                        rParams->connectionID =
1720
                            recvdatabuf[i]->connectionID;
1721

1722
                        // break from the loop
1723
                        // debug(" recvbuf %s \n ",recvbuf);
1724

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

1731
                        if(get_Recv_data_inf_cb != NULL) {
1732
                                mon_data_inf recv_data_inf;
1733

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

1749
                                // send data recv callback to monitoring module
1750

1751
                                (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
1752
                        }
1753

1754

1755
                        // free the allocated memory
1756
                        free(recvdatabuf[i]);
1757
                        recvdatabuf[i] = NULL;
1758

1759
                        returnValue = 1;
1760
                        break;
1761

1762
                    }
1763

1764
                    if (recvdatabuf[i] != NULL) {
1765

1766
                        if (timepass > timeout) {
1767

1768
                            info("ML: recv_data timeout called  \n");
1769

1770
                            // some data about the missing chunks should
1771
                            // be added here
1772
                            // exchange the pointers
1773
                            int buffersize = 0;
1774
                            buffersize = recvdatabuf[i]->bufsize;
1775
                            *bufsize = buffersize;
1776
                            // recvbuf = recvdatabuf[i]->recvbuf;
1777

1778
                            double nrMissFrags =
1779
                                (double) recvdatabuf[i]->nrFragments /
1780
                                (double) recvdatabuf[i]->recvFragments;
1781
                            int nrMissingFragments =
1782
                                (int) ceil(nrMissFrags);
1783

1784
                            // debug(" recvbuf %s \n",recvbuf );
1785

1786
                            memcpy(recvbuf, recvdatabuf[i]->recvbuf,
1787
                                   buffersize);
1788

1789
                            rParams->nrMissingFragments =
1790
                                nrMissingFragments;
1791
                            rParams->nrFragments =
1792
                                recvdatabuf[i]->nrFragments;
1793
                            rParams->msgtype = recvdatabuf[i]->msgtype;
1794
                            rParams->connectionID =
1795
                                recvdatabuf[i]->connectionID;
1796

1797
                                if(get_Recv_data_inf_cb != NULL) {
1798
                                        mon_data_inf recv_data_inf;
1799

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

1815
                                        // send data recv callback to monitoring module
1816

1817
                                        (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
1818
                                }
1819

1820
                            // free the allocated memory
1821
                            free(recvdatabuf[i]);
1822
                            recvdatabuf[i] = NULL;
1823

1824
                            returnValue = 1;
1825
                            break;
1826

1827
                        }
1828
                    }
1829

1830
                }
1831

1832
            }
1833
            // debug("2 recvbuf %s \n ",recvbuf);
1834
        }
1835
        return returnValue;
1836
    }
1837
#endif
1838

    
1839
}
1840

    
1841
int mlSocketIDToString(socketID_handle socketID,char* socketID_string, size_t len){
1842

    
1843
        char internal_addr[INET_ADDRSTRLEN];
1844
        char external_addr[INET_ADDRSTRLEN];
1845
        inet_ntop(AF_INET, &(socketID->internal_addr.udpaddr.sin_addr.s_addr), internal_addr, INET_ADDRSTRLEN);
1846
        inet_ntop(AF_INET, &(socketID->external_addr.udpaddr.sin_addr.s_addr), external_addr, INET_ADDRSTRLEN);
1847

    
1848
        snprintf(socketID_string,len,"%s:%d-%s:%d", internal_addr, ntohs(socketID->internal_addr.udpaddr.sin_port),
1849
                external_addr,        ntohs(socketID->external_addr.udpaddr.sin_port));
1850
        return 0;
1851

    
1852
}
1853

    
1854
int mlStringToSocketID(const char* socketID_string, socketID_handle socketID){
1855

    
1856
        //@TODO add checks against malformed string
1857
        char external_addr[INET_ADDRSTRLEN];
1858
        int external_port;
1859
        char internal_addr[INET_ADDRSTRLEN];
1860
        int internal_port;
1861

    
1862
        char *pch;
1863
        char *s = strdup(socketID_string);
1864

    
1865
        //replace ':' with a blank
1866
        pch=strchr(s,':');
1867
        while (pch!=NULL){
1868
                                *pch = ' ';
1869
                pch=strchr(pch+1,':');
1870
        }
1871
        pch=strchr(s,'-');
1872
        if(pch) *pch = ' ';
1873

    
1874
        sscanf(s,"%s %d %s %d", internal_addr, &internal_port,
1875
                external_addr, &external_port);
1876

    
1877
        if(inet_pton(AF_INET, internal_addr, &(socketID->internal_addr.udpaddr.sin_addr)) == 0)
1878
                return EINVAL;
1879
        socketID->internal_addr.udpaddr.sin_family = AF_INET;
1880
        socketID->internal_addr.udpaddr.sin_port = htons(internal_port);
1881

    
1882

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

    
1888
        free(s);
1889
        return 0;
1890

    
1891
}
1892

    
1893
int mlGetConnectionStatus(int connectionID){
1894

    
1895
        if(connectbuf[connectionID])
1896
                return connectbuf[connectionID]->status == READY;
1897
        return -1;
1898
    
1899
}
1900

    
1901

    
1902
int mlConnectionExist(socketID_handle socketID, bool ready){
1903

    
1904
    /*
1905
     * check if another connection for the external connectionID exist
1906
     * that was established \ within the last 2 seconds
1907
     */
1908
        int i;
1909
        for (i = 0; i < CONNECTBUFSIZE; i++)
1910
                if (connectbuf[i] != NULL)
1911
                        if (mlCompareSocketIDs(&(connectbuf[i]->external_socketID), socketID) == 0) {
1912
                                if (ready) return (connectbuf[i]->status == READY ? i : -1);;
1913
                                return i;
1914
                                }
1915

    
1916
    return -1;
1917

    
1918
}
1919

    
1920
//Added by Robert Birke as comodity functions
1921

    
1922
//int mlPrintSocketID(socketID_handle socketID) {
1923
//        char str[SOCKETID_STRING_SIZE];
1924
//        mlSocketIDToString(socketID, str, sizeof(str));
1925
//        printf(stderr,"int->%s<-ext\n",str);
1926
//}
1927

    
1928
/*
1929
 * hash code of a socketID
1930
 * TODO might think of a better way
1931
 */
1932
int mlHashSocketID(socketID_handle sock) {
1933
    return sock->internal_addr.udpaddr.sin_port +
1934
                          sock->external_addr.udpaddr.sin_port;
1935
}
1936

    
1937
int mlCompareSocketIDs(socketID_handle sock1, socketID_handle sock2) {
1938
        /*
1939
        * compare internal addr
1940
        */
1941
        if (sock1->internal_addr.udpaddr.sin_addr.s_addr !=
1942
            sock2->internal_addr.udpaddr.sin_addr.s_addr)
1943
                        return 1;
1944

    
1945
        if (sock1->internal_addr.udpaddr.sin_port !=
1946
                 sock2->internal_addr.udpaddr.sin_port)
1947
                        return 1;
1948

    
1949
        /*
1950
        * compare external addr
1951
        */
1952
        if (sock1->external_addr.udpaddr.sin_addr.s_addr !=
1953
            sock2->external_addr.udpaddr.sin_addr.s_addr)
1954
                        return 1;
1955

    
1956
        if (sock1->external_addr.udpaddr.sin_port !=
1957
                 sock2->external_addr.udpaddr.sin_port)
1958
                        return 1;
1959

    
1960
        return 0;
1961
}
1962

    
1963
int mlCompareSocketIDsByPort(socketID_handle sock1, socketID_handle sock2)
1964
{ 
1965
        if (sock1->internal_addr.udpaddr.sin_port !=
1966
                 sock2->internal_addr.udpaddr.sin_port)
1967
                        return 1;
1968

    
1969
        if (sock1->external_addr.udpaddr.sin_port !=
1970
                 sock2->external_addr.udpaddr.sin_port)
1971
                        return 1;
1972
        return 0;
1973
}
1974

    
1975
int mlGetPathMTU(int ConnectionId) {
1976
        if(ConnectionId < 0 || ConnectionId >= CONNECTBUFSIZE)
1977
                return -1;
1978
        if (connectbuf[ConnectionId] != NULL)
1979
                return connectbuf[ConnectionId]->pmtusize;
1980
        return -1;
1981
}
1982

    
1983
/**************************** END of GENERAL functions *************************/
1984

    
1985
/**************************** NAT functions *************************/
1986

    
1987
/* setter  */
1988
void mlSetStunServer(const int port,const char *ipaddr){
1989

    
1990
        stun_server.sin_family = AF_INET;
1991
        if (ipaddr == NULL)
1992
                stun_server.sin_addr.s_addr = htonl(INADDR_NONE);
1993
        else
1994
                stun_server.sin_addr.s_addr = resolve(ipaddr);
1995
        stun_server.sin_port = htons(port);
1996

    
1997
}
1998

    
1999
int mlGetExternalIP(char* external_addr){
2000

    
2001
        socketaddrgen udpgen;
2002
        struct sockaddr_in udpaddr;
2003

    
2004
        udpgen = local_socketID.external_addr;
2005
        udpaddr = udpgen.udpaddr;
2006

    
2007
        inet_ntop(AF_INET, &(udpaddr.sin_addr), external_addr,
2008
                        INET_ADDRSTRLEN);
2009

    
2010
        if (external_addr == NULL) {
2011

    
2012
        return -1;
2013

    
2014
        } else {
2015

    
2016
        return 0;
2017

    
2018
        }
2019

    
2020
}
2021

    
2022
/**************************** END of NAT functions *************************/