Statistics
| Branch: | Revision:

ml / ml.c @ 26f3bd83

History | View | Annotate | Download (54.2 KB)

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

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

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

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

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

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

    
80
/*
81
 * 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 {
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 = { 4, 0 };
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 INTERNALS ***********************/
1167

    
1168
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){
1169

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

    
1177
        }
1178
        register_recv_localsocketID_cb(local_socketID_cb);
1179
        create_socket(port, ipaddr);
1180

    
1181
}
1182

    
1183
/* register callbacks  */
1184
void mlRegisterGetRecvPktInf(get_recv_pkt_inf_cb recv_pkt_inf_cb){
1185

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

    
1191
}
1192

    
1193
void mlRegisterGetSendPktInf(get_send_pkt_inf_cb  send_pkt_inf_cb){
1194

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

    
1200
}
1201

    
1202

    
1203
void mlRegisterSetMonitoringHeaderPktCb(set_monitoring_header_pkt_cb monitoring_header_pkt_cb ){
1204

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

    
1210
}
1211

    
1212
void mlRegisterGetRecvDataInf(get_recv_data_inf_cb recv_data_inf_cb){
1213

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

    
1219
}
1220

    
1221
void mlRegisterGetSendDataInf(get_send_data_inf_cb  send_data_inf_cb){
1222

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

    
1228
}
1229

    
1230
void mlRegisterSetMonitoringHeaderDataCb(set_monitoring_header_data_cb monitoring_header_data_cb){
1231

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

    
1237
}
1238

    
1239
void mlRegisterRecvConnectionCb(receive_connection_cb recv_conn_cb){
1240

    
1241
        if (recv_conn_cb == NULL)
1242
                error("ML: Register receive_connection_cb: NULL ptr  \n");
1243
        else
1244
                receive_Connection_cb = recv_conn_cb;
1245

    
1246
}
1247

    
1248
void mlRegisterErrorConnectionCb(connection_failed_cb conn_failed){
1249

    
1250
        if (conn_failed == NULL)
1251
                error("ML: Register connection_failed_cb: NULL ptr  \n");
1252
        else
1253
        failed_Connection_cb = conn_failed;
1254

    
1255
}
1256

    
1257
void mlRegisterRecvDataCb(receive_data_cb data_cb,unsigned char msgtype){
1258

    
1259
    if (msgtype > 126) {
1260

    
1261
            error
1262
            ("ML: Could not register recv_data callback. Msgtype is greater then 126 \n");
1263

    
1264
    }
1265

    
1266
    if (data_cb == NULL) {
1267

    
1268
            error("ML: Register receive data callback: NUll ptr \n ");
1269

    
1270
    } else {
1271

    
1272
        recvcbbuf[msgtype] = data_cb;
1273

    
1274
    }
1275

    
1276
}
1277

    
1278
void mlCloseSocket(socketID_handle socketID){
1279

    
1280
        free(socketID);
1281

    
1282
}
1283

    
1284
void keepalive_fn(evutil_socket_t fd, short what, void *arg) {
1285
        socketID_handle peer = arg;
1286

    
1287
        int con_id = mlConnectionExist(peer, false);
1288
        if (con_id < 0 || connectbuf[con_id]->defaultSendParams.keepalive <= 0) {
1289
                /* Connection fell from under us or keepalive was disabled */
1290
                free(arg);
1291
                return;
1292
        }
1293

    
1294
        /* do what we gotta do */
1295
        if ( connectbuf[con_id]->status == READY) {
1296
                char keepaliveMsg[32] = "";
1297
                sprintf(keepaliveMsg, "KEEPALIVE %d", connectbuf[con_id]->keepalive_seq++);
1298
                send_msg(con_id, MSG_TYPE_ML_KEEPALIVE, keepaliveMsg, 1 + strlen(keepaliveMsg), false, 
1299
                        &(connectbuf[con_id]->defaultSendParams));
1300
        }
1301

    
1302
        /* re-schedule */
1303
        struct timeval t = { 0,0 };
1304
        t.tv_sec = connectbuf[con_id]->defaultSendParams.keepalive;
1305
        if (connectbuf[con_id]->defaultSendParams.keepalive) 
1306
                event_base_once(base, -1, EV_TIMEOUT, keepalive_fn, peer, &t);
1307
}
1308

    
1309
void setupKeepalive(int conn_id) {
1310
        /* Save the peer's address for us */
1311
        socketID_handle peer = malloc(sizeof(socket_ID));
1312
        memcpy(peer, &connectbuf[conn_id]->external_socketID, sizeof(socket_ID));
1313

    
1314
        struct timeval t = { 0,0 };
1315
        t.tv_sec = connectbuf[conn_id]->defaultSendParams.keepalive;
1316

    
1317
        if (connectbuf[conn_id]->defaultSendParams.keepalive) 
1318
                event_base_once(base, -1, EV_TIMEOUT, keepalive_fn, peer, &t);
1319
}
1320

    
1321
/* connection functions */
1322
int mlOpenConnection(socketID_handle external_socketID,receive_connection_cb connection_cb,void *arg, const send_params defaultSendParams){
1323

    
1324
        int con_id;
1325
        if (external_socketID == NULL) {
1326
                error("ML: cannot open connection: one of the socketIDs is NULL\n");
1327
                return -1;
1328
        }
1329
        if (NAT_traversal == false) {
1330
                error("ML: cannot open connection: NAT traversal for socketID still in progress\n");
1331
                return -1;
1332
        }
1333
        if (connection_cb == NULL) {
1334
                error("ML: cannot open connection: connection_cb is NULL\n");
1335
                return -1;
1336
        }
1337

    
1338
        // check if that connection already exist
1339

    
1340
        con_id = mlConnectionExist(external_socketID, false);
1341
        if (con_id >= 0) {
1342
                // overwrite defaultSendParams
1343
                bool newKeepalive = 
1344
                        connectbuf[con_id]->defaultSendParams.keepalive == 0 && defaultSendParams.keepalive != 0;
1345
                connectbuf[con_id]->defaultSendParams = defaultSendParams;
1346
                if (newKeepalive) setupKeepalive(con_id);
1347
                // if so check if it is ready to use
1348
                if (connectbuf[con_id]->status == READY) {
1349
                                // if so use the callback immediateley
1350
                                (connection_cb) (con_id, arg);
1351

    
1352
                // otherwise just write the connection cb and the arg pointer
1353
                // into the connection struct
1354
                } else {
1355
                        struct receive_connection_cb_list *temp;
1356
                        temp = malloc(sizeof(struct receive_connection_cb_list));
1357
                        temp->next = NULL;
1358
                        temp->connection_cb = connection_cb;
1359
                        temp->arg = arg;
1360
                        if(connectbuf[con_id]->connection_last != NULL) {
1361
                                connectbuf[con_id]->connection_last->next = temp;
1362
                                connectbuf[con_id]->connection_last = temp;
1363
                        } else
1364
                                connectbuf[con_id]->connection_last = connectbuf[con_id]->connection_head = temp;
1365
                }
1366
                return con_id;
1367
        }
1368
        // make entry in connection_establishment array
1369
        for (con_id = 0; con_id < CONNECTBUFSIZE; con_id++) {
1370
                if (connectbuf[con_id] == NULL) {
1371
                        connectbuf[con_id] = (connect_data *) malloc(sizeof(connect_data));
1372
                        memset(connectbuf[con_id],0,sizeof(connect_data));
1373
                        connectbuf[con_id]->starttime = time(NULL);
1374
                        memcpy(&connectbuf[con_id]->external_socketID, external_socketID, sizeof(socket_ID));
1375
                        connectbuf[con_id]->pmtusize = MAX;
1376
                        connectbuf[con_id]->status = INVITE;
1377
                        connectbuf[con_id]->seqnr = 0;
1378
                        connectbuf[con_id]->internal_connect = !compare_external_address_socketIDs(external_socketID, &local_socketID);
1379
                        /*
1380
                        * timeout values for the pmtu discovery
1381
                        */
1382
                        connectbuf[con_id]->timeout_value.tv_sec = 1;
1383
                        connectbuf[con_id]->timeout_value.tv_usec = 0;
1384
                        connectbuf[con_id]->connectionID = con_id;
1385

    
1386
                        connectbuf[con_id]->connection_head = connectbuf[con_id]->connection_last = malloc(sizeof(struct receive_connection_cb_list));
1387
                        connectbuf[con_id]->connection_last->next = NULL;
1388
                        connectbuf[con_id]->connection_last->connection_cb = connection_cb;
1389
                        connectbuf[con_id]->connection_last->arg = arg;
1390
                        connectbuf[con_id]->external_connectionID = -1;
1391

    
1392
                        connectbuf[con_id]->defaultSendParams = defaultSendParams;
1393
                        if (defaultSendParams.keepalive) setupKeepalive(con_id);
1394
                        break;
1395
                }
1396
        } //end of for
1397

    
1398
        if (con_id == CONNECTBUFSIZE) {
1399
                error("ML: Could not open connection: connection buffer full\n");
1400
                return -1;
1401
        }
1402

    
1403
        // create and send a connection message
1404
        send_conn_msg(con_id, MAX, INVITE);
1405

    
1406
        struct event *ev;
1407
        ev = evtimer_new(base, pmtu_timeout_cb, (void *) (long)con_id);
1408
        event_add(ev, &connectbuf[con_id]->timeout_value);
1409

    
1410
        return con_id;
1411

    
1412
}
1413

    
1414
void mlCloseConnection(const int connectionID){
1415

    
1416
        // remove it from the connection array
1417
        if(connectbuf[connectionID]) {
1418
                if(connectbuf[connectionID]->ctrl_msg_buf)
1419
                        free(connectbuf[connectionID]->ctrl_msg_buf);
1420
                free(connectbuf[connectionID]);
1421
                connectbuf[connectionID] = NULL;
1422
        }
1423

    
1424
}
1425

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

    
1428
        if (connectionID < 0) {
1429
                error("ML: send data failed: connectionID does not exist\n");
1430
                return;
1431
        }
