Statistics
| Branch: | Revision:

ml / ml.c @ e17edb88

History | View | Annotate | Download (59.1 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 + iov[2].iov_len;
331
                                        //transmit data header only in the first packet
332
                                        iov[2].iov_len = 0;
333
                                        break;
334
                        }
335
                } while(offset != msg_len + msg_h.len_mon_data_hdr && !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
        // Monitoring layer hook
406
        if(get_Recv_data_inf_cb != NULL) {
407
                // update pointer to the real data
408
                msgbuf += msg_h->len_mon_data_hdr;
409
                msg_size -= msg_h->len_mon_data_hdr;
410
                con_msg = (struct conn_msg *)msgbuf;
411

    
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
        } else {
430
                con_msg = (struct conn_msg *) msgbuf;
431
        }
432

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

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

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

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

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

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

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

    
512
                                if (receive_Connection_cb != NULL)
513
                                        (receive_Connection_cb) (msg_h->remote_con_id, NULL);
514

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

    
530
                        debug("ML: active connection established\n");
531
                        break;
532

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

    
552
                                if (receive_Connection_cb != NULL)
553
                                        (receive_Connection_cb) (msg_h->remote_con_id, NULL);
554

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

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

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

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

    
607
        if (recvdatabuf[recv_id] == NULL) {
608
                return;
609
        }
610

    
611

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

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

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

    
643
                        // send data recv callback to monitoring module
644

    
645
                        (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
646
                }
647

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

    
651
                recv_params rParams;
652

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

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

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

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

    
681
        int recv_id, free_recv_id = -1;
682

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

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

    
698

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

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

    
725
        if (msg_h->offset == 0)
726
                recvdatabuf[recv_id]->firstPacketArrived = 1;
727

    
728

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

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

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

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

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

    
765
                                // send data recv callback to monitoring module
766

    
767
                                (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
768
                        }
769

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

    
774
                                recv_params rParams;
775

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

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

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

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

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

    
821
        int con_id = (long) arg;
822
        pmtu new_pmtusize;
823

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

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

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

    
839
        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);
840

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

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

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

    
880
        //retry
881
        resend_conn_msg(con_id);
882
}
883

    
884

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

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

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

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

    
935
    // check the packettype
936
    msgbufptr = &msg[0];
937

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

    
942
    if (msgtype == 0) {
943

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

    
948
        int msgtype_c = connectbuf[connectionID]->status;
949
//        pmtusize = connectbuf[connectionID]->pmtutrysize;
950

    
951
        if (msgtype_c != msgtype) {
952
            dead = 1;
953
        }
954

    
955

    
956
    } else if (msgtype == 1) {
957

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

    
962
        int msgtype_c = connectbuf[connectionID]->status;
963
//        pmtusize = connectbuf[connectionID]->pmtutrysize;
964

    
965
        if (msgtype_c != msgtype) {
966
            dead = 1;
967
        }
968

    
969
    }
970
    // decrement the pmtu size
971
    new_pmtusize = pmtu_decrement(pmtusize);
972

    
973
//    connectbuf[connectionID]->pmtutrysize = new_pmtusize;
974

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

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

    
987
    if (msgtype == 0 && dead != 1) {
988

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

    
995
        // event_del(connectbuf[connectionID]->timeout);
996

    
997

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

    
1002
//        send_conn_msg(connectionID, new_pmtusize);
1003

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

    
1008
        // timeout_add(connectbuf[connectionID]->timeout,&connectbuf[connectionID]->timeout_value);
1009

    
1010
        /*
1011
         * libevent2
1012
         */
1013

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

    
1018
        // connectbuf[connectionID]->timeout = ev;
1019

    
1020
        event_add(ev, &connectbuf[connectionID]->timeout_value);
1021

    
1022
    } else if (msgtype == 1 && dead != 1) {
1023

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

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

    
1035

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

    
1041
        //send_conn_msg(connectionID, new_pmtusize);
1042

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

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

    
1057
    }
1058
}
1059

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

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

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

    
1079
        recvPacket(fd, msgbuf, &recvSize, &recv_addr, pmtu_error_cb_th, &ttl);
