Statistics
| Branch: | Revision:

napa-baselibs / ml / ml.c @ fa5e477b

History | View | Annotate | Download (62.6 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 <stdlib.h>
36
#include <unistd.h>
37
#include <stdio.h>
38
#include <stddef.h>
39
#include <stdint.h>
40
#include <string.h>
41
#include <sys/types.h>
42
#include <event2/event.h>
43
#include <time.h>
44
#include <math.h>
45
#include <assert.h>
46
#include <errno.h>
47

    
48
#ifndef WIN32
49
#include <arpa/inet.h>
50
#include <netdb.h>
51
#include <netinet/in.h>
52
#include <sys/socket.h>
53
#include <fcntl.h>
54
#else
55

    
56
#include <winsock2.h>
57
#include <ws2tcpip.h>
58
#endif
59

    
60
#include "util/udpSocket.h"
61
#include "util/stun.h"
62
#include "transmissionHandler.h"
63

    
64
#define LOG_MODULE "[ml] "
65
#include "ml_log.h"
66

    
67
/**************************** START OF INTERNALS ***********************/
68

    
69

    
70
/*
71
 * reserved message type for internal puposes
72
 */
73
#define MSG_TYPE_ML_KEEPALIVE 0x126        //TODO: check that it is really interpreted as internal
74

    
75
/*
76
 * a pointer to a libevent instance
77
 */
78
struct event_base *base;
79

    
80
/*
81
 * define the nr of connections the messaging layer can handle
82
 */
83
#define CONNECTBUFSIZE 10000
84
/*
85
 * define the nr of data that can be received parallel
86
 */
87
#define RECVDATABUFSIZE 10000
88
/*
89
 * define an array for message multiplexing
90
 */
91
#define MSGMULTIPLEXSIZE 127
92

    
93

    
94
/*
95
 * timeout before thinking that the STUN server can't be connected
96
 */
97
#define NAT_TRAVERSAL_TIMEOUT { 1, 0 }
98

    
99
/*
100
 * timeout before thinking of an mtu problem (check MAX_TRIALS as well)
101
 */
102
#define PMTU_TIMEOUT { 0, 500000 }
103

    
104
/*
105
 * retry sending connection messages this many times before reducing pmtu
106
 */
107
#define MAX_TRIALS 3
108

    
109
/*
110
 * default timeout value between the first and the last received packet of a message
111
 */
112
#define RECV_TIMEOUT_DEFAULT { 2, 0 }
113

    
114
/*
115
 * global variables
116
 */
117
/*
118
 * define a buffer of pointers to connect structures
119
 */
120
connect_data *connectbuf[CONNECTBUFSIZE];
121

    
122
/*
123
 * define a pointer buffer with pointers to recv_data structures
124
 */
125
recvdata *recvdatabuf[RECVDATABUFSIZE];
126

    
127
/*
128
 * define a pointer buffer for message multiplexing
129
 */
130
receive_data_cb recvcbbuf[MSGMULTIPLEXSIZE];
131

    
132
/*
133
 * stun server address
134
 */
135
struct sockaddr_in stun_server;
136

    
137
/*
138
 * receive timeout
139
 */
140
static struct timeval recv_timeout = RECV_TIMEOUT_DEFAULT;
141

    
142
/*
143
 * boolean NAT traversal successful if true
144
 */
145
boolean NAT_traversal;
146

    
147
/*
148
 * file descriptor for local socket
149
 */
150
evutil_socket_t socketfd;
151

    
152
/*
153
 * local socketID
154
 */
155
socket_ID local_socketID;
156

    
157
socketID_handle loc_socketID = &local_socketID;
158

    
159
/*
160
 * callback function pointers
161
 */
162
/*
163
 * monitoring module callbacks
164
 */
165
get_recv_pkt_inf_cb get_Recv_pkt_inf_cb = NULL;
166
get_send_pkt_inf_cb get_Send_pkt_inf_cb = NULL;
167
set_monitoring_header_pkt_cb set_Monitoring_header_pkt_cb = NULL;
168
get_recv_data_inf_cb get_Recv_data_inf_cb = NULL;
169
get_send_data_inf_cb get_Send_data_inf_cb = NULL;
170
set_monitoring_header_data_cb set_Monitoring_header_data_cb = NULL;
171
/*
172
 * connection callbacks
173
 */
174
receive_connection_cb receive_Connection_cb = NULL;
175
connection_failed_cb failed_Connection_cb = NULL;
176
/*
177
 * local socketID callback
178
 */
179
receive_localsocketID_cb receive_SocketID_cb;
180

    
181
/*
182
 * boolean that defines if received data is transmitted to the upper layer
183
 * via callback or via upper layer polling
184
 */
185
boolean recv_data_callback;
186

    
187
/*
188
 * helper function to get rid of a warning
189
 */
190
#ifndef WIN32
191
int min(int a, int b) {
192
        if (a > b) return b;
193
        return a;
194
}
195
#endif
196

    
197
/*
198
 * convert a socketID to a string. It uses a static buffer, so either strdup is needed, or the string will get lost!
199
 */
200
const char *conid_to_string(int con_id)
201
{
202
        static char s[INET_ADDRSTRLEN+1+5+1+INET_ADDRSTRLEN+1+5+1];
203
        mlSocketIDToString(&connectbuf[con_id]->external_socketID, s, sizeof(s));
204
        return s;
205
}
206

    
207
void register_recv_localsocketID_cb(receive_localsocketID_cb local_socketID_cb)
208
{
209
        if (local_socketID_cb == NULL) {
210
                error("ML : Register receive_localsocketID_cb: NULL ptr \n");
211
        } else {
212
                receive_SocketID_cb = local_socketID_cb;
213
        }
214
}
215

    
216

    
217
//void keep_connection_alive(const int connectionID)
218
//{
219
//
220
//    // to be done with the NAT traversal
221
//    // send a message over the wire
222
//    printf("\n");
223
//
224
//}
225

    
226
void unsetStunServer()
227
{
228
        stun_server.sin_addr.s_addr = INADDR_NONE;
229
}
230

    
231
bool isStunDefined()
232
{
233
        return stun_server.sin_addr.s_addr != INADDR_NONE;
234
}
235

    
236
void send_msg(int con_id, int msg_type, char* msg, int msg_len, bool truncable, send_params * sParams) {
237
        socketaddrgen udpgen;
238
        bool retry;
239
        int pkt_len, offset;
240
        struct iovec iov[4];
241

    
242
        char h_pkt[MON_PKT_HEADER_SPACE];
243
        char h_data[MON_DATA_HEADER_SPACE];
244

    
245
        struct msg_header msg_h;
246

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

    
249
        iov[0].iov_base = &msg_h;
250
        iov[0].iov_len = MSG_HEADER_SIZE;
251

    
252
        msg_h.local_con_id = htonl(con_id);
253
        msg_h.remote_con_id = htonl(connectbuf[con_id]->external_connectionID);
254
        msg_h.msg_type = msg_type;
255
        msg_h.msg_seq_num = htonl(connectbuf[con_id]->seqnr++);
256

    
257

    
258
        iov[1].iov_len = iov[2].iov_len = 0;
259
        iov[1].iov_base = h_pkt;
260
        iov[2].iov_base = h_data;
261

    
262

    
263
        if (connectbuf[con_id]->internal_connect)
264
                udpgen = connectbuf[con_id]->external_socketID.internal_addr;
265
        else
266
                udpgen = connectbuf[con_id]->external_socketID.external_addr;
267

    
268
        do{
269
                offset = 0;
270
                retry = false;
271
                // Monitoring layer hook
272
                if(set_Monitoring_header_data_cb != NULL) {
273
                        iov[2].iov_len = ((set_Monitoring_header_data_cb) (&(connectbuf[con_id]->external_socketID), msg_type));
274
                }
275
                msg_h.len_mon_data_hdr = iov[2].iov_len;
276

    
277
                if(get_Send_data_inf_cb != NULL && iov[2].iov_len != 0) {
278
                        mon_data_inf sd_data_inf;
279

    
280
                        memset(h_data, 0, MON_DATA_HEADER_SPACE);
281

    
282
                        sd_data_inf.remote_socketID = &(connectbuf[con_id]->external_socketID);
283
                        sd_data_inf.buffer = msg;
284
                        sd_data_inf.bufSize = msg_len;
285
                        sd_data_inf.msgtype = msg_type;
286
                        sd_data_inf.monitoringDataHeader = iov[2].iov_base;
287
                        sd_data_inf.monitoringDataHeaderLen = iov[2].iov_len;
288
                        sd_data_inf.priority = sParams->priority;
289
                        sd_data_inf.padding = sParams->padding;
290
                        sd_data_inf.confirmation = sParams->confirmation;
291
                        sd_data_inf.reliable = sParams->reliable;
292
                        memset(&sd_data_inf.arrival_time, 0, sizeof(struct timeval));
293

    
294
                        (get_Send_data_inf_cb) ((void *) &sd_data_inf);
295
                }
296

    
297
                do {
298
                        if(set_Monitoring_header_pkt_cb != NULL) {
299
                                iov[1].iov_len = (set_Monitoring_header_pkt_cb) (&(connectbuf[con_id]->external_socketID), msg_type);
300
                        }
301
                        pkt_len = min(connectbuf[con_id]->pmtusize - iov[2].iov_len - iov[1].iov_len - iov[0].iov_len, msg_len - offset) ;
302

    
303
                        iov[3].iov_len = pkt_len;
304
                        iov[3].iov_base = msg + offset;
305

    
306
                        //fill header
307
                        msg_h.len_mon_packet_hdr = iov[1].iov_len;
308
                        msg_h.offset = htonl(offset);
309
                        msg_h.msg_length = htonl(truncable ? pkt_len : msg_len);
310

    
311
                        //monitoring layer hook
312
                        if(get_Send_pkt_inf_cb != NULL && iov[1].iov_len) {
313
                                mon_pkt_inf pkt_info;
314

    
315
                                memset(h_pkt,0,MON_PKT_HEADER_SPACE);
316

    
317
                                pkt_info.remote_socketID = &(connectbuf[con_id]->external_socketID);
318
                                pkt_info.buffer = msg + offset;
319
                                pkt_info.bufSize = pkt_len;
320
                                pkt_info.msgtype = msg_type;
321
                                pkt_info.dataID = connectbuf[con_id]->seqnr;
322
                                pkt_info.offset = offset;
323
                                pkt_info.datasize = msg_len;
324
                                pkt_info.monitoringHeaderLen = iov[1].iov_len;
325
                                pkt_info.monitoringHeader = iov[1].iov_base;
326
                                pkt_info.ttl = -1;
327
                                memset(&(pkt_info.arrival_time),0,sizeof(struct timeval));
328

    
329
                                (get_Send_pkt_inf_cb) ((void *) &pkt_info);
330
                        }
331

    
332
                        debug("ML: sending packet to %s with rconID:%d lconID:%d\n", conid_to_string(con_id), ntohl(msg_h.remote_con_id), ntohl(msg_h.local_con_id));
333
                        switch(sendPacket(socketfd, iov, 4, &udpgen.udpaddr)) {
334
                                case MSGLEN:
335
                                        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), ntohl(msg_h.remote_con_id), ntohl(msg_h.local_con_id), msg_len, offset);
336
                                        // TODO: pmtu decremented here, but not in the "truncable" packet. That is currently resent without changing the claimed pmtu. Might need to be changed.
337
                                        connectbuf[con_id]->pmtusize = pmtu_decrement(connectbuf[con_id]->pmtusize);
338
                                        if (connectbuf[con_id]->pmtusize > 0) {
339
                                                connectbuf[con_id]->delay = true;
340
                                                retry = true;
341
                                        }
342
                                        offset = msg_len; // exit the while
343
                                        break;
344
                                case FAILURE:
345
                                        info("ML: sending message failed (to:%s conID:%d lconID:%d msgsize:%d offset:%d)\n", conid_to_string(con_id), ntohl(msg_h.remote_con_id), ntohl(msg_h.local_con_id), msg_len, offset);
346
                                        offset = msg_len; // exit the while
347
                                        break;
348
                                case THROTTLE:
349
                                    //    debug("THROTTLE on output"); 
350
                                        offset = msg_len; // exit the while
351
                                        break;
352
                                case OK:
353
                                        //update
354
                                        offset += pkt_len;
355
                                        //transmit data header only in the first packet
356
                                        iov[2].iov_len = 0;
357
                                        break;
358
                        }
359
                } while(offset != msg_len && !truncable);
360
        } while(retry);
