Statistics
| Branch: | Revision:

ml / ml.c @ 9bf9c247

History | View | Annotate | Download (61.5 KB)

1
/*
2
 *          Policy Management
3
 *
4
 *          NEC Europe Ltd. PROPRIETARY INFORMATION
5
 *
6
 * This software is supplied under the terms of a license agreement
7
 * or nondisclosure agreement with NEC Europe Ltd. and may not be
8
 * copied or disclosed except in accordance with the terms of that
9
 * agreement.
10
 *
11
 *      Copyright (c) 2009 NEC Europe Ltd. All Rights Reserved.
12
 *
13
 * Authors: Kristian Beckers  <beckers@nw.neclab.eu>
14
 *          Sebastian Kiesel  <kiesel@nw.neclab.eu>
15
 *          
16
 *
17
 * NEC Europe Ltd. DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED,
18
 * INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY
19
 * AND FITNESS FOR A PARTICULAR PURPOSE AND THE WARRANTY AGAINST LATENT
20
 * DEFECTS, WITH RESPECT TO THE PROGRAM AND THE ACCOMPANYING
21
 * DOCUMENTATION.
22
 *
23
 * No Liability For Consequential Damages IN NO EVENT SHALL NEC Europe
24
 * Ltd., NEC Corporation OR ANY OF ITS SUBSIDIARIES BE LIABLE FOR ANY
25
 * DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS
26
 * OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF INFORMATION, OR
27
 * OTHER PECUNIARY LOSS AND INDIRECT, CONSEQUENTIAL, INCIDENTAL,
28
 * ECONOMIC OR PUNITIVE DAMAGES) ARISING OUT OF THE USE OF OR INABILITY
29
 * TO USE THIS PROGRAM, EVEN IF NEC Europe Ltd. HAS BEEN ADVISED OF THE
30
 * POSSIBILITY OF SUCH DAMAGES.
31
 *
32
 *     THIS HEADER MAY NOT BE EXTRACTED OR MODIFIED IN ANY WAY.
33
 */
34

    
35
#include <arpa/inet.h>
36
#ifndef WIN32
37
#include <netinet/in.h>
38
#include <sys/socket.h>
39
#endif
40
#include <fcntl.h>
41
#include <event2/event.h>
42
#include <stdlib.h>
43
#include <unistd.h>
44
#include <stdio.h>
45
#include <stddef.h>
46
#include <stdint.h>
47
#include <string.h>
48
#include <sys/types.h>
49
#include <arpa/inet.h>
50
#include <netdb.h>
51
#include <errno.h>
52
#include <time.h>
53
#include <math.h>
54
#include <assert.h>
55

    
56
#include "util/udpSocket.h"
57
#include "util/stun.h"
58
#include "transmissionHandler.h"
59

    
60
#define LOG_MODULE "[ml] "
61
#include "ml_log.h"
62

    
63
/**************************** START OF INTERNALS ***********************/
64

    
65

    
66
/*
67
 * reserved message type for internal puposes
68
 */
69
#define MSG_TYPE_ML_KEEPALIVE 0x126        //TODO: check that it is really interpreted as internal
70

    
71
/*
72
 * a pointer to a libevent instance
73
 */
74
struct event_base *base;
75

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

    
89

    
90
/*
91
 * timeout before thinking that the STUN server can't be connected
92
 */
93
#define NAT_TRAVERSAL_TIMEOUT { 1, 0 }
94

    
95
/*
96
 * timeout before thinking of an mtu problem (check MAX_TRIALS as well)
97
 */
98
#define PMTU_TIMEOUT { 0, 500000 }
99

    
100
/*
101
 * retry sending connection messages this many times before reducing pmtu
102
 */
103
#define MAX_TRIALS 3
104

    
105
/*
106
 * default timeout value between the first and the last received packet of a message
107
 */
108
#define RECV_TIMEOUT_DEFAULT { 2, 0 }
109

    
110
/*
111
 * global variables
112
 */
113
/*
114
 * define a buffer of pointers to connect structures
115
 */
116
connect_data *connectbuf[CONNECTBUFSIZE];
117

    
118
/*
119
 * define a pointer buffer with pointers to recv_data structures
120
 */
121
recvdata *recvdatabuf[RECVDATABUFSIZE];
122

    
123
/*
124
 * define a pointer buffer for message multiplexing
125
 */
126
receive_data_cb recvcbbuf[MSGMULTIPLEXSIZE];
127

    
128
/*
129
 * stun server address
130
 */
131
struct sockaddr_in stun_server;
132

    
133
/*
134
 * receive timeout
135
 */
136
static struct timeval recv_timeout = RECV_TIMEOUT_DEFAULT;
137

    
138
/*
139
 * boolean NAT traversal successful if true
140
 */
141
boolean NAT_traversal;
142

    
143
/*
144
 * file descriptor for local socket
145
 */
146
evutil_socket_t socketfd;
147

    
148
/*
149
 * local socketID
150
 */
151
socket_ID local_socketID;
152

    
153
socketID_handle loc_socketID = &local_socketID;
154

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

    
177
/*
178
 * boolean that defines if received data is transmitted to the upper layer
179
 * via callback or via upper layer polling
180
 */
181
boolean recv_data_callback;
182

    
183
/*
184
 * helper function to get rid of a warning
185
 */