1080

    
1081

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

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

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

    
1099

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

    
1125

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

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

    
1153
void try_stun();
1154

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

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

    
1180

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

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

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

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

    
1217
        event_add(ev, NULL);
1218

    
1219
        try_stun();
1220

    
1221
        return socketfd;
1222
}
1223

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

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

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

    
1257
/**************************** END OF INTERNAL ***********************/
1258

    
1259
/**************************** MONL functions *************************/
1260

    
1261
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){
1262

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

    
1270
        }
1271
        register_recv_localsocketID_cb(local_socketID_cb);
1272
        return create_socket(port, ipaddr);
1273
}
1274

    
1275
/* register callbacks  */
1276
void mlRegisterGetRecvPktInf(get_recv_pkt_inf_cb recv_pkt_inf_cb){
1277

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

    
1283
}
1284

    
1285
void mlRegisterGetSendPktInf(get_send_pkt_inf_cb  send_pkt_inf_cb){
1286

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

    
1292
}
1293

    
1294

    
1295
void mlRegisterSetMonitoringHeaderPktCb(set_monitoring_header_pkt_cb monitoring_header_pkt_cb ){
1296

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

    
1302
}
1303

    
1304
void mlRegisterGetRecvDataInf(get_recv_data_inf_cb recv_data_inf_cb){
1305

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

    
1311
}
1312

    
1313
void mlRegisterGetSendDataInf(get_send_data_inf_cb  send_data_inf_cb){
1314

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

    
1320
}
1321

    
1322
void mlRegisterSetMonitoringHeaderDataCb(set_monitoring_header_data_cb monitoring_header_data_cb){
1323

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

    
1329
}
1330

    
1331
void mlSetRecvTimeout(struct timeval timeout_value){
1332

    
1333
        recv_timeout = timeout_value;
1334

    
1335
}
1336

    
1337
int mlGetStandardTTL(socketID_handle socketID,uint8_t *ttl){
1338

    
1339
        return getTTL(socketfd, ttl);
1340

    
1341
}
1342

    
1343
socketID_handle mlGetLocalSocketID(int *errorstatus){
1344

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

    
1350
        *errorstatus = 0;
1351
        return &local_socketID;
1352

    
1353
}
1354

    
1355

    
1356
/**************************** END of MONL functions *************************/
1357

    
1358
/**************************** GENERAL functions *************************/
1359

    
1360
void mlRegisterRecvConnectionCb(receive_connection_cb recv_conn_cb){
1361

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

    
1367
}
1368

    
1369
void mlRegisterErrorConnectionCb(connection_failed_cb conn_failed){
1370

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

    
1376
}
1377

    
1378
void mlRegisterRecvDataCb(receive_data_cb data_cb,unsigned char msgtype){
1379

    
1380
    if (msgtype > 126) {
1381

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

    
1385
    }
1386

    
1387
    if (data_cb == NULL) {
1388

    
1389
            error("ML: Register receive data callback: NUll ptr \n ");
1390

    
1391
    } else {
1392

    
1393
        recvcbbuf[msgtype] = data_cb;
1394

    
1395
    }
1396

    
1397
}
1398

    
1399
void mlCloseSocket(socketID_handle socketID){
1400

    
1401
        free(socketID);
1402

    
1403
}
1404

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

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

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

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

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

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

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

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

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

    
1459
        // check if that connection already exist
1460

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

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

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

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

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

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

    
1524
        return con_id;
1525

    
1526
}
1527

    
1528
void mlCloseConnection(const int connectionID){
1529

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

    
1545
}
1546

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

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

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

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

    
1567
        send_msg(connectionID, msgtype, sendbuf, bufsize, false, sParams);
1568

    
1569
}
1570

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

    
1574
    if (nr_entries < 1 || nr_entries > 5) {
1575

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

    
1580
    } else {
1581

    
1582
        if (nr_entries == 1) {
1583

    
1584
                mlSendData(connectionID, container->buffer_1,
1585
                      container->length_1, msgtype, sParams);
1586

    
1587
            return 1;
1588

    
1589
        } else if (nr_entries == 2) {
1590

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

    
1598
            return 1;
1599

    
1600
        } else if (nr_entries == 3) {
1601

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

    
1613

    
1614
            return 1;
1615

    
1616
        } else if (nr_entries == 4) {
1617

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

    
1631
            return 1;
1632

    
1633
        } else {
1634

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

    
1651
            return 1;
1652
        }
1653

    
1654
    }