361
}
362

    
363
void pmtu_timeout_cb(int fd, short event, void *arg);
364

    
365
void reschedule_conn_msg(int con_id)
366
{
367
        if (connectbuf[con_id]->timeout_event) {
368
                /* delete old timout */        
369
                event_del(connectbuf[con_id]->timeout_event);
370
                event_free(connectbuf[con_id]->timeout_event);
371
        }
372
        connectbuf[con_id]->timeout_event = event_new(base, -1, EV_TIMEOUT, &pmtu_timeout_cb, (void *) (long)con_id);
373
        evtimer_add(connectbuf[con_id]->timeout_event, &connectbuf[con_id]->timeout_value);
374
}
375

    
376
void send_conn_msg(int con_id, int buf_size, int command_type)
377
{
378
        if (buf_size < sizeof(struct conn_msg)) {
379
                error("ML: requested connection message size is too small\n");
380
                return;
381
        }
382

    
383
        if(connectbuf[con_id]->ctrl_msg_buf == NULL) {
384
                connectbuf[con_id]->ctrl_msg_buf = malloc(buf_size);
385
                memset(connectbuf[con_id]->ctrl_msg_buf, 0, buf_size);
386
        }
387

    
388
        if(connectbuf[con_id]->ctrl_msg_buf == NULL) {
389
                error("ML: can not allocate memory for connection message\n");
390
                return;
391
        }
392

    
393
        struct conn_msg *msg_header = (struct conn_msg*) connectbuf[con_id]->ctrl_msg_buf;
394

    
395
        msg_header->comand_type = command_type;
396
        msg_header->pmtu_size = connectbuf[con_id]->pmtusize;
397

    
398
        memcpy(&(msg_header->sock_id), loc_socketID, sizeof(socket_ID));
399
  {
400
                        char buf[SOCKETID_STRING_SIZE];
401
                        mlSocketIDToString(&((struct conn_msg*)connectbuf[con_id]->ctrl_msg_buf)->sock_id,buf,sizeof(buf));
402
                        debug("Local socket_address sent in INVITE: %s, sizeof msg %d\n", buf, sizeof(struct conn_msg));
403
   }
404
        send_msg(con_id, ML_CON_MSG, connectbuf[con_id]->ctrl_msg_buf, buf_size, true, &(connectbuf[con_id]->defaultSendParams));
405
}
406

    
407
void send_conn_msg_with_pmtu_discovery(int con_id, int buf_size, int command_type)
408
{
409
        struct timeval tout = PMTU_TIMEOUT;
410
        connectbuf[con_id]->timeout_value = tout;
411
        connectbuf[con_id]->trials = 1;
412
        send_conn_msg(con_id, buf_size, command_type);
413
        reschedule_conn_msg(con_id);
414
}
415

    
416
void resend_conn_msg(int con_id)
417
{
418
        connectbuf[con_id]->trials++;
419
        send_conn_msg(con_id, connectbuf[con_id]->pmtusize, connectbuf[con_id]->status);
420
        reschedule_conn_msg(con_id);
421
}
422

    
423
void recv_conn_msg(struct msg_header *msg_h, char *msgbuf, int msg_size, struct sockaddr_in *recv_addr)
424
{
425
        struct conn_msg *con_msg;
426
        int free_con_id, con_id;
427

    
428
        time_t now = time(NULL);
429
        double timediff = 0.0;
430
        char sock_id_str[1000];
431
        
432
        msgbuf += msg_h->len_mon_data_hdr;
433
        msg_size -= msg_h->len_mon_data_hdr;
434
        con_msg = (struct conn_msg *)msgbuf;
435
        
436
        //verify message validity
437
        if (msg_size < sizeof(struct conn_msg)) {
438
                char recv_addr_str[INET_ADDRSTRLEN];
439
                inet_ntop(AF_INET, &(recv_addr->sin_addr.s_addr), recv_addr_str, INET_ADDRSTRLEN);
440
                info("Invalid conn_msg received from %s\n", recv_addr_str);
441
                return;
442
        }
443

    
444
        //decode sock_id for debug messages
445
        mlSocketIDToString(&con_msg->sock_id,sock_id_str,999);
446

    
447
        if (con_msg->sock_id.internal_addr.udpaddr.sin_addr.s_addr != recv_addr->sin_addr.s_addr &&
448
            con_msg->sock_id.external_addr.udpaddr.sin_addr.s_addr != recv_addr->sin_addr.s_addr   ) {
449
                char recv_addr_str[INET_ADDRSTRLEN];
450
                inet_ntop(AF_INET, &(recv_addr->sin_addr.s_addr), recv_addr_str, INET_ADDRSTRLEN);
451
                info("Conn msg received from %s, but claims to be from %s", recv_addr_str, sock_id_str);
452
                return;
453
        }
454

    
455
        // Monitoring layer hook
456
        if(get_Recv_data_inf_cb != NULL) {
457
                // update pointer to the real data
458
                mon_data_inf recv_data_inf;
459
                recv_data_inf.remote_socketID = &(con_msg->sock_id);
460
                recv_data_inf.buffer = msgbuf;
461
                recv_data_inf.bufSize = msg_size;
462
                recv_data_inf.msgtype = msg_h->msg_type;
463
                recv_data_inf.monitoringDataHeaderLen = msg_h->len_mon_data_hdr;
464
                recv_data_inf.monitoringDataHeader = msg_h->len_mon_data_hdr ? msgbuf : NULL;
465
                gettimeofday(&recv_data_inf.arrival_time, NULL);
466
                recv_data_inf.firstPacketArrived = true;
467
                recv_data_inf.recvFragments = 1;
468
                recv_data_inf.priority = false;
469
                recv_data_inf.padding = false;
470
                recv_data_inf.confirmation = false;
471
                recv_data_inf.reliable = false;
472

    
473
                // send data recv callback to monitoring module
474
                (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
475
        }
476

    
477
        // check the connection command type
478
        switch (con_msg->comand_type) {
479
                /*
480
                * if INVITE: enter a new socket make new entry in connect array
481
                * send an ok
482
                */
483
                case INVITE:
484
                        info("ML: received INVITE from %s (size:%d)\n", sock_id_str, msg_size);
485
                        /*
486
                        * check if another connection for the external connectionID exist
487
                        * that was established within the last 2 seconds
488
                        */
489
                        free_con_id = -1;
490
                        for (con_id = 0; con_id < CONNECTBUFSIZE; con_id++) {
491
                                if (connectbuf[con_id] != NULL) {
492
                                        if (mlCompareSocketIDs(&(connectbuf[con_id]->external_socketID), &(con_msg->sock_id)) == 0) {
493
                                                //timediff = difftime(now, connectbuf[con_id]->starttime);        //TODO: why this timeout? Shouldn't the connection be closed instead if there is a timeout?
494
                                                //if (timediff < 2)
495
                                                //update remote connection ID
496
                                                if (connectbuf[con_id]->external_connectionID != msg_h->local_con_id) {
497
                                                        warn("ML: updating remote connection ID for %s: from %d to %d\n",sock_id_str, connectbuf[con_id]->external_connectionID, msg_h->local_con_id);
498
                                                        connectbuf[con_id]->external_connectionID = msg_h->local_con_id;
499
                                                }
500
                                                break;
501
                                        }
502
                                } else if(free_con_id == -1)
503
                                        free_con_id = con_id;
504
                        }
505

    
506
                        if (con_id == CONNECTBUFSIZE) {
507
                                // create an entry in the connecttrybuf
508
                                if(free_con_id == -1) {
509
                                        error("ML: no new connect_buf available\n");
510
                                        return;
511
                                }
512
                                connectbuf[free_con_id] = (connect_data *) malloc(sizeof(connect_data));
513
                                memset(connectbuf[free_con_id],0,sizeof(connect_data));
514
                                connectbuf[free_con_id]->connection_head = connectbuf[free_con_id]->connection_last = NULL;
515
                                connectbuf[free_con_id]->starttime = time(NULL);
516
                                memcpy(&(connectbuf[free_con_id]->external_socketID), &(con_msg->sock_id), sizeof(socket_ID));
517
                                connectbuf[free_con_id]->pmtusize = con_msg->pmtu_size;        // bootstrap pmtu from the other's size. Not strictly needed, but a good hint
518
                                connectbuf[free_con_id]->timeout_event = NULL;
519
                                connectbuf[free_con_id]->external_connectionID = msg_h->local_con_id;
520
                                connectbuf[free_con_id]->internal_connect =
521
                                        !compare_external_address_socketIDs(&(con_msg->sock_id), loc_socketID);
522
                                con_id = free_con_id;
523
                        }
524

    
525
                        //if(connectbuf[con_id]->status <= CONNECT) { //TODO: anwer anyway. Why the outher would invite otherwise?
526
                                //update status and send back answer
527
                                connectbuf[con_id]->status = CONNECT;
528
                                send_conn_msg_with_pmtu_discovery(con_id, con_msg->pmtu_size, CONNECT);
529
                        //}
530
                        break;
531
                case CONNECT:
532
                        info("ML: received CONNECT from %s (size:%d)\n", sock_id_str, msg_size);
533

    
534
                        if(msg_h->remote_con_id != -1 && connectbuf[msg_h->remote_con_id] == NULL) {
535
                                error("ML: received CONNECT for inexistent connection rconID:%d\n",msg_h->remote_con_id);
536
                                return;
537
                        }
538

    
539
                        /*
540
                        * check if the connection status is not already 1 or 2
541
                        */
542
                        if (connectbuf[msg_h->remote_con_id]->status == INVITE) {
543
                                // set the external connectionID
544
                                connectbuf[msg_h->remote_con_id]->external_connectionID = msg_h->local_con_id;
545
                                // change status con_msg the connection_data
546
                                connectbuf[msg_h->remote_con_id]->status = READY;
547
                                // change pmtusize in the connection_data: not needed. receiving a CONNECT means our INVITE went through. So why change pmtu?
548
                                //connectbuf[msg_h->remote_con_id]->pmtusize = con_msg->pmtu_size;
549

    
550
                                // send the READY
551
                                send_conn_msg_with_pmtu_discovery(msg_h->remote_con_id, con_msg->pmtu_size, READY);
552

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

    
556
                                // call all registered callbacks
557
                                while(connectbuf[msg_h->remote_con_id]->connection_head != NULL) {
558
                                        struct receive_connection_cb_list *temp;
559
                                        temp = connectbuf[msg_h->remote_con_id]->connection_head;
560
                                        (temp->connection_cb) (msg_h->remote_con_id, temp->arg);
561
                                        connectbuf[msg_h->remote_con_id]->connection_head = temp->next;
562
                                        free(temp);
563
                                }
564
                                connectbuf[msg_h->remote_con_id]->connection_head =
565
                                        connectbuf[msg_h->remote_con_id]->connection_last = NULL;
566
                        } else {
567
                                // send the READY
568
                                send_conn_msg_with_pmtu_discovery(msg_h->remote_con_id, con_msg->pmtu_size, READY);
569
                        }
570

    
571
                        debug("ML: active connection established\n");
572
                        break;
573

    
574
                        /*
575
                        * if READY: find the entry in the connection array set the
576
                        * connection active change the pmtu size
577
                        */
578
                case READY:
579
                        info("ML: received READY from %s (size:%d)\n", sock_id_str, msg_size);
580
                        if(connectbuf[msg_h->remote_con_id] == NULL) {
581
                                error("ML: received READY for inexistent connection\n");
582
                                return;
583
                        }
584
                        /*
585
                        * checks if the connection is not already established
586
                        */
587
                        if (connectbuf[msg_h->remote_con_id]->status == CONNECT) {
588
                                // change status of the connection
589
                                connectbuf[msg_h->remote_con_id]->status = READY;
590
                                // change pmtusize: not needed. pmtu doesn't have to be symmetric
591
                                //connectbuf[msg_h->remote_con_id]->pmtusize = con_msg->pmtu_size;
592

    
593
                                if (receive_Connection_cb != NULL)
594
                                        (receive_Connection_cb) (msg_h->remote_con_id, NULL);
595

    
596
                                while(connectbuf[msg_h->remote_con_id]->connection_head != NULL) {
597
                                        struct receive_connection_cb_list *temp;
598
                                        temp = connectbuf[msg_h->remote_con_id]->connection_head;
599
                                        (temp->connection_cb) (msg_h->remote_con_id, temp->arg);
600
                                        connectbuf[msg_h->remote_con_id]->connection_head = temp->next;
601
                                        free(temp);
602
                                }
603
                                connectbuf[msg_h->remote_con_id]->connection_head =
604
                                        connectbuf[msg_h->remote_con_id]->connection_last = NULL;
605
                                debug("ML: passive connection established\n");
606
                        }
607
                        break;
608
        }
609
}
610

    
611
void recv_stun_msg(char *msgbuf, int recvSize)
612
{
613
        /*
614
        * create empty stun message struct
615
        */
616
        StunMessage resp;
617
        memset(&resp, 0, sizeof(StunMessage));
618
        /*
619
        * parse the message
620
        */
621
        int returnValue = 0;
622
        returnValue = recv_stun_message(msgbuf, recvSize, &resp);
623

    
624
        if (returnValue == 0) {
625
                /*
626
                * read the reflexive Address into the local_socketID
627
                */
628
                struct sockaddr_in reflexiveAddr = {0};
629
                reflexiveAddr.sin_family = AF_INET;
630
                reflexiveAddr.sin_addr.s_addr = htonl(resp.mappedAddress.ipv4.addr);
631
                reflexiveAddr.sin_port = htons(resp.mappedAddress.ipv4.port);
632
                socketaddrgen reflexiveAddres = {0};
633
                reflexiveAddres.udpaddr = reflexiveAddr;
634
                local_socketID.external_addr = reflexiveAddres;
635
                NAT_traversal = true;
636
                // callback to the upper layer indicating that the socketID is now
637
                // ready to use
638
                {
639
                        char buf[SOCKETID_STRING_SIZE];
640
                        mlSocketIDToString(&local_socketID,buf,sizeof(buf));
641
                         debug("received local socket_address: %s\n", buf);
642
                }
643
                (receive_SocketID_cb) (&local_socketID, 0);
644
        }
645
}
646

    
647
//done
648
void recv_timeout_cb(int fd, short event, void *arg)
649
{
650
        int recv_id = (long) arg;
651
        debug("ML: recv_timeout_cb called. Timeout for id:%d\n",recv_id);
652

    
653
        if (recvdatabuf[recv_id] == NULL) {
654
                return;
655
        }
656

    
657

    
658
/*        if(recvdatabuf[recv_id]->status == ACTIVE) {
659
                //TODO make timeout at least a DEFINE
660
                struct timeval timeout = { 4, 0 };
661
                recvdatabuf[recv_id]->status = INACTIVE;
662
                event_base_once(base, -1, EV_TIMEOUT, recv_timeout_cb,
663
                        arg, &timeout);
664
                return;
665
        }
666
*/
667

    
668
        if(recvdatabuf[recv_id]->status == ACTIVE) {
669
                // Monitoring layer hook
670
                if(get_Recv_data_inf_cb != NULL) {
671
                        mon_data_inf recv_data_inf;
672

    
673
                        recv_data_inf.remote_socketID =
674
                                        &(connectbuf[recvdatabuf[recv_id]->connectionID]->external_socketID);
675
                        recv_data_inf.buffer = recvdatabuf[recv_id]->recvbuf;
676
                        recv_data_inf.bufSize = recvdatabuf[recv_id]->bufsize;
677
                        recv_data_inf.msgtype = recvdatabuf[recv_id]->msgtype;
678
                        recv_data_inf.monitoringDataHeaderLen = recvdatabuf[recv_id]->monitoringDataHeaderLen;
679
                        recv_data_inf.monitoringDataHeader = recvdatabuf[recv_id]->monitoringDataHeaderLen ?
680
                                recvdatabuf[recv_id]->recvbuf : NULL;
681
                        gettimeofday(&recv_data_inf.arrival_time, NULL);
682
                        recv_data_inf.firstPacketArrived = recvdatabuf[recv_id]->firstPacketArrived;
683
                        recv_data_inf.recvFragments = recvdatabuf[recv_id]->recvFragments;
684
                        recv_data_inf.priority = false;
685
                        recv_data_inf.padding = false;
686
                        recv_data_inf.confirmation = false;
687
                        recv_data_inf.reliable = false;
688

    
689
                        // send data recv callback to monitoring module
690

    
691
//                        (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
692
                }
693

    
694
                // Get the right callback
695
                receive_data_cb receive_data_callback = recvcbbuf[recvdatabuf[recv_id]->msgtype];
696

    
697
                recv_params rParams;
698

    
699
                rParams.nrMissingBytes = recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->arrivedBytes;
700
                rParams.recvFragments = recvdatabuf[recv_id]->recvFragments;
701
                rParams.msgtype = recvdatabuf[recv_id]->msgtype;
702
                rParams.connectionID = recvdatabuf[recv_id]->connectionID;
703
                rParams.remote_socketID =
704
                        &(connectbuf[recvdatabuf[recv_id]->connectionID]->external_socketID);
705
                rParams.firstPacketArrived = recvdatabuf[recv_id]->firstPacketArrived;
706

    
707
//                 (receive_data_callback) (recvdatabuf[recv_id]->recvbuf + recvdatabuf[recv_id]->monitoringDataHeaderLen, recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->monitoringDataHeaderLen,
708
//                         recvdatabuf[recv_id]->msgtype, &rParams);
709

    
710
                //clean up
711
                if (recvdatabuf[recv_id]->timeout_event) {
712
                        event_del(recvdatabuf[recv_id]->timeout_event);
713
                        event_free(recvdatabuf[recv_id]->timeout_event);
714
                        recvdatabuf[recv_id]->timeout_event = NULL;
715
                }
716
                free(recvdatabuf[recv_id]->recvbuf);
717
                free(recvdatabuf[recv_id]);
718
                recvdatabuf[recv_id] = NULL;
719
        }
720
}
721

    
722
// process a single recv data message
723
void recv_data_msg(struct msg_header *msg_h, char *msgbuf, int bufsize)
724
{
725
        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);
726

    
727
        int recv_id, free_recv_id = -1;
728

    
729
        if(connectbuf[msg_h->remote_con_id] == NULL) {
730
                debug("ML: Received a message not related to any opened connection!\n");
731
                return;
732
        }
733

    
734
        // check if a recv_data exist and enter data
735
        for (recv_id = 0; recv_id < RECVDATABUFSIZE; recv_id++)
736
                if (recvdatabuf[recv_id] != NULL) {
737
                        if (msg_h->remote_con_id == recvdatabuf[recv_id]->connectionID &&
738
                                        msg_h->msg_seq_num == recvdatabuf[recv_id]->seqnr)
739
                                                break;
740
                } else
741
                        if(free_recv_id == -1)
742
                                free_recv_id = recv_id;
743

    
744

    
745
        if(recv_id == RECVDATABUFSIZE) {
746
                //no recv_data found: create one
747
                recv_id = free_recv_id;
748
                recvdatabuf[recv_id] = (recvdata *) malloc(sizeof(recvdata));
749
                memset(recvdatabuf[recv_id], 0, sizeof(recvdata));
750
                recvdatabuf[recv_id]->connectionID = msg_h->remote_con_id;
751
                recvdatabuf[recv_id]->seqnr = msg_h->msg_seq_num;
752
                recvdatabuf[recv_id]->monitoringDataHeaderLen = msg_h->len_mon_data_hdr;
753
                recvdatabuf[recv_id]->bufsize = msg_h->msg_length + msg_h->len_mon_data_hdr;
754
                recvdatabuf[recv_id]->recvbuf = (char *) malloc(recvdatabuf[recv_id]->bufsize);
755
                recvdatabuf[recv_id]->arrivedBytes = 0;        //count this without the Mon headers
756
                /*
757
                * read the timeout data and set it
758
                */
759
                recvdatabuf[recv_id]->timeout_value = recv_timeout;
760
                recvdatabuf[recv_id]->timeout_event = NULL;
761
                recvdatabuf[recv_id]->recvID = recv_id;
762
                recvdatabuf[recv_id]->starttime = time(NULL);
763
                recvdatabuf[recv_id]->msgtype = msg_h->msg_type;
764

    
765
                // fill the buffer with zeros
766
                memset(recvdatabuf[recv_id]->recvbuf, 0, recvdatabuf[recv_id]->bufsize);
767
                debug(" new @ id:%d\n",recv_id);
768
        } else {        //message structure already exists, no need to create new
769
                debug(" found @ id:%d (arrived before this packet: bytes:%d fragments%d\n",recv_id, recvdatabuf[recv_id]->arrivedBytes, recvdatabuf[recv_id]->recvFragments);
770
        }
771

    
772
        //if first packet extract mon data header and advance pointer
773
        if (msg_h->offset == 0) {
774
                memcpy(recvdatabuf[recv_id]->recvbuf, msgbuf, msg_h->len_mon_data_hdr);
775
                msgbuf += msg_h->len_mon_data_hdr;
776
                bufsize -= msg_h->len_mon_data_hdr;
777
                recvdatabuf[recv_id]->firstPacketArrived = 1;
778
        }
779

    
780

    
781
        // increment fragmentnr
782
        recvdatabuf[recv_id]->recvFragments++;
783
        // increment the arrivedBytes
784
        recvdatabuf[recv_id]->arrivedBytes += bufsize;
785

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

    
789
        //TODO very basic checkif all fragments arrived: has to be reviewed
790
        if(recvdatabuf[recv_id]->arrivedBytes == recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->monitoringDataHeaderLen)
791
                recvdatabuf[recv_id]->status = COMPLETE; //buffer full -> msg completly arrived
792
        else
793
                recvdatabuf[recv_id]->status = ACTIVE;
794

    
795
        if (recv_data_callback) {
796
                if(recvdatabuf[recv_id]->status == COMPLETE) {
797
                        // Monitoring layer hook
798
                        if(get_Recv_data_inf_cb != NULL) {
799
                                mon_data_inf recv_data_inf;
800

    
801
                                recv_data_inf.remote_socketID =
802
                                         &(connectbuf[recvdatabuf[recv_id]->connectionID]->external_socketID);
803
                                recv_data_inf.buffer = recvdatabuf[recv_id]->recvbuf;
804
                                recv_data_inf.bufSize = recvdatabuf[recv_id]->bufsize;
805
                                recv_data_inf.msgtype = recvdatabuf[recv_id]->msgtype;
806
                                recv_data_inf.monitoringDataHeaderLen = recvdatabuf[recv_id]->monitoringDataHeaderLen;
807
                                recv_data_inf.monitoringDataHeader = recvdatabuf[recv_id]->monitoringDataHeaderLen ?
808
                                        recvdatabuf[recv_id]->recvbuf : NULL;
809
                                gettimeofday(&recv_data_inf.arrival_time, NULL);
810
                                recv_data_inf.firstPacketArrived = recvdatabuf[recv_id]->firstPacketArrived;
811
                                recv_data_inf.recvFragments = recvdatabuf[recv_id]->recvFragments;
812
                                recv_data_inf.priority = false;
813
                                recv_data_inf.padding = false;
814
                                recv_data_inf.confirmation = false;
815
                                recv_data_inf.reliable = false;
816

    
817
                                // send data recv callback to monitoring module
818

    
819
                                (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
820
                        }
821

    
822
                        // Get the right callback
823
                        receive_data_cb receive_data_callback = recvcbbuf[msg_h->msg_type];
824
                        if (receive_data_callback) {
825

    
826
                                recv_params rParams;
827

    
828
                                rParams.nrMissingBytes = recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->monitoringDataHeaderLen - recvdatabuf[recv_id]->arrivedBytes;
829
                                rParams.recvFragments = recvdatabuf[recv_id]->recvFragments;
830
                                rParams.msgtype = recvdatabuf[recv_id]->msgtype;
831
                                rParams.connectionID = recvdatabuf[recv_id]->connectionID;
832
                                rParams.remote_socketID =
833
                                        &(connectbuf[recvdatabuf[recv_id]->connectionID]->external_socketID);
834

    
835
                                char str[1000];
836
                                mlSocketIDToString(rParams.remote_socketID,str,999);
837
                                debug("ML: received message from conID:%d, %s\n",recvdatabuf[recv_id]->connectionID,str);
838
                                rParams.firstPacketArrived = recvdatabuf[recv_id]->firstPacketArrived;
839

    
840
                                (receive_data_callback) (recvdatabuf[recv_id]->recvbuf + recvdatabuf[recv_id]->monitoringDataHeaderLen, recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->monitoringDataHeaderLen,
841
                                        recvdatabuf[recv_id]->msgtype, (void *) &rParams);
842
                        } else {
843
                            warn("ML: callback not initialized for this message type: %d!\n",msg_h->msg_type);
844
                        }
845

    
846
                        //clean up
847
                        if (recvdatabuf[recv_id]->timeout_event) {
848
                                debug("ML: freeing timeout for %d",recv_id);
849
                                event_del(recvdatabuf[recv_id]->timeout_event);
850
                                event_free(recvdatabuf[recv_id]->timeout_event);
851
                                recvdatabuf[recv_id]->timeout_event = NULL;
852
                        } else {
853
                                debug("ML: received in 1 packet\n",recv_id);
854
                        }
855
                        free(recvdatabuf[recv_id]->recvbuf);
856
                        free(recvdatabuf[recv_id]);
857
                        recvdatabuf[recv_id] = NULL;
858
                } else { // not COMPLETE
859
                        if (!recvdatabuf[recv_id]->timeout_event) {
860
                                //start time out
861
                                //TODO make timeout at least a DEFINE
862
                                recvdatabuf[recv_id]->timeout_event = event_new(base, -1, EV_TIMEOUT, &recv_timeout_cb, (void *) (long)recv_id);
863
                                evtimer_add(recvdatabuf[recv_id]->timeout_event, &recv_timeout);
864
                        }
865
                }
866
        }
867
}
868

    
869
//done
870
void pmtu_timeout_cb(int fd, short event, void *arg)
871
{
872

    
873
        int con_id = (long) arg;
874
        pmtu new_pmtusize;
875

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

    
878
        if(connectbuf[con_id] == NULL) {
879
                error("ML: pmtu timeout called on non existing con_id\n");
880
                return;
881
        }
882

    
883
        if(connectbuf[con_id]->status == READY) {
884
                // nothing to do anymore
885
                event_del(connectbuf[con_id]->timeout_event);
886
                event_free(connectbuf[con_id]->timeout_event);
887
                connectbuf[con_id]->timeout_event = NULL;
888
                return;
889
        }
890

    
891
        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);
892

    
893
        if(connectbuf[con_id]->delay || connectbuf[con_id]->trials == MAX_TRIALS - 1) {
894
                double delay = connectbuf[con_id]->timeout_value.tv_sec + connectbuf[con_id]->timeout_value.tv_usec / 1000000.0;
895
                delay = delay * 2;
896
                info("\tML: increasing pmtu timeout to %f sec\n", delay);
897
                connectbuf[con_id]->timeout_value.tv_sec = floor(delay);
898
                connectbuf[con_id]->timeout_value.tv_usec = fmod(delay, 1.0) * 1000000.0;
899
                if(connectbuf[con_id]->delay) {
900
                        connectbuf[con_id]->delay = false;
901
                        reschedule_conn_msg(con_id);
902
                }
903
        }
904

    
905
        if(connectbuf[con_id]->trials == MAX_TRIALS) {
906
                // decrement the pmtu size
907
                struct timeval tout = PMTU_TIMEOUT;
908
                info("\tML: decreasing pmtu estimate from %d to %d\n", connectbuf[con_id]->pmtusize, pmtu_decrement(connectbuf[con_id]->pmtusize));
909
                connectbuf[con_id]->pmtusize = pmtu_decrement(connectbuf[con_id]->pmtusize);
910
                connectbuf[con_id]->timeout_value = tout; 
911
                connectbuf[con_id]->trials = 0;
912
        }
913

    
914
        //error in PMTU discovery?
915
        if (connectbuf[con_id]->pmtusize == P_ERROR) {
916
                if (connectbuf[con_id]->internal_connect == true) {
917
                        //as of now we tried directly connecting, now let's try trough the NAT
918
                        connectbuf[con_id]->internal_connect = false;
919
                        connectbuf[con_id]->pmtusize = DSLSLIM;
920
                } else {
921
                        //nothing to do we have to give up
922
                        error("ML: Could not create connection with connectionID %i!\n",con_id);
923
                        // envoke the callback for failed connection establishment
924
                        if(failed_Connection_cb != NULL)
925
                                (failed_Connection_cb) (con_id, NULL);
926
                        // delete the connection entry
927
                        mlCloseConnection(con_id);
928
                        return;
929
                }
930
        }
931

    
932
        //retry
933
        resend_conn_msg(con_id);
934
}
935

    
936

    
937
int schedule_pmtu_timeout(int con_id)
938
{
939
        if (! connectbuf[con_id]->timeout_event) {
940
                struct timeval tout = PMTU_TIMEOUT;
941
                connectbuf[con_id]->timeout_value = tout;
942
                connectbuf[con_id]->trials = 1;
943
                connectbuf[con_id]->timeout_event = event_new(base, -1, EV_TIMEOUT, &pmtu_timeout_cb, (void *) (long)con_id);
944
                evtimer_add(connectbuf[con_id]->timeout_event, &connectbuf[con_id]->timeout_value);
945
        }
946
}
947

    
948
/*
949
 * decrements the mtu size
950
 */
