Statistics
| Branch: | Revision:

ml / ml.c @ d875a065

History | View | Annotate | Download (54.8 KB)

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

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

    
57
#define LOG_MODULE "[ml] "
58
#include "ml_log.h"
59

    
60
/**************************** START OF INTERNALS ***********************/
61

    
62
/*
63
 * a pointer to a libevent instance
64
 */
65
struct event_base *base;
66

    
67
/*
68
 * define the nr of connections the messaging layer can handle
69
 */
70
#define CONNECTBUFSIZE 10000
71
/*
72
 * define the nr of data that can be received parallel
73
 */
74
#define RECVDATABUFSIZE 10000
75
/*
76
 * define an array for message multiplexing
77
 */
78
#define MSGMULTIPLEXSIZE 127
79

    
80
/*
81
 * global variables
82
 */
83
/*
84
 * define a buffer of pointers to connect structures
85
 */
86
connect_data *connectbuf[CONNECTBUFSIZE];
87

    
88
/*
89
 * define a pointer buffer with pointers to recv_data structures
90
 */
91
recvdata *recvdatabuf[RECVDATABUFSIZE];
92

    
93
/*
94
 * define a pointer buffer for message multiplexing
95
 */
96
receive_data_cb recvcbbuf[MSGMULTIPLEXSIZE];
97

    
98
/*
99
 * stun server address
100
 */
101
struct sockaddr_in stun_server;
102

    
103
/*
104
 * receive timeout
105
 */
106
struct timeval recv_timeout;
107

    
108
/*
109
 * boolean NAT traversal successful if true
110
 */
111
boolean NAT_traversal;
112

    
113
/*
114
 * file descriptor for local socket
115
 */
116
evutil_socket_t socketfd;
117

    
118
/*
119
 * local socketID
120
 */
121
socket_ID local_socketID;
122

    
123
socketID_handle loc_socketID = &local_socketID;
124

    
125
/*
126
 * callback function pointers
127
 */
128
/*
129
 * monitoring module callbacks
130
 */
131
get_recv_pkt_inf_cb get_Recv_pkt_inf_cb = NULL;
132
get_send_pkt_inf_cb get_Send_pkt_inf_cb = NULL;
133
set_monitoring_header_pkt_cb set_Monitoring_header_pkt_cb = NULL;
134
get_recv_data_inf_cb get_Recv_data_inf_cb = NULL;
135
get_send_data_inf_cb get_Send_data_inf_cb = NULL;
136
set_monitoring_header_data_cb set_Monitoring_header_data_cb = NULL;
137
/*
138
 * connection callbacks
139
 */
140
receive_connection_cb receive_Connection_cb = NULL;
141
connection_failed_cb failed_Connection_cb = NULL;
142
/*
143
 * local socketID callback
144
 */
145
receive_localsocketID_cb receive_SocketID_cb;
146

    
147
/*
148
 * boolean that defines if received data is transmitted to the upper layer
149
 * via callback or via upper layer polling
150
 */
151
boolean recv_data_callback;
152

    
153
/*
154
 * helper function to get rid of a warning
155
 */