1655

    
1656
}
1657

    
1658
int mlRecvData(const int connectionID,char *recvbuf,int *bufsize,recv_params *rParams){
1659

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

1668
        info("ML: recv data called \n");
1669

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

1675
        for (i = 0; i < RECVDATABUFSIZE; i++) {
1676

1677
            if (recvdatabuf[i] != NULL) {
1678

1679
                if (recvdatabuf[i]->connectionID == connectionID) {
1680

1681
                    info("ML: recv data has entry  \n");
1682

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

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

1691
                    if (1 == recvdatabuf[i]->status) {
1692

1693
                        // info("transmissionHandler: recv_data set is
1694
                        // complete \n" );
1695

1696
                        // debug("debud \n");
1697

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

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

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

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

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

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

1729
                        if(get_Recv_data_inf_cb != NULL) {
1730
                                mon_data_inf recv_data_inf;
1731

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

1747
                                // send data recv callback to monitoring module
1748

1749
                                (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
1750
                        }
1751

1752

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

1757
                        returnValue = 1;
1758
                        break;
1759

1760
                    }
1761

1762
                    if (recvdatabuf[i] != NULL) {
1763

1764
                        if (timepass > timeout) {
1765

1766
                            info("ML: recv_data timeout called  \n");
1767

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

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

1782
                            // debug(" recvbuf %s \n",recvbuf );
1783

1784
                            memcpy(recvbuf, recvdatabuf[i]->recvbuf,
1785
                                   buffersize);
1786

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

1795
                                if(get_Recv_data_inf_cb != NULL) {
1796
                                        mon_data_inf recv_data_inf;
1797

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

1813
                                        // send data recv callback to monitoring module
1814

1815
                                        (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
1816
                                }
1817

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

1822
                            returnValue = 1;
1823
                            break;
1824

1825
                        }
1826
                    }
1827

1828
                }
1829

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

    
1837
}
1838

    
1839
int mlSocketIDToString(socketID_handle socketID,char* socketID_string, size_t len){
1840

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

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

    
1850
}
1851

    
1852
int mlStringToSocketID(const char* socketID_string, socketID_handle socketID){
1853

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

    
1860
        char *pch;
1861
        char *s = strdup(socketID_string);
1862

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

    
1872
        sscanf(s,"%s %d %s %d", internal_addr, &internal_port,
1873
                external_addr, &external_port);
1874

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

    
1880

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

    
1886
        free(s);
1887
        return 0;
1888

    
1889
}
1890

    
1891
int mlGetConnectionStatus(int connectionID){
1892

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

    
1899

    
1900
int mlConnectionExist(socketID_handle socketID, bool ready){
1901

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

    
1914
    return -1;
1915

    
1916
}
1917

    
1918
//Added by Robert Birke as comodity functions
1919

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

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

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

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

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

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

    
1958
        return 0;
1959
}
1960

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

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

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

    
1981
/**************************** END of GENERAL functions *************************/
1982

    
1983
/**************************** NAT functions *************************/
1984

    
1985
/* setter  */
1986
void mlSetStunServer(const int port,const char *ipaddr){
1987

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

    
1995
}
1996

    
1997
int mlGetExternalIP(char* external_addr){
1998

    
1999
        socketaddrgen udpgen;
2000
        struct sockaddr_in udpaddr;
2001

    
2002
        udpgen = local_socketID.external_addr;
2003
        udpaddr = udpgen.udpaddr;
2004

    
2005
        inet_ntop(AF_INET, &(udpaddr.sin_addr), external_addr,
2006
                        INET_ADDRSTRLEN);
2007

    
2008
        if (external_addr == NULL) {
2009

    
2010
        return -1;
2011

    
2012
        } else {
2013

    
2014
        return 0;
2015

    
2016
        }
2017

    
2018
}
2019

    
2020
/**************************** END of NAT functions *************************/