951
pmtu pmtu_decrement(pmtu pmtusize)
952
{
953
        pmtu pmtu_return_size;
954
        switch(pmtusize) {
955
        case MAX:
956
                //return DSL;
957
                return DSLSLIM;        //shortcut to use less vales
958
        case DSL:
959
                return DSLMEDIUM;
960
        case DSLMEDIUM:
961
                return DSLSLIM;
962
        case DSLSLIM:
963
                //return BELOWDSL;
964
                return MIN;        //shortcut to use less vales
965
        case BELOWDSL:
966
                return MIN;
967
        case MIN:
968
                return P_ERROR;
969
        default:
970
                warn("ML: strange pmtu size encountered:%d, changing to some safe value:%d\n", pmtusize, MIN);
971
                return MIN;
972
        }
973
}
974

    
975
// called when an ICMP pmtu error message (type 3, code 4) is received
976
void pmtu_error_cb_th(char *msg, int msglen)
977
{
978
        debug("ML: pmtu_error callback called msg_size: %d\n",msglen);
979
        //TODO debug
980
        return;
981

    
982
    char *msgbufptr = NULL;
983
    int msgtype;
984
    int connectionID;
985
    pmtu pmtusize;
986
    pmtu new_pmtusize;
987
    int dead = 0;
988

    
989
    // check the packettype
990
    msgbufptr = &msg[0];
991

    
992
    // check the msgtype
993
    msgbufptr = &msg[1];
994
    memcpy(&msgtype, msgbufptr, 4);
995

    
996
    if (msgtype == 0) {
997

    
998
        // get the connectionID
999
        msgbufptr = &msg[5];
1000
        memcpy(&connectionID, msgbufptr, 4);
1001

    
1002
        int msgtype_c = connectbuf[connectionID]->status;
1003
//        pmtusize = connectbuf[connectionID]->pmtutrysize;
1004

    
1005
        if (msgtype_c != msgtype) {
1006
            dead = 1;
1007
        }
1008

    
1009

    
1010
    } else if (msgtype == 1) {
1011

    
1012
        // read the connectionID
1013
        msgbufptr = &msg[9];
1014
        memcpy(&connectionID, msgbufptr, 4);
1015

    
1016
        int msgtype_c = connectbuf[connectionID]->status;
1017
//        pmtusize = connectbuf[connectionID]->pmtutrysize;
1018

    
1019
        if (msgtype_c != msgtype) {
1020
            dead = 1;
1021
        }
1022

    
1023
    }
1024
    // decrement the pmtu size
1025
    new_pmtusize = pmtu_decrement(pmtusize);
1026

    
1027
//    connectbuf[connectionID]->pmtutrysize = new_pmtusize;
1028

    
1029
    if (new_pmtusize == P_ERROR) {
1030
                error("ML:  Could not create connection with connectionID %i !\n",
1031
                        connectionID);
1032

    
1033
                if(failed_Connection_cb != NULL)
1034
                        (failed_Connection_cb) (connectionID, NULL);
1035
                // set the message type to a non existent message
1036
                msgtype = 2;
1037
                // delete the connection entry
1038
                 mlCloseConnection(connectionID);
1039
        }
1040

    
1041
    if (msgtype == 0 && dead != 1) {
1042

    
1043
        // stop the timeout event
1044
        // timeout_del(connectbuf[connectionID]->timeout);
1045
        /*
1046
         * libevent2
1047
         */
1048

    
1049
        // event_del(connectbuf[connectionID]->timeout);
1050

    
1051

    
1052
        // create and send a connection message
1053
//         create_conn_msg(new_pmtusize, connectionID,
1054
//                         &local_socketID, INVITE);
1055

    
1056
//        send_conn_msg(connectionID, new_pmtusize);
1057

    
1058
        // set a timeout event for the pmtu discovery
1059
        // timeout_set(connectbuf[connectionID]->timeout,pmtu_timeout_cb,(void
1060
        // *)&connectionID);
1061

    
1062
        // timeout_add(connectbuf[connectionID]->timeout,&connectbuf[connectionID]->timeout_value);
1063

    
1064
        /*
1065
         * libevent2
1066
         */
1067

    
1068
        struct event *ev;
1069
        ev = evtimer_new(base, pmtu_timeout_cb,
1070
                         (void *) connectbuf[connectionID]);
1071

    
1072
        // connectbuf[connectionID]->timeout = ev;
1073

    
1074
        event_add(ev, &connectbuf[connectionID]->timeout_value);
1075

    
1076
    } else if (msgtype == 1 && dead != 1) {
1077

    
1078
        // stop the timeout event
1079
        // timeout_del(connectbuf[connectionID]->timeout);
1080

    
1081
        /*
1082
         * libevent2
1083
         */
1084
        // info("still here 11 \n");
1085
        // printf("ev %d \n",connectbuf[connectionID]->timeout);
1086
        // event_del(connectbuf[connectionID]->timeout );
1087
        // evtimer_del(connectbuf[connectionID]->timeout );
1088

    
1089

    
1090
//         // create and send a connection message
1091
//         create_conn_msg(new_pmtusize,
1092
//                         connectbuf[connectionID]->connectionID,
1093
//                         NULL, CONNECT);
1094

    
1095
        //send_conn_msg(connectionID, new_pmtusize);
1096

    
1097
        // set a timeout event for the pmtu discovery
1098
        // timeout_set(connectbuf[connectionID]->timeout,pmtu_timeout_cb,(void
1099
        // *)&connectionID);
1100
        // timeout_add(connectbuf[connectionID]->timeout,&connectbuf[connectionID]->timeout_value);
1101

    
1102
        /*
1103
         * libevent2
1104
         */
1105
        // struct event *ev;
1106
        // ev = evtimer_new(base,pmtu_timeout_cb, (void
1107
        // *)connectbuf[connectionID]);
1108
        // connectbuf[connectionID]->timeout = ev;
1109
        // event_add(ev,&connectbuf[connectionID]->timeout_value);
1110

    
1111
    }
1112
}
1113

    
1114
/*
1115
 * what to do once a packet arrived if it is a conn packet send it to
1116
 * recv_conn handler if it is a data packet send it to the recv_data
1117
 * handler
1118
 */