156
int min(int a, int b) {
157
        if (a > b) return b;
158
        return a;
159
}
160

    
161
void register_recv_localsocketID_cb(receive_localsocketID_cb local_socketID_cb)
162
{
163
        if (local_socketID_cb == NULL)
164
                error("ML : Register receive_localsocketID_cb: NULL ptr \n");
165
        else
166
        receive_SocketID_cb = local_socketID_cb;
167
}
168

    
169

    
170
//void keep_connection_alive(const int connectionID)
171
//{
172
//
173
//    // to be done with the NAT traversal
174
//    // send a message over the wire
175
//    printf("\n");
176
//
177
//}
178

    
179
void unsetStunServer()
180
{
181
        stun_server.sin_addr.s_addr = 0;
182
}
183

    
184
bool isStunDefined()
185
{
186
        return stun_server.sin_addr.s_addr;
187
}
188

    
189
void send_msg(int con_id, int msg_type, char* msg, int msg_len, bool truncable, send_params * sParams) {
190
        socketaddrgen udpgen;
191
        bool retry;
192
        int pkt_len, offset;
193
        struct iovec iov[4];
194

    
195
        char h_pkt[MON_HEADER_SPACE];
196
        char h_data[MON_HEADER_SPACE];
197

    
198
        struct msg_header msg_h;
199

    
200
        char str[1000];
201
        mlSocketIDToString(&connectbuf[con_id]->external_socketID,str,999);
202
        debug("ML: send_msg to conID:%d extID:%d, %s\n",con_id,connectbuf[con_id]->external_connectionID,str);
203

    
204
        iov[0].iov_base = &msg_h;
205
        iov[0].iov_len = MSG_HEADER_SIZE;
206

    
207
        msg_h.local_con_id = con_id;
208
        msg_h.remote_con_id = connectbuf[con_id]->external_connectionID;
209
        msg_h.msg_type = msg_type;
210
        msg_h.msg_seq_num = connectbuf[con_id]->seqnr++;
211

    
212

    
213
        iov[1].iov_len = iov[2].iov_len = 0;
214
        iov[1].iov_base = h_pkt;
215
        iov[2].iov_base = h_data;
216

    
217

    
218
        if (connectbuf[con_id]->internal_connect)
219
                udpgen = connectbuf[con_id]->external_socketID.internal_addr;
220
        else
221
                udpgen = connectbuf[con_id]->external_socketID.external_addr;
222

    
223
        do{
224
                offset = 0;
225
                retry = false;
226
                // Monitoring layer hook
227
                if(set_Monitoring_header_data_cb != NULL) {
228
                        iov[2].iov_len = ((set_Monitoring_header_data_cb) (&(connectbuf[con_id]->external_socketID), msg_type));
229
                }
230
                msg_h.len_mon_data_hdr = iov[2].iov_len;
231

    
232
                if(get_Send_data_inf_cb != NULL && iov[2].iov_len != 0) {
233
                        mon_data_inf sd_data_inf;
234

    
235
                        sd_data_inf.remote_socketID = &(connectbuf[con_id]->external_socketID);
236
                        sd_data_inf.buffer = msg;
237
                        sd_data_inf.bufSize = msg_len;
238
                        sd_data_inf.msgtype = msg_type;
239
                        sd_data_inf.monitoringDataHeader = iov[2].iov_base;
240
                        sd_data_inf.monitoringDataHeaderLen = iov[2].iov_len;
241
                        sd_data_inf.priority = sParams->priority;
242
                        sd_data_inf.padding = sParams->padding;
243
                        sd_data_inf.confirmation = sParams->confirmation;
244
                        sd_data_inf.reliable = sParams->reliable;
245
                        memset(&sd_data_inf.arrival_time, 0, sizeof(struct timeval));
246

    
247
                        (get_Send_data_inf_cb) ((void *) &sd_data_inf);
248
                }
249

    
250
                do {
251
                        if(set_Monitoring_header_pkt_cb != NULL) {
252
                                iov[1].iov_len = (set_Monitoring_header_pkt_cb) (&(connectbuf[con_id]->external_socketID), msg_type);
253
                        }
254
                        pkt_len = min(connectbuf[con_id]->pmtusize - iov[2].iov_len - iov[1].iov_len - iov[0].iov_len, msg_len - offset) ;
255

    
256
                        iov[3].iov_len = pkt_len;
257
                        iov[3].iov_base = msg + offset;
258

    
259
                        //fill header
260
                        msg_h.len_mon_packet_hdr = iov[1].iov_len;
261
                        msg_h.offset = offset;
262
                        msg_h.msg_length = truncable ? pkt_len : msg_len;
263

    
264
                        //monitoring layer hook
265
                        if(get_Send_pkt_inf_cb != NULL && iov[1].iov_len) {
266
                                mon_pkt_inf pkt_info;
267

    
268
                                pkt_info.remote_socketID = &(connectbuf[con_id]->external_socketID);
269
                                pkt_info.buffer = msg + offset;
270
                                pkt_info.bufSize = pkt_len;
271
                                pkt_info.msgtype = msg_type;
272
                                pkt_info.dataID = connectbuf[con_id]->seqnr;
273
                                pkt_info.offset = offset;
274
                                pkt_info.datasize = msg_len;
275
                                pkt_info.monitoringHeaderLen = iov[1].iov_len;
276
                                pkt_info.monitoringHeader = iov[1].iov_base;
277
                                pkt_info.ttl = -1;
278
                                memset(&(pkt_info.arrival_time),0,sizeof(struct timeval));
279

    
280
                                (get_Send_pkt_inf_cb) ((void *) &pkt_info);
281
                        }
282

    
283
                        debug("ML: sending packet with rconID:%d lconID:%d\n",msg_h.remote_con_id,msg_h.local_con_id);
284
                        switch(sendPacket(socketfd, iov, 4, &udpgen.udpaddr)) {
285
                                case MSGLEN:
286
                                        connectbuf[con_id]->pmtusize = pmtu_decrement(connectbuf[con_id]->pmtusize);
287
                                        connectbuf[con_id]->delay = true;
288
                                        retry = true;
289
                                        offset = msg_len; // exit the while
290
                                        break;
291
                                case FAILURE:
292
                                        offset = msg_len; // exit the while
293
                                        break;
294
                                case OK:
295
                                        //update
296
                                        offset += pkt_len + iov[2].iov_len;
297
                                        //transmit data header only in the first packet
298
                                        iov[2].iov_len = 0;
299
                                        break;
300
                        }
301
                } while(offset != msg_len + msg_h.len_mon_data_hdr && !truncable);
302
        } while(retry);
303
}
304

    
305
void send_conn_msg(int con_id, int buf_size, int command_type)
306
{
307
        if (buf_size < sizeof(struct conn_msg)) {
308
                error("ML: requested connection message size is too small\n");
309
                return;
310
        }
311

    
312
        if(connectbuf[con_id]->ctrl_msg_buf == NULL) {
313
                connectbuf[con_id]->ctrl_msg_buf = malloc(buf_size);
314
                memset(connectbuf[con_id]->ctrl_msg_buf, 0, buf_size);
315
        }
316

    
317
        if(connectbuf[con_id]->ctrl_msg_buf == NULL) {
318
                error("ML: can not allocate memory for connection message\n");
319
                return;
320
        }
321

    
322
        struct conn_msg *msg_header = (struct conn_msg*) connectbuf[con_id]->ctrl_msg_buf;
323

    
324
        msg_header->comand_type = command_type;
325
        msg_header->pmtu_size = connectbuf[con_id]->pmtusize;
326

    
327
        memcpy(&(msg_header->sock_id), loc_socketID, sizeof(socket_ID));
328

    
329
        send_msg(con_id, ML_CON_MSG, connectbuf[con_id]->ctrl_msg_buf, buf_size, true, &(connectbuf[con_id]->defaultSendParams));
330
}
331

    
332
void
333
recv_conn_msg(struct msg_header *msg_h, char *msgbuf, int bufsize)
334
{
335
        struct conn_msg *con_msg;
336
        int free_con_id, con_id;
337

    
338
        time_t now = time(NULL);
339
        double timediff = 0.0;
340
        char str[1000];
341

    
342
        // Monitoring layer hook
343
        if(get_Recv_data_inf_cb != NULL && msg_h->len_mon_data_hdr != 0) {
344
                // update pointer to the real data
345
                msgbuf += msg_h->len_mon_data_hdr;
346
                bufsize -= msg_h->len_mon_data_hdr;
347
                con_msg = (struct conn_msg *)msgbuf;
348

    
349
                mon_data_inf recv_data_inf;
350
                recv_data_inf.remote_socketID = &(con_msg->sock_id);
351
                recv_data_inf.buffer = msgbuf;
352
                recv_data_inf.bufSize = bufsize;
353
                recv_data_inf.msgtype = msg_h->msg_type;
354
                recv_data_inf.monitoringDataHeaderLen = msg_h->len_mon_data_hdr;
355
                recv_data_inf.monitoringDataHeader = msg_h->len_mon_data_hdr ? msgbuf : NULL;
356
                gettimeofday(&recv_data_inf.arrival_time, NULL);
357
                recv_data_inf.firstPacketArrived = true;
358
                recv_data_inf.recvFragments = 1;
359
                recv_data_inf.priority = false;
360
                recv_data_inf.padding = false;
361
                recv_data_inf.confirmation = false;
362
                recv_data_inf.reliable = false;
363

    
364
                // send data recv callback to monitoring module
365
                (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
366
        } else {
367
                con_msg = (struct conn_msg *) msgbuf;
368
        }
369

    
370
        //decode sock_id for debug messages
371
        mlSocketIDToString(&con_msg->sock_id,str,999);
372

    
373
        // check the connection command type
374
        switch (con_msg->comand_type) {
375
                /*
376
                * if INVITE: enter a new socket make new entry in connect array
377
                * send an ok
378
                */
379
                case INVITE:
380
                        info("ML: received INVITE from %s\n",str);
381
                        /*
382
                        * check if another connection for the external connectionID exist
383
                        * that was established within the last 2 seconds
384
                        */
385
                        free_con_id = -1;
386
                        for (con_id = 0; con_id < CONNECTBUFSIZE; con_id++) {
387
                                if (connectbuf[con_id] != NULL) {
388
                                        if (mlCompareSocketIDs(&(connectbuf[con_id]->external_socketID), &(con_msg->sock_id)) == 0) {
389
                                                //timediff = difftime(now, connectbuf[con_id]->starttime);        //TODO: why this timeout? Shouldn't the connection be closed instead if there is a timeout?
390
                                                //if (timediff < 2)
391
                                                //update remote connection ID
392
                                                if (connectbuf[con_id]->external_connectionID != msg_h->local_con_id) {
393
                                                        warn("ML: updating remote connection ID for %s: from %d to %d\n",str, connectbuf[con_id]->external_connectionID, msg_h->local_con_id);
394
                                                        connectbuf[con_id]->external_connectionID = msg_h->local_con_id;
395
                                                }
396
                                                break;
397
                                        }
398
                                } else if(free_con_id == -1)
399
                                        free_con_id = con_id;
400
                        }
401

    
402
                        if (con_id == CONNECTBUFSIZE) {
403
                                // create an entry in the connecttrybuf
404
                                if(free_con_id == -1) {
405
                                        error("ML: no new connect_buf available\n");
406
                                        return;
407
                                }
408
                                connectbuf[free_con_id] = (connect_data *) malloc(sizeof(connect_data));
409
                                memset(connectbuf[free_con_id],0,sizeof(connect_data));
410
                                connectbuf[free_con_id]->connection_head = connectbuf[free_con_id]->connection_last = NULL;
411
                                connectbuf[free_con_id]->starttime = time(NULL);
412
                                memcpy(&(connectbuf[free_con_id]->external_socketID), &(con_msg->sock_id), sizeof(socket_ID));
413
                                connectbuf[free_con_id]->pmtusize = con_msg->pmtu_size;
414
                                connectbuf[free_con_id]->external_connectionID = msg_h->local_con_id;
415
                                connectbuf[free_con_id]->internal_connect =
416
                                        !compare_external_address_socketIDs(&(con_msg->sock_id), loc_socketID);
417
                                con_id = free_con_id;
418
                        }
419

    
420
                        //if(connectbuf[con_id]->status <= CONNECT) { //TODO: anwer anyway. Why the outher would invite otherwise?
421
                                //update status and send back answer
422
                                connectbuf[con_id]->status = CONNECT;
423
                                send_conn_msg(con_id, con_msg->pmtu_size, CONNECT);
424
                        //}
425
                        break;
426
                case CONNECT:
427
                        info("ML: received CONNECT from %s\n",str);
428

    
429
                        if(msg_h->remote_con_id != -1 && connectbuf[msg_h->remote_con_id] == NULL) {
430
                                error("ML: received CONNECT for inexistent connection rconID:%d\n",msg_h->remote_con_id);
431
                                return;
432
                        }
433

    
434
                        /*
435
                        * check if the connection status is not already 1 or 2
436
                        */
437
                        if (connectbuf[msg_h->remote_con_id]->status == INVITE) {
438
                                // set the external connectionID
439
                                connectbuf[msg_h->remote_con_id]->external_connectionID = msg_h->local_con_id;
440
                                // change status con_msg the connection_data
441
                                connectbuf[msg_h->remote_con_id]->status = READY;
442
                                // change pmtusize in the connection_data
443
                                connectbuf[msg_h->remote_con_id]->pmtusize = con_msg->pmtu_size;
444

    
445
                                // send the READY
446
                                send_conn_msg(msg_h->remote_con_id, con_msg->pmtu_size, READY);
447

    
448
                                if (receive_Connection_cb != NULL)
449
                                        (receive_Connection_cb) (msg_h->remote_con_id, NULL);
450

    
451
                                // call all registered callbacks
452
                                while(connectbuf[msg_h->remote_con_id]->connection_head != NULL) {
453
                                        struct receive_connection_cb_list *temp;
454
                                        temp = connectbuf[msg_h->remote_con_id]->connection_head;
455
                                        (temp->connection_cb) (msg_h->remote_con_id, temp->arg);
456
                                        connectbuf[msg_h->remote_con_id]->connection_head = temp->next;
457
                                        free(temp);
458
                                }
459
                                connectbuf[msg_h->remote_con_id]->connection_head =
460
                                        connectbuf[msg_h->remote_con_id]->connection_last = NULL;
461
                        } else
462
                                // send the READY
463
                                send_conn_msg(msg_h->remote_con_id, con_msg->pmtu_size, READY);
464

    
465
                        debug("ML: active connection established\n");
466
                        break;
467

    
468
                        /*
469
                        * if READY: find the entry in the connection array set the
470
                        * connection active change the pmtu size
471
                        */
472
                case READY:
473
                        info("ML: received READY from %s\n",str);
474
                        if(connectbuf[msg_h->remote_con_id] == NULL) {
475
                                error("ML: received READY for inexistent connection\n");
476
                                return;
477
                        }
478
                        /*
479
                        * checks if the connection is not already established
480
                        */
481
                        if (connectbuf[msg_h->remote_con_id]->status == CONNECT) {
482
                                // change status of the connection
483
                                connectbuf[msg_h->remote_con_id]->status = 2;
484
                                // change pmtusize
485
                                connectbuf[msg_h->remote_con_id]->pmtusize = con_msg->pmtu_size;
486

    
487
                                if (receive_Connection_cb != NULL)
488
                                        (receive_Connection_cb) (msg_h->remote_con_id, NULL);
489

    
490
                                while(connectbuf[msg_h->remote_con_id]->connection_head != NULL) {
491
                                        struct receive_connection_cb_list *temp;
492
                                        temp = connectbuf[msg_h->remote_con_id]->connection_head;
493
                                        (temp->connection_cb) (msg_h->remote_con_id, temp->arg);
494
                                        connectbuf[msg_h->remote_con_id]->connection_head = temp->next;
495
                                        free(temp);
496
                                }
497
                                connectbuf[msg_h->remote_con_id]->connection_head =
498
                                        connectbuf[msg_h->remote_con_id]->connection_last = NULL;
499
                                debug("ML: passive connection established\n");
500
                        }
501
                        break;
502
        }
503
}
504

    
505
void recv_stun_msg(char *msgbuf, int recvSize)
506
{
507
        /*
508
        * create empty stun message struct
509
        */
510
        StunMessage resp;
511
        memset(&resp, 0, sizeof(StunMessage));
512
        /*
513
        * parse the message
514
        */
515
        int returnValue = 0;
516
        returnValue = recv_stun_message(msgbuf, recvSize, &resp);
517

    
518
        if (returnValue == 0) {
519
                /*
520
                * read the reflexive Address into the local_socketID
521
                */
522
                struct sockaddr_in reflexiveAddr;
523
                reflexiveAddr.sin_family = AF_INET;
524
                reflexiveAddr.sin_addr.s_addr = htonl(resp.mappedAddress.ipv4.addr);
525
                reflexiveAddr.sin_port = htons(resp.mappedAddress.ipv4.port);
526
                socketaddrgen reflexiveAddres;
527
                reflexiveAddres.udpaddr = reflexiveAddr;
528
                local_socketID.external_addr = reflexiveAddres;
529
                NAT_traversal = true;
530
                // callback to the upper layer indicating that the socketID is now
531
                // ready to use
532
                (receive_SocketID_cb) (&local_socketID, 0);
533
        }
534
}
535

    
536
//done
537
void recv_timeout_cb(int fd, short event, void *arg)
538
{
539
        int recv_id = (long) arg;
540
        debug("ML: recv_timeout_cb called. Timeout for id:%d\n",recv_id);
541

    
542
        if (recvdatabuf[recv_id] == NULL) {
543
                return;
544
        }
545

    
546

    
547
/*        if(recvdatabuf[recv_id]->status == ACTIVE) {
548
                //TODO make timeout at least a DEFINE
549
                struct timeval timeout = { 4, 0 };
550
                recvdatabuf[recv_id]->status = INACTIVE;
551
                event_base_once(base, -1, EV_TIMEOUT, recv_timeout_cb,
552
                        arg, &timeout);
553
                return;
554
        }
555
*/
556

    
557
        if(recvdatabuf[recv_id]->status == ACTIVE) {
558
                // Monitoring layer hook
559
                if(get_Recv_data_inf_cb != NULL) {
560
                        mon_data_inf recv_data_inf;
561

    
562
                        recv_data_inf.remote_socketID =
563
                                        &(connectbuf[recvdatabuf[recv_id]->connectionID]->external_socketID);
564
                        recv_data_inf.buffer = recvdatabuf[recv_id]->recvbuf;
565
                        recv_data_inf.bufSize = recvdatabuf[recv_id]->bufsize;
566
                        recv_data_inf.msgtype = recvdatabuf[recv_id]->msgtype;
567
                        recv_data_inf.monitoringDataHeaderLen = recvdatabuf[recv_id]->monitoringDataHeaderLen;
568
                        recv_data_inf.monitoringDataHeader = recvdatabuf[recv_id]->monitoringDataHeaderLen ?
569
                                recvdatabuf[recv_id]->recvbuf : NULL;
570
                        gettimeofday(&recv_data_inf.arrival_time, NULL);
571
                        recv_data_inf.firstPacketArrived = recvdatabuf[recv_id]->firstPacketArrived;
572
                        recv_data_inf.recvFragments = recvdatabuf[recv_id]->recvFragments;
573
                        recv_data_inf.priority = false;
574
                        recv_data_inf.padding = false;
575
                        recv_data_inf.confirmation = false;
576
                        recv_data_inf.reliable = false;
577

    
578
                        // send data recv callback to monitoring module
579

    
580
                        (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
581
                }
582

    
583
                // Get the right callback
584
                receive_data_cb receive_data_callback = recvcbbuf[recvdatabuf[recv_id]->msgtype];
585

    
586
                recv_params rParams;
587

    
588
                rParams.nrMissingBytes = recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->arrivedBytes;
589
                rParams.recvFragments = recvdatabuf[recv_id]->recvFragments;
590
                rParams.msgtype = recvdatabuf[recv_id]->msgtype;
591
                rParams.connectionID = recvdatabuf[recv_id]->connectionID;
592
                rParams.remote_socketID =
593
                        &(connectbuf[recvdatabuf[recv_id]->connectionID]->external_socketID);
594
                rParams.firstPacketArrived = recvdatabuf[recv_id]->firstPacketArrived;
595

    
596
                (receive_data_callback) (recvdatabuf[recv_id]->recvbuf + recvdatabuf[recv_id]->monitoringDataHeaderLen, recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->monitoringDataHeaderLen,
597
                        recvdatabuf[recv_id]->msgtype, &rParams);
598

    
599
                //clean up
600
                free(recvdatabuf[recv_id]->recvbuf);
601
                free(recvdatabuf[recv_id]);
602
                recvdatabuf[recv_id] = NULL;
603
        }
604
}
605

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

    
611
        int recv_id, free_recv_id = -1;
612

    
613
        if(connectbuf[msg_h->remote_con_id] == NULL) {
614
                debug("ML: Received a message not related to any opened connection!\n");
615
                return;
616
        }
617

    
618
        // check if a recv_data exist and enter data
619
        for (recv_id = 0; recv_id < RECVDATABUFSIZE; recv_id++)
620
                if (recvdatabuf[recv_id] != NULL) {
621
                        if (msg_h->remote_con_id == recvdatabuf[recv_id]->connectionID &&
622
                                        msg_h->msg_seq_num == recvdatabuf[recv_id]->seqnr)
623
                                                break;
624
                } else
625
                        if(free_recv_id == -1)
626
                                free_recv_id = recv_id;
627

    
628

    
629
        if(recv_id == RECVDATABUFSIZE) {
630
                //no recv_data found: create one
631
                recv_id = free_recv_id;
632
                recvdatabuf[recv_id] = (recvdata *) malloc(sizeof(recvdata));
633
                memset(recvdatabuf[recv_id], 0, sizeof(recvdata));
634
                recvdatabuf[recv_id]->connectionID = msg_h->remote_con_id;
635
                recvdatabuf[recv_id]->seqnr = msg_h->msg_seq_num;
636
                recvdatabuf[recv_id]->monitoringDataHeaderLen = msg_h->len_mon_data_hdr;
637
                recvdatabuf[recv_id]->bufsize = msg_h->msg_length + msg_h->len_mon_data_hdr;
638
                recvdatabuf[recv_id]->recvbuf = (char *) malloc(recvdatabuf[recv_id]->bufsize);
639
                /*
640
                * read the timeout data and set it
641
                */
642
                recvdatabuf[recv_id]->timeout_value.tv_sec = recv_timeout.tv_sec;
643
                recvdatabuf[recv_id]->timeout_value.tv_usec = recv_timeout.tv_usec;
644
                recvdatabuf[recv_id]->timeout_event = NULL;
645
                recvdatabuf[recv_id]->recvID = recv_id;
646
                recvdatabuf[recv_id]->starttime = time(NULL);
647
                recvdatabuf[recv_id]->msgtype = msg_h->msg_type;
648

    
649
                // fill the buffer with zeros
650
                memset(recvdatabuf[recv_id]->recvbuf, 0, msg_h->msg_length);
651
                debug(" new @ id:%d\n",recv_id);
652
        } else {        //message structure already exists, no need to create new
653
                debug(" found @ id:%d\n",recv_id);
654
        }
655

    
656
        if (msg_h->offset == 0)
657
                recvdatabuf[recv_id]->firstPacketArrived = 1;
658

    
659

    
660
        // increment fragmentnr
661
        recvdatabuf[recv_id]->recvFragments++;
662
        // increment the arrivedBytes
663
        recvdatabuf[recv_id]->arrivedBytes += bufsize;
664

    
665
        // enter the data into the buffer
666
        memcpy(recvdatabuf[recv_id]->recvbuf + msg_h->offset, msgbuf, bufsize);
667

    
668
        //TODO very basic checkif all fragments arrived: has to be reviewed
669
        if(recvdatabuf[recv_id]->arrivedBytes == recvdatabuf[recv_id]->bufsize)
670
                recvdatabuf[recv_id]->status = COMPLETE; //buffer full -> msg completly arrived
671
        else
672
                recvdatabuf[recv_id]->status = ACTIVE;
673

    
674
        if (recv_data_callback) {
675
                if(recvdatabuf[recv_id]->status == COMPLETE) {
676
                        // Monitoring layer hook
677
                        if(get_Recv_data_inf_cb != NULL) {
678
                                mon_data_inf recv_data_inf;
679

    
680
                                recv_data_inf.remote_socketID =
681
                                         &(connectbuf[recvdatabuf[recv_id]->connectionID]->external_socketID);
682
                                recv_data_inf.buffer = recvdatabuf[recv_id]->recvbuf;
683
                                recv_data_inf.bufSize = recvdatabuf[recv_id]->bufsize;
684
                                recv_data_inf.msgtype = recvdatabuf[recv_id]->msgtype;
685
                                recv_data_inf.monitoringDataHeaderLen = recvdatabuf[recv_id]->monitoringDataHeaderLen;
686
                                recv_data_inf.monitoringDataHeader = recvdatabuf[recv_id]->monitoringDataHeaderLen ?
687
                                        recvdatabuf[recv_id]->recvbuf : NULL;
688
                                gettimeofday(&recv_data_inf.arrival_time, NULL);
689
                                recv_data_inf.firstPacketArrived = recvdatabuf[recv_id]->firstPacketArrived;
690
                                recv_data_inf.recvFragments = recvdatabuf[recv_id]->recvFragments;
691
                                recv_data_inf.priority = false;
692
                                recv_data_inf.padding = false;
693
                                recv_data_inf.confirmation = false;
694
                                recv_data_inf.reliable = false;
695

    
696
                                // send data recv callback to monitoring module
697

    
698
                                (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
699
                        }
700

    
701
                        // Get the right callback
702
                        receive_data_cb receive_data_callback = recvcbbuf[msg_h->msg_type];
703
                        if (receive_data_callback) {
704

    
705
                                recv_params rParams;
706

    
707
                                rParams.nrMissingBytes = recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->arrivedBytes;
708
                                rParams.recvFragments = recvdatabuf[recv_id]->recvFragments;
709
                                rParams.msgtype = recvdatabuf[recv_id]->msgtype;
710
                                rParams.connectionID = recvdatabuf[recv_id]->connectionID;
711
                                rParams.remote_socketID =
712
                                        &(connectbuf[recvdatabuf[recv_id]->connectionID]->external_socketID);
713

    
714
                                char str[1000];
715
                                mlSocketIDToString(rParams.remote_socketID,str,999);
716
                                debug("ML: received message from conID:%d, %s\n",recvdatabuf[recv_id]->connectionID,str);
717
                                rParams.firstPacketArrived = recvdatabuf[recv_id]->firstPacketArrived;
718

    
719
                                (receive_data_callback) (recvdatabuf[recv_id]->recvbuf + recvdatabuf[recv_id]->monitoringDataHeaderLen, recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->monitoringDataHeaderLen,
720
                                        recvdatabuf[recv_id]->msgtype, (void *) &rParams);
721
                        } else {
722
                            warn("ML: callback not initialized for this message type: %d!\n",msg_h->msg_type);
723
                        }
724

    
725
                        //clean up
726
                        if (recvdatabuf[recv_id]->timeout_event) {
727
                                int ret;
728
                                debug("ML: freeing timeout for %d",recv_id);
729
                                ret = event_del(recvdatabuf[recv_id]->timeout_event);
730
                                event_free(recvdatabuf[recv_id]->timeout_event);
731
                                debug(" ret: %d\n",ret);
732
                        } else {
733
                                debug("ML: received in 1 packet\n",recv_id);
734
                        }
735
                        free(recvdatabuf[recv_id]->recvbuf);
736
                        free(recvdatabuf[recv_id]);
737
                        recvdatabuf[recv_id] = NULL;
738
                } else { // not COMPLETE
739
                        if (!recvdatabuf[recv_id]->timeout_event) {
740
                                //start time out
741
                                //TODO make timeout at least a DEFINE
742
                                struct timeval timeout = { 2, 0 };        //TODO: use some configurable timeout here
743
                                recvdatabuf[recv_id]->timeout_event = event_new(base, -1, EV_TIMEOUT, &recv_timeout_cb, (void *) (long)recv_id);
744
                                evtimer_add(recvdatabuf[recv_id]->timeout_event, &timeout);
745
                        }
746
                }
747
        }
748
}
749

    
750
//done
751
void pmtu_timeout_cb(int fd, short event, void *arg)
752
{
753
        debug("ML: pmtu timeout called\n");
754

    
755
        int con_id = (long) arg;
756
        pmtu new_pmtusize;
757
        struct timeval timeout;
758

    
759
        if(connectbuf[con_id] == NULL) {
760
                error("ML: pmtu timeout called on non existing con_id\n");
761
                return;
762
        }
763

    
764
        if(connectbuf[con_id]->status == READY) {
765
                // nothing to do anymore
766
                return;
767
        }
768

    
769
        timeout = connectbuf[con_id]->timeout_value;
770

    
771
        if(connectbuf[con_id]->delay || connectbuf[con_id]->trials == MAX_TRIALS - 1) {
772
                double delay = timeout.tv_sec + timeout.tv_usec / 1000000.0;
773
                delay = delay * 2;
774
                timeout.tv_sec = floor(delay);
775
                timeout.tv_usec = fmod(delay, 1.0) * 1000000.0;
776
                if(connectbuf[con_id]->delay) {
777
                        connectbuf[con_id]->delay = false;
778
                        goto reschedule;
779
                }
780
        }
781

    
782
        if(connectbuf[con_id]->trials == MAX_TRIALS) {
783
                // decrement the pmtu size
784
                connectbuf[con_id]->pmtusize = pmtu_decrement(connectbuf[con_id]->pmtusize);
785
                connectbuf[con_id]->trials = 0;
786
        }
787

    
788
        //error in PMTU discovery?
789
        if (connectbuf[con_id]->pmtusize == ERROR) {
790
                if (connectbuf[con_id]->internal_connect == true) {
791
                        //as of now we tried directly connecting, now let's try trough the NAT
792
                        connectbuf[con_id]->internal_connect = false;
793
                        connectbuf[con_id]->pmtusize = MAX;
794
                } else {
795
                        //nothing to do we have to give up
796
                        error("ML: Could not create connection with connectionID %i!\n",con_id);
797
                        // envoke the callback for failed connection establishment
798
                        if(failed_Connection_cb != NULL)
799
                                (failed_Connection_cb) (con_id, NULL);
800
                        // delete the connection entry
801
                        mlCloseConnection(con_id);
802
                        return;
803
                }
804
        }
805

    
806
        //retry with new pmtu size
807
        connectbuf[con_id]->trials++;
808
        send_conn_msg(con_id, connectbuf[con_id]->pmtusize, connectbuf[con_id]->status);
809

    
810
reschedule:
811
        /* reschedule */
812
        event_base_once(base, -1, EV_TIMEOUT, pmtu_timeout_cb, (void *) (long)con_id, &timeout);
813
}
814

    
815
/*
816
 * decrements the mtu size
817
 */
818
pmtu pmtu_decrement(pmtu pmtusize)
819
{
820
        pmtu pmtu_return_size;
821
        switch(pmtusize) {
822
        case MAX:
823
                return DSL;
824
        case DSL:
825
                return DSLMEDIUM;
826
        case DSLMEDIUM:
827
                return DSLSLIM;
828
        case DSLSLIM:
829
                return BELOWDSL;
830
        case BELOWDSL:
831
                return MIN;
832
        default:
833
                return ERROR;
834
        }
835
}
836

    
837
void pmtu_error_cb_th(char *msg, int msglen)
838
{
839
        debug("ML: pmtu_error callback called msg_size: %d\n",msglen);
840
        //TODO debug
841
        return;
842

    
843
    char *msgbufptr = NULL;
844
    int msgtype;
845
    int connectionID;
846
    pmtu pmtusize;
847
    pmtu new_pmtusize;
848
    int dead = 0;
849

    
850
    // check the packettype
851
    msgbufptr = &msg[0];
852

    
853
    // check the msgtype
854
    msgbufptr = &msg[1];
855
    memcpy(&msgtype, msgbufptr, 4);
856

    
857
    if (msgtype == 0) {
858

    
859
        // get the connectionID
860
        msgbufptr = &msg[5];
861
        memcpy(&connectionID, msgbufptr, 4);
862

    
863
        int msgtype_c = connectbuf[connectionID]->status;
864
//        pmtusize = connectbuf[connectionID]->pmtutrysize;
865

    
866
        if (msgtype_c != msgtype) {
867
            dead = 1;
868
        }
869

    
870

    
871
    } else if (msgtype == 1) {
872

    
873
        // read the connectionID
874
        msgbufptr = &msg[9];
875
        memcpy(&connectionID, msgbufptr, 4);
876

    
877
        int msgtype_c = connectbuf[connectionID]->status;
878
//        pmtusize = connectbuf[connectionID]->pmtutrysize;
879

    
880
        if (msgtype_c != msgtype) {
881
            dead = 1;
882
        }
883

    
884
    }
885
    // decrement the pmtu size
886
    new_pmtusize = pmtu_decrement(pmtusize);
887

    
888
//    connectbuf[connectionID]->pmtutrysize = new_pmtusize;
889

    
890
    if (new_pmtusize == ERROR) {
891
                error("ML:  Could not create connection with connectionID %i !\n",
892
                        connectionID);
893

    
894
                if(failed_Connection_cb != NULL)
895
                        (failed_Connection_cb) (connectionID, NULL);
896
                // set the message type to a non existent message
897
                msgtype = 2;
898
                // delete the connection entry
899
                 mlCloseConnection(connectionID);
900
        }
901

    
902
    if (msgtype == 0 && dead != 1) {
903

    
904
        // stop the timeout event
905
        // timeout_del(connectbuf[connectionID]->timeout);
906
        /*
907
         * libevent2
908
         */
909

    
910
        // event_del(connectbuf[connectionID]->timeout);
911

    
912

    
913
        // create and send a connection message
914
//         create_conn_msg(new_pmtusize, connectionID,
915
//                         &local_socketID, INVITE);
916

    
917
//        send_conn_msg(connectionID, new_pmtusize);
918

    
919
        // set a timeout event for the pmtu discovery
920
        // timeout_set(connectbuf[connectionID]->timeout,pmtu_timeout_cb,(void
921
        // *)&connectionID);
922

    
923
        // timeout_add(connectbuf[connectionID]->timeout,&connectbuf[connectionID]->timeout_value);
924

    
925
        /*
926
         * libevent2
927
         */
928

    
929
        struct event *ev;
930
        ev = evtimer_new(base, pmtu_timeout_cb,
931
                         (void *) connectbuf[connectionID]);
932

    
933
        // connectbuf[connectionID]->timeout = ev;
934

    
935
        event_add(ev, &connectbuf[connectionID]->timeout_value);
936

    
937
    } else if (msgtype == 1 && dead != 1) {
938

    
939
        // stop the timeout event
940
        // timeout_del(connectbuf[connectionID]->timeout);
941

    
942
        /*
943
         * libevent2
944
         */
945
        // info("still here 11 \n");
946
        // printf("ev %d \n",connectbuf[connectionID]->timeout);
947
        // event_del(connectbuf[connectionID]->timeout );
948
        // evtimer_del(connectbuf[connectionID]->timeout );
949

    
950

    
951
//         // create and send a connection message
952
//         create_conn_msg(new_pmtusize,
953
//                         connectbuf[connectionID]->connectionID,
954
//                         NULL, CONNECT);
955

    
956
        //send_conn_msg(connectionID, new_pmtusize);
957

    
958
        // set a timeout event for the pmtu discovery
959
        // timeout_set(connectbuf[connectionID]->timeout,pmtu_timeout_cb,(void
960
        // *)&connectionID);
961
        // timeout_add(connectbuf[connectionID]->timeout,&connectbuf[connectionID]->timeout_value);
962

    
963
        /*
964
         * libevent2
965
         */
966
        // struct event *ev;
967
        // ev = evtimer_new(base,pmtu_timeout_cb, (void
968
        // *)connectbuf[connectionID]);
969
        // connectbuf[connectionID]->timeout = ev;
970
        // event_add(ev,&connectbuf[connectionID]->timeout_value);
971

    
972
    }
973
}
974

    
975
/*
976
 * what to do once a packet arrived if it is a conn packet send it to
977
 * recv_conn handler if it is a data packet send it to the recv_data
978
 * handler
979
 */
980

    
981
//done --
982
void recv_pkg(int fd, short event, void *arg)
983
{
984
        debug("ML: recv_pkg called\n");
985

    
986
        struct msg_header *msg_h;
987
        char msgbuf[MAX];
988
        char *bufptr = msgbuf;
989
        int ttl;
990
        struct sockaddr_in recv_addr;
991
        pmtu recvSize = MAX;
992
        int msg_size;
993

    
994
        recvPacket(fd, msgbuf, &recvSize, &recv_addr, pmtu_error_cb_th, &ttl);
995

    
996

    
997
        // check if it is not just an ERROR message
998
        if(recvSize < 0)
999
                return;
1000

    
1001
        // @TODO check if this simplistic STUN message recognition really always works, probably not
1002
        unsigned short stun_bind_response = 0x0101;
1003
        unsigned short * msgspot = (unsigned short *) msgbuf;
1004
        if (*msgspot == stun_bind_response) {
1005
                debug("ML: recv_pkg: parse stun message called\n");
1006
                recv_stun_msg(msgbuf, recvSize);
1007
                return;
1008
        }
1009

    
1010
        msg_h = (struct msg_header *) msgbuf;
1011
        bufptr += MSG_HEADER_SIZE + msg_h->len_mon_packet_hdr;
1012
        msg_size = recvSize - MSG_HEADER_SIZE - msg_h->len_mon_packet_hdr;
1013

    
1014

    
1015
        if(get_Recv_pkt_inf_cb != NULL && msg_h->len_mon_packet_hdr != 0) {
1016
                mon_pkt_inf msginfNow;
1017
                msginfNow.monitoringHeaderLen = msg_h->len_mon_packet_hdr;
1018
                msginfNow.monitoringHeader = msg_h->len_mon_packet_hdr ? &msgbuf[0] + MSG_HEADER_SIZE : NULL;
1019
                //TODO rethink this ...
1020
                if(msg_h->msg_type == ML_CON_MSG) {
1021
                        struct conn_msg *c_msg = (struct conn_msg *) bufptr;
1022
                        msginfNow.remote_socketID = &(c_msg->sock_id);
1023
                }
1024
                else if(connectbuf[msg_h->remote_con_id] == NULL) {
1025
                        error("ML: received pkg called with non existent connection\n");
1026
                        return;
1027
                } else
1028
                        msginfNow.remote_socketID = &(connectbuf[msg_h->remote_con_id]->external_socketID);
1029
                msginfNow.buffer = bufptr;
1030
                msginfNow.bufSize = recvSize;
1031
                msginfNow.msgtype = msg_h->msg_type;
1032
                msginfNow.ttl = ttl;
1033
                msginfNow.dataID = msg_h->msg_seq_num;
1034
                msginfNow.offset = msg_h->offset;
1035
                msginfNow.datasize = msg_h->msg_length;
1036
                gettimeofday(&msginfNow.arrival_time, NULL);
1037
                (get_Recv_pkt_inf_cb) ((void *) &msginfNow);
1038
        }
1039

    
1040

    
1041
        switch(msg_h->msg_type) {
1042
                case ML_CON_MSG:
1043
                        debug("ML: received conn pkg\n");
1044
                        recv_conn_msg(msg_h, bufptr, msg_size);
1045
                        break;
1046
                default:
1047
                        if(msg_h->msg_type < 127) {
1048
                                debug("ML: received data pkg\n");
1049
                                recv_data_msg(msg_h, bufptr, msg_size);
1050
                                break;
1051
                        }
1052
                        debug("ML: unrecognised msg_type\n");
1053
                        break;
1054
        }
1055
}
1056

    
1057
/*
1058
 * compare the external IP address of two socketIDs
1059
 */
1060
int
1061
compare_external_address_socketIDs(socketID_handle sock1, socketID_handle sock2)
1062
{
1063
        if( sock1->external_addr.udpaddr.sin_addr.s_addr == sock2->external_addr.udpaddr.sin_addr.s_addr)
1064
                return 0;
1065
        return 1;
1066
}
1067

    
1068
void try_stun();
1069

    
1070
/*
1071
 * the timeout of the NAT traversal
1072
 */
1073
void nat_traversal_timeout(int fd, short event, void *arg)
1074
{
1075
        if (NAT_traversal == false) {
1076
                debug("ML: NAT traversal request re-send\n");
1077
                if(receive_SocketID_cb)
1078
                        (receive_SocketID_cb) (&local_socketID, 2);
1079
                try_stun();
1080
        }
1081
}
1082

    
1083
unsigned long resolve(const char *ipaddr)
1084
{
1085
        struct hostent *h = gethostbyname(ipaddr);
1086
        if (!h) {
1087
                error("ML: Unable to resolve host name %s\n", ipaddr);
1088
        exit(-1);
1089
    }
1090
    unsigned long *addr = (unsigned long *) (h->h_addr);
1091
    return *addr;
1092
}
1093

    
1094

    
1095
/*
1096
 * returns a handle to the socketID struct the ipaddr can be a null
1097
 * pointer. Then all available ipaddr on the machine are choosen.
1098
 */
1099
void create_socket(const int port, const char *ipaddr)
1100
{
1101
        struct sockaddr_in udpaddr;
1102
        udpaddr.sin_family = AF_INET;
1103
        if (ipaddr == NULL) {
1104
                /*
1105
                * try to guess the local IP address
1106
                */
1107
                const char *ipaddr_iface = mlAutodetectIPAddress();
1108
                if (ipaddr_iface) {
1109
                        udpaddr.sin_addr.s_addr = inet_addr(ipaddr_iface);
1110
                } else {
1111
                        udpaddr.sin_addr.s_addr = INADDR_ANY;
1112
                }
1113
        } else {
1114
                udpaddr.sin_addr.s_addr = inet_addr(ipaddr);
1115
        }
1116
        udpaddr.sin_port = htons(port);
1117

    
1118
        socketaddrgen udpgen;
1119
        memset(&udpgen,0,sizeof(socketaddrgen));        //this will be sent over the net, so set it to 0
1120
        udpgen.udpaddr = udpaddr;
1121
        local_socketID.internal_addr = udpgen;
1122

    
1123
        socketfd = createSocket(port, ipaddr);
1124

    
1125
        struct event *ev;
1126
        ev = event_new(base, socketfd, EV_READ | EV_PERSIST, recv_pkg, NULL);
1127

    
1128
        event_add(ev, NULL);
1129

    
1130
        try_stun();
1131
}
1132

    
1133
/*
1134
 * try to figure out external IP using STUN, if defined
1135
 */
1136
void try_stun()
1137
{
1138
        if (isStunDefined()) {
1139
                /*
1140
                * send the NAT traversal STUN request
1141
                */
1142
                 send_stun_request(socketfd, &stun_server);
1143

    
1144
                /*
1145
                * enter a NAT traversal timeout that takes care of retransmission
1146
                */
1147
                struct event *ev1;
1148
                struct timeval timeout_value_NAT_traversal = { 1, 0 };
1149
                ev1 = evtimer_new(base, nat_traversal_timeout, NULL);
1150
                event_add(ev1, &timeout_value_NAT_traversal);
1151

    
1152
                NAT_traversal = false;
1153
        } else {
1154
                /*
1155
                * Assume we have accessibility and copy internal address to external one
1156
                */
1157
                local_socketID.external_addr = local_socketID.internal_addr;
1158
                NAT_traversal = true; // @TODO: this is not really NAT traversal, but a flag that init is over
1159
                // callback to the upper layer indicating that the socketID is now
1160
                // ready to use
1161
                if(receive_SocketID_cb)
1162
                        (receive_SocketID_cb) (&local_socketID, 0); //success
1163
        }
1164
}
1165

    
1166
/**************************** END OF INTERNAL ***********************/
1167

    
1168
/**************************** MONL functions *************************/
1169

    
1170
void mlInit(bool recv_data_cb,struct timeval timeout_value,const int port,const char *ipaddr,const int stun_port,const char *stun_ipaddr,receive_localsocketID_cb local_socketID_cb,void *arg){
1171

    
1172
        base = (struct event_base *) arg;
1173
        recv_data_callback = recv_data_cb;
1174
        mlSetRecvTimeout(timeout_value);
1175
        if (stun_ipaddr) {
1176
                 mlSetStunServer(stun_port, stun_ipaddr);
1177
        } else {
1178

    
1179
        }
1180
        register_recv_localsocketID_cb(local_socketID_cb);
1181
        create_socket(port, ipaddr);
1182

    
1183
}
1184

    
1185
/* register callbacks  */
1186
void mlRegisterGetRecvPktInf(get_recv_pkt_inf_cb recv_pkt_inf_cb){
1187

    
1188
        if (recv_pkt_inf_cb == NULL)
1189
                error("ML: Register get_recv_pkt_inf_cb failed: NULL ptr  \n");
1190
        else
1191
                get_Recv_pkt_inf_cb = recv_pkt_inf_cb;
1192

    
1193
}
1194

    
1195
void mlRegisterGetSendPktInf(get_send_pkt_inf_cb  send_pkt_inf_cb){
1196

    
1197
        if (send_pkt_inf_cb == NULL)
1198
                error("ML: Register get_send_pkt_inf_cb: NULL ptr  \n");
1199
        else
1200
                get_Send_pkt_inf_cb = send_pkt_inf_cb;
1201

    
1202
}
1203

    
1204

    
1205
void mlRegisterSetMonitoringHeaderPktCb(set_monitoring_header_pkt_cb monitoring_header_pkt_cb ){
1206

    
1207
        if (monitoring_header_pkt_cb == NULL)
1208
                error("ML: Register set_monitoring_header_pkt_cb: NULL ptr  \n");
1209
        else
1210
                set_Monitoring_header_pkt_cb = monitoring_header_pkt_cb;
1211

    
1212
}
1213

    
1214
void mlRegisterGetRecvDataInf(get_recv_data_inf_cb recv_data_inf_cb){
1215

    
1216
        if (recv_data_inf_cb == NULL)
1217
                error("ML: Register get_recv_data_inf_cb: NULL ptr  \n");
1218
        else
1219
                get_Recv_data_inf_cb = recv_data_inf_cb;
1220

    
1221
}
1222

    
1223
void mlRegisterGetSendDataInf(get_send_data_inf_cb  send_data_inf_cb){
1224

    
1225
        if (send_data_inf_cb == NULL)
1226
                error("ML: Register get_send_data_inf_cb: NULL ptr  \n");
1227
        else
1228
                get_Send_data_inf_cb = send_data_inf_cb;
1229

    
1230
}
1231

    
1232
void mlRegisterSetMonitoringHeaderDataCb(set_monitoring_header_data_cb monitoring_header_data_cb){
1233

    
1234
        if (monitoring_header_data_cb == NULL)
1235
                error("ML: Register set_monitoring_header_data_cb : NULL ptr  \n");
1236
        else
1237
        set_Monitoring_header_data_cb = monitoring_header_data_cb;
1238

    
1239
}
1240

    
1241
void mlSetRecvTimeout(struct timeval timeout_value){
1242

    
1243
        recv_timeout = timeout_value;
1244

    
1245
}
1246

    
1247
int mlGetStandardTTL(socketID_handle socketID,uint8_t *ttl){
1248

    
1249
        return getTTL(socketfd, ttl);
1250

    
1251
}
1252

    
1253
socketID_handle mlGetLocalSocketID(int *errorstatus){
1254

    
1255
        if (NAT_traversal == false) {
1256
                *errorstatus = 2;
1257
                return NULL;
1258
        }
1259

    
1260
        *errorstatus = 0;
1261
        return &local_socketID;
1262

    
1263
}
1264

    
1265

    
1266
/**************************** END of MONL functions *************************/
1267

    
1268
/**************************** GENERAL functions *************************/
1269

    
1270
void mlRegisterRecvConnectionCb(receive_connection_cb recv_conn_cb){
1271

    
1272
        if (recv_conn_cb == NULL)
1273
                error("ML: Register receive_connection_cb: NULL ptr  \n");
1274
        else
1275
                receive_Connection_cb = recv_conn_cb;
1276

    
1277
}
1278

    
1279
void mlRegisterErrorConnectionCb(connection_failed_cb conn_failed){
1280

    
1281
        if (conn_failed == NULL)
1282
                error("ML: Register connection_failed_cb: NULL ptr  \n");
1283
        else
1284
        failed_Connection_cb = conn_failed;
1285

    
1286
}
1287

    
1288
void mlRegisterRecvDataCb(receive_data_cb data_cb,unsigned char msgtype){
1289

    
1290
    if (msgtype > 126) {
1291

    
1292
            error
1293
            ("ML: Could not register recv_data callback. Msgtype is greater then 126 \n");
1294

    
1295
    }
1296

    
1297
    if (data_cb == NULL) {
1298

    
1299
            error("ML: Register receive data callback: NUll ptr \n ");
1300

    
1301
    } else {
1302

    
1303
        recvcbbuf[msgtype] = data_cb;
1304

    
1305
    }
1306

    
1307
}
1308

    
1309
void mlCloseSocket(socketID_handle socketID){
1310

    
1311
        free(socketID);
1312

    
1313
}
1314

    
1315
void keepalive_fn(evutil_socket_t fd, short what, void *arg) {
1316
        socketID_handle peer = arg;
1317

    
1318
        int con_id = mlConnectionExist(peer, false);
1319
        if (con_id < 0 || connectbuf[con_id]->defaultSendParams.keepalive <= 0) {
1320
                /* Connection fell from under us or keepalive was disabled */
1321
                free(arg);
1322
                return;
1323
        }
1324

    
1325
        /* do what we gotta do */
1326
        if ( connectbuf[con_id]->status == READY) {
1327
                char keepaliveMsg[32] = "";
1328
                sprintf(keepaliveMsg, "KEEPALIVE %d", connectbuf[con_id]->keepalive_seq++);
1329
                send_msg(con_id, MSG_TYPE_ML_KEEPALIVE, keepaliveMsg, 1 + strlen(keepaliveMsg), false, 
1330
                        &(connectbuf[con_id]->defaultSendParams));
1331
        }
1332

    
1333
        /* re-schedule */
1334
        struct timeval t = { 0,0 };
1335
        t.tv_sec = connectbuf[con_id]->defaultSendParams.keepalive;
1336
        if (connectbuf[con_id]->defaultSendParams.keepalive) 
1337
                event_base_once(base, -1, EV_TIMEOUT, keepalive_fn, peer, &t);
1338
}
1339

    
1340
void setupKeepalive(int conn_id) {
1341
        /* Save the peer's address for us */
1342
        socketID_handle peer = malloc(sizeof(socket_ID));
1343
        memcpy(peer, &connectbuf[conn_id]->external_socketID, sizeof(socket_ID));
1344

    
1345
        struct timeval t = { 0,0 };
1346
        t.tv_sec = connectbuf[conn_id]->defaultSendParams.keepalive;
1347

    
1348
        if (connectbuf[conn_id]->defaultSendParams.keepalive) 
1349
                event_base_once(base, -1, EV_TIMEOUT, keepalive_fn, peer, &t);
1350
}
1351

    
1352
/* connection functions */
1353
int mlOpenConnection(socketID_handle external_socketID,receive_connection_cb connection_cb,void *arg, const send_params defaultSendParams){
1354

    
1355
        int con_id;
1356
        if (external_socketID == NULL) {
1357
                error("ML: cannot open connection: one of the socketIDs is NULL\n");
1358
                return -1;
1359
        }
1360
        if (NAT_traversal == false) {
1361
                error("ML: cannot open connection: NAT traversal for socketID still in progress\n");
1362
                return -1;
1363
        }
1364
        if (connection_cb == NULL) {
1365
                error("ML: cannot open connection: connection_cb is NULL\n");
1366
                return -1;
1367
        }
1368

    
1369
        // check if that connection already exist
1370

    
1371
        con_id = mlConnectionExist(external_socketID, false);
1372
        if (con_id >= 0) {
1373
                // overwrite defaultSendParams
1374
                bool newKeepalive = 
1375
                        connectbuf[con_id]->defaultSendParams.keepalive == 0 && defaultSendParams.keepalive != 0;
1376
                connectbuf[con_id]->defaultSendParams = defaultSendParams;
1377
                if (newKeepalive) setupKeepalive(con_id);
1378
                // if so check if it is ready to use
1379
                if (connectbuf[con_id]->status == READY) {
1380
                                // if so use the callback immediately
1381
                                (connection_cb) (con_id, arg);
1382

    
1383
                // otherwise just write the connection cb and the arg pointer
1384
                // into the connection struct
1385
                } else {
1386
                        struct receive_connection_cb_list *temp;
1387
                        temp = malloc(sizeof(struct receive_connection_cb_list));
1388
                        temp->next = NULL;
1389
                        temp->connection_cb = connection_cb;
1390
                        temp->arg = arg;
1391
                        if(connectbuf[con_id]->connection_last != NULL) {
1392
                                connectbuf[con_id]->connection_last->next = temp;
1393
                                connectbuf[con_id]->connection_last = temp;
1394
                        } else
1395
                                connectbuf[con_id]->connection_last = connectbuf[con_id]->connection_head = temp;
1396
                }
1397
                return con_id;
1398
        }
1399
        // make entry in connection_establishment array
1400
        for (con_id = 0; con_id < CONNECTBUFSIZE; con_id++) {
1401
                if (connectbuf[con_id] == NULL) {
1402
                        connectbuf[con_id] = (connect_data *) malloc(sizeof(connect_data));
1403
                        memset(connectbuf[con_id],0,sizeof(connect_data));
1404
                        connectbuf[con_id]->starttime = time(NULL);
1405
                        memcpy(&connectbuf[con_id]->external_socketID, external_socketID, sizeof(socket_ID));
1406
                        connectbuf[con_id]->pmtusize = DSLSLIM;
1407
                        connectbuf[con_id]->status = INVITE;
1408
                        connectbuf[con_id]->seqnr = 0;
1409
                        connectbuf[con_id]->internal_connect = !compare_external_address_socketIDs(external_socketID, &local_socketID);
1410
                        /*
1411
                        * timeout values for the pmtu discovery
1412
                        */
1413
                        connectbuf[con_id]->timeout_value.tv_sec = 0;        //TODO: make this timeout configurable
1414
                        connectbuf[con_id]->timeout_value.tv_usec = 250000;
1415
                        connectbuf[con_id]->connectionID = con_id;
1416

    
1417
                        connectbuf[con_id]->connection_head = connectbuf[con_id]->connection_last = malloc(sizeof(struct receive_connection_cb_list));
1418
                        connectbuf[con_id]->connection_last->next = NULL;
1419
                        connectbuf[con_id]->connection_last->connection_cb = connection_cb;
1420
                        connectbuf[con_id]->connection_last->arg = arg;
1421
                        connectbuf[con_id]->external_connectionID = -1;
1422

    
1423
                        connectbuf[con_id]->defaultSendParams = defaultSendParams;
1424
                        if (defaultSendParams.keepalive) setupKeepalive(con_id);
1425
                        break;
1426
                }
1427
        } //end of for
1428

    
1429
        if (con_id == CONNECTBUFSIZE) {
1430
                error("ML: Could not open connection: connection buffer full\n");
1431
                return -1;
1432
        }
1433

    
1434
        // create and send a connection message
1435
        send_conn_msg(con_id, MAX, INVITE);
1436

    
1437
        struct event *ev;
1438
        ev = evtimer_new(base, pmtu_timeout_cb, (void *) (long)con_id);
1439
        event_add(ev, &connectbuf[con_id]->timeout_value);
1440

    
1441
        return con_id;
1442

    
1443
}
1444

    
1445
void mlCloseConnection(const int connectionID){
1446

    
1447
        // remove it from the connection array
1448
        if(connectbuf[connectionID]) {
1449
                if(connectbuf[connectionID]->ctrl_msg_buf)
1450
                        free(connectbuf[connectionID]->ctrl_msg_buf);
1451
                free(connectbuf[connectionID]);
1452
                connectbuf[connectionID] = NULL;
1453
        }
1454

    
1455
}
1456

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

    
1459
        if (connectionID < 0) {
1460
                error("ML: send data failed: connectionID does not exist\n");
1461
                return;
1462
        }
1463

    
1464
        if (connectbuf[connectionID] == NULL) {
1465
                error("ML: send data failed: connectionID does not exist\n");
1466
                return;
1467
        }
1468
        if (connectbuf[connectionID]->status != READY) {
1469
            error("ML: send data failed: connection is not active\n");
1470
            return;
1471
        }
1472

    
1473
        if (sParams == NULL) {
1474
                sParams = &(connectbuf[connectionID]->defaultSendParams);
1475
        }
1476

    
1477
        send_msg(connectionID, msgtype, sendbuf, bufsize, false, sParams);
1478

    
1479
}
1480

    
1481
/* transmit data functions  */
1482
int mlSendAllData(const int connectionID,send_all_data_container *container,int nr_entries,unsigned char msgtype,send_params *sParams){
1483

    
1484
    if (nr_entries < 1 || nr_entries > 5) {
1485

    
1486
        error
1487
            ("ML : sendALlData : nr_enties is not between 1 and 5 \n ");
1488
        return 0;
1489

    
1490
    } else {
1491

    
1492
        if (nr_entries == 1) {
1493

    
1494
                mlSendData(connectionID, container->buffer_1,
1495
                      container->length_1, msgtype, sParams);
1496

    
1497
            return 1;
1498

    
1499
        } else if (nr_entries == 2) {
1500

    
1501
            int buflen = container->length_1 + container->length_2;
1502
            char buf[buflen];
1503
            memcpy(buf, container->buffer_1, container->length_1);
1504
            memcpy(&buf[container->length_1], container->buffer_2,
1505
                   container->length_2);
1506
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1507

    
1508
            return 1;
1509

    
1510
        } else if (nr_entries == 3) {
1511

    
1512
            int buflen =
1513
                container->length_1 + container->length_2 +
1514
                container->length_3;
1515
            char buf[buflen];
1516
            memcpy(buf, container->buffer_1, container->length_1);
1517
            memcpy(&buf[container->length_1], container->buffer_2,
1518
                   container->length_2);
1519
            memcpy(&buf[container->length_2], container->buffer_3,
1520
                   container->length_3);
1521
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1522

    
1523

    
1524
            return 1;
1525

    
1526
        } else if (nr_entries == 4) {
1527

    
1528
            int buflen =
1529
                container->length_1 + container->length_2 +
1530
                container->length_3 + container->length_4;
1531
            char buf[buflen];
1532
            memcpy(buf, container->buffer_1, container->length_1);
1533
            memcpy(&buf[container->length_1], container->buffer_2,
1534
                   container->length_2);
1535
            memcpy(&buf[container->length_2], container->buffer_3,
1536
                   container->length_3);
1537
            memcpy(&buf[container->length_3], container->buffer_4,
1538
                   container->length_4);
1539
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1540

    
1541
            return 1;
1542

    
1543
        } else {
1544

    
1545
            int buflen =
1546
                container->length_1 + container->length_2 +
1547
                container->length_3 + container->length_4 +
1548
                container->length_5;
1549
            char buf[buflen];
1550
            memcpy(buf, container->buffer_1, container->length_1);
1551
            memcpy(&buf[container->length_1], container->buffer_2,
1552
                   container->length_2);
1553
            memcpy(&buf[container->length_2], container->buffer_3,
1554
                   container->length_3);
1555
            memcpy(&buf[container->length_3], container->buffer_4,
1556
                   container->length_4);
1557
            memcpy(&buf[container->length_4], container->buffer_5,
1558
                   container->length_5);
1559
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1560

    
1561
            return 1;
1562
        }
1563

    
1564
    }
1565

    
1566
}
1567

    
1568
int mlRecvData(const int connectionID,char *recvbuf,int *bufsize,recv_params *rParams){
1569

    
1570
        //TODO yet to be converted
1571
        return 0;
1572
#if 0
1573
        if (rParams == NULL) {
1574
                error("ML: recv_data failed: recv_params is a NULL ptr\n");
1575
                return 0;
1576
    } else {
1577

1578
        info("ML: recv data called \n");
1579

1580
        int i = 0;
1581
        int returnValue = 0;
1582
        double timeout = (double) recv_timeout.tv_sec;
1583
        time_t endtime = time(NULL);
1584

1585
        for (i = 0; i < RECVDATABUFSIZE; i++) {
1586

1587
            if (recvdatabuf[i] != NULL) {
1588

1589
                if (recvdatabuf[i]->connectionID == connectionID) {
1590

1591
                    info("ML: recv data has entry  \n");
1592

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

1595
                    // check if the specified connection has data and it
1596
                    // is complete
1597
                    // check the data seqnr
1598
                    // if(connectionID == recvdatabuf[i]->connectionID &&
1599
                    // 1 == recvdatabuf[i]->status){
1600

1601
                    if (1 == recvdatabuf[i]->status) {
1602

1603
                        // info("transmissionHandler: recv_data set is
1604
                        // complete \n" );
1605

1606
                        // debug("debud \n");
1607

1608
                        // exchange the pointers
1609
                        int buffersize = 0;
1610
                        buffersize = recvdatabuf[i]->bufsize;
1611
                        *bufsize = buffersize;
1612
                        // recvbuf = recvdatabuf[i]->recvbuf;
1613

1614
                        // info("buffersize %d \n",buffersize);
1615
                        memcpy(recvbuf, recvdatabuf[i]->recvbuf,
1616
                               buffersize);
1617
                        // debug(" recvbuf %s \n",recvbuf );
1618

1619
//                         double nrMissFrags =
1620
//                             (double) recvdatabuf[i]->nrFragments /
1621
//                             (double) recvdatabuf[i]->recvFragments;
1622
//                         int nrMissingFragments = (int) ceil(nrMissFrags);
1623

1624
//                        rParams->nrMissingFragments = nrMissingFragments;
1625
//                         rParams->nrFragments = recvdatabuf[i]->nrFragments;
1626
                        rParams->msgtype = recvdatabuf[i]->msgtype;
1627
                        rParams->connectionID =
1628
                            recvdatabuf[i]->connectionID;
1629

1630
                        // break from the loop
1631
                        // debug(" recvbuf %s \n ",recvbuf);
1632

1633
                        // double nrMissFrags =
1634
                        // (double)recvdatabuf[i]->nrFragments /
1635
                        // (double)recvdatabuf[i]->recvFragments;
1636
                        // int nrMissingFragments =
1637
                        // (int)ceil(nrMissFrags);
1638

1639
                        if(get_Recv_data_inf_cb != NULL) {
1640
                                mon_data_inf recv_data_inf;
1641

1642
                                recv_data_inf.remote_socketID = &(connectbuf[connectionID]->external_socketID);
1643
                                recv_data_inf.buffer = recvdatabuf[i]->recvbuf;
1644
                                recv_data_inf.bufSize = recvdatabuf[i]->bufsize;
1645
                                recv_data_inf.msgtype = recvdatabuf[i]->msgtype;
1646
//                                 recv_data_inf.monitoringHeaderType = recvdatabuf[i]->monitoringHeaderType;
1647
//                                 recv_data_inf.monitoringDataHeader = recvdatabuf[i]->monitoringDataHeader;
1648
                                gettimeofday(&recv_data_inf.arrival_time, NULL);
1649
                                recv_data_inf.firstPacketArrived = recvdatabuf[i]->firstPacketArrived;
1650
                                recv_data_inf.nrMissingFragments = nrMissingFragments;
1651
                                recv_data_inf.nrFragments = recvdatabuf[i]->nrFragments;
1652
                                recv_data_inf.priority = false;
1653
                                recv_data_inf.padding = false;
1654
                                recv_data_inf.confirmation = false;
1655
                                recv_data_inf.reliable = false;
1656

1657
                                // send data recv callback to monitoring module
1658

1659
                                (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
1660
                        }
1661

1662

1663
                        // free the allocated memory
1664
                        free(recvdatabuf[i]);
1665
                        recvdatabuf[i] = NULL;
1666

1667
                        returnValue = 1;
1668
                        break;
1669

1670
                    }
1671

1672
                    if (recvdatabuf[i] != NULL) {
1673

1674
                        if (timepass > timeout) {
1675

1676
                            info("ML: recv_data timeout called  \n");
1677

1678
                            // some data about the missing chunks should
1679
                            // be added here
1680
                            // exchange the pointers
1681
                            int buffersize = 0;
1682
                            buffersize = recvdatabuf[i]->bufsize;
1683
                            *bufsize = buffersize;
1684
                            // recvbuf = recvdatabuf[i]->recvbuf;
1685

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

1692
                            // debug(" recvbuf %s \n",recvbuf );
1693

1694
                            memcpy(recvbuf, recvdatabuf[i]->recvbuf,
1695
                                   buffersize);
1696

1697
                            rParams->nrMissingFragments =
1698
                                nrMissingFragments;
1699
                            rParams->nrFragments =
1700
                                recvdatabuf[i]->nrFragments;
1701
                            rParams->msgtype = recvdatabuf[i]->msgtype;
1702
                            rParams->connectionID =
1703
                                recvdatabuf[i]->connectionID;
1704

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

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

1723
                                        // send data recv callback to monitoring module
1724

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

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

1732
                            returnValue = 1;
1733
                            break;
1734

1735
                        }
1736
                    }
1737

1738
                }
1739

1740
            }
1741
            // debug("2 recvbuf %s \n ",recvbuf);
1742
        }
1743
        return returnValue;
1744
    }
1745
#endif
1746

    
1747
}
1748

    
1749
int mlSocketIDToString(socketID_handle socketID,char* socketID_string, size_t len){
1750

    
1751
        char internal_addr[INET_ADDRSTRLEN];
1752
        char external_addr[INET_ADDRSTRLEN];
1753
        inet_ntop(AF_INET, &(socketID->internal_addr.udpaddr.sin_addr.s_addr), internal_addr, INET_ADDRSTRLEN);
1754
        inet_ntop(AF_INET, &(socketID->external_addr.udpaddr.sin_addr.s_addr), external_addr, INET_ADDRSTRLEN);
1755

    
1756
        snprintf(socketID_string,len,"%s:%d-%s:%d", internal_addr, ntohs(socketID->internal_addr.udpaddr.sin_port),
1757
                external_addr,        ntohs(socketID->external_addr.udpaddr.sin_port));
1758
        return 0;
1759

    
1760
}
1761

    
1762
int mlStringToSocketID(const char* socketID_string, socketID_handle socketID){
1763

    
1764
        //@TODO add checks against malformed string
1765
        char external_addr[INET_ADDRSTRLEN];
1766
        int external_port;
1767
        char internal_addr[INET_ADDRSTRLEN];
1768
        int internal_port;
1769

    
1770
        char *pch;
1771
        char *s = strdup(socketID_string);
1772

    
1773
        //replace ':' with a blank
1774
        pch=strchr(s,':');
1775
        while (pch!=NULL){
1776
                                *pch = ' ';
1777
                pch=strchr(pch+1,':');
1778
        }
1779
        pch=strchr(s,'-');
1780
        if(pch) *pch = ' ';
1781

    
1782
        sscanf(s,"%s %d %s %d", internal_addr, &internal_port,
1783
                external_addr, &external_port);
1784

    
1785
        if(inet_pton(AF_INET, internal_addr, &(socketID->internal_addr.udpaddr.sin_addr)) == 0)
1786
                return EINVAL;
1787
        socketID->internal_addr.udpaddr.sin_family = AF_INET;
1788
        socketID->internal_addr.udpaddr.sin_port = htons(internal_port);
1789

    
1790

    
1791
        if(inet_pton(AF_INET, external_addr, &(socketID->external_addr.udpaddr.sin_addr)) ==0)
1792
                return EINVAL;
1793
        socketID->external_addr.udpaddr.sin_family = AF_INET;
1794
        socketID->external_addr.udpaddr.sin_port = htons(external_port);
1795

    
1796
        free(s);
1797
        return 0;
1798

    
1799
}
1800

    
1801
int mlGetConnectionStatus(int connectionID){
1802

    
1803
        if(connectbuf[connectionID])
1804
                return connectbuf[connectionID]->status == READY;
1805
        return -1;
1806
    
1807
}
1808

    
1809

    
1810
int mlConnectionExist(socketID_handle socketID, bool ready){
1811

    
1812
    /*
1813
     * check if another connection for the external connectionID exist
1814
     * that was established \ within the last 2 seconds
1815
     */
1816
        int i;
1817
        for (i = 0; i < CONNECTBUFSIZE; i++)
1818
                if (connectbuf[i] != NULL)
1819
                        if (mlCompareSocketIDs(&(connectbuf[i]->external_socketID), socketID) == 0) {
1820
                                if (ready) return (connectbuf[i]->status == READY ? i : -1);;
1821
                                return i;
1822
                                }
1823

    
1824
    return -1;
1825

    
1826
}
1827

    
1828
//Added by Robert Birke as comodity functions
1829

    
1830
//int mlPrintSocketID(socketID_handle socketID) {
1831
//        char str[SOCKETID_STRING_SIZE];
1832
//        mlSocketIDToString(socketID, str, sizeof(str));
1833
//        printf(stderr,"int->%s<-ext\n",str);
1834
//}
1835

    
1836
/*
1837
 * hash code of a socketID
1838
 * TODO might think of a better way
1839
 */
1840
int mlHashSocketID(socketID_handle sock) {
1841
    return sock->internal_addr.udpaddr.sin_port +
1842
                          sock->external_addr.udpaddr.sin_port;
1843
}
1844

    
1845
int mlCompareSocketIDs(socketID_handle sock1, socketID_handle sock2) {
1846
        /*
1847
        * compare internal addr
1848
        */
1849
        if (sock1->internal_addr.udpaddr.sin_addr.s_addr !=
1850
            sock2->internal_addr.udpaddr.sin_addr.s_addr)
1851
                        return 1;
1852

    
1853
        if (sock1->internal_addr.udpaddr.sin_port !=
1854
                 sock2->internal_addr.udpaddr.sin_port)
1855
                        return 1;
1856

    
1857
        /*
1858
        * compare external addr
1859
        */
1860
        if (sock1->external_addr.udpaddr.sin_addr.s_addr !=
1861
            sock2->external_addr.udpaddr.sin_addr.s_addr)
1862
                        return 1;
1863

    
1864
        if (sock1->external_addr.udpaddr.sin_port !=
1865
                 sock2->external_addr.udpaddr.sin_port)
1866
                        return 1;
1867

    
1868
        return 0;
1869
}
1870

    
1871
int mlCompareSocketIDsByPort(socketID_handle sock1, socketID_handle sock2)
1872
{ 
1873
        if (sock1->internal_addr.udpaddr.sin_port !=
1874
                 sock2->internal_addr.udpaddr.sin_port)
1875
                        return 1;
1876

    
1877
        if (sock1->external_addr.udpaddr.sin_port !=
1878
                 sock2->external_addr.udpaddr.sin_port)
1879
                        return 1;
1880
        return 0;
1881
}
1882

    
1883
int mlGetPathMTU(int ConnectionId) {
1884
        if(ConnectionId < 0 || ConnectionId >= CONNECTBUFSIZE)
1885
                return -1;
1886
        if (connectbuf[ConnectionId] != NULL)
1887
                return connectbuf[ConnectionId]->pmtusize;
1888
        return -1;
1889
}
1890

    
1891
/**************************** END of GENERAL functions *************************/
1892

    
1893
/**************************** NAT functions *************************/
1894

    
1895
/* setter  */
1896
void mlSetStunServer(const int port,const char *ipaddr){
1897

    
1898
        stun_server.sin_family = AF_INET;
1899
        if (ipaddr == NULL)
1900
                stun_server.sin_addr.s_addr = htonl(INADDR_ANY);
1901
        else
1902
                stun_server.sin_addr.s_addr = resolve(ipaddr);
1903
        stun_server.sin_port = htons(port);
1904

    
1905
}
1906

    
1907
int mlGetExternalIP(char* external_addr){
1908

    
1909
        socketaddrgen udpgen;
1910
        struct sockaddr_in udpaddr;
1911

    
1912
        udpgen = local_socketID.external_addr;
1913
        udpaddr = udpgen.udpaddr;
1914

    
1915
        inet_ntop(AF_INET, &(udpaddr.sin_addr), external_addr,
1916
                        INET_ADDRSTRLEN);
1917

    
1918
        if (external_addr == NULL) {
1919

    
1920
        return -1;
1921

    
1922
        } else {
1923

    
1924
        return 0;
1925

    
1926
        }
1927

    
1928
}
1929

    
1930
/**************************** END of NAT functions *************************/