1432

    
1433
        if (connectbuf[connectionID] == NULL) {
1434
                error("ML: send data failed: connectionID does not exist\n");
1435
                return;
1436
        }
1437
        if (connectbuf[connectionID]->status != READY) {
1438
            error("ML: send data failed: connection is not active\n");
1439
            return;
1440
        }
1441

    
1442
        if (sParams == NULL) {
1443
                sParams = &(connectbuf[connectionID]->defaultSendParams);
1444
        }
1445

    
1446
        send_msg(connectionID, msgtype, sendbuf, bufsize, false, sParams);
1447

    
1448
}
1449

    
1450
/* transmit data functions  */
1451
int mlSendAllData(const int connectionID,send_all_data_container *container,int nr_entries,unsigned char msgtype,send_params *sParams){
1452

    
1453
    if (nr_entries < 1 || nr_entries > 5) {
1454

    
1455
        error
1456
            ("ML : sendALlData : nr_enties is not between 1 and 5 \n ");
1457
        return 0;
1458

    
1459
    } else {
1460

    
1461
        if (nr_entries == 1) {
1462

    
1463
                mlSendData(connectionID, container->buffer_1,
1464
                      container->length_1, msgtype, sParams);
1465

    
1466
            return 1;
1467

    
1468
        } else if (nr_entries == 2) {
1469

    
1470
            int buflen = container->length_1 + container->length_2;
1471
            char buf[buflen];
1472
            memcpy(buf, container->buffer_1, container->length_1);
1473
            memcpy(&buf[container->length_1], container->buffer_2,
1474
                   container->length_2);
1475
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1476

    
1477
            return 1;
1478

    
1479
        } else if (nr_entries == 3) {
1480

    
1481
            int buflen =
1482
                container->length_1 + container->length_2 +
1483
                container->length_3;
1484
            char buf[buflen];
1485
            memcpy(buf, container->buffer_1, container->length_1);
1486
            memcpy(&buf[container->length_1], container->buffer_2,
1487
                   container->length_2);
1488
            memcpy(&buf[container->length_2], container->buffer_3,
1489
                   container->length_3);
1490
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1491

    
1492

    
1493
            return 1;
1494

    
1495
        } else if (nr_entries == 4) {
1496

    
1497
            int buflen =
1498
                container->length_1 + container->length_2 +
1499
                container->length_3 + container->length_4;
1500
            char buf[buflen];
1501
            memcpy(buf, container->buffer_1, container->length_1);
1502
            memcpy(&buf[container->length_1], container->buffer_2,
1503
                   container->length_2);
1504
            memcpy(&buf[container->length_2], container->buffer_3,
1505
                   container->length_3);
1506
            memcpy(&buf[container->length_3], container->buffer_4,
1507
                   container->length_4);
1508
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1509

    
1510
            return 1;
1511

    
1512
        } else {
1513

    
1514
            int buflen =
1515
                container->length_1 + container->length_2 +
1516
                container->length_3 + container->length_4 +
1517
                container->length_5;
1518
            char buf[buflen];
1519
            memcpy(buf, container->buffer_1, container->length_1);
1520
            memcpy(&buf[container->length_1], container->buffer_2,
1521
                   container->length_2);
1522
            memcpy(&buf[container->length_2], container->buffer_3,
1523
                   container->length_3);
1524
            memcpy(&buf[container->length_3], container->buffer_4,
1525
                   container->length_4);
1526
            memcpy(&buf[container->length_4], container->buffer_5,
1527
                   container->length_5);
1528
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1529

    
1530
            return 1;
1531
        }
1532

    
1533
    }
1534

    
1535
}
1536

    
1537
int mlRecvData(const int connectionID,char *recvbuf,int *bufsize,recv_params *rParams){
1538

    
1539
        //TODO yet to be converted
1540
        return 0;
1541
#if 0
1542
        if (rParams == NULL) {
1543
                error("ML: recv_data failed: recv_params is a NULL ptr\n");
1544
                return 0;
1545
    } else {
1546

1547
        info("ML: recv data called \n");
1548

1549
        int i = 0;
1550
        int returnValue = 0;
1551
        double timeout = (double) recv_timeout.tv_sec;
1552
        time_t endtime = time(NULL);
1553

1554
        for (i = 0; i < RECVDATABUFSIZE; i++) {
1555

1556
            if (recvdatabuf[i] != NULL) {
1557

1558
                if (recvdatabuf[i]->connectionID == connectionID) {
1559

1560
                    info("ML: recv data has entry  \n");
1561

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

1564
                    // check if the specified connection has data and it
1565
                    // is complete
1566
                    // check the data seqnr
1567
                    // if(connectionID == recvdatabuf[i]->connectionID &&
1568
                    // 1 == recvdatabuf[i]->status){
1569

1570
                    if (1 == recvdatabuf[i]->status) {
1571

1572
                        // info("transmissionHandler: recv_data set is
1573
                        // complete \n" );
1574

1575
                        // debug("debud \n");
1576

1577
                        // exchange the pointers
1578
                        int buffersize = 0;
1579
                        buffersize = recvdatabuf[i]->bufsize;
1580
                        *bufsize = buffersize;
1581
                        // recvbuf = recvdatabuf[i]->recvbuf;
1582

1583
                        // info("buffersize %d \n",buffersize);
1584
                        memcpy(recvbuf, recvdatabuf[i]->recvbuf,
1585
                               buffersize);
1586
                        // debug(" recvbuf %s \n",recvbuf );
1587

1588
//                         double nrMissFrags =
1589
//                             (double) recvdatabuf[i]->nrFragments /
1590
//                             (double) recvdatabuf[i]->recvFragments;
1591
//                         int nrMissingFragments = (int) ceil(nrMissFrags);
1592

1593
//                        rParams->nrMissingFragments = nrMissingFragments;
1594
//                         rParams->nrFragments = recvdatabuf[i]->nrFragments;
1595
                        rParams->msgtype = recvdatabuf[i]->msgtype;
1596
                        rParams->connectionID =
1597
                            recvdatabuf[i]->connectionID;
1598

1599
                        // break from the loop
1600
                        // debug(" recvbuf %s \n ",recvbuf);
1601

1602
                        // double nrMissFrags =
1603
                        // (double)recvdatabuf[i]->nrFragments /
1604
                        // (double)recvdatabuf[i]->recvFragments;
1605
                        // int nrMissingFragments =
1606
                        // (int)ceil(nrMissFrags);
1607

1608
                        if(get_Recv_data_inf_cb != NULL) {
1609
                                mon_data_inf recv_data_inf;
1610

1611
                                recv_data_inf.remote_socketID = &(connectbuf[connectionID]->external_socketID);
1612
                                recv_data_inf.buffer = recvdatabuf[i]->recvbuf;
1613
                                recv_data_inf.bufSize = recvdatabuf[i]->bufsize;
1614
                                recv_data_inf.msgtype = recvdatabuf[i]->msgtype;
1615
//                                 recv_data_inf.monitoringHeaderType = recvdatabuf[i]->monitoringHeaderType;
1616
//                                 recv_data_inf.monitoringDataHeader = recvdatabuf[i]->monitoringDataHeader;
1617
                                gettimeofday(&recv_data_inf.arrival_time, NULL);
1618
                                recv_data_inf.firstPacketArrived = recvdatabuf[i]->firstPacketArrived;
1619
                                recv_data_inf.nrMissingFragments = nrMissingFragments;
1620
                                recv_data_inf.nrFragments = recvdatabuf[i]->nrFragments;
1621
                                recv_data_inf.priority = false;
1622
                                recv_data_inf.padding = false;
1623
                                recv_data_inf.confirmation = false;
1624
                                recv_data_inf.reliable = false;
1625

1626
                                // send data recv callback to monitoring module
1627

1628
                                (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
1629
                        }
1630

1631

1632
                        // free the allocated memory
1633
                        free(recvdatabuf[i]);
1634
                        recvdatabuf[i] = NULL;
1635

1636
                        returnValue = 1;
1637
                        break;
1638

1639
                    }
1640

1641
                    if (recvdatabuf[i] != NULL) {
1642

1643
                        if (timepass > timeout) {
1644

1645
                            info("ML: recv_data timeout called  \n");
1646

1647
                            // some data about the missing chunks should
1648
                            // be added here
1649
                            // exchange the pointers
1650
                            int buffersize = 0;
1651
                            buffersize = recvdatabuf[i]->bufsize;
1652
                            *bufsize = buffersize;
1653
                            // recvbuf = recvdatabuf[i]->recvbuf;
1654

1655
                            double nrMissFrags =
1656
                                (double) recvdatabuf[i]->nrFragments /
1657
                                (double) recvdatabuf[i]->recvFragments;
1658
                            int nrMissingFragments =
1659
                                (int) ceil(nrMissFrags);
1660

1661
                            // debug(" recvbuf %s \n",recvbuf );
1662

1663
                            memcpy(recvbuf, recvdatabuf[i]->recvbuf,
1664
                                   buffersize);
1665

1666
                            rParams->nrMissingFragments =
1667
                                nrMissingFragments;
1668
                            rParams->nrFragments =
1669
                                recvdatabuf[i]->nrFragments;
1670
                            rParams->msgtype = recvdatabuf[i]->msgtype;
1671
                            rParams->connectionID =
1672
                                recvdatabuf[i]->connectionID;
1673

1674
                                if(get_Recv_data_inf_cb != NULL) {
1675
                                        mon_data_inf recv_data_inf;
1676

1677
                                        recv_data_inf.remote_socketID = &(connectbuf[connectionID]->external_socketID);
1678
                                        recv_data_inf.buffer = recvdatabuf[i]->recvbuf;
1679
                                        recv_data_inf.bufSize = recvdatabuf[i]->bufsize;
1680
                                        recv_data_inf.msgtype = recvdatabuf[i]->msgtype;
1681
                                        recv_data_inf.monitoringHeaderType = recvdatabuf[i]->monitoringHeaderType;
1682
                                        recv_data_inf.monitoringDataHeader = recvdatabuf[i]->monitoringDataHeader;
1683
                                        gettimeofday(&recv_data_inf.arrival_time, NULL);
1684
                                        recv_data_inf.firstPacketArrived = recvdatabuf[i]->firstPacketArrived;
1685
                                        recv_data_inf.nrMissingFragments = nrMissingFragments;
1686
                                        recv_data_inf.nrFragments = recvdatabuf[i]->nrFragments;
1687
                                        recv_data_inf.priority = false;
1688
                                        recv_data_inf.padding = false;
1689
                                        recv_data_inf.confirmation = false;
1690
                                        recv_data_inf.reliable = false;
1691

1692
                                        // send data recv callback to monitoring module
1693

1694
                                        (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
1695
                                }
1696

1697
                            // free the allocated memory
1698
                            free(recvdatabuf[i]);
1699
                            recvdatabuf[i] = NULL;
1700

1701
                            returnValue = 1;
1702
                            break;
1703

1704
                        }
1705
                    }
1706

1707
                }
1708

1709
            }
1710
            // debug("2 recvbuf %s \n ",recvbuf);
1711
        }
1712
        return returnValue;
1713
    }
1714
#endif
1715

    
1716
}
1717

    
1718
/* setter  */
1719
void mlSetStunServer(const int port,const char *ipaddr){
1720

    
1721
        stun_server.sin_family = AF_INET;
1722
        if (ipaddr == NULL)
1723
                stun_server.sin_addr.s_addr = htonl(INADDR_ANY);
1724
        else
1725
                stun_server.sin_addr.s_addr = resolve(ipaddr);
1726
        stun_server.sin_port = htons(port);
1727

    
1728
}
1729

    
1730
void mlSetRecvTimeout(struct timeval timeout_value){
1731

    
1732
        recv_timeout = timeout_value;
1733

    
1734
}
1735

    
1736
int mlGetStandardTTL(socketID_handle socketID,uint8_t *ttl){
1737

    
1738
        return getTTL(socketfd, ttl);
1739

    
1740
}
1741

    
1742
socketID_handle mlGetLocalSocketID(int *errorstatus){
1743

    
1744
        if (NAT_traversal == false) {
1745
                *errorstatus = 2;
1746
                return NULL;
1747
        }
1748

    
1749
        *errorstatus = 0;
1750
        return &local_socketID;
1751

    
1752
}
1753

    
1754
int mlGetExternalIP(char* external_addr){
1755

    
1756
        socketaddrgen udpgen;
1757
        struct sockaddr_in udpaddr;
1758

    
1759
        udpgen = local_socketID.external_addr;
1760
        udpaddr = udpgen.udpaddr;
1761

    
1762
        inet_ntop(AF_INET, &(udpaddr.sin_addr), external_addr,
1763
                        INET_ADDRSTRLEN);
1764

    
1765
        if (external_addr == NULL) {
1766

    
1767
        return -1;
1768

    
1769
        } else {
1770

    
1771
        return 0;
1772

    
1773
        }
1774

    
1775
}
1776

    
1777
int mlSocketIDToString(socketID_handle socketID,char* socketID_string, size_t len){
1778

    
1779
        char internal_addr[INET_ADDRSTRLEN];
1780
        char external_addr[INET_ADDRSTRLEN];
1781
        inet_ntop(AF_INET, &(socketID->internal_addr.udpaddr.sin_addr.s_addr), internal_addr, INET_ADDRSTRLEN);
1782
        inet_ntop(AF_INET, &(socketID->external_addr.udpaddr.sin_addr.s_addr), external_addr, INET_ADDRSTRLEN);
1783

    
1784
        snprintf(socketID_string,len,"%s:%d-%s:%d", internal_addr, ntohs(socketID->internal_addr.udpaddr.sin_port),
1785
                external_addr,        ntohs(socketID->external_addr.udpaddr.sin_port));
1786
        return 0;
1787

    
1788
}
1789

    
1790
int mlStringToSocketID(const char* socketID_string, socketID_handle socketID){
1791

    
1792
        //@TODO add checks against malformed string
1793
        char external_addr[INET_ADDRSTRLEN];
1794
        int external_port;
1795
        char internal_addr[INET_ADDRSTRLEN];
1796
        int internal_port;
1797

    
1798
        char *pch;
1799
        char *s = strdup(socketID_string);
1800

    
1801
        //replace ':' with a blank
1802
        pch=strchr(s,':');
1803
        while (pch!=NULL){
1804
                                *pch = ' ';
1805
                pch=strchr(pch+1,':');
1806
        }
1807
        pch=strchr(s,'-');
1808
        if(pch) *pch = ' ';
1809

    
1810
        sscanf(s,"%s %d %s %d", internal_addr, &internal_port,
1811
                external_addr, &external_port);
1812

    
1813
        if(inet_pton(AF_INET, internal_addr, &(socketID->internal_addr.udpaddr.sin_addr)) == 0)
1814
                return EINVAL;
1815
        socketID->internal_addr.udpaddr.sin_family = AF_INET;
1816
        socketID->internal_addr.udpaddr.sin_port = htons(internal_port);
1817

    
1818

    
1819
        if(inet_pton(AF_INET, external_addr, &(socketID->external_addr.udpaddr.sin_addr)) ==0)
1820
                return EINVAL;
1821
        socketID->external_addr.udpaddr.sin_family = AF_INET;
1822
        socketID->external_addr.udpaddr.sin_port = htons(external_port);
1823

    
1824
        free(s);
1825
        return 0;
1826

    
1827
}
1828

    
1829
int mlGetConnectionStatus(int connectionID){
1830

    
1831
        if(connectbuf[connectionID])
1832
                return connectbuf[connectionID]->status == READY;
1833
        return -1;
1834
    
1835
}
1836

    
1837

    
1838
int mlConnectionExist(socketID_handle socketID, bool ready){
1839

    
1840
    /*
1841
     * check if another connection for the external connectionID exist
1842
     * that was established \ within the last 2 seconds
1843
     */
1844
        int i;
1845
        for (i = 0; i < CONNECTBUFSIZE; i++)
1846
                if (connectbuf[i] != NULL)
1847
                        if (mlCompareSocketIDs(&(connectbuf[i]->external_socketID), socketID) == 0) {
1848
                                if (ready) return (connectbuf[i]->status == READY ? i : -1);;
1849
                                return i;
1850
                                }
1851

    
1852
    return -1;
1853

    
1854
}
1855

    
1856
//Added by Robert Birke as comodity functions
1857

    
1858
//int mlPrintSocketID(socketID_handle socketID) {
1859
//        char str[SOCKETID_STRING_SIZE];
1860
//        mlSocketIDToString(socketID, str, sizeof(str));
1861
//        printf(stderr,"int->%s<-ext\n",str);
1862
//}
1863

    
1864
/*
1865
 * hash code of a socketID
1866
 * TODO might think of a better way
1867
 */
1868
int mlHashSocketID(socketID_handle sock) {
1869
    return sock->internal_addr.udpaddr.sin_port +
1870
                          sock->external_addr.udpaddr.sin_port;
1871
}
1872

    
1873
int mlCompareSocketIDs(socketID_handle sock1, socketID_handle sock2) {
1874
        /*
1875
        * compare internal addr
1876
        */
1877
        if (sock1->internal_addr.udpaddr.sin_addr.s_addr !=
1878
            sock2->internal_addr.udpaddr.sin_addr.s_addr)
1879
                        return 1;
1880

    
1881
        if (sock1->internal_addr.udpaddr.sin_port !=
1882
                 sock2->internal_addr.udpaddr.sin_port)
1883
                        return 1;
1884

    
1885
        /*
1886
        * compare external addr
1887
        */
1888
        if (sock1->external_addr.udpaddr.sin_addr.s_addr !=
1889
            sock2->external_addr.udpaddr.sin_addr.s_addr)
1890
                        return 1;
1891

    
1892
        if (sock1->external_addr.udpaddr.sin_port !=
1893
                 sock2->external_addr.udpaddr.sin_port)
1894
                        return 1;
1895

    
1896
        return 0;
1897
}
1898

    
1899
int mlCompareSocketIDsByPort(socketID_handle sock1, socketID_handle sock2)
1900
{ 
1901
        if (sock1->internal_addr.udpaddr.sin_port !=
1902
                 sock2->internal_addr.udpaddr.sin_port)
1903
                        return 1;
1904

    
1905
        if (sock1->external_addr.udpaddr.sin_port !=
1906
                 sock2->external_addr.udpaddr.sin_port)
1907
                        return 1;
1908
        return 0;
1909
}
1910

    
1911
int mlGetPathMTU(int ConnectionId) {
1912
        if(ConnectionId < 0 || ConnectionId >= CONNECTBUFSIZE)
1913
                return -1;
1914
        if (connectbuf[ConnectionId] != NULL)
1915
                return connectbuf[ConnectionId]->pmtusize;
1916
        return -1;
1917
}