1119

    
1120
//done --
1121
void recv_pkg(int fd, short event, void *arg)
1122
{
1123
        debug("ML: recv_pkg called\n");
1124

    
1125
        struct msg_header *msg_h;
1126
        char msgbuf[MAX];
1127
        pmtu recvSize = MAX;
1128
        char *bufptr = msgbuf;
1129
        int ttl;
1130
        struct sockaddr_in recv_addr;
1131
        int msg_size;
1132

    
1133
        recvPacket(fd, msgbuf, &recvSize, &recv_addr, pmtu_error_cb_th, &ttl);
1134

    
1135

    
1136
        // check if it is not just an ERROR message
1137
        if(recvSize < 0)
1138
                return;
1139

    
1140
        // @TODO check if this simplistic STUN message recognition really always works, probably not
1141
        unsigned short stun_bind_response = 0x0101;
1142
        unsigned short * msgspot = (unsigned short *) msgbuf;
1143
        if (*msgspot == stun_bind_response) {
1144
                debug("ML: recv_pkg: parse stun message called on %d bytes\n", recvSize);
1145
                recv_stun_msg(msgbuf, recvSize);
1146
                return;
1147
        }
1148

    
1149
        msg_h = (struct msg_header *) msgbuf;
1150

    
1151
        /* convert header from network to host order */
1152
        msg_h->offset = ntohl(msg_h->offset);
1153
        msg_h->msg_length = ntohl(msg_h->msg_length);
1154
        msg_h->local_con_id = ntohl(msg_h->local_con_id);
1155
        msg_h->remote_con_id = ntohl(msg_h->remote_con_id);
1156
        msg_h->msg_seq_num = ntohl(msg_h->msg_seq_num);
1157

    
1158
        //verify minimum size
1159
        if (recvSize < sizeof(struct msg_header)) {
1160
          info("UDP packet too small, can't be an ML packet");
1161
          return;
1162
        }
1163

    
1164
        //TODO add more verifications
1165

    
1166
        bufptr += MSG_HEADER_SIZE + msg_h->len_mon_packet_hdr;
1167
        msg_size = recvSize - MSG_HEADER_SIZE - msg_h->len_mon_packet_hdr;
1168

    
1169
        //verify more fields
1170
        if (msg_size < 0) {
1171
          info("Corrupted UDP packet received");
1172
          return;
1173
        }
1174

    
1175
        if(get_Recv_pkt_inf_cb != NULL) {
1176
                mon_pkt_inf msginfNow;
1177
                msginfNow.monitoringHeaderLen = msg_h->len_mon_packet_hdr;
1178
                msginfNow.monitoringHeader = msg_h->len_mon_packet_hdr ? &msgbuf[0] + MSG_HEADER_SIZE : NULL;
1179
                //TODO rethink this ...
1180
                if(msg_h->msg_type == ML_CON_MSG) {
1181
                        struct conn_msg *c_msg = (struct conn_msg *) bufptr;
1182
                        msginfNow.remote_socketID = &(c_msg->sock_id);
1183
                }
1184
                else if(connectbuf[msg_h->remote_con_id] == NULL) {
1185
                        error("ML: received pkg called with non existent connection\n");
1186
                        return;
1187
                } else
1188
                        msginfNow.remote_socketID = &(connectbuf[msg_h->remote_con_id]->external_socketID);
1189
                msginfNow.buffer = bufptr;
1190
                msginfNow.bufSize = recvSize;
1191
                msginfNow.msgtype = msg_h->msg_type;
1192
                msginfNow.ttl = ttl;
1193
                msginfNow.dataID = msg_h->msg_seq_num;
1194
                msginfNow.offset = msg_h->offset;
1195
                msginfNow.datasize = msg_h->msg_length;
1196
                gettimeofday(&msginfNow.arrival_time, NULL);
1197
                (get_Recv_pkt_inf_cb) ((void *) &msginfNow);
1198
        }
1199

    
1200

    
1201
        switch(msg_h->msg_type) {
1202
                case ML_CON_MSG:
1203
                        debug("ML: received conn pkg\n");
1204
                        recv_conn_msg(msg_h, bufptr, msg_size, &recv_addr);
1205
                        break;
1206
                default:
1207
                        if(msg_h->msg_type < 127) {
1208
                                debug("ML: received data pkg\n");
1209
                                recv_data_msg(msg_h, bufptr, msg_size);
1210
                                break;
1211
                        }
1212
                        debug("ML: unrecognised msg_type\n");
1213
                        break;
1214
        }
1215
}
1216

    
1217
/*
1218
 * compare the external IP address of two socketIDs
1219
 */