186
int min(int a, int b) {
187
        if (a > b) return b;
188
        return a;
189
}
190

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

    
201
void register_recv_localsocketID_cb(receive_localsocketID_cb local_socketID_cb)
202
{
203
        if (local_socketID_cb == NULL) {
204
                error("ML : Register receive_localsocketID_cb: NULL ptr \n");
205
        } else {
206
                receive_SocketID_cb = local_socketID_cb;
207
        }
208
}
209

    
210

    
211
//void keep_connection_alive(const int connectionID)
212
//{
213
//
214
//    // to be done with the NAT traversal
215
//    // send a message over the wire
216
//    printf("\n");
217
//
218
//}
219

    
220
void unsetStunServer()
221
{
222
        stun_server.sin_addr.s_addr = INADDR_NONE;
223
}
224

    
225
bool isStunDefined()
226
{
227
        return stun_server.sin_addr.s_addr != INADDR_NONE;
228
}
229

    
230
void send_msg(int con_id, int msg_type, char* msg, int msg_len, bool truncable, send_params * sParams) {
231
        socketaddrgen udpgen;
232
        bool retry;
233
        int pkt_len, offset;
234
        struct iovec iov[4];
235

    
236
        char h_pkt[MON_PKT_HEADER_SPACE];
237
        char h_data[MON_DATA_HEADER_SPACE];
238

    
239
        struct msg_header msg_h;
240

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

    
243
        iov[0].iov_base = &msg_h;
244
        iov[0].iov_len = MSG_HEADER_SIZE;
245

    
246
        msg_h.local_con_id = htonl(con_id);
247
        msg_h.remote_con_id = htonl(connectbuf[con_id]->external_connectionID);
248
        msg_h.msg_type = msg_type;
249
        msg_h.msg_seq_num = htonl(connectbuf[con_id]->seqnr++);
250

    
251

    
252
        iov[1].iov_len = iov[2].iov_len = 0;
253
        iov[1].iov_base = h_pkt;
254
        iov[2].iov_base = h_data;
255

    
256

    
257
        if (connectbuf[con_id]->internal_connect)
258
                udpgen = connectbuf[con_id]->external_socketID.internal_addr;
259
        else
260
                udpgen = connectbuf[con_id]->external_socketID.external_addr;
261

    
262
        do{
263
                offset = 0;
264
                retry = false;
265
                // Monitoring layer hook
266
                if(set_Monitoring_header_data_cb != NULL) {
267
                        iov[2].iov_len = ((set_Monitoring_header_data_cb) (&(connectbuf[con_id]->external_socketID), msg_type));
268
                }
269
                msg_h.len_mon_data_hdr = iov[2].iov_len;
270

    
271
                if(get_Send_data_inf_cb != NULL && iov[2].iov_len != 0) {
272
                        mon_data_inf sd_data_inf;
273

    
274
                        memset(h_data, 0, MON_DATA_HEADER_SPACE);
275

    
276
                        sd_data_inf.remote_socketID = &(connectbuf[con_id]->external_socketID);
277
                        sd_data_inf.buffer = msg;
278
                        sd_data_inf.bufSize = msg_len;
279
                        sd_data_inf.msgtype = msg_type;
280
                        sd_data_inf.monitoringDataHeader = iov[2].iov_base;
281
                        sd_data_inf.monitoringDataHeaderLen = iov[2].iov_len;
282
                        sd_data_inf.priority = sParams->priority;
283
                        sd_data_inf.padding = sParams->padding;
284
                        sd_data_inf.confirmation = sParams->confirmation;
285
                        sd_data_inf.reliable = sParams->reliable;
286
                        memset(&sd_data_inf.arrival_time, 0, sizeof(struct timeval));
287

    
288
                        (get_Send_data_inf_cb) ((void *) &sd_data_inf);
289
                }
290

    
291
                do {
292
                        if(set_Monitoring_header_pkt_cb != NULL) {
293
                                iov[1].iov_len = (set_Monitoring_header_pkt_cb) (&(connectbuf[con_id]->external_socketID), msg_type);
294
                        }
295
                        pkt_len = min(connectbuf[con_id]->pmtusize - iov[2].iov_len - iov[1].iov_len - iov[0].iov_len, msg_len - offset) ;
296

    
297
                        iov[3].iov_len = pkt_len;
298
                        iov[3].iov_base = msg + offset;
299

    
300
                        //fill header
301
                        msg_h.len_mon_packet_hdr = iov[1].iov_len;
302
                        msg_h.offset = htonl(offset);
303
                        msg_h.msg_length = htonl(truncable ? pkt_len : msg_len);
304

    
305
                        //monitoring layer hook
306
                        if(get_Send_pkt_inf_cb != NULL && iov[1].iov_len) {
307
                                mon_pkt_inf pkt_info;
308

    
309
                                memset(h_pkt,0,MON_PKT_HEADER_SPACE);
310

    
311
                                pkt_info.remote_socketID = &(connectbuf[con_id]->external_socketID);
312
                                pkt_info.buffer = msg + offset;
313
                                pkt_info.bufSize = pkt_len;
314
                                pkt_info.msgtype = msg_type;
315
                                pkt_info.dataID = connectbuf[con_id]->seqnr;
316
                                pkt_info.offset = offset;
317
                                pkt_info.datasize = msg_len;
318
                                pkt_info.monitoringHeaderLen = iov[1].iov_len;
319
                                pkt_info.monitoringHeader = iov[1].iov_base;
320
                                pkt_info.ttl = -1;
321
                                memset(&(pkt_info.arrival_time),0,sizeof(struct timeval));
322

    
323
                                (get_Send_pkt_inf_cb) ((void *) &pkt_info);
324
                        }
325

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

    
353
void pmtu_timeout_cb(int fd, short event, void *arg);
354

    
355
void reschedule_conn_msg(int con_id)
356
{
357
        if (connectbuf[con_id]->timeout_event) {
358
                /* delete old timout */        
359
                event_del(connectbuf[con_id]->timeout_event);
360
                event_free(connectbuf[con_id]->timeout_event);
361
        }
362
        connectbuf[con_id]->timeout_event = event_new(base, -1, EV_TIMEOUT, &pmtu_timeout_cb, (void *) (long)con_id);
363
        evtimer_add(connectbuf[con_id]->timeout_event, &connectbuf[con_id]->timeout_value);
364
}
365

    
366
void send_conn_msg(int con_id, int buf_size, int command_type)
367
{
368
        if (buf_size < sizeof(struct conn_msg)) {
369
                error("ML: requested connection message size is too small\n");
370
                return;
371
        }
372

    
373
        if(connectbuf[con_id]->ctrl_msg_buf == NULL) {
374
                connectbuf[con_id]->ctrl_msg_buf = malloc(buf_size);
375
                memset(connectbuf[con_id]->ctrl_msg_buf, 0, buf_size);
376
        }
377

    
378
        if(connectbuf[con_id]->ctrl_msg_buf == NULL) {
379
                error("ML: can not allocate memory for connection message\n");
380
                return;
381
        }
382

    
383
        struct conn_msg *msg_header = (struct conn_msg*) connectbuf[con_id]->ctrl_msg_buf;
384

    
385
        msg_header->comand_type = command_type;
386
        msg_header->pmtu_size = connectbuf[con_id]->pmtusize;
387

    
388
        memcpy(&(msg_header->sock_id), loc_socketID, sizeof(socket_ID));
389

    
390
        send_msg(con_id, ML_CON_MSG, connectbuf[con_id]->ctrl_msg_buf, buf_size, true, &(connectbuf[con_id]->defaultSendParams));
391
}
392

    
393
void send_conn_msg_with_pmtu_discovery(int con_id, int buf_size, int command_type)
394
{
395
        struct timeval tout = PMTU_TIMEOUT;
396
        connectbuf[con_id]->timeout_value = tout;
397
        connectbuf[con_id]->trials = 1;
398
        send_conn_msg(con_id, buf_size, command_type);
399
        reschedule_conn_msg(con_id);
400
}
401

    
402
void resend_conn_msg(int con_id)
403
{
404
        connectbuf[con_id]->trials++;
405
        send_conn_msg(con_id, connectbuf[con_id]->pmtusize, connectbuf[con_id]->status);
406
        reschedule_conn_msg(con_id);
407
}
408

    
409
void recv_conn_msg(struct msg_header *msg_h, char *msgbuf, int msg_size, struct sockaddr_in *recv_addr)
410
{
411
        struct conn_msg *con_msg;
412
        int free_con_id, con_id;
413

    
414
        time_t now = time(NULL);
415
        double timediff = 0.0;
416
        char sock_id_str[1000];
417
        
418
        msgbuf += msg_h->len_mon_data_hdr;
419
        msg_size -= msg_h->len_mon_data_hdr;
420
        con_msg = (struct conn_msg *)msgbuf;
421
        
422
        //verify message validity
423
        if (msg_size < sizeof(struct conn_msg)) {
424
                char recv_addr_str[INET_ADDRSTRLEN];
425
                inet_ntop(AF_INET, &(recv_addr->sin_addr.s_addr), recv_addr_str, INET_ADDRSTRLEN);
426
                info("Invalid conn_msg received from %s\n", recv_addr_str);
427
                return;
428
        }
429

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

    
433
        if (con_msg->sock_id.internal_addr.udpaddr.sin_addr.s_addr != recv_addr->sin_addr.s_addr &&
434
            con_msg->sock_id.external_addr.udpaddr.sin_addr.s_addr != recv_addr->sin_addr.s_addr   ) {
435
                char recv_addr_str[INET_ADDRSTRLEN];
436
                inet_ntop(AF_INET, &(recv_addr->sin_addr.s_addr), recv_addr_str, INET_ADDRSTRLEN);
437
                info("Conn msg received from %s, but claims to be from %s", recv_addr_str, sock_id_str);
438
                return;
439
        }
440

    
441
        // Monitoring layer hook
442
        if(get_Recv_data_inf_cb != NULL) {
443
                // update pointer to the real data
444
                mon_data_inf recv_data_inf;
445
                recv_data_inf.remote_socketID = &(con_msg->sock_id);
446
                recv_data_inf.buffer = msgbuf;
447
                recv_data_inf.bufSize = msg_size;
448
                recv_data_inf.msgtype = msg_h->msg_type;
449
                recv_data_inf.monitoringDataHeaderLen = msg_h->len_mon_data_hdr;
450
                recv_data_inf.monitoringDataHeader = msg_h->len_mon_data_hdr ? msgbuf : NULL;
451
                gettimeofday(&recv_data_inf.arrival_time, NULL);
452
                recv_data_inf.firstPacketArrived = true;
453
                recv_data_inf.recvFragments = 1;
454
                recv_data_inf.priority = false;
455
                recv_data_inf.padding = false;
456
                recv_data_inf.confirmation = false;
457
                recv_data_inf.reliable = false;
458

    
459
                // send data recv callback to monitoring module
460
                (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
461
        }
462

    
463
        // check the connection command type
464
        switch (con_msg->comand_type) {
465
                /*
466
                * if INVITE: enter a new socket make new entry in connect array
467
                * send an ok
468
                */
469
                case INVITE:
470
                        info("ML: received INVITE from %s (size:%d)\n", sock_id_str, msg_size);
471
                        /*
472
                        * check if another connection for the external connectionID exist
473
                        * that was established within the last 2 seconds
474
                        */
475
                        free_con_id = -1;
476
                        for (con_id = 0; con_id < CONNECTBUFSIZE; con_id++) {
477
                                if (connectbuf[con_id] != NULL) {
478
                                        if (mlCompareSocketIDs(&(connectbuf[con_id]->external_socketID), &(con_msg->sock_id)) == 0) {
479
                                                //timediff = difftime(now, connectbuf[con_id]->starttime);        //TODO: why this timeout? Shouldn't the connection be closed instead if there is a timeout?
480
                                                //if (timediff < 2)
481
                                                //update remote connection ID
482
                                                if (connectbuf[con_id]->external_connectionID != msg_h->local_con_id) {
483
                                                        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);
484
                                                        connectbuf[con_id]->external_connectionID = msg_h->local_con_id;
485
                                                }
486
                                                break;
487
                                        }
488
                                } else if(free_con_id == -1)
489
                                        free_con_id = con_id;
490
                        }
491

    
492
                        if (con_id == CONNECTBUFSIZE) {
493
                                // create an entry in the connecttrybuf
494
                                if(free_con_id == -1) {
495
                                        error("ML: no new connect_buf available\n");
496
                                        return;
497
                                }
498
                                connectbuf[free_con_id] = (connect_data *) malloc(sizeof(connect_data));
499
                                memset(connectbuf[free_con_id],0,sizeof(connect_data));
500
                                connectbuf[free_con_id]->connection_head = connectbuf[free_con_id]->connection_last = NULL;
501
                                connectbuf[free_con_id]->starttime = time(NULL);
502
                                memcpy(&(connectbuf[free_con_id]->external_socketID), &(con_msg->sock_id), sizeof(socket_ID));
503
                                connectbuf[free_con_id]->pmtusize = con_msg->pmtu_size;        // bootstrap pmtu from the other's size. Not strictly needed, but a good hint
504
                                connectbuf[free_con_id]->timeout_event = NULL;
505
                                connectbuf[free_con_id]->external_connectionID = msg_h->local_con_id;
506
                                connectbuf[free_con_id]->internal_connect =
507
                                        !compare_external_address_socketIDs(&(con_msg->sock_id), loc_socketID);
508
                                con_id = free_con_id;
509
                        }
510

    
511
                        //if(connectbuf[con_id]->status <= CONNECT) { //TODO: anwer anyway. Why the outher would invite otherwise?
512
                                //update status and send back answer
513
                                connectbuf[con_id]->status = CONNECT;
514
                                send_conn_msg_with_pmtu_discovery(con_id, con_msg->pmtu_size, CONNECT);
515
                        //}
516
                        break;
517
                case CONNECT:
518
                        info("ML: received CONNECT from %s (size:%d)\n", sock_id_str, msg_size);
519

    
520
                        if(msg_h->remote_con_id != -1 && connectbuf[msg_h->remote_con_id] == NULL) {
521
                                error("ML: received CONNECT for inexistent connection rconID:%d\n",msg_h->remote_con_id);
522
                                return;
523
                        }
524

    
525
                        /*
526
                        * check if the connection status is not already 1 or 2
527
                        */
528
                        if (connectbuf[msg_h->remote_con_id]->status == INVITE) {
529
                                // set the external connectionID
530
                                connectbuf[msg_h->remote_con_id]->external_connectionID = msg_h->local_con_id;
531
                                // change status con_msg the connection_data
532
                                connectbuf[msg_h->remote_con_id]->status = READY;
533
                                // change pmtusize in the connection_data: not needed. receiving a CONNECT means our INVITE went through. So why change pmtu?
534
                                //connectbuf[msg_h->remote_con_id]->pmtusize = con_msg->pmtu_size;
535

    
536
                                // send the READY
537
                                send_conn_msg_with_pmtu_discovery(msg_h->remote_con_id, con_msg->pmtu_size, READY);
538

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

    
542
                                // call all registered callbacks
543
                                while(connectbuf[msg_h->remote_con_id]->connection_head != NULL) {
544
                                        struct receive_connection_cb_list *temp;
545
                                        temp = connectbuf[msg_h->remote_con_id]->connection_head;
546
                                        (temp->connection_cb) (msg_h->remote_con_id, temp->arg);
547
                                        connectbuf[msg_h->remote_con_id]->connection_head = temp->next;
548
                                        free(temp);
549
                                }
550
                                connectbuf[msg_h->remote_con_id]->connection_head =
551
                                        connectbuf[msg_h->remote_con_id]->connection_last = NULL;
552
                        } else {
553
                                // send the READY
554
                                send_conn_msg_with_pmtu_discovery(msg_h->remote_con_id, con_msg->pmtu_size, READY);
555
                        }
556

    
557
                        debug("ML: active connection established\n");
558
                        break;
559

    
560
                        /*
561
                        * if READY: find the entry in the connection array set the
562
                        * connection active change the pmtu size
563
                        */
564
                case READY:
565
                        info("ML: received READY from %s (size:%d)\n", sock_id_str, msg_size);
566
                        if(connectbuf[msg_h->remote_con_id] == NULL) {
567
                                error("ML: received READY for inexistent connection\n");
568
                                return;
569
                        }
570
                        /*
571
                        * checks if the connection is not already established
572
                        */
573
                        if (connectbuf[msg_h->remote_con_id]->status == CONNECT) {
574
                                // change status of the connection
575
                                connectbuf[msg_h->remote_con_id]->status = READY;
576
                                // change pmtusize: not needed. pmtu doesn't have to be symmetric
577
                                //connectbuf[msg_h->remote_con_id]->pmtusize = con_msg->pmtu_size;
578

    
579
                                if (receive_Connection_cb != NULL)
580
                                        (receive_Connection_cb) (msg_h->remote_con_id, NULL);
581

    
582
                                while(connectbuf[msg_h->remote_con_id]->connection_head != NULL) {
583
                                        struct receive_connection_cb_list *temp;
584
                                        temp = connectbuf[msg_h->remote_con_id]->connection_head;
585
                                        (temp->connection_cb) (msg_h->remote_con_id, temp->arg);
586
                                        connectbuf[msg_h->remote_con_id]->connection_head = temp->next;
587
                                        free(temp);
588
                                }
589
                                connectbuf[msg_h->remote_con_id]->connection_head =
590
                                        connectbuf[msg_h->remote_con_id]->connection_last = NULL;
591
                                debug("ML: passive connection established\n");
592
                        }
593
                        break;
594
        }
595
}
596

    
597
void recv_stun_msg(char *msgbuf, int recvSize)
598
{
599
        /*
600
        * create empty stun message struct
601
        */
602
        StunMessage resp;
603
        memset(&resp, 0, sizeof(StunMessage));
604
        /*
605
        * parse the message
606
        */
607
        int returnValue = 0;
608
        returnValue = recv_stun_message(msgbuf, recvSize, &resp);
609

    
610
        if (returnValue == 0) {
611
                /*
612
                * read the reflexive Address into the local_socketID
613
                */
614
                struct sockaddr_in reflexiveAddr = {0};
615
                reflexiveAddr.sin_family = AF_INET;
616
                reflexiveAddr.sin_addr.s_addr = htonl(resp.mappedAddress.ipv4.addr);
617
                reflexiveAddr.sin_port = htons(resp.mappedAddress.ipv4.port);
618
                socketaddrgen reflexiveAddres = {0};
619
                reflexiveAddres.udpaddr = reflexiveAddr;
620
                local_socketID.external_addr = reflexiveAddres;
621
                NAT_traversal = true;
622
                // callback to the upper layer indicating that the socketID is now
623
                // ready to use
624
                (receive_SocketID_cb) (&local_socketID, 0);
625
        }
626
}
627

    
628
//done
629
void recv_timeout_cb(int fd, short event, void *arg)
630
{
631
        int recv_id = (long) arg;
632
        debug("ML: recv_timeout_cb called. Timeout for id:%d\n",recv_id);
633

    
634
        if (recvdatabuf[recv_id] == NULL) {
635
                return;
636
        }
637

    
638

    
639
/*        if(recvdatabuf[recv_id]->status == ACTIVE) {
640
                //TODO make timeout at least a DEFINE
641
                struct timeval timeout = { 4, 0 };
642
                recvdatabuf[recv_id]->status = INACTIVE;
643
                event_base_once(base, -1, EV_TIMEOUT, recv_timeout_cb,
644
                        arg, &timeout);
645
                return;
646
        }
647
*/
648

    
649
        if(recvdatabuf[recv_id]->status == ACTIVE) {
650
                // Monitoring layer hook
651
                if(get_Recv_data_inf_cb != NULL) {
652
                        mon_data_inf recv_data_inf;
653

    
654
                        recv_data_inf.remote_socketID =
655
                                        &(connectbuf[recvdatabuf[recv_id]->connectionID]->external_socketID);
656
                        recv_data_inf.buffer = recvdatabuf[recv_id]->recvbuf;
657
                        recv_data_inf.bufSize = recvdatabuf[recv_id]->bufsize;
658
                        recv_data_inf.msgtype = recvdatabuf[recv_id]->msgtype;
659
                        recv_data_inf.monitoringDataHeaderLen = recvdatabuf[recv_id]->monitoringDataHeaderLen;
660
                        recv_data_inf.monitoringDataHeader = recvdatabuf[recv_id]->monitoringDataHeaderLen ?
661
                                recvdatabuf[recv_id]->recvbuf : NULL;
662
                        gettimeofday(&recv_data_inf.arrival_time, NULL);
663
                        recv_data_inf.firstPacketArrived = recvdatabuf[recv_id]->firstPacketArrived;
664
                        recv_data_inf.recvFragments = recvdatabuf[recv_id]->recvFragments;
665
                        recv_data_inf.priority = false;
666
                        recv_data_inf.padding = false;
667
                        recv_data_inf.confirmation = false;
668
                        recv_data_inf.reliable = false;
669

    
670
                        // send data recv callback to monitoring module
671

    
672
                        (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
673
                }
674

    
675
                // Get the right callback
676
                receive_data_cb receive_data_callback = recvcbbuf[recvdatabuf[recv_id]->msgtype];
677

    
678
                recv_params rParams;
679

    
680
                rParams.nrMissingBytes = recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->arrivedBytes;
681
                rParams.recvFragments = recvdatabuf[recv_id]->recvFragments;
682
                rParams.msgtype = recvdatabuf[recv_id]->msgtype;
683
                rParams.connectionID = recvdatabuf[recv_id]->connectionID;
684
                rParams.remote_socketID =
685
                        &(connectbuf[recvdatabuf[recv_id]->connectionID]->external_socketID);
686
                rParams.firstPacketArrived = recvdatabuf[recv_id]->firstPacketArrived;
687

    
688
                (receive_data_callback) (recvdatabuf[recv_id]->recvbuf + recvdatabuf[recv_id]->monitoringDataHeaderLen, recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->monitoringDataHeaderLen,
689
                        recvdatabuf[recv_id]->msgtype, &rParams);
690

    
691
                //clean up
692
                if (recvdatabuf[recv_id]->timeout_event) {
693
                        event_del(recvdatabuf[recv_id]->timeout_event);
694
                        event_free(recvdatabuf[recv_id]->timeout_event);
695
                        recvdatabuf[recv_id]->timeout_event = NULL;
696
                }
697
                free(recvdatabuf[recv_id]->recvbuf);
698
                free(recvdatabuf[recv_id]);
699
                recvdatabuf[recv_id] = NULL;
700
        }
701
}
702

    
703
// process a single recv data message
704
void recv_data_msg(struct msg_header *msg_h, char *msgbuf, int bufsize)
705
{
706
        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);
707

    
708
        int recv_id, free_recv_id = -1;
709

    
710
        if(connectbuf[msg_h->remote_con_id] == NULL) {
711
                debug("ML: Received a message not related to any opened connection!\n");
712
                return;
713
        }
714

    
715
        // check if a recv_data exist and enter data
716
        for (recv_id = 0; recv_id < RECVDATABUFSIZE; recv_id++)
717
                if (recvdatabuf[recv_id] != NULL) {
718
                        if (msg_h->remote_con_id == recvdatabuf[recv_id]->connectionID &&
719
                                        msg_h->msg_seq_num == recvdatabuf[recv_id]->seqnr)
720
                                                break;
721
                } else
722
                        if(free_recv_id == -1)
723
                                free_recv_id = recv_id;
724

    
725

    
726
        if(recv_id == RECVDATABUFSIZE) {
727
                //no recv_data found: create one
728
                recv_id = free_recv_id;
729
                recvdatabuf[recv_id] = (recvdata *) malloc(sizeof(recvdata));
730
                memset(recvdatabuf[recv_id], 0, sizeof(recvdata));
731
                recvdatabuf[recv_id]->connectionID = msg_h->remote_con_id;
732
                recvdatabuf[recv_id]->seqnr = msg_h->msg_seq_num;
733
                recvdatabuf[recv_id]->monitoringDataHeaderLen = msg_h->len_mon_data_hdr;
734
                recvdatabuf[recv_id]->bufsize = msg_h->msg_length + msg_h->len_mon_data_hdr;
735
                recvdatabuf[recv_id]->recvbuf = (char *) malloc(recvdatabuf[recv_id]->bufsize);
736
                recvdatabuf[recv_id]->arrivedBytes = 0;        //count this without the Mon headers
737
                /*
738
                * read the timeout data and set it
739
                */
740
                recvdatabuf[recv_id]->timeout_value = recv_timeout;
741
                recvdatabuf[recv_id]->timeout_event = NULL;
742
                recvdatabuf[recv_id]->recvID = recv_id;
743
                recvdatabuf[recv_id]->starttime = time(NULL);
744
                recvdatabuf[recv_id]->msgtype = msg_h->msg_type;
745

    
746
                // fill the buffer with zeros
747
                memset(recvdatabuf[recv_id]->recvbuf, 0, recvdatabuf[recv_id]->bufsize);
748
                debug(" new @ id:%d\n",recv_id);
749
        } else {        //message structure already exists, no need to create new
750
                debug(" found @ id:%d (arrived before this packet: bytes:%d fragments%d\n",recv_id, recvdatabuf[recv_id]->arrivedBytes, recvdatabuf[recv_id]->recvFragments);
751
        }
752

    
753
        //if first packet extract mon data header and advance pointer
754
        if (msg_h->offset == 0) {
755
                memcpy(recvdatabuf[recv_id]->recvbuf, msgbuf, msg_h->len_mon_data_hdr);
756
                msgbuf += msg_h->len_mon_data_hdr;
757
                bufsize -= msg_h->len_mon_data_hdr;
758
                recvdatabuf[recv_id]->firstPacketArrived = 1;
759
        }
760

    
761

    
762
        // increment fragmentnr
763
        recvdatabuf[recv_id]->recvFragments++;
764
        // increment the arrivedBytes
765
        recvdatabuf[recv_id]->arrivedBytes += bufsize;
766

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

    
770
        //TODO very basic checkif all fragments arrived: has to be reviewed
771
        if(recvdatabuf[recv_id]->arrivedBytes == recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->monitoringDataHeaderLen)
772
                recvdatabuf[recv_id]->status = COMPLETE; //buffer full -> msg completly arrived
773
        else
774
                recvdatabuf[recv_id]->status = ACTIVE;
775

    
776
        if (recv_data_callback) {
777
                if(recvdatabuf[recv_id]->status == COMPLETE) {
778
                        // Monitoring layer hook
779
                        if(get_Recv_data_inf_cb != NULL) {
780
                                mon_data_inf recv_data_inf;
781

    
782
                                recv_data_inf.remote_socketID =
783
                                         &(connectbuf[recvdatabuf[recv_id]->connectionID]->external_socketID);
784
                                recv_data_inf.buffer = recvdatabuf[recv_id]->recvbuf;
785
                                recv_data_inf.bufSize = recvdatabuf[recv_id]->bufsize;
786
                                recv_data_inf.msgtype = recvdatabuf[recv_id]->msgtype;
787
                                recv_data_inf.monitoringDataHeaderLen = recvdatabuf[recv_id]->monitoringDataHeaderLen;
788
                                recv_data_inf.monitoringDataHeader = recvdatabuf[recv_id]->monitoringDataHeaderLen ?
789
                                        recvdatabuf[recv_id]->recvbuf : NULL;
790
                                gettimeofday(&recv_data_inf.arrival_time, NULL);
791
                                recv_data_inf.firstPacketArrived = recvdatabuf[recv_id]->firstPacketArrived;
792
                                recv_data_inf.recvFragments = recvdatabuf[recv_id]->recvFragments;
793
                                recv_data_inf.priority = false;
794
                                recv_data_inf.padding = false;
795
                                recv_data_inf.confirmation = false;
796
                                recv_data_inf.reliable = false;
797

    
798
                                // send data recv callback to monitoring module
799

    
800
                                (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
801
                        }
802

    
803
                        // Get the right callback
804
                        receive_data_cb receive_data_callback = recvcbbuf[msg_h->msg_type];
805
                        if (receive_data_callback) {
806

    
807
                                recv_params rParams;
808

    
809
                                rParams.nrMissingBytes = recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->monitoringDataHeaderLen - recvdatabuf[recv_id]->arrivedBytes;
810
                                rParams.recvFragments = recvdatabuf[recv_id]->recvFragments;
811
                                rParams.msgtype = recvdatabuf[recv_id]->msgtype;
812
                                rParams.connectionID = recvdatabuf[recv_id]->connectionID;
813
                                rParams.remote_socketID =
814
                                        &(connectbuf[recvdatabuf[recv_id]->connectionID]->external_socketID);
815

    
816
                                char str[1000];
817
                                mlSocketIDToString(rParams.remote_socketID,str,999);
818
                                debug("ML: received message from conID:%d, %s\n",recvdatabuf[recv_id]->connectionID,str);
819
                                rParams.firstPacketArrived = recvdatabuf[recv_id]->firstPacketArrived;
820

    
821
                                (receive_data_callback) (recvdatabuf[recv_id]->recvbuf + recvdatabuf[recv_id]->monitoringDataHeaderLen, recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->monitoringDataHeaderLen,
822
                                        recvdatabuf[recv_id]->msgtype, (void *) &rParams);
823
                        } else {
824
                            warn("ML: callback not initialized for this message type: %d!\n",msg_h->msg_type);
825
                        }
826

    
827
                        //clean up
828
                        if (recvdatabuf[recv_id]->timeout_event) {
829
                                debug("ML: freeing timeout for %d",recv_id);
830
                                event_del(recvdatabuf[recv_id]->timeout_event);
831
                                event_free(recvdatabuf[recv_id]->timeout_event);
832
                                recvdatabuf[recv_id]->timeout_event = NULL;
833
                        } else {
834
                                debug("ML: received in 1 packet\n",recv_id);
835
                        }
836
                        free(recvdatabuf[recv_id]->recvbuf);
837
                        free(recvdatabuf[recv_id]);
838
                        recvdatabuf[recv_id] = NULL;
839
                } else { // not COMPLETE
840
                        if (!recvdatabuf[recv_id]->timeout_event) {
841
                                //start time out
842
                                //TODO make timeout at least a DEFINE
843
                                recvdatabuf[recv_id]->timeout_event = event_new(base, -1, EV_TIMEOUT, &recv_timeout_cb, (void *) (long)recv_id);
844
                                evtimer_add(recvdatabuf[recv_id]->timeout_event, &recv_timeout);
845
                        }
846
                }
847
        }
848
}
849

    
850
//done
851
void pmtu_timeout_cb(int fd, short event, void *arg)
852
{
853

    
854
        int con_id = (long) arg;
855
        pmtu new_pmtusize;
856

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

    
859
        if(connectbuf[con_id] == NULL) {
860
                error("ML: pmtu timeout called on non existing con_id\n");
861
                return;
862
        }
863

    
864
        if(connectbuf[con_id]->status == READY) {
865
                // nothing to do anymore
866
                event_del(connectbuf[con_id]->timeout_event);
867
                event_free(connectbuf[con_id]->timeout_event);
868
                connectbuf[con_id]->timeout_event = NULL;
869
                return;
870
        }
871

    
872
        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);
873

    
874
        if(connectbuf[con_id]->delay || connectbuf[con_id]->trials == MAX_TRIALS - 1) {
875
                double delay = connectbuf[con_id]->timeout_value.tv_sec + connectbuf[con_id]->timeout_value.tv_usec / 1000000.0;
876
                delay = delay * 2;
877
                info("\tML: increasing pmtu timeout to %f sec\n", delay);
878
                connectbuf[con_id]->timeout_value.tv_sec = floor(delay);
879
                connectbuf[con_id]->timeout_value.tv_usec = fmod(delay, 1.0) * 1000000.0;
880
                if(connectbuf[con_id]->delay) {
881
                        connectbuf[con_id]->delay = false;
882
                        reschedule_conn_msg(con_id);
883
                }
884
        }
885

    
886
        if(connectbuf[con_id]->trials == MAX_TRIALS) {
887
                // decrement the pmtu size
888
                struct timeval tout = PMTU_TIMEOUT;
889
                info("\tML: decreasing pmtu estimate from %d to %d\n", connectbuf[con_id]->pmtusize, pmtu_decrement(connectbuf[con_id]->pmtusize));
890
                connectbuf[con_id]->pmtusize = pmtu_decrement(connectbuf[con_id]->pmtusize);
891
                connectbuf[con_id]->timeout_value = tout; 
892
                connectbuf[con_id]->trials = 0;
893
        }
894

    
895
        //error in PMTU discovery?
896
        if (connectbuf[con_id]->pmtusize == ERROR) {
897
                if (connectbuf[con_id]->internal_connect == true) {
898
                        //as of now we tried directly connecting, now let's try trough the NAT
899
                        connectbuf[con_id]->internal_connect = false;
900
                        connectbuf[con_id]->pmtusize = DSLSLIM;
901
                } else {
902
                        //nothing to do we have to give up
903
                        error("ML: Could not create connection with connectionID %i!\n",con_id);
904
                        // envoke the callback for failed connection establishment
905
                        if(failed_Connection_cb != NULL)
906
                                (failed_Connection_cb) (con_id, NULL);
907
                        // delete the connection entry
908
                        mlCloseConnection(con_id);
909
                        return;
910
                }
911
        }
912

    
913
        //retry
914
        resend_conn_msg(con_id);
915
}
916

    
917

    
918
int schedule_pmtu_timeout(int con_id)
919
{
920
        if (! connectbuf[con_id]->timeout_event) {
921
                struct timeval tout = PMTU_TIMEOUT;
922
                connectbuf[con_id]->timeout_value = tout;
923
                connectbuf[con_id]->trials = 1;
924
                connectbuf[con_id]->timeout_event = event_new(base, -1, EV_TIMEOUT, &pmtu_timeout_cb, (void *) (long)con_id);
925
                evtimer_add(connectbuf[con_id]->timeout_event, &connectbuf[con_id]->timeout_value);
926
        }
927
}
928

    
929
/*
930
 * decrements the mtu size
931
 */
932
pmtu pmtu_decrement(pmtu pmtusize)
933
{
934
        pmtu pmtu_return_size;
935
        switch(pmtusize) {
936
        case MAX:
937
                //return DSL;
938
                return DSLSLIM;        //shortcut to use less vales
939
        case DSL:
940
                return DSLMEDIUM;
941
        case DSLMEDIUM:
942
                return DSLSLIM;
943
        case DSLSLIM:
944
                //return BELOWDSL;
945
                return MIN;        //shortcut to use less vales
946
        case BELOWDSL:
947
                return MIN;
948
        case MIN:
949
                return ERROR;
950
        default:
951
                warn("ML: strange pmtu size encountered:%d, changing to some safe value:%d\n", pmtusize, MIN);
952
                return MIN;
953
        }
954
}
955

    
956
// called when an ICMP pmtu error message (type 3, code 4) is received
957
void pmtu_error_cb_th(char *msg, int msglen)
958
{
959
        debug("ML: pmtu_error callback called msg_size: %d\n",msglen);
960
        //TODO debug
961
        return;
962

    
963
    char *msgbufptr = NULL;
964
    int msgtype;
965
    int connectionID;
966
    pmtu pmtusize;
967
    pmtu new_pmtusize;
968
    int dead = 0;
969

    
970
    // check the packettype
971
    msgbufptr = &msg[0];
972

    
973
    // check the msgtype
974
    msgbufptr = &msg[1];
975
    memcpy(&msgtype, msgbufptr, 4);
976

    
977
    if (msgtype == 0) {
978

    
979
        // get the connectionID
980
        msgbufptr = &msg[5];
981
        memcpy(&connectionID, msgbufptr, 4);
982

    
983
        int msgtype_c = connectbuf[connectionID]->status;
984
//        pmtusize = connectbuf[connectionID]->pmtutrysize;
985

    
986
        if (msgtype_c != msgtype) {
987
            dead = 1;
988
        }
989

    
990

    
991
    } else if (msgtype == 1) {
992

    
993
        // read the connectionID
994
        msgbufptr = &msg[9];
995
        memcpy(&connectionID, msgbufptr, 4);
996

    
997
        int msgtype_c = connectbuf[connectionID]->status;
998
//        pmtusize = connectbuf[connectionID]->pmtutrysize;
999

    
1000
        if (msgtype_c != msgtype) {
1001
            dead = 1;
1002
        }
1003

    
1004
    }
1005
    // decrement the pmtu size
1006
    new_pmtusize = pmtu_decrement(pmtusize);
1007

    
1008
//    connectbuf[connectionID]->pmtutrysize = new_pmtusize;
1009

    
1010
    if (new_pmtusize == ERROR) {
1011
                error("ML:  Could not create connection with connectionID %i !\n",
1012
                        connectionID);
1013

    
1014
                if(failed_Connection_cb != NULL)
1015
                        (failed_Connection_cb) (connectionID, NULL);
1016
                // set the message type to a non existent message
1017
                msgtype = 2;
1018
                // delete the connection entry
1019
                 mlCloseConnection(connectionID);
1020
        }
1021

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

    
1024
        // stop the timeout event
1025
        // timeout_del(connectbuf[connectionID]->timeout);
1026
        /*
1027
         * libevent2
1028
         */
1029

    
1030
        // event_del(connectbuf[connectionID]->timeout);
1031

    
1032

    
1033
        // create and send a connection message
1034
//         create_conn_msg(new_pmtusize, connectionID,
1035
//                         &local_socketID, INVITE);
1036

    
1037
//        send_conn_msg(connectionID, new_pmtusize);
1038

    
1039
        // set a timeout event for the pmtu discovery
1040
        // timeout_set(connectbuf[connectionID]->timeout,pmtu_timeout_cb,(void
1041
        // *)&connectionID);
1042

    
1043
        // timeout_add(connectbuf[connectionID]->timeout,&connectbuf[connectionID]->timeout_value);
1044

    
1045
        /*
1046
         * libevent2
1047
         */
1048

    
1049
        struct event *ev;
1050
        ev = evtimer_new(base, pmtu_timeout_cb,
1051
                         (void *) connectbuf[connectionID]);
1052

    
1053
        // connectbuf[connectionID]->timeout = ev;
1054

    
1055
        event_add(ev, &connectbuf[connectionID]->timeout_value);
1056

    
1057
    } else if (msgtype == 1 && dead != 1) {
1058

    
1059
        // stop the timeout event
1060
        // timeout_del(connectbuf[connectionID]->timeout);
1061

    
1062
        /*
1063
         * libevent2
1064
         */
1065
        // info("still here 11 \n");
1066
        // printf("ev %d \n",connectbuf[connectionID]->timeout);
1067
        // event_del(connectbuf[connectionID]->timeout );
1068
        // evtimer_del(connectbuf[connectionID]->timeout );
1069

    
1070

    
1071
//         // create and send a connection message
1072
//         create_conn_msg(new_pmtusize,
1073
//                         connectbuf[connectionID]->connectionID,
1074
//                         NULL, CONNECT);
1075

    
1076
        //send_conn_msg(connectionID, new_pmtusize);
1077

    
1078
        // set a timeout event for the pmtu discovery
1079
        // timeout_set(connectbuf[connectionID]->timeout,pmtu_timeout_cb,(void
1080
        // *)&connectionID);
1081
        // timeout_add(connectbuf[connectionID]->timeout,&connectbuf[connectionID]->timeout_value);
1082

    
1083
        /*
1084
         * libevent2
1085
         */
1086
        // struct event *ev;
1087
        // ev = evtimer_new(base,pmtu_timeout_cb, (void
1088
        // *)connectbuf[connectionID]);
1089
        // connectbuf[connectionID]->timeout = ev;
1090
        // event_add(ev,&connectbuf[connectionID]->timeout_value);
1091

    
1092
    }
1093
}
1094

    
1095
/*
1096
 * what to do once a packet arrived if it is a conn packet send it to
1097
 * recv_conn handler if it is a data packet send it to the recv_data
1098
 * handler
1099
 */
1100

    
1101
//done --
1102
void recv_pkg(int fd, short event, void *arg)
1103
{
1104
        debug("ML: recv_pkg called\n");
1105

    
1106
        struct msg_header *msg_h;
1107
        char msgbuf[MAX];
1108
        pmtu recvSize = MAX;
1109
        char *bufptr = msgbuf;
1110
        int ttl;
1111
        struct sockaddr_in recv_addr;
1112
        int msg_size;
1113

    
1114
        recvPacket(fd, msgbuf, &recvSize, &recv_addr, pmtu_error_cb_th, &ttl);
1115

    
1116

    
1117
        // check if it is not just an ERROR message
1118
        if(recvSize < 0)
1119
                return;
1120

    
1121
        // @TODO check if this simplistic STUN message recognition really always works, probably not
1122
        unsigned short stun_bind_response = 0x0101;
1123
        unsigned short * msgspot = (unsigned short *) msgbuf;
1124
        if (*msgspot == stun_bind_response) {
1125
                debug("ML: recv_pkg: parse stun message called\n");
1126
                recv_stun_msg(msgbuf, recvSize);
1127
                return;
1128
        }
1129

    
1130
        msg_h = (struct msg_header *) msgbuf;
1131

    
1132
        /* convert header from network to host order */
1133
        msg_h->offset = ntohl(msg_h->offset);
1134
        msg_h->msg_length = ntohl(msg_h->msg_length);
1135
        msg_h->local_con_id = ntohl(msg_h->local_con_id);
1136
        msg_h->remote_con_id = ntohl(msg_h->remote_con_id);
1137
        msg_h->msg_seq_num = ntohl(msg_h->msg_seq_num);
1138

    
1139
        //verify minimum size
1140
        if (recvSize < sizeof(struct msg_header)) {
1141
          info("UDP packet too small, can't be an ML packet");
1142
          return;
1143
        }
1144

    
1145
        //TODO add more verifications
1146

    
1147
        bufptr += MSG_HEADER_SIZE + msg_h->len_mon_packet_hdr;
1148
        msg_size = recvSize - MSG_HEADER_SIZE - msg_h->len_mon_packet_hdr;
1149

    
1150
        //verify more fields
1151
        if (msg_size < 0) {
1152
          info("Corrupted UDP packet received");
1153
          return;
1154
        }
1155

    
1156
        if(get_Recv_pkt_inf_cb != NULL) {
1157
                mon_pkt_inf msginfNow;
1158
                msginfNow.monitoringHeaderLen = msg_h->len_mon_packet_hdr;
1159
                msginfNow.monitoringHeader = msg_h->len_mon_packet_hdr ? &msgbuf[0] + MSG_HEADER_SIZE : NULL;
1160
                //TODO rethink this ...
1161
                if(msg_h->msg_type == ML_CON_MSG) {
1162
                        struct conn_msg *c_msg = (struct conn_msg *) bufptr;
1163
                        msginfNow.remote_socketID = &(c_msg->sock_id);
1164
                }
1165
                else if(connectbuf[msg_h->remote_con_id] == NULL) {
1166
                        error("ML: received pkg called with non existent connection\n");
1167
                        return;
1168
                } else
1169
                        msginfNow.remote_socketID = &(connectbuf[msg_h->remote_con_id]->external_socketID);
1170
                msginfNow.buffer = bufptr;
1171
                msginfNow.bufSize = recvSize;
1172
                msginfNow.msgtype = msg_h->msg_type;
1173
                msginfNow.ttl = ttl;
1174
                msginfNow.dataID = msg_h->msg_seq_num;
1175
                msginfNow.offset = msg_h->offset;
1176
                msginfNow.datasize = msg_h->msg_length;
1177
                gettimeofday(&msginfNow.arrival_time, NULL);
1178
                (get_Recv_pkt_inf_cb) ((void *) &msginfNow);
1179
        }
1180

    
1181

    
1182
        switch(msg_h->msg_type) {
1183
                case ML_CON_MSG:
1184
                        debug("ML: received conn pkg\n");
1185
                        recv_conn_msg(msg_h, bufptr, msg_size, &recv_addr);
1186
                        break;
1187
                default:
1188
                        if(msg_h->msg_type < 127) {
1189
                                debug("ML: received data pkg\n");
1190
                                recv_data_msg(msg_h, bufptr, msg_size);
1191
                                break;
1192
                        }
1193
                        debug("ML: unrecognised msg_type\n");
1194
                        break;
1195
        }
1196
}
1197

    
1198
/*
1199
 * compare the external IP address of two socketIDs
1200
 */
1201
int
1202
compare_external_address_socketIDs(socketID_handle sock1, socketID_handle sock2)
1203
{
1204
        if( sock1->external_addr.udpaddr.sin_addr.s_addr == sock2->external_addr.udpaddr.sin_addr.s_addr)
1205
                return 0;
1206
        return 1;
1207
}
1208

    
1209
void try_stun();
1210

    
1211
/*
1212
 * the timeout of the NAT traversal
1213
 */
1214
void nat_traversal_timeout(int fd, short event, void *arg)
1215
{
1216
        if (NAT_traversal == false) {
1217
                debug("ML: NAT traversal request re-send\n");
1218
                if(receive_SocketID_cb)
1219
                        (receive_SocketID_cb) (&local_socketID, 2);
1220
                try_stun();
1221
        }
1222
}
1223

    
1224
//return IP address, or INADDR_NONE if can't resolve
1225
unsigned long resolve(const char *ipaddr)
1226
{
1227
        struct hostent *h = gethostbyname(ipaddr);
1228
        if (!h) {
1229
                error("ML: Unable to resolve host name %s\n", ipaddr);
1230
                return INADDR_NONE;
1231
        }
1232
        unsigned long *addr = (unsigned long *) (h->h_addr);
1233
        return *addr;
1234
}
1235

    
1236

    
1237
/*
1238
 * returns the file descriptor, or <0 on error. The ipaddr can be a null
1239
 * pointer. Then all available ipaddr on the machine are choosen.
1240
 */
1241
int create_socket(const int port, const char *ipaddr)
1242
{
1243
        struct sockaddr_in udpaddr = {0};
1244
        udpaddr.sin_family = AF_INET;
1245
        if (ipaddr == NULL) {
1246
                /*
1247
                * try to guess the local IP address
1248
                */
1249
                const char *ipaddr_iface = mlAutodetectIPAddress();
1250
                if (ipaddr_iface) {
1251
                        udpaddr.sin_addr.s_addr = inet_addr(ipaddr_iface);
1252
                } else {
1253
                        udpaddr.sin_addr.s_addr = INADDR_ANY;
1254
                }
1255
        } else {
1256
                udpaddr.sin_addr.s_addr = inet_addr(ipaddr);
1257
        }
1258
        udpaddr.sin_port = htons(port);
1259

    
1260
        socketaddrgen udpgen;
1261
        memset(&udpgen,0,sizeof(socketaddrgen));        //this will be sent over the net, so set it to 0
1262
        udpgen.udpaddr = udpaddr;
1263
        local_socketID.internal_addr = udpgen;
1264

    
1265
        socketfd = createSocket(port, ipaddr);
1266
        if (socketfd < 0){
1267
                return socketfd;
1268
        }
1269

    
1270
        struct event *ev;
1271
        ev = event_new(base, socketfd, EV_READ | EV_PERSIST, recv_pkg, NULL);
1272

    
1273
        event_add(ev, NULL);
1274

    
1275
        try_stun();
1276

    
1277
        return socketfd;
1278
}
1279

    
1280
/*
1281
 * try to figure out external IP using STUN, if defined
1282
 */
1283
void try_stun()
1284
{
1285
        if (isStunDefined()) {
1286
                /*
1287
                * send the NAT traversal STUN request
1288
                */
1289
                 send_stun_request(socketfd, &stun_server);
1290

    
1291
                /*
1292
                * enter a NAT traversal timeout that takes care of retransmission
1293
                */
1294
                struct event *ev1;
1295
                struct timeval timeout_value_NAT_traversal = NAT_TRAVERSAL_TIMEOUT;
1296
                ev1 = evtimer_new(base, nat_traversal_timeout, NULL);
1297
                event_add(ev1, &timeout_value_NAT_traversal);
1298

    
1299
                NAT_traversal = false;
1300
        } else {
1301
                /*
1302
                * Assume we have accessibility and copy internal address to external one
1303
                */
1304
                local_socketID.external_addr = local_socketID.internal_addr;
1305
                NAT_traversal = true; // @TODO: this is not really NAT traversal, but a flag that init is over
1306
                // callback to the upper layer indicating that the socketID is now
1307
                // ready to use
1308
                if(receive_SocketID_cb)
1309
                        (receive_SocketID_cb) (&local_socketID, 0); //success
1310
        }
1311
}
1312

    
1313
/**************************** END OF INTERNAL ***********************/
1314

    
1315
/**************************** MONL functions *************************/
1316

    
1317
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){
1318

    
1319
        base = (struct event_base *) arg;
1320
        recv_data_callback = recv_data_cb;
1321
        mlSetRecvTimeout(timeout_value);
1322
        if (stun_ipaddr) {
1323
                 mlSetStunServer(stun_port, stun_ipaddr);
1324
        } else {
1325

    
1326
        }
1327
        register_recv_localsocketID_cb(local_socketID_cb);
1328
        return create_socket(port, ipaddr);
1329
}
1330

    
1331
/* register callbacks  */
1332
void mlRegisterGetRecvPktInf(get_recv_pkt_inf_cb recv_pkt_inf_cb){
1333

    
1334
        if (recv_pkt_inf_cb == NULL) {
1335
                error("ML: Register get_recv_pkt_inf_cb failed: NULL ptr  \n");
1336
        } else {
1337
                get_Recv_pkt_inf_cb = recv_pkt_inf_cb;
1338
        }
1339
}
1340

    
1341
void mlRegisterGetSendPktInf(get_send_pkt_inf_cb  send_pkt_inf_cb){
1342

    
1343
        if (send_pkt_inf_cb == NULL) {
1344
                error("ML: Register get_send_pkt_inf_cb: NULL ptr  \n");
1345
        } else {
1346
                get_Send_pkt_inf_cb = send_pkt_inf_cb;
1347
        }
1348
}
1349

    
1350

    
1351
void mlRegisterSetMonitoringHeaderPktCb(set_monitoring_header_pkt_cb monitoring_header_pkt_cb ){
1352

    
1353
        if (monitoring_header_pkt_cb == NULL) {
1354
                error("ML: Register set_monitoring_header_pkt_cb: NULL ptr  \n");
1355
        } else {
1356
                set_Monitoring_header_pkt_cb = monitoring_header_pkt_cb;
1357
        }
1358
}
1359

    
1360
void mlRegisterGetRecvDataInf(get_recv_data_inf_cb recv_data_inf_cb){
1361

    
1362
        if (recv_data_inf_cb == NULL) {
1363
                error("ML: Register get_recv_data_inf_cb: NULL ptr  \n");
1364
        } else {
1365
                get_Recv_data_inf_cb = recv_data_inf_cb;
1366
        }
1367
}
1368

    
1369
void mlRegisterGetSendDataInf(get_send_data_inf_cb  send_data_inf_cb){
1370

    
1371
        if (send_data_inf_cb == NULL) {
1372
                error("ML: Register get_send_data_inf_cb: NULL ptr  \n");
1373
        } else {
1374
                get_Send_data_inf_cb = send_data_inf_cb;
1375
        }
1376
}
1377

    
1378
void mlRegisterSetMonitoringHeaderDataCb(set_monitoring_header_data_cb monitoring_header_data_cb){
1379

    
1380
        if (monitoring_header_data_cb == NULL) {
1381
                error("ML: Register set_monitoring_header_data_cb : NULL ptr  \n");
1382
        } else {
1383
                set_Monitoring_header_data_cb = monitoring_header_data_cb;
1384
        }
1385
}
1386

    
1387
void mlSetRecvTimeout(struct timeval timeout_value){
1388

    
1389
        recv_timeout = timeout_value;
1390

    
1391
}
1392

    
1393
int mlGetStandardTTL(socketID_handle socketID,uint8_t *ttl){
1394

    
1395
        return getTTL(socketfd, ttl);
1396

    
1397
}
1398

    
1399
socketID_handle mlGetLocalSocketID(int *errorstatus){
1400

    
1401
        if (NAT_traversal == false) {
1402
                *errorstatus = 2;
1403
                return NULL;
1404
        }
1405

    
1406
        *errorstatus = 0;
1407
        return &local_socketID;
1408

    
1409
}
1410

    
1411

    
1412
/**************************** END of MONL functions *************************/
1413

    
1414
/**************************** GENERAL functions *************************/
1415

    
1416
void mlRegisterRecvConnectionCb(receive_connection_cb recv_conn_cb){
1417

    
1418
        if (recv_conn_cb == NULL) {
1419
                error("ML: Register receive_connection_cb: NULL ptr  \n");
1420
        }else {
1421
                receive_Connection_cb = recv_conn_cb;
1422
        }
1423
}
1424

    
1425
void mlRegisterErrorConnectionCb(connection_failed_cb conn_failed){
1426

    
1427
        if (conn_failed == NULL) {
1428
                error("ML: Register connection_failed_cb: NULL ptr  \n");
1429
        } else {
1430
                failed_Connection_cb = conn_failed;
1431
        }
1432
}
1433

    
1434
void mlRegisterRecvDataCb(receive_data_cb data_cb,unsigned char msgtype){
1435

    
1436
    if (msgtype > 126) {
1437

    
1438
            error
1439
            ("ML: Could not register recv_data callback. Msgtype is greater then 126 \n");
1440

    
1441
    }
1442

    
1443
    if (data_cb == NULL) {
1444

    
1445
            error("ML: Register receive data callback: NUll ptr \n ");
1446

    
1447
    } else {
1448

    
1449
        recvcbbuf[msgtype] = data_cb;
1450

    
1451
    }
1452

    
1453
}
1454

    
1455
void mlCloseSocket(socketID_handle socketID){
1456

    
1457
        free(socketID);
1458

    
1459
}
1460

    
1461
void keepalive_fn(evutil_socket_t fd, short what, void *arg) {
1462
        socketID_handle peer = arg;
1463

    
1464
        int con_id = mlConnectionExist(peer, false);
1465
        if (con_id < 0 || connectbuf[con_id]->defaultSendParams.keepalive <= 0) {
1466
                /* Connection fell from under us or keepalive was disabled */
1467
                free(arg);
1468
                return;
1469
        }
1470

    
1471
        /* do what we gotta do */
1472
        if ( connectbuf[con_id]->status == READY) {
1473
                char keepaliveMsg[32] = "";
1474
                sprintf(keepaliveMsg, "KEEPALIVE %d", connectbuf[con_id]->keepalive_seq++);
1475
                send_msg(con_id, MSG_TYPE_ML_KEEPALIVE, keepaliveMsg, 1 + strlen(keepaliveMsg), false, 
1476
                        &(connectbuf[con_id]->defaultSendParams));
1477
        }
1478

    
1479
        /* re-schedule */
1480
        struct timeval t = { 0,0 };
1481
        t.tv_sec = connectbuf[con_id]->defaultSendParams.keepalive;
1482
        if (connectbuf[con_id]->defaultSendParams.keepalive) 
1483
                event_base_once(base, -1, EV_TIMEOUT, keepalive_fn, peer, &t);
1484
}
1485

    
1486
void setupKeepalive(int conn_id) {
1487
        /* Save the peer's address for us */
1488
        socketID_handle peer = malloc(sizeof(socket_ID));
1489
        memcpy(peer, &connectbuf[conn_id]->external_socketID, sizeof(socket_ID));
1490

    
1491
        struct timeval t = { 0,0 };
1492
        t.tv_sec = connectbuf[conn_id]->defaultSendParams.keepalive;
1493

    
1494
        if (connectbuf[conn_id]->defaultSendParams.keepalive) 
1495
                event_base_once(base, -1, EV_TIMEOUT, keepalive_fn, peer, &t);
1496
}
1497

    
1498
/* connection functions */
1499
int mlOpenConnection(socketID_handle external_socketID,receive_connection_cb connection_cb,void *arg, const send_params defaultSendParams){
1500

    
1501
        int con_id;
1502
        if (external_socketID == NULL) {
1503
                error("ML: cannot open connection: one of the socketIDs is NULL\n");
1504
                return -1;
1505
        }
1506
        if (NAT_traversal == false) {
1507
                error("ML: cannot open connection: NAT traversal for socketID still in progress\n");
1508
                return -1;
1509
        }
1510
        if (connection_cb == NULL) {
1511
                error("ML: cannot open connection: connection_cb is NULL\n");
1512
                return -1;
1513
        }
1514

    
1515
        // check if that connection already exist
1516

    
1517
        con_id = mlConnectionExist(external_socketID, false);
1518
        if (con_id >= 0) {
1519
                // overwrite defaultSendParams
1520
                bool newKeepalive = 
1521
                        connectbuf[con_id]->defaultSendParams.keepalive == 0 && defaultSendParams.keepalive != 0;
1522
                connectbuf[con_id]->defaultSendParams = defaultSendParams;
1523
                if (newKeepalive) setupKeepalive(con_id);
1524
                // if so check if it is ready to use
1525
                if (connectbuf[con_id]->status == READY) {
1526
                                // if so use the callback immediately
1527
                                (connection_cb) (con_id, arg);
1528

    
1529
                // otherwise just write the connection cb and the arg pointer
1530
                // into the connection struct
1531
                } else {
1532
                        struct receive_connection_cb_list *temp;
1533
                        temp = malloc(sizeof(struct receive_connection_cb_list));
1534
                        temp->next = NULL;
1535
                        temp->connection_cb = connection_cb;
1536
                        temp->arg = arg;
1537
                        if(connectbuf[con_id]->connection_last != NULL) {
1538
                                connectbuf[con_id]->connection_last->next = temp;
1539
                                connectbuf[con_id]->connection_last = temp;
1540
                        } else
1541
                                connectbuf[con_id]->connection_last = connectbuf[con_id]->connection_head = temp;
1542
                }
1543
                return con_id;
1544
        }
1545
        // make entry in connection_establishment array
1546
        for (con_id = 0; con_id < CONNECTBUFSIZE; con_id++) {
1547
                if (connectbuf[con_id] == NULL) {
1548
                        connectbuf[con_id] = (connect_data *) malloc(sizeof(connect_data));
1549
                        memset(connectbuf[con_id],0,sizeof(connect_data));
1550
                        connectbuf[con_id]->starttime = time(NULL);
1551
                        memcpy(&connectbuf[con_id]->external_socketID, external_socketID, sizeof(socket_ID));
1552
                        connectbuf[con_id]->pmtusize = DSLSLIM;
1553
                        connectbuf[con_id]->timeout_event = NULL;
1554
                        connectbuf[con_id]->status = INVITE;
1555
                        connectbuf[con_id]->seqnr = 0;
1556
                        connectbuf[con_id]->internal_connect = !compare_external_address_socketIDs(external_socketID, &local_socketID);
1557
                        connectbuf[con_id]->connectionID = con_id;
1558

    
1559
                        connectbuf[con_id]->connection_head = connectbuf[con_id]->connection_last = malloc(sizeof(struct receive_connection_cb_list));
1560
                        connectbuf[con_id]->connection_last->next = NULL;
1561
                        connectbuf[con_id]->connection_last->connection_cb = connection_cb;
1562
                        connectbuf[con_id]->connection_last->arg = arg;
1563
                        connectbuf[con_id]->external_connectionID = -1;
1564

    
1565
                        connectbuf[con_id]->defaultSendParams = defaultSendParams;
1566
                        if (defaultSendParams.keepalive) setupKeepalive(con_id);
1567
                        break;
1568
                }
1569
        } //end of for
1570

    
1571
        if (con_id == CONNECTBUFSIZE) {
1572
                error("ML: Could not open connection: connection buffer full\n");
1573
                return -1;
1574
        }
1575

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

    
1580
        return con_id;
1581

    
1582
}
1583

    
1584
void mlCloseConnection(const int connectionID){
1585

    
1586
        // remove it from the connection array
1587
        if(connectbuf[connectionID]) {
1588
                if(connectbuf[connectionID]->ctrl_msg_buf) {
1589
                        free(connectbuf[connectionID]->ctrl_msg_buf);
1590
                }
1591
                // remove related events
1592
                if (connectbuf[connectionID]->timeout_event) {
1593
                        event_del(connectbuf[connectionID]->timeout_event);
1594
                        event_free(connectbuf[connectionID]->timeout_event);
1595
                        connectbuf[connectionID]->timeout_event = NULL;
1596
                }
1597
                free(connectbuf[connectionID]);
1598
                connectbuf[connectionID] = NULL;
1599
        }
1600

    
1601
}
1602

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

    
1605
        if (connectionID < 0) {
1606
                error("ML: send data failed: connectionID does not exist\n");
1607
                return;
1608
        }
1609

    
1610
        if (connectbuf[connectionID] == NULL) {
1611
                error("ML: send data failed: connectionID does not exist\n");
1612
                return;
1613
        }
1614
        if (connectbuf[connectionID]->status != READY) {
1615
            error("ML: send data failed: connection is not active\n");
1616
            return;
1617
        }
1618

    
1619
        if (sParams == NULL) {
1620
                sParams = &(connectbuf[connectionID]->defaultSendParams);
1621
        }
1622

    
1623
        send_msg(connectionID, msgtype, sendbuf, bufsize, false, sParams);
1624

    
1625
}
1626

    
1627
/* transmit data functions  */
1628
int mlSendAllData(const int connectionID,send_all_data_container *container,int nr_entries,unsigned char msgtype,send_params *sParams){
1629

    
1630
    if (nr_entries < 1 || nr_entries > 5) {
1631

    
1632
        error
1633
            ("ML : sendALlData : nr_enties is not between 1 and 5 \n ");
1634
        return 0;
1635

    
1636
    } else {
1637

    
1638
        if (nr_entries == 1) {
1639

    
1640
                mlSendData(connectionID, container->buffer_1,
1641
                      container->length_1, msgtype, sParams);
1642

    
1643
            return 1;
1644

    
1645
        } else if (nr_entries == 2) {
1646

    
1647
            int buflen = container->length_1 + container->length_2;
1648
            char buf[buflen];
1649
            memcpy(buf, container->buffer_1, container->length_1);
1650
            memcpy(&buf[container->length_1], container->buffer_2,
1651
                   container->length_2);
1652
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1653

    
1654
            return 1;
1655

    
1656
        } else if (nr_entries == 3) {
1657

    
1658
            int buflen =
1659
                container->length_1 + container->length_2 +
1660
                container->length_3;
1661
            char buf[buflen];
1662
            memcpy(buf, container->buffer_1, container->length_1);
1663
            memcpy(&buf[container->length_1], container->buffer_2,
1664
                   container->length_2);
1665
            memcpy(&buf[container->length_2], container->buffer_3,
1666
                   container->length_3);
1667
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1668

    
1669

    
1670
            return 1;
1671

    
1672
        } else if (nr_entries == 4) {
1673

    
1674
            int buflen =
1675
                container->length_1 + container->length_2 +
1676
                container->length_3 + container->length_4;
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
            memcpy(&buf[container->length_2], container->buffer_3,
1682
                   container->length_3);
1683
            memcpy(&buf[container->length_3], container->buffer_4,
1684
                   container->length_4);
1685
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1686

    
1687
            return 1;
1688

    
1689
        } else {
1690

    
1691
            int buflen =
1692
                container->length_1 + container->length_2 +
1693
                container->length_3 + container->length_4 +
1694
                container->length_5;
1695
            char buf[buflen];
1696
            memcpy(buf, container->buffer_1, container->length_1);
1697
            memcpy(&buf[container->length_1], container->buffer_2,
1698
                   container->length_2);
1699
            memcpy(&buf[container->length_2], container->buffer_3,
1700
                   container->length_3);
1701
            memcpy(&buf[container->length_3], container->buffer_4,
1702
                   container->length_4);
1703
            memcpy(&buf[container->length_4], container->buffer_5,
1704
                   container->length_5);
1705
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1706

    
1707
            return 1;
1708
        }
1709

    
1710
    }
1711

    
1712
}
1713

    
1714
int mlRecvData(const int connectionID,char *recvbuf,int *bufsize,recv_params *rParams){
1715

    
1716
        //TODO yet to be converted
1717
        return 0;
1718
#if 0
1719
        if (rParams == NULL) {
1720
                error("ML: recv_data failed: recv_params is a NULL ptr\n");
1721
                return 0;
1722
    } else {
1723

1724
        info("ML: recv data called \n");
1725

1726
        int i = 0;
1727
        int returnValue = 0;
1728
        double timeout = (double) recv_timeout.tv_sec;
1729
        time_t endtime = time(NULL);
1730

1731
        for (i = 0; i < RECVDATABUFSIZE; i++) {
1732

1733
            if (recvdatabuf[i] != NULL) {
1734

1735
                if (recvdatabuf[i]->connectionID == connectionID) {
1736

1737
                    info("ML: recv data has entry  \n");
1738

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

1741
                    // check if the specified connection has data and it
1742
                    // is complete
1743
                    // check the data seqnr
1744
                    // if(connectionID == recvdatabuf[i]->connectionID &&
1745
                    // 1 == recvdatabuf[i]->status){
1746

1747
                    if (1 == recvdatabuf[i]->status) {
1748

1749
                        // info("transmissionHandler: recv_data set is
1750
                        // complete \n" );
1751

1752
                        // debug("debud \n");
1753

1754
                        // exchange the pointers
1755
                        int buffersize = 0;
1756
                        buffersize = recvdatabuf[i]->bufsize;
1757
                        *bufsize = buffersize;
1758
                        // recvbuf = recvdatabuf[i]->recvbuf;
1759

1760
                        // info("buffersize %d \n",buffersize);
1761
                        memcpy(recvbuf, recvdatabuf[i]->recvbuf,
1762
                               buffersize);
1763
                        // debug(" recvbuf %s \n",recvbuf );
1764

1765
//                         double nrMissFrags =
1766
//                             (double) recvdatabuf[i]->nrFragments /
1767
//                             (double) recvdatabuf[i]->recvFragments;
1768
//                         int nrMissingFragments = (int) ceil(nrMissFrags);
1769

1770
//                        rParams->nrMissingFragments = nrMissingFragments;
1771
//                         rParams->nrFragments = recvdatabuf[i]->nrFragments;
1772
                        rParams->msgtype = recvdatabuf[i]->msgtype;
1773
                        rParams->connectionID =
1774
                            recvdatabuf[i]->connectionID;
1775

1776
                        // break from the loop
1777
                        // debug(" recvbuf %s \n ",recvbuf);
1778

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

1785
                        if(get_Recv_data_inf_cb != NULL) {
1786
                                mon_data_inf recv_data_inf;
1787

1788
                                recv_data_inf.remote_socketID = &(connectbuf[connectionID]->external_socketID);
1789
                                recv_data_inf.buffer = recvdatabuf[i]->recvbuf;
1790
                                recv_data_inf.bufSize = recvdatabuf[i]->bufsize;
1791
                                recv_data_inf.msgtype = recvdatabuf[i]->msgtype;
1792
//                                 recv_data_inf.monitoringHeaderType = recvdatabuf[i]->monitoringHeaderType;
1793
//                                 recv_data_inf.monitoringDataHeader = recvdatabuf[i]->monitoringDataHeader;
1794
                                gettimeofday(&recv_data_inf.arrival_time, NULL);
1795
                                recv_data_inf.firstPacketArrived = recvdatabuf[i]->firstPacketArrived;
1796
                                recv_data_inf.nrMissingFragments = nrMissingFragments;
1797
                                recv_data_inf.nrFragments = recvdatabuf[i]->nrFragments;
1798
                                recv_data_inf.priority = false;
1799
                                recv_data_inf.padding = false;
1800
                                recv_data_inf.confirmation = false;
1801
                                recv_data_inf.reliable = false;
1802

1803
                                // send data recv callback to monitoring module
1804

1805
                                (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
1806
                        }
1807

1808

1809
                        // free the allocated memory
1810
                        free(recvdatabuf[i]);
1811
                        recvdatabuf[i] = NULL;
1812

1813
                        returnValue = 1;
1814
                        break;
1815

1816
                    }
1817

1818
                    if (recvdatabuf[i] != NULL) {
1819

1820
                        if (timepass > timeout) {
1821

1822
                            info("ML: recv_data timeout called  \n");
1823

1824
                            // some data about the missing chunks should
1825
                            // be added here
1826
                            // exchange the pointers
1827
                            int buffersize = 0;
1828
                            buffersize = recvdatabuf[i]->bufsize;
1829
                            *bufsize = buffersize;
1830
                            // recvbuf = recvdatabuf[i]->recvbuf;
1831

1832
                            double nrMissFrags =
1833
                                (double) recvdatabuf[i]->nrFragments /
1834
                                (double) recvdatabuf[i]->recvFragments;
1835
                            int nrMissingFragments =
1836
                                (int) ceil(nrMissFrags);
1837

1838
                            // debug(" recvbuf %s \n",recvbuf );
1839

1840
                            memcpy(recvbuf, recvdatabuf[i]->recvbuf,
1841
                                   buffersize);
1842

1843
                            rParams->nrMissingFragments =
1844
                                nrMissingFragments;
1845
                            rParams->nrFragments =
1846
                                recvdatabuf[i]->nrFragments;
1847
                            rParams->msgtype = recvdatabuf[i]->msgtype;
1848
                            rParams->connectionID =
1849
                                recvdatabuf[i]->connectionID;
1850

1851
                                if(get_Recv_data_inf_cb != NULL) {
1852
                                        mon_data_inf recv_data_inf;
1853

1854
                                        recv_data_inf.remote_socketID = &(connectbuf[connectionID]->external_socketID);
1855
                                        recv_data_inf.buffer = recvdatabuf[i]->recvbuf;
1856
                                        recv_data_inf.bufSize = recvdatabuf[i]->bufsize;
1857
                                        recv_data_inf.msgtype = recvdatabuf[i]->msgtype;
1858
                                        recv_data_inf.monitoringHeaderType = recvdatabuf[i]->monitoringHeaderType;
1859
                                        recv_data_inf.monitoringDataHeader = recvdatabuf[i]->monitoringDataHeader;
1860
                                        gettimeofday(&recv_data_inf.arrival_time, NULL);
1861
                                        recv_data_inf.firstPacketArrived = recvdatabuf[i]->firstPacketArrived;
1862
                                        recv_data_inf.nrMissingFragments = nrMissingFragments;
1863
                                        recv_data_inf.nrFragments = recvdatabuf[i]->nrFragments;
1864
                                        recv_data_inf.priority = false;
1865
                                        recv_data_inf.padding = false;
1866
                                        recv_data_inf.confirmation = false;
1867
                                        recv_data_inf.reliable = false;
1868

1869
                                        // send data recv callback to monitoring module
1870

1871
                                        (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
1872
                                }
1873

1874
                            // free the allocated memory
1875
                            free(recvdatabuf[i]);
1876
                            recvdatabuf[i] = NULL;
1877

1878
                            returnValue = 1;
1879
                            break;
1880

1881
                        }
1882
                    }
1883

1884
                }
1885

1886
            }
1887
            // debug("2 recvbuf %s \n ",recvbuf);
1888
        }
1889
        return returnValue;
1890
    }
1891
#endif
1892

    
1893
}
1894

    
1895
int mlSocketIDToString(socketID_handle socketID,char* socketID_string, size_t len){
1896

    
1897
        char internal_addr[INET_ADDRSTRLEN];
1898
        char external_addr[INET_ADDRSTRLEN];
1899

    
1900
        assert(socketID);
1901

    
1902
        inet_ntop(AF_INET, &(socketID->internal_addr.udpaddr.sin_addr.s_addr), internal_addr, INET_ADDRSTRLEN);
1903
        inet_ntop(AF_INET, &(socketID->external_addr.udpaddr.sin_addr.s_addr), external_addr, INET_ADDRSTRLEN);
1904

    
1905
        snprintf(socketID_string,len,"%s:%d-%s:%d", internal_addr, ntohs(socketID->internal_addr.udpaddr.sin_port),
1906
                external_addr,        ntohs(socketID->external_addr.udpaddr.sin_port));
1907
        return 0;
1908

    
1909
}
1910

    
1911
int mlStringToSocketID(const char* socketID_string, socketID_handle socketID){
1912

    
1913
        //@TODO add checks against malformed string
1914
        char external_addr[INET_ADDRSTRLEN];
1915
        int external_port;
1916
        char internal_addr[INET_ADDRSTRLEN];
1917
        int internal_port;
1918

    
1919
        char *pch;
1920
        char *s = strdup(socketID_string);
1921

    
1922
        //replace ':' with a blank
1923
        pch=strchr(s,':');
1924
        while (pch!=NULL){
1925
                                *pch = ' ';
1926
                pch=strchr(pch+1,':');
1927
        }
1928
        pch=strchr(s,'-');
1929
        if(pch) *pch = ' ';
1930

    
1931
        sscanf(s,"%s %d %s %d", internal_addr, &internal_port,
1932
                external_addr, &external_port);
1933

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

    
1937
        if(inet_pton(AF_INET, internal_addr, &(socketID->internal_addr.udpaddr.sin_addr)) == 0)
1938
                return EINVAL;
1939
        socketID->internal_addr.udpaddr.sin_family = AF_INET;
1940
        socketID->internal_addr.udpaddr.sin_port = htons(internal_port);
1941

    
1942

    
1943
        if(inet_pton(AF_INET, external_addr, &(socketID->external_addr.udpaddr.sin_addr)) ==0)
1944
                return EINVAL;
1945
        socketID->external_addr.udpaddr.sin_family = AF_INET;
1946
        socketID->external_addr.udpaddr.sin_port = htons(external_port);
1947

    
1948
        free(s);
1949
        return 0;
1950

    
1951
}
1952

    
1953
int mlGetConnectionStatus(int connectionID){
1954

    
1955
        if(connectbuf[connectionID])
1956
                return connectbuf[connectionID]->status == READY;
1957
        return -1;
1958
    
1959
}
1960

    
1961

    
1962
int mlConnectionExist(socketID_handle socketID, bool ready){
1963

    
1964
    /*
1965
     * check if another connection for the external connectionID exist
1966
     * that was established \ within the last 2 seconds
1967
     */
1968
        int i;
1969
        for (i = 0; i < CONNECTBUFSIZE; i++)
1970
                if (connectbuf[i] != NULL)
1971
                        if (mlCompareSocketIDs(&(connectbuf[i]->external_socketID), socketID) == 0) {
1972
                                if (ready) return (connectbuf[i]->status == READY ? i : -1);;
1973
                                return i;
1974
                                }
1975

    
1976
    return -1;
1977

    
1978
}
1979

    
1980
//Added by Robert Birke as comodity functions
1981

    
1982
//int mlPrintSocketID(socketID_handle socketID) {
1983
//        char str[SOCKETID_STRING_SIZE];
1984
//        mlSocketIDToString(socketID, str, sizeof(str));
1985
//        printf(stderr,"int->%s<-ext\n",str);
1986
//}
1987

    
1988
/*
1989
 * hash code of a socketID
1990
 * TODO might think of a better way
1991
 */
1992
int mlHashSocketID(socketID_handle sock) {
1993
    return sock->internal_addr.udpaddr.sin_port +
1994
                          sock->external_addr.udpaddr.sin_port;
1995
}
1996

    
1997
int mlCompareSocketIDs(socketID_handle sock1, socketID_handle sock2) {
1998

    
1999
        assert(sock1 && sock2);
2000

    
2001
        /*
2002
        * compare internal addr
2003
        */
2004
        if(sock1 == NULL || sock2 == NULL)
2005
                return 1;
2006

    
2007
        if (sock1->internal_addr.udpaddr.sin_addr.s_addr !=
2008
            sock2->internal_addr.udpaddr.sin_addr.s_addr)
2009
                        return 1;
2010

    
2011
        if (sock1->internal_addr.udpaddr.sin_port !=
2012
                 sock2->internal_addr.udpaddr.sin_port)
2013
                        return 1;
2014

    
2015
        /*
2016
        * compare external addr
2017
        */
2018
        if (sock1->external_addr.udpaddr.sin_addr.s_addr !=
2019
            sock2->external_addr.udpaddr.sin_addr.s_addr)
2020
                        return 1;
2021

    
2022
        if (sock1->external_addr.udpaddr.sin_port !=
2023
                 sock2->external_addr.udpaddr.sin_port)
2024
                        return 1;
2025

    
2026
        return 0;
2027
}
2028

    
2029
int mlCompareSocketIDsByPort(socketID_handle sock1, socketID_handle sock2)
2030
{
2031
        if(sock1 == NULL || sock2 == NULL)
2032
                return 1;
2033
 
2034
        if (sock1->internal_addr.udpaddr.sin_port !=
2035
                 sock2->internal_addr.udpaddr.sin_port)
2036
                        return 1;
2037

    
2038
        if (sock1->external_addr.udpaddr.sin_port !=
2039
                 sock2->external_addr.udpaddr.sin_port)
2040
                        return 1;
2041
        return 0;
2042
}
2043

    
2044
int mlGetPathMTU(int ConnectionId) {
2045
        if(ConnectionId < 0 || ConnectionId >= CONNECTBUFSIZE)
2046
                return -1;
2047
        if (connectbuf[ConnectionId] != NULL)
2048
                return connectbuf[ConnectionId]->pmtusize;
2049
        return -1;
2050
}
2051

    
2052
/**************************** END of GENERAL functions *************************/
2053

    
2054
/**************************** NAT functions *************************/
2055

    
2056
/* setter  */
2057
void mlSetStunServer(const int port,const char *ipaddr){
2058

    
2059
        stun_server.sin_family = AF_INET;
2060
        if (ipaddr == NULL)
2061
                stun_server.sin_addr.s_addr = htonl(INADDR_NONE);
2062
        else
2063
                stun_server.sin_addr.s_addr = resolve(ipaddr);
2064
        stun_server.sin_port = htons(port);
2065

    
2066
}
2067

    
2068
int mlGetExternalIP(char* external_addr){
2069

    
2070
        socketaddrgen udpgen;
2071
        struct sockaddr_in udpaddr;
2072

    
2073
        udpgen = local_socketID.external_addr;
2074
        udpaddr = udpgen.udpaddr;
2075

    
2076
        inet_ntop(AF_INET, &(udpaddr.sin_addr), external_addr,
2077
                        INET_ADDRSTRLEN);
2078

    
2079
        if (external_addr == NULL) {
2080

    
2081
        return -1;
2082

    
2083
        } else {
2084

    
2085
        return 0;
2086

    
2087
        }
2088

    
2089
}
2090

    
2091
/**************************** END of NAT functions *************************/