1220
int
1221
compare_external_address_socketIDs(socketID_handle sock1, socketID_handle sock2)
1222
{
1223
        if( sock1->external_addr.udpaddr.sin_addr.s_addr == sock2->external_addr.udpaddr.sin_addr.s_addr)
1224
                return 0;
1225
        return 1;
1226
}
1227

    
1228
void try_stun();
1229

    
1230
/*
1231
 * the timeout of the NAT traversal
1232
 */
1233
void nat_traversal_timeout(int fd, short event, void *arg)
1234
{
1235
debug("X. NatTrTo %d\n", NAT_traversal);
1236
        if (NAT_traversal == false) {
1237
                debug("ML: NAT traversal request re-send\n");
1238
                if(receive_SocketID_cb)
1239
                        (receive_SocketID_cb) (&local_socketID, 2);
1240
                try_stun();
1241
        }
1242
debug("X. NatTrTo\n");
1243
}
1244

    
1245
//return IP address, or INADDR_NONE if can't resolve
1246
unsigned long resolve(const char *ipaddr)
1247
{
1248
        struct hostent *h = gethostbyname(ipaddr);
1249
        if (!h) {
1250
                error("ML: Unable to resolve host name %s\n", ipaddr);
1251
                return INADDR_NONE;
1252
        }
1253
        unsigned long *addr = (unsigned long *) (h->h_addr);
1254
        return *addr;
1255
}
1256

    
1257

    
1258
/*
1259
 * returns the file descriptor, or <0 on error. The ipaddr can be a null
1260
 * pointer. Then all available ipaddr on the machine are choosen.
1261
 */
1262
int create_socket(const int port, const char *ipaddr)
1263
{
1264
        struct sockaddr_in udpaddr = {0};
1265
        udpaddr.sin_family = AF_INET;
1266
        debug("X. create_socket %s, %d\n", ipaddr, port);
1267
        if (ipaddr == NULL) {
1268
                /*
1269
                * try to guess the local IP address
1270
                */
1271
                const char *ipaddr_iface = mlAutodetectIPAddress();
1272
                if (ipaddr_iface) {
1273
                        udpaddr.sin_addr.s_addr = inet_addr(ipaddr_iface);
1274
                } else {
1275
                        udpaddr.sin_addr.s_addr = INADDR_ANY;
1276
                }
1277
        } else {
1278
                udpaddr.sin_addr.s_addr = inet_addr(ipaddr);
1279
        }
1280
        udpaddr.sin_port = htons(port);
1281

    
1282
        socketaddrgen udpgen;
1283
        memset(&udpgen,0,sizeof(socketaddrgen));        //this will be sent over the net, so set it to 0
1284
        udpgen.udpaddr = udpaddr;
1285
        local_socketID.internal_addr = udpgen;
1286

    
1287
        socketfd = createSocket(port, ipaddr);
1288
        if (socketfd < 0){
1289
                return socketfd;
1290
        }
1291

    
1292
        struct event *ev;
1293
        ev = event_new(base, socketfd, EV_READ | EV_PERSIST, recv_pkg, NULL);
1294

    
1295
        event_add(ev, NULL);
1296

    
1297
        try_stun();
1298

    
1299
        return socketfd;
1300
}
1301

    
1302
/*
1303
 * try to figure out external IP using STUN, if defined
1304
 */
1305
void try_stun()
1306
{
1307
        if (isStunDefined()) {
1308
                /*
1309
                * send the NAT traversal STUN request
1310
                */
1311
                 send_stun_request(socketfd, &stun_server);
1312

    
1313
                /*
1314
                * enter a NAT traversal timeout that takes care of retransmission
1315
                */
1316
                struct event *ev1;
1317
                struct timeval timeout_value_NAT_traversal = NAT_TRAVERSAL_TIMEOUT;
1318
                ev1 = evtimer_new(base, nat_traversal_timeout, NULL);
1319
                event_add(ev1, &timeout_value_NAT_traversal);
1320

    
1321
                NAT_traversal = false;
1322
        } else {
1323
                /*
1324
                * Assume we have accessibility and copy internal address to external one
1325
                */
1326
                local_socketID.external_addr = local_socketID.internal_addr;
1327
                NAT_traversal = true; // @TODO: this is not really NAT traversal, but a flag that init is over
1328
                // callback to the upper layer indicating that the socketID is now
1329
                // ready to use
1330
                if(receive_SocketID_cb)
1331
                        (receive_SocketID_cb) (&local_socketID, 0); //success
1332
        }
1333
}
1334

    
1335
/**************************** END OF INTERNAL ***********************/
1336

    
1337
/**************************** MONL functions *************************/
1338

    
1339
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){
1340

    
1341
/*X*/ //  fprintf(stderr,"MLINIT1 %s, %d, %s, %d\n", ipaddr, port, stun_ipaddr, stun_port);
1342
        base = (struct event_base *) arg;
1343
        recv_data_callback = recv_data_cb;
1344
        mlSetRecvTimeout(timeout_value);
1345
        if (stun_ipaddr) {
1346
                 mlSetStunServer(stun_port, stun_ipaddr);
1347
        } else {
1348

    
1349
        }
1350
        register_recv_localsocketID_cb(local_socketID_cb);
1351
/*X*/ //  fprintf(stderr,"MLINIT1\n");
1352
        return create_socket(port, ipaddr);
1353
}
1354

    
1355
void mlSetThrottle(int bucketsize, int drainrate) {
1356
        setOutputRateParams(bucketsize, drainrate);
1357
}
1358
     
1359

    
1360
/* register callbacks  */
1361
void mlRegisterGetRecvPktInf(get_recv_pkt_inf_cb recv_pkt_inf_cb){
1362

    
1363
        if (recv_pkt_inf_cb == NULL) {
1364
                error("ML: Register get_recv_pkt_inf_cb failed: NULL ptr  \n");
1365
        } else {
1366
                get_Recv_pkt_inf_cb = recv_pkt_inf_cb;
1367
        }
1368
}
1369

    
1370
void mlRegisterGetSendPktInf(get_send_pkt_inf_cb  send_pkt_inf_cb){
1371

    
1372
        if (send_pkt_inf_cb == NULL) {
1373
                error("ML: Register get_send_pkt_inf_cb: NULL ptr  \n");
1374
        } else {
1375
                get_Send_pkt_inf_cb = send_pkt_inf_cb;
1376
        }
1377
}
1378

    
1379

    
1380
void mlRegisterSetMonitoringHeaderPktCb(set_monitoring_header_pkt_cb monitoring_header_pkt_cb ){
1381

    
1382
        if (monitoring_header_pkt_cb == NULL) {
1383
                error("ML: Register set_monitoring_header_pkt_cb: NULL ptr  \n");
1384
        } else {
1385
                set_Monitoring_header_pkt_cb = monitoring_header_pkt_cb;
1386
        }
1387
}
1388

    
1389
void mlRegisterGetRecvDataInf(get_recv_data_inf_cb recv_data_inf_cb){
1390

    
1391
        if (recv_data_inf_cb == NULL) {
1392
                error("ML: Register get_recv_data_inf_cb: NULL ptr  \n");
1393
        } else {
1394
                get_Recv_data_inf_cb = recv_data_inf_cb;
1395
        }
1396
}
1397

    
1398
void mlRegisterGetSendDataInf(get_send_data_inf_cb  send_data_inf_cb){
1399

    
1400
        if (send_data_inf_cb == NULL) {
1401
                error("ML: Register get_send_data_inf_cb: NULL ptr  \n");
1402
        } else {
1403
                get_Send_data_inf_cb = send_data_inf_cb;
1404
        }
1405
}
1406

    
1407
void mlRegisterSetMonitoringHeaderDataCb(set_monitoring_header_data_cb monitoring_header_data_cb){
1408

    
1409
        if (monitoring_header_data_cb == NULL) {
1410
                error("ML: Register set_monitoring_header_data_cb : NULL ptr  \n");
1411
        } else {
1412
                set_Monitoring_header_data_cb = monitoring_header_data_cb;
1413
        }
1414
}
1415

    
1416
void mlSetRecvTimeout(struct timeval timeout_value){
1417

    
1418
        recv_timeout = timeout_value;
1419

    
1420
}
1421

    
1422
int mlGetStandardTTL(socketID_handle socketID,uint8_t *ttl){
1423

    
1424
        return getTTL(socketfd, ttl);
1425

    
1426
}
1427

    
1428
socketID_handle mlGetLocalSocketID(int *errorstatus){
1429

    
1430
        if (NAT_traversal == false) {
1431
                *errorstatus = 2;
1432
                return NULL;
1433
        }
1434

    
1435
        *errorstatus = 0;
1436
        return &local_socketID;
1437

    
1438
}
1439

    
1440

    
1441
/**************************** END of MONL functions *************************/
1442

    
1443
/**************************** GENERAL functions *************************/
1444

    
1445
void mlRegisterRecvConnectionCb(receive_connection_cb recv_conn_cb){
1446

    
1447
        if (recv_conn_cb == NULL) {
1448
                error("ML: Register receive_connection_cb: NULL ptr  \n");
1449
        }else {
1450
                receive_Connection_cb = recv_conn_cb;
1451
        }
1452
}
1453

    
1454
void mlRegisterErrorConnectionCb(connection_failed_cb conn_failed){
1455

    
1456
        if (conn_failed == NULL) {
1457
                error("ML: Register connection_failed_cb: NULL ptr  \n");
1458
        } else {
1459
                failed_Connection_cb = conn_failed;
1460
        }
1461
}
1462

    
1463
void mlRegisterRecvDataCb(receive_data_cb data_cb,unsigned char msgtype){
1464

    
1465
    if (msgtype > 126) {
1466

    
1467
            error
1468
            ("ML: Could not register recv_data callback. Msgtype is greater then 126 \n");
1469

    
1470
    }
1471

    
1472
    if (data_cb == NULL) {
1473

    
1474
            error("ML: Register receive data callback: NUll ptr \n ");
1475

    
1476
    } else {
1477

    
1478
        recvcbbuf[msgtype] = data_cb;
1479

    
1480
    }
1481

    
1482
}
1483

    
1484
void mlCloseSocket(socketID_handle socketID){
1485

    
1486
        free(socketID);
1487

    
1488
}
1489

    
1490
void keepalive_fn(evutil_socket_t fd, short what, void *arg) {
1491
        socketID_handle peer = arg;
1492

    
1493
        int con_id = mlConnectionExist(peer, false);
1494
        if (con_id < 0 || connectbuf[con_id]->defaultSendParams.keepalive <= 0) {
1495
                /* Connection fell from under us or keepalive was disabled */
1496
                free(arg);
1497
                return;
1498
        }
1499

    
1500
        /* do what we gotta do */
1501
        if ( connectbuf[con_id]->status == READY) {
1502
                char keepaliveMsg[32] = "";
1503
                sprintf(keepaliveMsg, "KEEPALIVE %d", connectbuf[con_id]->keepalive_seq++);
1504
                send_msg(con_id, MSG_TYPE_ML_KEEPALIVE, keepaliveMsg, 1 + strlen(keepaliveMsg), false, 
1505
                        &(connectbuf[con_id]->defaultSendParams));
1506
        }
1507

    
1508
        /* re-schedule */
1509
        struct timeval t = { 0,0 };
1510
        t.tv_sec = connectbuf[con_id]->defaultSendParams.keepalive;
1511
        if (connectbuf[con_id]->defaultSendParams.keepalive) 
1512
                event_base_once(base, -1, EV_TIMEOUT, keepalive_fn, peer, &t);
1513
}
1514

    
1515
void setupKeepalive(int conn_id) {
1516
        /* Save the peer's address for us */
1517
        socketID_handle peer = malloc(sizeof(socket_ID));
1518
        memcpy(peer, &connectbuf[conn_id]->external_socketID, sizeof(socket_ID));
1519

    
1520
        struct timeval t = { 0,0 };
1521
        t.tv_sec = connectbuf[conn_id]->defaultSendParams.keepalive;
1522

    
1523
        if (connectbuf[conn_id]->defaultSendParams.keepalive) 
1524
                event_base_once(base, -1, EV_TIMEOUT, keepalive_fn, peer, &t);
1525
}
1526

    
1527
/* connection functions */
1528
int mlOpenConnection(socketID_handle external_socketID,receive_connection_cb connection_cb,void *arg, const send_params defaultSendParams){
1529

    
1530
        int con_id;
1531
        if (external_socketID == NULL) {
1532
                error("ML: cannot open connection: one of the socketIDs is NULL\n");
1533
                return -1;
1534
        }
1535
        if (NAT_traversal == false) {
1536
                error("ML: cannot open connection: NAT traversal for socketID still in progress\n");
1537
                return -1;
1538
        }
1539
        if (connection_cb == NULL) {
1540
                error("ML: cannot open connection: connection_cb is NULL\n");
1541
                return -1;
1542
        }
1543

    
1544
        // check if that connection already exist
1545

    
1546
        con_id = mlConnectionExist(external_socketID, false);
1547
        if (con_id >= 0) {
1548
                // overwrite defaultSendParams
1549
                bool newKeepalive = 
1550
                        connectbuf[con_id]->defaultSendParams.keepalive == 0 && defaultSendParams.keepalive != 0;
1551
                connectbuf[con_id]->defaultSendParams = defaultSendParams;
1552
                if (newKeepalive) setupKeepalive(con_id);
1553
                // if so check if it is ready to use
1554
                if (connectbuf[con_id]->status == READY) {
1555
                                // if so use the callback immediately
1556
                                (connection_cb) (con_id, arg);
1557

    
1558
                // otherwise just write the connection cb and the arg pointer
1559
                // into the connection struct
1560
                } else {
1561
                        struct receive_connection_cb_list *temp;
1562
                        temp = malloc(sizeof(struct receive_connection_cb_list));
1563
                        temp->next = NULL;
1564
                        temp->connection_cb = connection_cb;
1565
                        temp->arg = arg;
1566
                        if(connectbuf[con_id]->connection_last != NULL) {
1567
                                connectbuf[con_id]->connection_last->next = temp;
1568
                                connectbuf[con_id]->connection_last = temp;
1569
                        } else
1570
                                connectbuf[con_id]->connection_last = connectbuf[con_id]->connection_head = temp;
1571
                }
1572
                return con_id;
1573
        }
1574
        // make entry in connection_establishment array
1575
        for (con_id = 0; con_id < CONNECTBUFSIZE; con_id++) {
1576
                if (connectbuf[con_id] == NULL) {
1577
                        connectbuf[con_id] = (connect_data *) malloc(sizeof(connect_data));
1578
                        memset(connectbuf[con_id],0,sizeof(connect_data));
1579
                        connectbuf[con_id]->starttime = time(NULL);
1580
                        memcpy(&connectbuf[con_id]->external_socketID, external_socketID, sizeof(socket_ID));
1581
                        connectbuf[con_id]->pmtusize = DSLSLIM;
1582
                        connectbuf[con_id]->timeout_event = NULL;
1583
                        connectbuf[con_id]->status = INVITE;
1584
                        connectbuf[con_id]->seqnr = 0;
1585
                        connectbuf[con_id]->internal_connect = !compare_external_address_socketIDs(external_socketID, &local_socketID);
1586
                        connectbuf[con_id]->connectionID = con_id;
1587

    
1588
                        connectbuf[con_id]->connection_head = connectbuf[con_id]->connection_last = malloc(sizeof(struct receive_connection_cb_list));
1589
                        connectbuf[con_id]->connection_last->next = NULL;
1590
                        connectbuf[con_id]->connection_last->connection_cb = connection_cb;
1591
                        connectbuf[con_id]->connection_last->arg = arg;
1592
                        connectbuf[con_id]->external_connectionID = -1;
1593

    
1594
                        connectbuf[con_id]->defaultSendParams = defaultSendParams;
1595
                        if (defaultSendParams.keepalive) setupKeepalive(con_id);
1596
                        break;
1597
                }
1598
        } //end of for
1599

    
1600
        if (con_id == CONNECTBUFSIZE) {
1601
                error("ML: Could not open connection: connection buffer full\n");
1602
                return -1;
1603
        }
1604

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

    
1609
        return con_id;
1610

    
1611
}
1612

    
1613
void mlCloseConnection(const int connectionID){
1614

    
1615
        // remove it from the connection array
1616
        if(connectbuf[connectionID]) {
1617
                if(connectbuf[connectionID]->ctrl_msg_buf) {
1618
                        free(connectbuf[connectionID]->ctrl_msg_buf);
1619
                }
1620
                // remove related events
1621
                if (connectbuf[connectionID]->timeout_event) {
1622
                        event_del(connectbuf[connectionID]->timeout_event);
1623
                        event_free(connectbuf[connectionID]->timeout_event);
1624
                        connectbuf[connectionID]->timeout_event = NULL;
1625
                }
1626
                free(connectbuf[connectionID]);
1627
                connectbuf[connectionID] = NULL;
1628
        }
1629

    
1630
}
1631

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

    
1634
        if (connectionID < 0) {
1635
                error("ML: send data failed: connectionID does not exist\n");
1636
                return;
1637
        }
1638

    
1639
        if (connectbuf[connectionID] == NULL) {
1640
                error("ML: send data failed: connectionID does not exist\n");
1641
                return;
1642
        }
1643
        if (connectbuf[connectionID]->status != READY) {
1644
            error("ML: send data failed: connection is not active\n");
1645
            return;
1646
        }
1647

    
1648
        if (sParams == NULL) {
1649
                sParams = &(connectbuf[connectionID]->defaultSendParams);
1650
        }
1651

    
1652
        send_msg(connectionID, msgtype, sendbuf, bufsize, false, sParams);
1653

    
1654
}
1655

    
1656
/* transmit data functions  */
1657
int mlSendAllData(const int connectionID,send_all_data_container *container,int nr_entries,unsigned char msgtype,send_params *sParams){
1658

    
1659
    if (nr_entries < 1 || nr_entries > 5) {
1660

    
1661
        error
1662
            ("ML : sendALlData : nr_enties is not between 1 and 5 \n ");
1663
        return 0;
1664

    
1665
    } else {
1666

    
1667
        if (nr_entries == 1) {
1668

    
1669
                mlSendData(connectionID, container->buffer_1,
1670
                      container->length_1, msgtype, sParams);
1671

    
1672
            return 1;
1673

    
1674
        } else if (nr_entries == 2) {
1675

    
1676
            int buflen = container->length_1 + container->length_2;
1677
            char buf[buflen];
1678
            memcpy(buf, container->buffer_1, container->length_1);
1679
            memcpy(&buf[container->length_1], container->buffer_2,
1680
                   container->length_2);
1681
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1682

    
1683
            return 1;
1684

    
1685
        } else if (nr_entries == 3) {
1686

    
1687
            int buflen =
1688
                container->length_1 + container->length_2 +
1689
                container->length_3;
1690
            char buf[buflen];
1691
            memcpy(buf, container->buffer_1, container->length_1);
1692
            memcpy(&buf[container->length_1], container->buffer_2,
1693
                   container->length_2);
1694
            memcpy(&buf[container->length_2], container->buffer_3,
1695
                   container->length_3);
1696
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1697

    
1698

    
1699
            return 1;
1700

    
1701
        } else if (nr_entries == 4) {
1702

    
1703
            int buflen =
1704
                container->length_1 + container->length_2 +
1705
                container->length_3 + container->length_4;
1706
            char buf[buflen];
1707
            memcpy(buf, container->buffer_1, container->length_1);
1708
            memcpy(&buf[container->length_1], container->buffer_2,
1709
                   container->length_2);
1710
            memcpy(&buf[container->length_2], container->buffer_3,
1711
                   container->length_3);
1712
            memcpy(&buf[container->length_3], container->buffer_4,
1713
                   container->length_4);
1714
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1715

    
1716
            return 1;
1717

    
1718
        } else {
1719

    
1720
            int buflen =
1721
                container->length_1 + container->length_2 +
1722
                container->length_3 + container->length_4 +
1723
                container->length_5;
1724
            char buf[buflen];
1725
            memcpy(buf, container->buffer_1, container->length_1);
1726
            memcpy(&buf[container->length_1], container->buffer_2,
1727
                   container->length_2);
1728
            memcpy(&buf[container->length_2], container->buffer_3,
1729
                   container->length_3);
1730
            memcpy(&buf[container->length_3], container->buffer_4,
1731
                   container->length_4);
1732
            memcpy(&buf[container->length_4], container->buffer_5,
1733
                   container->length_5);
1734
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1735

    
1736
            return 1;
1737
        }
1738

    
1739
    }
1740

    
1741
}
1742

    
1743
int mlRecvData(const int connectionID,char *recvbuf,int *bufsize,recv_params *rParams){
1744

    
1745
        //TODO yet to be converted
1746
        return 0;
1747
#if 0
1748
        if (rParams == NULL) {
1749
                error("ML: recv_data failed: recv_params is a NULL ptr\n");
1750
                return 0;
1751
    } else {
1752

1753
        info("ML: recv data called \n");
1754

1755
        int i = 0;
1756
        int returnValue = 0;
1757
        double timeout = (double) recv_timeout.tv_sec;
1758
        time_t endtime = time(NULL);
1759

1760
        for (i = 0; i < RECVDATABUFSIZE; i++) {
1761

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

1764
                if (recvdatabuf[i]->connectionID == connectionID) {
1765

1766
                    info("ML: recv data has entry  \n");
1767

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

1770
                    // check if the specified connection has data and it
1771
                    // is complete
1772
                    // check the data seqnr
1773
                    // if(connectionID == recvdatabuf[i]->connectionID &&
1774
                    // 1 == recvdatabuf[i]->status){
1775

1776
                    if (1 == recvdatabuf[i]->status) {
1777

1778
                        // info("transmissionHandler: recv_data set is
1779
                        // complete \n" );
1780

1781
                        // debug("debud \n");
1782

1783
                        // exchange the pointers
1784
                        int buffersize = 0;
1785
                        buffersize = recvdatabuf[i]->bufsize;
1786
                        *bufsize = buffersize;
1787
                        // recvbuf = recvdatabuf[i]->recvbuf;
1788

1789
                        // info("buffersize %d \n",buffersize);
1790
                        memcpy(recvbuf, recvdatabuf[i]->recvbuf,
1791
                               buffersize);
1792
                        // debug(" recvbuf %s \n",recvbuf );
1793

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

1799
//                        rParams->nrMissingFragments = nrMissingFragments;
1800
//                         rParams->nrFragments = recvdatabuf[i]->nrFragments;
1801
                        rParams->msgtype = recvdatabuf[i]->msgtype;
1802
                        rParams->connectionID =
1803
                            recvdatabuf[i]->connectionID;
1804

1805
                        // break from the loop
1806
                        // debug(" recvbuf %s \n ",recvbuf);
1807

1808
                        // double nrMissFrags =
1809
                        // (double)recvdatabuf[i]->nrFragments /
1810
                        // (double)recvdatabuf[i]->recvFragments;
1811
                        // int nrMissingFragments =
1812
                        // (int)ceil(nrMissFrags);
1813

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

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

1832
                                // send data recv callback to monitoring module
1833

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

1837

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

1842
                        returnValue = 1;
1843
                        break;
1844

1845
                    }
1846

1847
                    if (recvdatabuf[i] != NULL) {
1848

1849
                        if (timepass > timeout) {
1850

1851
                            info("ML: recv_data timeout called  \n");
1852

1853
                            // some data about the missing chunks should
1854
                            // be added here
1855
                            // exchange the pointers
1856
                            int buffersize = 0;
1857
                            buffersize = recvdatabuf[i]->bufsize;
1858
                            *bufsize = buffersize;
1859
                            // recvbuf = recvdatabuf[i]->recvbuf;
1860

1861
                            double nrMissFrags =
1862
                                (double) recvdatabuf[i]->nrFragments /
1863
                                (double) recvdatabuf[i]->recvFragments;
1864
                            int nrMissingFragments =
1865
                                (int) ceil(nrMissFrags);
1866

1867
                            // debug(" recvbuf %s \n",recvbuf );
1868

1869
                            memcpy(recvbuf, recvdatabuf[i]->recvbuf,
1870
                                   buffersize);
1871

1872
                            rParams->nrMissingFragments =
1873
                                nrMissingFragments;
1874
                            rParams->nrFragments =
1875
                                recvdatabuf[i]->nrFragments;
1876
                            rParams->msgtype = recvdatabuf[i]->msgtype;
1877
                            rParams->connectionID =
1878
                                recvdatabuf[i]->connectionID;
1879

1880
                                if(get_Recv_data_inf_cb != NULL) {
1881
                                        mon_data_inf recv_data_inf;
1882

1883
                                        recv_data_inf.remote_socketID = &(connectbuf[connectionID]->external_socketID);
1884
                                        recv_data_inf.buffer = recvdatabuf[i]->recvbuf;
1885
                                        recv_data_inf.bufSize = recvdatabuf[i]->bufsize;
1886
                                        recv_data_inf.msgtype = recvdatabuf[i]->msgtype;
1887
                                        recv_data_inf.monitoringHeaderType = recvdatabuf[i]->monitoringHeaderType;
1888
                                        recv_data_inf.monitoringDataHeader = recvdatabuf[i]->monitoringDataHeader;
1889
                                        gettimeofday(&recv_data_inf.arrival_time, NULL);
1890
                                        recv_data_inf.firstPacketArrived = recvdatabuf[i]->firstPacketArrived;
1891
                                        recv_data_inf.nrMissingFragments = nrMissingFragments;
1892
                                        recv_data_inf.nrFragments = recvdatabuf[i]->nrFragments;
1893
                                        recv_data_inf.priority = false;
1894
                                        recv_data_inf.padding = false;
1895
                                        recv_data_inf.confirmation = false;
1896
                                        recv_data_inf.reliable = false;
1897

1898
                                        // send data recv callback to monitoring module
1899

1900
                                        (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
1901
                                }
1902

1903
                            // free the allocated memory
1904
                            free(recvdatabuf[i]);
1905
                            recvdatabuf[i] = NULL;
1906

1907
                            returnValue = 1;
1908
                            break;
1909

1910
                        }
1911
                    }
1912

1913
                }
1914

1915
            }
1916
            // debug("2 recvbuf %s \n ",recvbuf);
1917
        }
1918
        return returnValue;
1919
    }
1920
#endif
1921

    
1922
}
1923

    
1924
int mlSocketIDToString(socketID_handle socketID,char* socketID_string, size_t len){
1925

    
1926
        char internal_addr[INET_ADDRSTRLEN];
1927
        char external_addr[INET_ADDRSTRLEN];
1928

    
1929
        assert(socketID);
1930

    
1931
        inet_ntop(AF_INET, &(socketID->internal_addr.udpaddr.sin_addr.s_addr), internal_addr, INET_ADDRSTRLEN);
1932
        inet_ntop(AF_INET, &(socketID->external_addr.udpaddr.sin_addr.s_addr), external_addr, INET_ADDRSTRLEN);
1933

    
1934
        snprintf(socketID_string,len,"%s:%d-%s:%d", internal_addr, ntohs(socketID->internal_addr.udpaddr.sin_port),
1935
                external_addr,        ntohs(socketID->external_addr.udpaddr.sin_port));
1936
        return 0;
1937

    
1938
}
1939

    
1940
int mlStringToSocketID(const char* socketID_string, socketID_handle socketID){
1941

    
1942
        //@TODO add checks against malformed string
1943
        char external_addr[INET_ADDRSTRLEN];
1944
        int external_port;
1945
        char internal_addr[INET_ADDRSTRLEN];
1946
        int internal_port;
1947

    
1948
        char *pch;
1949
        char *s = strdup(socketID_string);
1950

    
1951
        //replace ':' with a blank
1952
        pch=strchr(s,':');
1953
        while (pch!=NULL){
1954
                                *pch = ' ';
1955
                pch=strchr(pch+1,':');
1956
        }
1957
        pch=strchr(s,'-');
1958
        if(pch) *pch = ' ';
1959

    
1960
        sscanf(s,"%s %d %s %d", internal_addr, &internal_port,
1961
                external_addr, &external_port);
1962

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

    
1966
        if(inet_pton(AF_INET, internal_addr, &(socketID->internal_addr.udpaddr.sin_addr)) == 0)
1967
                return EINVAL;
1968
        socketID->internal_addr.udpaddr.sin_family = AF_INET;
1969
        socketID->internal_addr.udpaddr.sin_port = htons(internal_port);
1970

    
1971

    
1972
        if(inet_pton(AF_INET, external_addr, &(socketID->external_addr.udpaddr.sin_addr)) ==0)
1973
                return EINVAL;
1974
        socketID->external_addr.udpaddr.sin_family = AF_INET;
1975
        socketID->external_addr.udpaddr.sin_port = htons(external_port);
1976

    
1977
        free(s);
1978
        return 0;
1979

    
1980
}
1981

    
1982
int mlGetConnectionStatus(int connectionID){
1983

    
1984
        if(connectbuf[connectionID])
1985
                return connectbuf[connectionID]->status == READY;
1986
        return -1;
1987
    
1988
}
1989

    
1990

    
1991
int mlConnectionExist(socketID_handle socketID, bool ready){
1992

    
1993
    /*
1994
     * check if another connection for the external connectionID exist
1995
     * that was established \ within the last 2 seconds
1996
     */
1997
        int i;
1998
        for (i = 0; i < CONNECTBUFSIZE; i++)
1999
                if (connectbuf[i] != NULL)
2000
                        if (mlCompareSocketIDs(&(connectbuf[i]->external_socketID), socketID) == 0) {
2001
                                if (ready) return (connectbuf[i]->status == READY ? i : -1);;
2002
                                return i;
2003
                                }
2004

    
2005
    return -1;
2006

    
2007
}
2008

    
2009
//Added by Robert Birke as comodity functions
2010

    
2011
//int mlPrintSocketID(socketID_handle socketID) {
2012
//        char str[SOCKETID_STRING_SIZE];
2013
//        mlSocketIDToString(socketID, str, sizeof(str));
2014
//        printf(stderr,"int->%s<-ext\n",str);
2015
//}
2016

    
2017
/*
2018
 * hash code of a socketID
2019
 * TODO might think of a better way
2020
 */
2021
int mlHashSocketID(socketID_handle sock) {
2022
        //assert(sock);
2023
   return sock->internal_addr.udpaddr.sin_port +
2024
                        sock->external_addr.udpaddr.sin_port;
2025
}
2026

    
2027
int mlCompareSocketIDs(socketID_handle sock1, socketID_handle sock2) {
2028

    
2029
        assert(sock1 && sock2);
2030

    
2031
        /*
2032
        * compare internal addr
2033
        */
2034
        if(sock1 == NULL || sock2 == NULL)
2035
                return 1;
2036

    
2037
        if (sock1->internal_addr.udpaddr.sin_addr.s_addr !=
2038
            sock2->internal_addr.udpaddr.sin_addr.s_addr)
2039
                        return 1;
2040

    
2041
        if (sock1->internal_addr.udpaddr.sin_port !=
2042
                 sock2->internal_addr.udpaddr.sin_port)
2043
                        return 1;
2044

    
2045
        /*
2046
        * compare external addr
2047
        */
2048
        if (sock1->external_addr.udpaddr.sin_addr.s_addr !=
2049
            sock2->external_addr.udpaddr.sin_addr.s_addr)
2050
                        return 1;
2051

    
2052
        if (sock1->external_addr.udpaddr.sin_port !=
2053
                 sock2->external_addr.udpaddr.sin_port)
2054
                        return 1;
2055

    
2056
        return 0;
2057
}
2058

    
2059
int mlCompareSocketIDsByPort(socketID_handle sock1, socketID_handle sock2)
2060
{
2061
        if(sock1 == NULL || sock2 == NULL)
2062
                return 1;
2063
 
2064
        if (sock1->internal_addr.udpaddr.sin_port !=
2065
                 sock2->internal_addr.udpaddr.sin_port)
2066
                        return 1;
2067

    
2068
        if (sock1->external_addr.udpaddr.sin_port !=
2069
                 sock2->external_addr.udpaddr.sin_port)
2070
                        return 1;
2071
        return 0;
2072
}
2073

    
2074
int mlGetPathMTU(int ConnectionId) {
2075
        if(ConnectionId < 0 || ConnectionId >= CONNECTBUFSIZE)
2076
                return -1;
2077
        if (connectbuf[ConnectionId] != NULL)
2078
                return connectbuf[ConnectionId]->pmtusize;
2079
        return -1;
2080
}
2081

    
2082
/**************************** END of GENERAL functions *************************/
2083

    
2084
/**************************** NAT functions *************************/
2085

    
2086
/* setter  */
2087
void mlSetStunServer(const int port,const char *ipaddr){
2088

    
2089
        stun_server.sin_family = AF_INET;
2090
        if (ipaddr == NULL)
2091
                stun_server.sin_addr.s_addr = htonl(INADDR_NONE);
2092
        else
2093
                stun_server.sin_addr.s_addr = resolve(ipaddr);
2094
        stun_server.sin_port = htons(port);
2095

    
2096
}
2097

    
2098
int mlGetExternalIP(char* external_addr){
2099

    
2100
        socketaddrgen udpgen;
2101
        struct sockaddr_in udpaddr;
2102

    
2103
        udpgen = local_socketID.external_addr;
2104
        udpaddr = udpgen.udpaddr;
2105

    
2106
        inet_ntop(AF_INET, &(udpaddr.sin_addr), external_addr,
2107
                        INET_ADDRSTRLEN);
2108

    
2109
        if (external_addr == NULL) {
2110

    
2111
        return -1;
2112

    
2113
        } else {
2114

    
2115
        return 0;
2116

    
2117
        }
2118

    
2119
}
2120

    
2121
/**************************** END of NAT functions *************************/