Statistics
| Branch: | Revision:

ml / ml.c @ 0e902e25

History | View | Annotate | Download (52.7 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
        iov[0].iov_base = &msg_h;
201
        iov[0].iov_len = MSG_HEADER_SIZE;
202

    
203
        msg_h.local_con_id = con_id;
204
        msg_h.remote_con_id = connectbuf[con_id]->external_connectionID;
205
        msg_h.msg_type = msg_type;
206
        msg_h.msg_seq_num = connectbuf[con_id]->seqnr++;
207

    
208

    
209
        iov[1].iov_len = iov[2].iov_len = 0;
210
        iov[1].iov_base = h_pkt;
211
        iov[2].iov_base = h_data;
212

    
213

    
214
        if (connectbuf[con_id]->internal_connect)
215
                udpgen = connectbuf[con_id]->external_socketID.internal_addr;
216
        else
217
                udpgen = connectbuf[con_id]->external_socketID.external_addr;
218

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

    
228
                if(get_Send_data_inf_cb != NULL && iov[2].iov_len != 0) {
229
                        mon_data_inf sd_data_inf;
230

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

    
243
                        (get_Send_data_inf_cb) ((void *) &sd_data_inf);
244
                }
245

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

    
252
                        iov[3].iov_len = pkt_len;
253
                        iov[3].iov_base = msg + offset;
254

    
255
                        //fill header
256
                        msg_h.len_mon_packet_hdr = iov[1].iov_len;
257
                        msg_h.offset = offset;
258
                        msg_h.msg_length = truncable ? pkt_len : msg_len;
259

    
260
                        //monitoring layer hook
261
                        if(get_Send_pkt_inf_cb != NULL && iov[1].iov_len) {
262
                                mon_pkt_inf pkt_info;
263

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

    
276
                                (get_Send_pkt_inf_cb) ((void *) &pkt_info);
277
                        }
278

    
279

    
280
                        switch(sendPacket(socketfd, iov, 4, &udpgen.udpaddr)) {
281
                                case MSGLEN:
282
                                        connectbuf[con_id]->pmtusize = pmtu_decrement(connectbuf[con_id]->pmtusize);
283
                                        connectbuf[con_id]->delay = true;
284
                                        retry = true;
285
                                        offset = msg_len; // exit the while
286
                                        break;
287
                                case FAILURE:
288
                                        offset = msg_len; // exit the while
289
                                        break;
290
                                case OK:
291
                                        //update
292
                                        offset += pkt_len + iov[2].iov_len;
293
                                        //transmit data header only in the first packet
294
                                        iov[2].iov_len = 0;
295
                                        break;
296
                        }
297
                } while(offset != msg_len + msg_h.len_mon_data_hdr && !truncable);
298
        } while(retry);
299
}
300

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

    
308
        if(connectbuf[con_id]->ctrl_msg_buf == NULL) {
309
                connectbuf[con_id]->ctrl_msg_buf = malloc(buf_size);
310
                memset(connectbuf[con_id]->ctrl_msg_buf, 0, buf_size);
311
        }
312

    
313
        if(connectbuf[con_id]->ctrl_msg_buf == NULL) {
314
                error("ML: can not allocate memory for connection message\n");
315
                return;
316
        }
317

    
318
        struct conn_msg *msg_header = (struct conn_msg*) connectbuf[con_id]->ctrl_msg_buf;
319

    
320
        msg_header->comand_type = command_type;
321
        msg_header->pmtu_size = connectbuf[con_id]->pmtusize;
322

    
323
        memcpy(&(msg_header->sock_id), loc_socketID, sizeof(socket_ID));
324

    
325
        send_msg(con_id, ML_CON_MSG, connectbuf[con_id]->ctrl_msg_buf, buf_size, true, &(connectbuf[con_id]->defaultSendParams));
326
}
327

    
328
void
329
recv_conn_msg(struct msg_header *msg_h, char *msgbuf, int bufsize)
330
{
331
        struct conn_msg *con_msg;
332
        int free_con_id, con_id;
333

    
334
        time_t now = time(NULL);
335
        double timediff = 0.0;
336

    
337
        // Monitoring layer hook
338
        if(get_Recv_data_inf_cb != NULL && msg_h->len_mon_data_hdr != 0) {
339
                // update pointer to the real data
340
                msgbuf += msg_h->len_mon_data_hdr;
341
                bufsize -= msg_h->len_mon_data_hdr;
342
                con_msg = (struct conn_msg *)msgbuf;
343

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

    
359
                // send data recv callback to monitoring module
360
                (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
361
        } else
362
                con_msg = (struct conn_msg *) msgbuf;
363

    
364
        // check the connection command type
365
        switch (con_msg->comand_type) {
366
                /*
367
                * if INVITE: enter a new socket make new entry in connect array
368
                * send an ok
369
                */
370
                case INVITE:
371
                        debug("ML: received INVITE\n");
372
                        /*
373
                        * check if another connection for the external connectionID exist
374
                        * that was established within the last 2 seconds
375
                        */
376
                        free_con_id = -1;
377
                        for (con_id = 0; con_id < CONNECTBUFSIZE; con_id++) {
378
                                if (connectbuf[con_id] != NULL) {
379
                                        if (mlCompareSocketIDs(&(connectbuf[con_id]->external_socketID), &(con_msg->sock_id)) == 0) {
380
                                                timediff = difftime(now, connectbuf[con_id]->starttime);
381
                                                if (timediff < 2)
382
                                                        break;
383
                                        }
384
                                } else if(free_con_id == -1)
385
                                        free_con_id = con_id;
386
                        }
387

    
388
                        if (con_id == CONNECTBUFSIZE) {
389
                                // create an entry in the connecttrybuf
390
                                if(free_con_id == -1) {
391
                                        error("ML: no new connect_buf available\n");
392
                                        return;
393
                                }
394
                                connectbuf[free_con_id] = (connect_data *) malloc(sizeof(connect_data));
395
                                memset(connectbuf[free_con_id],0,sizeof(connect_data));
396
                                connectbuf[free_con_id]->connection_head = connectbuf[free_con_id]->connection_last = NULL;
397
                                connectbuf[free_con_id]->starttime = time(NULL);
398
                                memcpy(&(connectbuf[free_con_id]->external_socketID), &(con_msg->sock_id), sizeof(socket_ID));
399
                                connectbuf[free_con_id]->pmtusize = con_msg->pmtu_size;
400
                                connectbuf[free_con_id]->external_connectionID = msg_h->local_con_id;
401
                                connectbuf[free_con_id]->internal_connect =
402
                                        !compare_external_address_socketIDs(&(con_msg->sock_id), loc_socketID);
403
                                con_id = free_con_id;
404
                        }
405

    
406
                        if(connectbuf[con_id]->status <= CONNECT) {
407
                                //update status and send back answer
408
                                connectbuf[con_id]->status = CONNECT;
409
                                send_conn_msg(con_id, con_msg->pmtu_size, CONNECT);
410
                        }
411
                        break;
412
                case CONNECT:
413
                        debug("ML: received CONNECT\n");
414

    
415
                        if(msg_h->remote_con_id != -1 && connectbuf[msg_h->remote_con_id] == NULL) {
416
                                error("ML: received CONNECT for inexistent connection\n");
417
                                return;
418
                        }
419

    
420
                        /*
421
                        * check if the connection status is not already 1 or 2
422
                        */
423
                        if (connectbuf[msg_h->remote_con_id]->status == INVITE) {
424
                                // set the external connectionID
425
                                connectbuf[msg_h->remote_con_id]->external_connectionID = msg_h->local_con_id;
426
                                // change status con_msg the connection_data
427
                                connectbuf[msg_h->remote_con_id]->status = READY;
428
                                // change pmtusize in the connection_data
429
                                connectbuf[msg_h->remote_con_id]->pmtusize = con_msg->pmtu_size;
430

    
431
                                // send the READY
432
                                send_conn_msg(msg_h->remote_con_id, con_msg->pmtu_size, READY);
433

    
434
                                if (receive_Connection_cb != NULL)
435
                                        (receive_Connection_cb) (msg_h->remote_con_id, NULL);
436

    
437
                                // call all registered callbacks
438
                                while(connectbuf[msg_h->remote_con_id]->connection_head != NULL) {
439
                                        struct receive_connection_cb_list *temp;
440
                                        temp = connectbuf[msg_h->remote_con_id]->connection_head;
441
                                        (temp->connection_cb) (msg_h->remote_con_id, temp->arg);
442
                                        connectbuf[msg_h->remote_con_id]->connection_head = temp->next;
443
                                        free(temp);
444
                                }
445
                                connectbuf[msg_h->remote_con_id]->connection_head =
446
                                        connectbuf[msg_h->remote_con_id]->connection_last = NULL;
447
                        } else
448
                                // send the READY
449
                                send_conn_msg(msg_h->remote_con_id, con_msg->pmtu_size, READY);
450

    
451
                        debug("ML: active connection established\n");
452
                        break;
453

    
454
                        /*
455
                        * if READY: find the entry in the connection array set the
456
                        * connection active change the pmtu size
457
                        */
458
                case READY:
459
                        debug("ML: received READY\n");
460
                        if(connectbuf[msg_h->remote_con_id] == NULL) {
461
                                error("ML: received READY for inexistent connection\n");
462
                                return;
463
                        }
464
                        /*
465
                        * checks if the connection is not already established
466
                        */
467
                        if (connectbuf[msg_h->remote_con_id]->status == CONNECT) {
468
                                // change status of the connection
469
                                connectbuf[msg_h->remote_con_id]->status = 2;
470
                                // change pmtusize
471
                                connectbuf[msg_h->remote_con_id]->pmtusize = con_msg->pmtu_size;
472

    
473
                                if (receive_Connection_cb != NULL)
474
                                        (receive_Connection_cb) (msg_h->remote_con_id, NULL);
475

    
476
                                while(connectbuf[msg_h->remote_con_id]->connection_head != NULL) {
477
                                        struct receive_connection_cb_list *temp;
478
                                        temp = connectbuf[msg_h->remote_con_id]->connection_head;
479
                                        (temp->connection_cb) (msg_h->remote_con_id, temp->arg);
480
                                        connectbuf[msg_h->remote_con_id]->connection_head = temp->next;
481
                                        free(temp);
482
                                }
483
                                connectbuf[msg_h->remote_con_id]->connection_head =
484
                                        connectbuf[msg_h->remote_con_id]->connection_last = NULL;
485
                                debug("ML: passive connection established\n");
486
                        }
487
                        break;
488
        }
489
}
490

    
491
void recv_stun_msg(char *msgbuf, int recvSize)
492
{
493
        /*
494
        * create empty stun message struct
495
        */
496
        StunMessage resp;
497
        memset(&resp, 0, sizeof(StunMessage));
498
        /*
499
        * parse the message
500
        */
501
        int returnValue = 0;
502
        returnValue = recv_stun_message(msgbuf, recvSize, &resp);
503

    
504
        if (returnValue == 0) {
505
                /*
506
                * read the reflexive Address into the local_socketID
507
                */
508
                struct sockaddr_in reflexiveAddr;
509
                reflexiveAddr.sin_family = AF_INET;
510
                reflexiveAddr.sin_addr.s_addr = htonl(resp.mappedAddress.ipv4.addr);
511
                reflexiveAddr.sin_port = htons(resp.mappedAddress.ipv4.port);
512
                socketaddrgen reflexiveAddres;
513
                reflexiveAddres.udpaddr = reflexiveAddr;
514
                local_socketID.external_addr = reflexiveAddres;
515
                NAT_traversal = true;
516
                // callback to the upper layer indicating that the socketID is now
517
                // ready to use
518
                (receive_SocketID_cb) (&local_socketID, 0);
519
        }
520
}
521

    
522
//done
523
void recv_timeout_cb(int fd, short event, void *arg)
524
{
525
        int recv_id = (long) arg;
526
        debug("ML: recv_timeout_cb called\n");
527

    
528
        if (recvdatabuf[recv_id] == NULL) {
529
                return;
530
        }
531

    
532

    
533
/*        if(recvdatabuf[recv_id]->status == ACTIVE) {
534
                //TODO make timeout at least a DEFINE
535
                struct timeval timeout = { 4, 0 };
536
                recvdatabuf[recv_id]->status = INACTIVE;
537
                event_base_once(base, -1, EV_TIMEOUT, recv_timeout_cb,
538
                        arg, &timeout);
539
                return;
540
        }
541
*/
542

    
543
        if(recvdatabuf[recv_id]->status == ACTIVE) {
544
                // Monitoring layer hook
545
                if(get_Recv_data_inf_cb != NULL) {
546
                        mon_data_inf recv_data_inf;
547

    
548
                        recv_data_inf.remote_socketID =
549
                                        &(connectbuf[recvdatabuf[recv_id]->connectionID]->external_socketID);
550
                        recv_data_inf.buffer = recvdatabuf[recv_id]->recvbuf;
551
                        recv_data_inf.bufSize = recvdatabuf[recv_id]->bufsize;
552
                        recv_data_inf.msgtype = recvdatabuf[recv_id]->msgtype;
553
                        recv_data_inf.monitoringDataHeaderLen = recvdatabuf[recv_id]->monitoringDataHeaderLen;
554
                        recv_data_inf.monitoringDataHeader = recvdatabuf[recv_id]->monitoringDataHeaderLen ?
555
                                recvdatabuf[recv_id]->recvbuf : NULL;
556
                        gettimeofday(&recv_data_inf.arrival_time, NULL);
557
                        recv_data_inf.firstPacketArrived = recvdatabuf[recv_id]->firstPacketArrived;
558
                        recv_data_inf.recvFragments = recvdatabuf[recv_id]->recvFragments;
559
                        recv_data_inf.priority = false;
560
                        recv_data_inf.padding = false;
561
                        recv_data_inf.confirmation = false;
562
                        recv_data_inf.reliable = false;
563

    
564
                        // send data recv callback to monitoring module
565

    
566
                        (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
567
                }
568

    
569
                // Get the right callback
570
                receive_data_cb receive_data_callback = recvcbbuf[recvdatabuf[recv_id]->msgtype];
571

    
572
                recv_params rParams;
573

    
574
                rParams.nrMissingBytes = recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->arrivedBytes;
575
                rParams.recvFragments = recvdatabuf[recv_id]->recvFragments;
576
                rParams.msgtype = recvdatabuf[recv_id]->msgtype;
577
                rParams.connectionID = recvdatabuf[recv_id]->connectionID;
578
                rParams.remote_socketID =
579
                        &(connectbuf[recvdatabuf[recv_id]->connectionID]->external_socketID);
580
                rParams.firstPacketArrived = recvdatabuf[recv_id]->firstPacketArrived;
581

    
582
                (receive_data_callback) (recvdatabuf[recv_id]->recvbuf + recvdatabuf[recv_id]->monitoringDataHeaderLen, recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->monitoringDataHeaderLen,
583
                        recvdatabuf[recv_id]->msgtype, &rParams);
584

    
585
                //clean up
586
                free(recvdatabuf[recv_id]->recvbuf);
587
                free(recvdatabuf[recv_id]);
588
                recvdatabuf[recv_id] = NULL;
589
        }
590
}
591

    
592
// process a single recv data message
593
void recv_data_msg(struct msg_header *msg_h, char *msgbuf, int bufsize)
594
{
595
        debug("ML: received data message called\n");
596

    
597
        int recv_id, free_recv_id = -1;
598

    
599
        if(connectbuf[msg_h->remote_con_id] == NULL) {
600
                debug("ML: Received a message not related to any opened connection!\n");
601
                return;
602
        }
603

    
604
        // check if a recv_data exist and enter data
605
        for (recv_id = 0; recv_id < RECVDATABUFSIZE; recv_id++)
606
                if (recvdatabuf[recv_id] != NULL) {
607
                        if (msg_h->remote_con_id == recvdatabuf[recv_id]->connectionID &&
608
                                        msg_h->msg_seq_num == recvdatabuf[recv_id]->seqnr)
609
                                                break;
610
                } else
611
                        if(free_recv_id == -1)
612
                                free_recv_id = recv_id;
613

    
614

    
615
        if(recv_id == RECVDATABUFSIZE) {
616
                //no recv_data found: create one
617
                recv_id = free_recv_id;
618
                recvdatabuf[recv_id] = (recvdata *) malloc(sizeof(recvdata));
619
                memset(recvdatabuf[recv_id], 0, sizeof(recvdata));
620
                recvdatabuf[recv_id]->connectionID = msg_h->remote_con_id;
621
                recvdatabuf[recv_id]->seqnr = msg_h->msg_seq_num;
622
                recvdatabuf[recv_id]->monitoringDataHeaderLen = msg_h->len_mon_data_hdr;
623
                recvdatabuf[recv_id]->bufsize = msg_h->msg_length + msg_h->len_mon_data_hdr;
624
                recvdatabuf[recv_id]->recvbuf = (char *) malloc(recvdatabuf[recv_id]->bufsize);
625
                /*
626
                * read the timeout data and set it
627
                */
628
                recvdatabuf[recv_id]->timeout_value.tv_sec = recv_timeout.tv_sec;
629
                recvdatabuf[recv_id]->timeout_value.tv_usec = recv_timeout.tv_usec;
630
                recvdatabuf[recv_id]->timeout_event = NULL;
631
                recvdatabuf[recv_id]->recvID = recv_id;
632
                recvdatabuf[recv_id]->starttime = time(NULL);
633
                recvdatabuf[recv_id]->msgtype = msg_h->msg_type;
634

    
635
                // fill the buffer with zeros
636
                memset(recvdatabuf[recv_id]->recvbuf, 0, msg_h->msg_length);
637
        }
638

    
639
        if (msg_h->offset == 0)
640
                recvdatabuf[recv_id]->firstPacketArrived = 1;
641

    
642

    
643
        // increment fragmentnr
644
        recvdatabuf[recv_id]->recvFragments++;
645
        // increment the arrivedBytes
646
        recvdatabuf[recv_id]->arrivedBytes += bufsize;
647

    
648
        // enter the data into the buffer
649
        memcpy(recvdatabuf[recv_id]->recvbuf + msg_h->offset, msgbuf, bufsize);
650

    
651
        //TODO very basic checkif all fragments arrived: has to be reviewed
652
        if(recvdatabuf[recv_id]->arrivedBytes == recvdatabuf[recv_id]->bufsize)
653
                recvdatabuf[recv_id]->status = COMPLETE; //buffer full -> msg completly arrived
654
        else
655
                recvdatabuf[recv_id]->status = ACTIVE;
656

    
657
        if (recv_data_callback) {
658
                if(recvdatabuf[recv_id]->status == COMPLETE) {
659
                        // Monitoring layer hook
660
                        if(get_Recv_data_inf_cb != NULL) {
661
                                mon_data_inf recv_data_inf;
662

    
663
                                recv_data_inf.remote_socketID =
664
                                         &(connectbuf[recvdatabuf[recv_id]->connectionID]->external_socketID);
665
                                recv_data_inf.buffer = recvdatabuf[recv_id]->recvbuf;
666
                                recv_data_inf.bufSize = recvdatabuf[recv_id]->bufsize;
667
                                recv_data_inf.msgtype = recvdatabuf[recv_id]->msgtype;
668
                                recv_data_inf.monitoringDataHeaderLen = recvdatabuf[recv_id]->monitoringDataHeaderLen;
669
                                recv_data_inf.monitoringDataHeader = recvdatabuf[recv_id]->monitoringDataHeaderLen ?
670
                                        recvdatabuf[recv_id]->recvbuf : NULL;
671
                                gettimeofday(&recv_data_inf.arrival_time, NULL);
672
                                recv_data_inf.firstPacketArrived = recvdatabuf[recv_id]->firstPacketArrived;
673
                                recv_data_inf.recvFragments = recvdatabuf[recv_id]->recvFragments;
674
                                recv_data_inf.priority = false;
675
                                recv_data_inf.padding = false;
676
                                recv_data_inf.confirmation = false;
677
                                recv_data_inf.reliable = false;
678

    
679
                                // send data recv callback to monitoring module
680

    
681
                                (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
682
                        }
683

    
684
                        // Get the right callback
685
                        receive_data_cb receive_data_callback = recvcbbuf[msg_h->msg_type];
686
                        if (receive_data_callback) {
687

    
688
                                recv_params rParams;
689

    
690
                                rParams.nrMissingBytes = recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->arrivedBytes;
691
                                rParams.recvFragments = recvdatabuf[recv_id]->recvFragments;
692
                                rParams.msgtype = recvdatabuf[recv_id]->msgtype;
693
                                rParams.connectionID = recvdatabuf[recv_id]->connectionID;
694
                                rParams.remote_socketID =
695
                                        &(connectbuf[recvdatabuf[recv_id]->connectionID]->external_socketID);
696
                                rParams.firstPacketArrived = recvdatabuf[recv_id]->firstPacketArrived;
697

    
698
                                (receive_data_callback) (recvdatabuf[recv_id]->recvbuf + recvdatabuf[recv_id]->monitoringDataHeaderLen, recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->monitoringDataHeaderLen,
699
                                        recvdatabuf[recv_id]->msgtype, (void *) &rParams);
700
                        } else {
701
                            warn("ML: callback not initialized for this message type: %d!\n",msg_h->msg_type);
702
                        }
703

    
704
                        //clean up
705
                        if (recvdatabuf[recv_id]->timeout_event) {
706
                                int ret;
707
                                ret = event_del(recvdatabuf[recv_id]->timeout_event);
708
                                event_free(recvdatabuf[recv_id]->timeout_event);
709
                        }
710
                        free(recvdatabuf[recv_id]->recvbuf);
711
                        free(recvdatabuf[recv_id]);
712
                        recvdatabuf[recv_id] = NULL;
713
                } else { // not COMPLETE
714
                        if (!recvdatabuf[recv_id]->timeout_event) {
715
                                //start time out
716
                                //TODO make timeout at least a DEFINE
717
                                struct timeval timeout = { 4, 0 };
718
                                recvdatabuf[recv_id]->timeout_event = event_new(base, -1, EV_TIMEOUT, &recv_timeout_cb, (void *) (long)recv_id);
719
                                evtimer_add(recvdatabuf[recv_id]->timeout_event, &timeout);
720
                        }
721
                }
722
        }
723
}
724

    
725
//done
726
void pmtu_timeout_cb(int fd, short event, void *arg)
727
{
728
        debug("ML: pmtu timeout called\n");
729

    
730
        int con_id = (long) arg;
731
        pmtu new_pmtusize;
732
        struct timeval timeout;
733

    
734
        if(connectbuf[con_id] == NULL) {
735
                error("ML: pmtu timeout called on non existing con_id\n");
736
                return;
737
        }
738

    
739
        if(connectbuf[con_id]->status == READY) {
740
                // nothing to do anymore
741
                return;
742
        }
743

    
744
        timeout = connectbuf[con_id]->timeout_value;
745

    
746
        if(connectbuf[con_id]->delay || connectbuf[con_id]->trials == MAX_TRIALS - 1) {
747
                double delay = timeout.tv_sec + timeout.tv_usec / 1000000.0;
748
                delay = delay * 5;
749
                timeout.tv_sec = floor(delay);
750
                timeout.tv_usec = fmod(delay, 1.0) * 1000000.0;
751
                if(connectbuf[con_id]->delay) {
752
                        connectbuf[con_id]->delay = false;
753
                        goto reschedule;
754
                }
755
        }
756

    
757
        if(connectbuf[con_id]->trials == MAX_TRIALS) {
758
                // decrement the pmtu size
759
                connectbuf[con_id]->pmtusize = pmtu_decrement(connectbuf[con_id]->pmtusize);
760
                connectbuf[con_id]->trials = 0;
761
        }
762

    
763
        //error in PMTU discovery?
764
        if (connectbuf[con_id]->pmtusize == ERROR) {
765
                if (connectbuf[con_id]->internal_connect == true) {
766
                        //as of now we tried directly connecting, now let's try trough the NAT
767
                        connectbuf[con_id]->internal_connect = false;
768
                        connectbuf[con_id]->pmtusize = MAX;
769
                } else {
770
                        //nothing to do we have to give up
771
                        error("ML: Could not create connection with connectionID %i!\n",con_id);
772
                        // envoke the callback for failed connection establishment
773
                        if(failed_Connection_cb != NULL)
774
                                (failed_Connection_cb) (con_id, NULL);
775
                        // delete the connection entry
776
                        mlCloseConnection(con_id);
777
                        return;
778
                }
779
        }
780

    
781
        //retry with new pmtu size
782
        connectbuf[con_id]->trials++;
783
        send_conn_msg(con_id, connectbuf[con_id]->pmtusize, connectbuf[con_id]->status);
784

    
785
reschedule:
786
        /* reschedule */
787
        event_base_once(base, -1, EV_TIMEOUT, pmtu_timeout_cb, (void *) (long)con_id, &timeout);
788
}
789

    
790
/*
791
 * decrements the mtu size
792
 */
793
pmtu pmtu_decrement(pmtu pmtusize)
794
{
795
        pmtu pmtu_return_size;
796
        switch(pmtusize) {
797
        case MAX:
798
                return DSL;
799
        case DSL:
800
                return DSLMEDIUM;
801
        case DSLMEDIUM:
802
                return DSLSLIM;
803
        case DSLSLIM:
804
                return BELOWDSL;
805
        case BELOWDSL:
806
                return MIN;
807
        default:
808
                return ERROR;
809
        }
810
}
811

    
812
void pmtu_error_cb_th(char *msg, int msglen)
813
{
814
        debug("ML: pmtu_error callback called msg_size: %d\n",msglen);
815
        //TODO debug
816
        return;
817

    
818
    char *msgbufptr = NULL;
819
    int msgtype;
820
    int connectionID;
821
    pmtu pmtusize;
822
    pmtu new_pmtusize;
823
    int dead = 0;
824

    
825
    // check the packettype
826
    msgbufptr = &msg[0];
827

    
828
    // check the msgtype
829
    msgbufptr = &msg[1];
830
    memcpy(&msgtype, msgbufptr, 4);
831

    
832
    if (msgtype == 0) {
833

    
834
        // get the connectionID
835
        msgbufptr = &msg[5];
836
        memcpy(&connectionID, msgbufptr, 4);
837

    
838
        int msgtype_c = connectbuf[connectionID]->status;
839
//        pmtusize = connectbuf[connectionID]->pmtutrysize;
840

    
841
        if (msgtype_c != msgtype) {
842
            dead = 1;
843
        }
844

    
845

    
846
    } else if (msgtype == 1) {
847

    
848
        // read the connectionID
849
        msgbufptr = &msg[9];
850
        memcpy(&connectionID, msgbufptr, 4);
851

    
852
        int msgtype_c = connectbuf[connectionID]->status;
853
//        pmtusize = connectbuf[connectionID]->pmtutrysize;
854

    
855
        if (msgtype_c != msgtype) {
856
            dead = 1;
857
        }
858

    
859
    }
860
    // decrement the pmtu size
861
    new_pmtusize = pmtu_decrement(pmtusize);
862

    
863
//    connectbuf[connectionID]->pmtutrysize = new_pmtusize;
864

    
865
    if (new_pmtusize == ERROR) {
866
                error("ML:  Could not create connection with connectionID %i !\n",
867
                        connectionID);
868

    
869
                if(failed_Connection_cb != NULL)
870
                        (failed_Connection_cb) (connectionID, NULL);
871
                // set the message type to a non existent message
872
                msgtype = 2;
873
                // delete the connection entry
874
                 mlCloseConnection(connectionID);
875
        }
876

    
877
    if (msgtype == 0 && dead != 1) {
878

    
879
        // stop the timeout event
880
        // timeout_del(connectbuf[connectionID]->timeout);
881
        /*
882
         * libevent2
883
         */
884

    
885
        // event_del(connectbuf[connectionID]->timeout);
886

    
887

    
888
        // create and send a connection message
889
//         create_conn_msg(new_pmtusize, connectionID,
890
//                         &local_socketID, INVITE);
891

    
892
//        send_conn_msg(connectionID, new_pmtusize);
893

    
894
        // set a timeout event for the pmtu discovery
895
        // timeout_set(connectbuf[connectionID]->timeout,pmtu_timeout_cb,(void
896
        // *)&connectionID);
897

    
898
        // timeout_add(connectbuf[connectionID]->timeout,&connectbuf[connectionID]->timeout_value);
899

    
900
        /*
901
         * libevent2
902
         */
903

    
904
        struct event *ev;
905
        ev = evtimer_new(base, pmtu_timeout_cb,
906
                         (void *) connectbuf[connectionID]);
907

    
908
        // connectbuf[connectionID]->timeout = ev;
909

    
910
        event_add(ev, &connectbuf[connectionID]->timeout_value);
911

    
912
    } else if (msgtype == 1 && dead != 1) {
913

    
914
        // stop the timeout event
915
        // timeout_del(connectbuf[connectionID]->timeout);
916

    
917
        /*
918
         * libevent2
919
         */
920
        // info("still here 11 \n");
921
        // printf("ev %d \n",connectbuf[connectionID]->timeout);
922
        // event_del(connectbuf[connectionID]->timeout );
923
        // evtimer_del(connectbuf[connectionID]->timeout );
924

    
925

    
926
//         // create and send a connection message
927
//         create_conn_msg(new_pmtusize,
928
//                         connectbuf[connectionID]->connectionID,
929
//                         NULL, CONNECT);
930

    
931
        //send_conn_msg(connectionID, new_pmtusize);
932

    
933
        // set a timeout event for the pmtu discovery
934
        // timeout_set(connectbuf[connectionID]->timeout,pmtu_timeout_cb,(void
935
        // *)&connectionID);
936
        // timeout_add(connectbuf[connectionID]->timeout,&connectbuf[connectionID]->timeout_value);
937

    
938
        /*
939
         * libevent2
940
         */
941
        // struct event *ev;
942
        // ev = evtimer_new(base,pmtu_timeout_cb, (void
943
        // *)connectbuf[connectionID]);
944
        // connectbuf[connectionID]->timeout = ev;
945
        // event_add(ev,&connectbuf[connectionID]->timeout_value);
946

    
947
    }
948
}
949

    
950
/*
951
 * what to do once a packet arrived if it is a conn packet send it to
952
 * recv_conn handler if it is a data packet send it to the recv_data
953
 * handler
954
 */
955

    
956
//done --
957
void recv_pkg(int fd, short event, void *arg)
958
{
959
        debug("ML: recv_pkg called\n");
960

    
961
        struct msg_header *msg_h;
962
        char msgbuf[MAX];
963
        char *bufptr = msgbuf;
964
        int ttl;
965
        struct sockaddr_in recv_addr;
966
        pmtu recvSize = MAX;
967
        int msg_size;
968

    
969
        recvPacket(fd, msgbuf, &recvSize, &recv_addr, pmtu_error_cb_th, &ttl);
970

    
971

    
972
        // check if it is not just an ERROR message
973
        if(recvSize < 0)
974
                return;
975

    
976
        // @TODO check if this simplistic STUN message recognition really always works, probably not
977
        unsigned short stun_bind_response = 0x0101;
978
        unsigned short * msgspot = (unsigned short *) msgbuf;
979
        if (*msgspot == stun_bind_response) {
980
                debug("ML: recv_pkg: parse stun message called\n");
981
                recv_stun_msg(msgbuf, recvSize);
982
                return;
983
        }
984

    
985
        msg_h = (struct msg_header *) msgbuf;
986
        bufptr += MSG_HEADER_SIZE + msg_h->len_mon_packet_hdr;
987
        msg_size = recvSize - MSG_HEADER_SIZE - msg_h->len_mon_packet_hdr;
988

    
989

    
990
        if(get_Recv_pkt_inf_cb != NULL && msg_h->len_mon_packet_hdr != 0) {
991
                mon_pkt_inf msginfNow;
992
                msginfNow.monitoringHeaderLen = msg_h->len_mon_packet_hdr;
993
                msginfNow.monitoringHeader = msg_h->len_mon_packet_hdr ? &msgbuf[0] + MSG_HEADER_SIZE : NULL;
994
                //TODO rethink this ...
995
                if(msg_h->msg_type == ML_CON_MSG) {
996
                        struct conn_msg *c_msg = (struct conn_msg *) bufptr;
997
                        msginfNow.remote_socketID = &(c_msg->sock_id);
998
                }
999
                else if(connectbuf[msg_h->remote_con_id] == NULL) {
1000
                        error("ML: received pkg called with non existent connection\n");
1001
                        return;
1002
                } else
1003
                        msginfNow.remote_socketID = &(connectbuf[msg_h->remote_con_id]->external_socketID);
1004
                msginfNow.buffer = bufptr;
1005
                msginfNow.bufSize = recvSize;
1006
                msginfNow.msgtype = msg_h->msg_type;
1007
                msginfNow.ttl = ttl;
1008
                msginfNow.dataID = msg_h->msg_seq_num;
1009
                msginfNow.offset = msg_h->offset;
1010
                msginfNow.datasize = msg_h->msg_length;
1011
                gettimeofday(&msginfNow.arrival_time, NULL);
1012
                (get_Recv_pkt_inf_cb) ((void *) &msginfNow);
1013
        }
1014

    
1015

    
1016
        switch(msg_h->msg_type) {
1017
                case ML_CON_MSG:
1018
                        debug("ML: received conn pkg\n");
1019
                        recv_conn_msg(msg_h, bufptr, msg_size);
1020
                        break;
1021
                default:
1022
                        if(msg_h->msg_type < 127) {
1023
                                debug("ML: received data pkg\n");
1024
                                recv_data_msg(msg_h, bufptr, msg_size);
1025
                                break;
1026
                        }
1027
                        debug("ML: unrecognised msg_type\n");
1028
                        break;
1029
        }
1030
}
1031

    
1032
/*
1033
 * compare the external IP address of two socketIDs
1034
 */
1035
int
1036
compare_external_address_socketIDs(socketID_handle sock1, socketID_handle sock2)
1037
{
1038
        if( sock1->external_addr.udpaddr.sin_addr.s_addr == sock2->external_addr.udpaddr.sin_addr.s_addr)
1039
                return 0;
1040
        return 1;
1041
}
1042

    
1043
void try_stun();
1044

    
1045
/*
1046
 * the timeout of the NAT traversal
1047
 */
1048
void nat_traversal_timeout(int fd, short event, void *arg)
1049
{
1050
        if (NAT_traversal == false) {
1051
                debug("ML: NAT traversal request re-send\n");
1052
                if(receive_SocketID_cb)
1053
                        (receive_SocketID_cb) (&local_socketID, 2);
1054
                try_stun();
1055
        }
1056
}
1057

    
1058
unsigned long resolve(const char *ipaddr)
1059
{
1060
        struct hostent *h = gethostbyname(ipaddr);
1061
        if (!h) {
1062
                error("ML: Unable to resolve host name %s\n", ipaddr);
1063
        exit(-1);
1064
    }
1065
    unsigned long *addr = (unsigned long *) (h->h_addr);
1066
    return *addr;
1067
}
1068

    
1069

    
1070
/*
1071
 * returns a handle to the socketID struct the ipaddr can be a null
1072
 * pointer. Then all available ipaddr on the machine are choosen.
1073
 */
1074
void create_socket(const int port, const char *ipaddr)
1075
{
1076
        struct sockaddr_in udpaddr;
1077
        udpaddr.sin_family = AF_INET;
1078
        if (ipaddr == NULL) {
1079
                /*
1080
                * try to guess the local IP address
1081
                */
1082
                const char *ipaddr_iface = mlAutodetectIPAddress();
1083
                if (ipaddr_iface) {
1084
                        udpaddr.sin_addr.s_addr = inet_addr(ipaddr_iface);
1085
                } else {
1086
                        udpaddr.sin_addr.s_addr = INADDR_ANY;
1087
                }
1088
        } else {
1089
                udpaddr.sin_addr.s_addr = inet_addr(ipaddr);
1090
        }
1091
        udpaddr.sin_port = htons(port);
1092

    
1093
        socketaddrgen udpgen;
1094
        memset(&udpgen,0,sizeof(socketaddrgen));        //this will be sent over the net, so set it to 0
1095
        udpgen.udpaddr = udpaddr;
1096
        local_socketID.internal_addr = udpgen;
1097

    
1098
        socketfd = createSocket(port, ipaddr);
1099

    
1100
        struct event *ev;
1101
        ev = event_new(base, socketfd, EV_READ | EV_PERSIST, recv_pkg, NULL);
1102

    
1103
        event_add(ev, NULL);
1104

    
1105
        try_stun();
1106
}
1107

    
1108
/*
1109
 * try to figure out external IP using STUN, if defined
1110
 */
1111
void try_stun()
1112
{
1113
        if (isStunDefined()) {
1114
                /*
1115
                * send the NAT traversal STUN request
1116
                */
1117
                 send_stun_request(socketfd, &stun_server);
1118

    
1119
                /*
1120
                * enter a NAT traversal timeout that takes care of retransmission
1121
                */
1122
                struct event *ev1;
1123
                struct timeval timeout_value_NAT_traversal = { 2, 0 };
1124
                ev1 = evtimer_new(base, nat_traversal_timeout, NULL);
1125
                event_add(ev1, &timeout_value_NAT_traversal);
1126

    
1127
                NAT_traversal = false;
1128
        } else {
1129
                /*
1130
                * Assume we have accessibility and copy internal address to external one
1131
                */
1132
                local_socketID.external_addr = local_socketID.internal_addr;
1133
                NAT_traversal = true; // @TODO: this is not really NAT traversal, but a flag that init is over
1134
                // callback to the upper layer indicating that the socketID is now
1135
                // ready to use
1136
                if(receive_SocketID_cb)
1137
                        (receive_SocketID_cb) (&local_socketID, 0); //success
1138
        }
1139
}
1140

    
1141
/**************************** END OF INTERNALS ***********************/
1142

    
1143
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){
1144

    
1145
        base = (struct event_base *) arg;
1146
        recv_data_callback = recv_data_cb;
1147
        mlSetRecvTimeout(timeout_value);
1148
        if (stun_ipaddr) {
1149
                 mlSetStunServer(stun_port, stun_ipaddr);
1150
        } else {
1151

    
1152
        }
1153
        register_recv_localsocketID_cb(local_socketID_cb);
1154
        create_socket(port, ipaddr);
1155

    
1156
}
1157

    
1158
/* register callbacks  */
1159
void mlRegisterGetRecvPktInf(get_recv_pkt_inf_cb recv_pkt_inf_cb){
1160

    
1161
        if (recv_pkt_inf_cb == NULL)
1162
                error("ML: Register get_recv_pkt_inf_cb failed: NULL ptr  \n");
1163
        else
1164
                get_Recv_pkt_inf_cb = recv_pkt_inf_cb;
1165

    
1166
}
1167

    
1168
void mlRegisterGetSendPktInf(get_send_pkt_inf_cb  send_pkt_inf_cb){
1169

    
1170
        if (send_pkt_inf_cb == NULL)
1171
                error("ML: Register get_send_pkt_inf_cb: NULL ptr  \n");
1172
        else
1173
                get_Send_pkt_inf_cb = send_pkt_inf_cb;
1174

    
1175
}
1176

    
1177

    
1178
void mlRegisterSetMonitoringHeaderPktCb(set_monitoring_header_pkt_cb monitoring_header_pkt_cb ){
1179

    
1180
        if (monitoring_header_pkt_cb == NULL)
1181
                error("ML: Register set_monitoring_header_pkt_cb: NULL ptr  \n");
1182
        else
1183
                set_Monitoring_header_pkt_cb = monitoring_header_pkt_cb;
1184

    
1185
}
1186

    
1187
void mlRegisterGetRecvDataInf(get_recv_data_inf_cb recv_data_inf_cb){
1188

    
1189
        if (recv_data_inf_cb == NULL)
1190
                error("ML: Register get_recv_data_inf_cb: NULL ptr  \n");
1191
        else
1192
                get_Recv_data_inf_cb = recv_data_inf_cb;
1193

    
1194
}
1195

    
1196
void mlRegisterGetSendDataInf(get_send_data_inf_cb  send_data_inf_cb){
1197

    
1198
        if (send_data_inf_cb == NULL)
1199
                error("ML: Register get_send_data_inf_cb: NULL ptr  \n");
1200
        else
1201
                get_Send_data_inf_cb = send_data_inf_cb;
1202

    
1203
}
1204

    
1205
void mlRegisterSetMonitoringHeaderDataCb(set_monitoring_header_data_cb monitoring_header_data_cb){
1206

    
1207
        if (monitoring_header_data_cb == NULL)
1208
                error("ML: Register set_monitoring_header_data_cb : NULL ptr  \n");
1209
        else
1210
        set_Monitoring_header_data_cb = monitoring_header_data_cb;
1211

    
1212
}
1213

    
1214
void mlRegisterRecvConnectionCb(receive_connection_cb recv_conn_cb){
1215

    
1216
        if (recv_conn_cb == NULL)
1217
                error("ML: Register receive_connection_cb: NULL ptr  \n");
1218
        else
1219
                receive_Connection_cb = recv_conn_cb;
1220

    
1221
}
1222

    
1223
void mlRegisterErrorConnectionCb(connection_failed_cb conn_failed){
1224

    
1225
        if (conn_failed == NULL)
1226
                error("ML: Register connection_failed_cb: NULL ptr  \n");
1227
        else
1228
        failed_Connection_cb = conn_failed;
1229

    
1230
}
1231

    
1232
void mlRegisterRecvDataCb(receive_data_cb data_cb,unsigned char msgtype){
1233

    
1234
    if (msgtype > 126) {
1235

    
1236
            error
1237
            ("ML: Could not register recv_data callback. Msgtype is greater then 126 \n");
1238

    
1239
    }
1240

    
1241
    if (data_cb == NULL) {
1242

    
1243
            error("ML: Register receive data callback: NUll ptr \n ");
1244

    
1245
    } else {
1246

    
1247
        recvcbbuf[msgtype] = data_cb;
1248

    
1249
    }
1250

    
1251
}
1252

    
1253
void mlCloseSocket(socketID_handle socketID){
1254

    
1255
        free(socketID);
1256

    
1257
}
1258

    
1259
void keepalive_fn(evutil_socket_t fd, short what, void *arg) {
1260
        socketID_handle peer = arg;
1261

    
1262
        int con_id = mlConnectionExist(peer, false);
1263
        if (con_id < 0 || connectbuf[con_id]->defaultSendParams.keepalive <= 0) {
1264
                /* Connection fell from under us or keepalive was disabled */
1265
                free(arg);
1266
                return;
1267
        }
1268

    
1269
        /* do what we gotta do */
1270
        if ( connectbuf[con_id]->status == READY) {
1271
                char keepaliveMsg[32] = "";
1272
                sprintf(keepaliveMsg, "KEEPALIVE %d", connectbuf[con_id]->keepalive_seq++);
1273
                send_msg(con_id, MSG_TYPE_ML_KEEPALIVE, keepaliveMsg, 1 + strlen(keepaliveMsg), false, 
1274
                        &(connectbuf[con_id]->defaultSendParams));
1275
        }
1276

    
1277
        /* re-schedule */
1278
        struct timeval t = { 0,0 };
1279
        t.tv_sec = time(NULL) + connectbuf[con_id]->defaultSendParams.keepalive;
1280

    
1281
        event_base_once(base, -1, EV_TIMEOUT, keepalive_fn, peer, &t);
1282
}
1283

    
1284
void setupKeepalive(int conn_id) {
1285
        /* Save the peer's address for us */
1286
        socketID_handle peer = malloc(sizeof(socket_ID));
1287
        memcpy(peer, &connectbuf[conn_id]->external_socketID, sizeof(socket_ID));
1288

    
1289
        struct timeval t = { 0,0 };
1290
        t.tv_sec = time(NULL) + connectbuf[conn_id]->defaultSendParams.keepalive;
1291

    
1292
        event_base_once(base, -1, EV_TIMEOUT, keepalive_fn, peer, &t);
1293
}
1294

    
1295
/* connection functions */
1296
int mlOpenConnection(socketID_handle external_socketID,receive_connection_cb connection_cb,void *arg, const send_params defaultSendParams){
1297

    
1298
        int con_id;
1299
        if (external_socketID == NULL) {
1300
                error("ML: cannot open connection: one of the socketIDs is NULL\n");
1301
                return -1;
1302
        }
1303
        if (NAT_traversal == false) {
1304
                error("ML: cannot open connection: NAT traversal for socketID still in progress\n");
1305
                return -1;
1306
        }
1307
        if (connection_cb == NULL) {
1308
                error("ML: cannot open connection: connection_cb is NULL\n");
1309
                return -1;
1310
        }
1311

    
1312
        // check if that connection already exist
1313

    
1314
        con_id = mlConnectionExist(external_socketID, false);
1315
        if (con_id >= 0) {
1316
                // overwrite defaultSendParams
1317
                bool newKeepalive = 
1318
                        connectbuf[con_id]->defaultSendParams.keepalive == 0 && defaultSendParams.keepalive != 0;
1319
                connectbuf[con_id]->defaultSendParams = defaultSendParams;
1320
                if (newKeepalive) setupKeepalive(con_id);
1321
                // if so check if it is ready to use
1322
                if (connectbuf[con_id]->status == READY) {
1323
                                // if so use the callback immediateley
1324
                                (connection_cb) (con_id, arg);
1325

    
1326
                // otherwise just write the connection cb and the arg pointer
1327
                // into the connection struct
1328
                } else {
1329
                        struct receive_connection_cb_list *temp;
1330
                        temp = malloc(sizeof(struct receive_connection_cb_list));
1331
                        temp->next = NULL;
1332
                        temp->connection_cb = connection_cb;
1333
                        temp->arg = arg;
1334
                        if(connectbuf[con_id]->connection_last != NULL) {
1335
                                connectbuf[con_id]->connection_last->next = temp;
1336
                                connectbuf[con_id]->connection_last = temp;
1337
                        } else
1338
                                connectbuf[con_id]->connection_last = connectbuf[con_id]->connection_head = temp;
1339
                }
1340
                return con_id;
1341
        }
1342
        // make entry in connection_establishment array
1343
        for (con_id = 0; con_id < CONNECTBUFSIZE; con_id++) {
1344
                if (connectbuf[con_id] == NULL) {
1345
                        connectbuf[con_id] = (connect_data *) malloc(sizeof(connect_data));
1346
                        memset(connectbuf[con_id],0,sizeof(connect_data));
1347
                        connectbuf[con_id]->starttime = time(NULL);
1348
                        memcpy(&connectbuf[con_id]->external_socketID, external_socketID, sizeof(socket_ID));
1349
                        connectbuf[con_id]->pmtusize = MAX;
1350
                        connectbuf[con_id]->status = INVITE;
1351
                        connectbuf[con_id]->seqnr = 0;
1352
                        connectbuf[con_id]->internal_connect = !compare_external_address_socketIDs(external_socketID, &local_socketID);
1353
                        /*
1354
                        * timeout values for the pmtu discovery
1355
                        */
1356
                        connectbuf[con_id]->timeout_value.tv_sec = 15;
1357
                        connectbuf[con_id]->timeout_value.tv_usec = 0;
1358
                        connectbuf[con_id]->connectionID = con_id;
1359

    
1360
                        connectbuf[con_id]->connection_head = connectbuf[con_id]->connection_last = malloc(sizeof(struct receive_connection_cb_list));
1361
                        connectbuf[con_id]->connection_last->next = NULL;
1362
                        connectbuf[con_id]->connection_last->connection_cb = connection_cb;
1363
                        connectbuf[con_id]->connection_last->arg = arg;
1364
                        connectbuf[con_id]->external_connectionID = -1;
1365

    
1366
                        connectbuf[con_id]->defaultSendParams = defaultSendParams;
1367
                        if (defaultSendParams.keepalive) setupKeepalive(con_id);
1368
                        break;
1369
                }
1370
        } //end of for
1371

    
1372
        if (con_id == CONNECTBUFSIZE) {
1373
                error("ML: Could not open connection: connection buffer full\n");
1374
                return -1;
1375
        }
1376

    
1377
        // create and send a connection message
1378
        send_conn_msg(con_id, MAX, INVITE);
1379

    
1380
        struct event *ev;
1381
        ev = evtimer_new(base, pmtu_timeout_cb, (void *) (long)con_id);
1382
        event_add(ev, &connectbuf[con_id]->timeout_value);
1383

    
1384
        return con_id;
1385

    
1386
}
1387

    
1388
void mlCloseConnection(const int connectionID){
1389

    
1390
        // remove it from the connection array
1391
        if(connectbuf[connectionID]) {
1392
                if(connectbuf[connectionID]->ctrl_msg_buf)
1393
                        free(connectbuf[connectionID]->ctrl_msg_buf);
1394
                free(connectbuf[connectionID]);
1395
                connectbuf[connectionID] = NULL;
1396
        }
1397

    
1398
}
1399

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

    
1402
        if (connectionID < 0) {
1403
                error("ML: send data failed: connectionID does not exist\n");
1404
                return;
1405
        }
1406

    
1407
        if (connectbuf[connectionID] == NULL) {
1408
                error("ML: send data failed: connectionID does not exist\n");
1409
                return;
1410
        }
1411
        if (connectbuf[connectionID]->status != READY) {
1412
            error("ML: send data failed: connection is not active\n");
1413
            return;
1414
        }
1415

    
1416
        if (sParams == NULL) {
1417
                sParams = &(connectbuf[connectionID]->defaultSendParams);
1418
        }
1419

    
1420
        send_msg(connectionID, msgtype, sendbuf, bufsize, false, sParams);
1421

    
1422
}
1423

    
1424
/* transmit data functions  */
1425
int mlSendAllData(const int connectionID,send_all_data_container *container,int nr_entries,unsigned char msgtype,send_params *sParams){
1426

    
1427
    if (nr_entries < 1 || nr_entries > 5) {
1428

    
1429
        error
1430
            ("ML : sendALlData : nr_enties is not between 1 and 5 \n ");
1431
        return 0;
1432

    
1433
    } else {
1434

    
1435
        if (nr_entries == 1) {
1436

    
1437
                mlSendData(connectionID, container->buffer_1,
1438
                      container->length_1, msgtype, sParams);
1439

    
1440
            return 1;
1441

    
1442
        } else if (nr_entries == 2) {
1443

    
1444
            int buflen = container->length_1 + container->length_2;
1445
            char buf[buflen];
1446
            memcpy(buf, container->buffer_1, container->length_1);
1447
            memcpy(&buf[container->length_1], container->buffer_2,
1448
                   container->length_2);
1449
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1450

    
1451
            return 1;
1452

    
1453
        } else if (nr_entries == 3) {
1454

    
1455
            int buflen =
1456
                container->length_1 + container->length_2 +
1457
                container->length_3;
1458
            char buf[buflen];
1459
            memcpy(buf, container->buffer_1, container->length_1);
1460
            memcpy(&buf[container->length_1], container->buffer_2,
1461
                   container->length_2);
1462
            memcpy(&buf[container->length_2], container->buffer_3,
1463
                   container->length_3);
1464
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1465

    
1466

    
1467
            return 1;
1468

    
1469
        } else if (nr_entries == 4) {
1470

    
1471
            int buflen =
1472
                container->length_1 + container->length_2 +
1473
                container->length_3 + container->length_4;
1474
            char buf[buflen];
1475
            memcpy(buf, container->buffer_1, container->length_1);
1476
            memcpy(&buf[container->length_1], container->buffer_2,
1477
                   container->length_2);
1478
            memcpy(&buf[container->length_2], container->buffer_3,
1479
                   container->length_3);
1480
            memcpy(&buf[container->length_3], container->buffer_4,
1481
                   container->length_4);
1482
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1483

    
1484
            return 1;
1485

    
1486
        } else {
1487

    
1488
            int buflen =
1489
                container->length_1 + container->length_2 +
1490
                container->length_3 + container->length_4 +
1491
                container->length_5;
1492
            char buf[buflen];
1493
            memcpy(buf, container->buffer_1, container->length_1);
1494
            memcpy(&buf[container->length_1], container->buffer_2,
1495
                   container->length_2);
1496
            memcpy(&buf[container->length_2], container->buffer_3,
1497
                   container->length_3);
1498
            memcpy(&buf[container->length_3], container->buffer_4,
1499
                   container->length_4);
1500
            memcpy(&buf[container->length_4], container->buffer_5,
1501
                   container->length_5);
1502
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1503

    
1504
            return 1;
1505
        }
1506

    
1507
    }
1508

    
1509
}
1510

    
1511
int mlRecvData(const int connectionID,char *recvbuf,int *bufsize,recv_params *rParams){
1512

    
1513
        //TODO yet to be converted
1514
        return 0;
1515
#if 0
1516
        if (rParams == NULL) {
1517
                error("ML: recv_data failed: recv_params is a NULL ptr\n");
1518
                return 0;
1519
    } else {
1520

1521
        info("ML: recv data called \n");
1522

1523
        int i = 0;
1524
        int returnValue = 0;
1525
        double timeout = (double) recv_timeout.tv_sec;
1526
        time_t endtime = time(NULL);
1527

1528
        for (i = 0; i < RECVDATABUFSIZE; i++) {
1529

1530
            if (recvdatabuf[i] != NULL) {
1531

1532
                if (recvdatabuf[i]->connectionID == connectionID) {
1533

1534
                    info("ML: recv data has entry  \n");
1535

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

1538
                    // check if the specified connection has data and it
1539
                    // is complete
1540
                    // check the data seqnr
1541
                    // if(connectionID == recvdatabuf[i]->connectionID &&
1542
                    // 1 == recvdatabuf[i]->status){
1543

1544
                    if (1 == recvdatabuf[i]->status) {
1545

1546
                        // info("transmissionHandler: recv_data set is
1547
                        // complete \n" );
1548

1549
                        // debug("debud \n");
1550

1551
                        // exchange the pointers
1552
                        int buffersize = 0;
1553
                        buffersize = recvdatabuf[i]->bufsize;
1554
                        *bufsize = buffersize;
1555
                        // recvbuf = recvdatabuf[i]->recvbuf;
1556

1557
                        // info("buffersize %d \n",buffersize);
1558
                        memcpy(recvbuf, recvdatabuf[i]->recvbuf,
1559
                               buffersize);
1560
                        // debug(" recvbuf %s \n",recvbuf );
1561

1562
//                         double nrMissFrags =
1563
//                             (double) recvdatabuf[i]->nrFragments /
1564
//                             (double) recvdatabuf[i]->recvFragments;
1565
//                         int nrMissingFragments = (int) ceil(nrMissFrags);
1566

1567
//                        rParams->nrMissingFragments = nrMissingFragments;
1568
//                         rParams->nrFragments = recvdatabuf[i]->nrFragments;
1569
                        rParams->msgtype = recvdatabuf[i]->msgtype;
1570
                        rParams->connectionID =
1571
                            recvdatabuf[i]->connectionID;
1572

1573
                        // break from the loop
1574
                        // debug(" recvbuf %s \n ",recvbuf);
1575

1576
                        // double nrMissFrags =
1577
                        // (double)recvdatabuf[i]->nrFragments /
1578
                        // (double)recvdatabuf[i]->recvFragments;
1579
                        // int nrMissingFragments =
1580
                        // (int)ceil(nrMissFrags);
1581

1582
                        if(get_Recv_data_inf_cb != NULL) {
1583
                                mon_data_inf recv_data_inf;
1584

1585
                                recv_data_inf.remote_socketID = &(connectbuf[connectionID]->external_socketID);
1586
                                recv_data_inf.buffer = recvdatabuf[i]->recvbuf;
1587
                                recv_data_inf.bufSize = recvdatabuf[i]->bufsize;
1588
                                recv_data_inf.msgtype = recvdatabuf[i]->msgtype;
1589
//                                 recv_data_inf.monitoringHeaderType = recvdatabuf[i]->monitoringHeaderType;
1590
//                                 recv_data_inf.monitoringDataHeader = recvdatabuf[i]->monitoringDataHeader;
1591
                                gettimeofday(&recv_data_inf.arrival_time, NULL);
1592
                                recv_data_inf.firstPacketArrived = recvdatabuf[i]->firstPacketArrived;
1593
                                recv_data_inf.nrMissingFragments = nrMissingFragments;
1594
                                recv_data_inf.nrFragments = recvdatabuf[i]->nrFragments;
1595
                                recv_data_inf.priority = false;
1596
                                recv_data_inf.padding = false;
1597
                                recv_data_inf.confirmation = false;
1598
                                recv_data_inf.reliable = false;
1599

1600
                                // send data recv callback to monitoring module
1601

1602
                                (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
1603
                        }
1604

1605

1606
                        // free the allocated memory
1607
                        free(recvdatabuf[i]);
1608
                        recvdatabuf[i] = NULL;
1609

1610
                        returnValue = 1;
1611
                        break;
1612

1613
                    }
1614

1615
                    if (recvdatabuf[i] != NULL) {
1616

1617
                        if (timepass > timeout) {
1618

1619
                            info("ML: recv_data timeout called  \n");
1620

1621
                            // some data about the missing chunks should
1622
                            // be added here
1623
                            // exchange the pointers
1624
                            int buffersize = 0;
1625
                            buffersize = recvdatabuf[i]->bufsize;
1626
                            *bufsize = buffersize;
1627
                            // recvbuf = recvdatabuf[i]->recvbuf;
1628

1629
                            double nrMissFrags =
1630
                                (double) recvdatabuf[i]->nrFragments /
1631
                                (double) recvdatabuf[i]->recvFragments;
1632
                            int nrMissingFragments =
1633
                                (int) ceil(nrMissFrags);
1634

1635
                            // debug(" recvbuf %s \n",recvbuf );
1636

1637
                            memcpy(recvbuf, recvdatabuf[i]->recvbuf,
1638
                                   buffersize);
1639

1640
                            rParams->nrMissingFragments =
1641
                                nrMissingFragments;
1642
                            rParams->nrFragments =
1643
                                recvdatabuf[i]->nrFragments;
1644
                            rParams->msgtype = recvdatabuf[i]->msgtype;
1645
                            rParams->connectionID =
1646
                                recvdatabuf[i]->connectionID;
1647

1648
                                if(get_Recv_data_inf_cb != NULL) {
1649
                                        mon_data_inf recv_data_inf;
1650

1651
                                        recv_data_inf.remote_socketID = &(connectbuf[connectionID]->external_socketID);
1652
                                        recv_data_inf.buffer = recvdatabuf[i]->recvbuf;
1653
                                        recv_data_inf.bufSize = recvdatabuf[i]->bufsize;
1654
                                        recv_data_inf.msgtype = recvdatabuf[i]->msgtype;
1655
                                        recv_data_inf.monitoringHeaderType = recvdatabuf[i]->monitoringHeaderType;
1656
                                        recv_data_inf.monitoringDataHeader = recvdatabuf[i]->monitoringDataHeader;
1657
                                        gettimeofday(&recv_data_inf.arrival_time, NULL);
1658
                                        recv_data_inf.firstPacketArrived = recvdatabuf[i]->firstPacketArrived;
1659
                                        recv_data_inf.nrMissingFragments = nrMissingFragments;
1660
                                        recv_data_inf.nrFragments = recvdatabuf[i]->nrFragments;
1661
                                        recv_data_inf.priority = false;
1662
                                        recv_data_inf.padding = false;
1663
                                        recv_data_inf.confirmation = false;
1664
                                        recv_data_inf.reliable = false;
1665

1666
                                        // send data recv callback to monitoring module
1667

1668
                                        (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
1669
                                }
1670

1671
                            // free the allocated memory
1672
                            free(recvdatabuf[i]);
1673
                            recvdatabuf[i] = NULL;
1674

1675
                            returnValue = 1;
1676
                            break;
1677

1678
                        }
1679
                    }
1680

1681
                }
1682

1683
            }
1684
            // debug("2 recvbuf %s \n ",recvbuf);
1685
        }
1686
        return returnValue;
1687
    }
1688
#endif
1689

    
1690
}
1691

    
1692
/* setter  */
1693
void mlSetStunServer(const int port,const char *ipaddr){
1694

    
1695
        stun_server.sin_family = AF_INET;
1696
        if (ipaddr == NULL)
1697
                stun_server.sin_addr.s_addr = htonl(INADDR_ANY);
1698
        else
1699
                stun_server.sin_addr.s_addr = resolve(ipaddr);
1700
        stun_server.sin_port = htons(port);
1701

    
1702
}
1703

    
1704
void mlSetRecvTimeout(struct timeval timeout_value){
1705

    
1706
        recv_timeout = timeout_value;
1707

    
1708
}
1709

    
1710
int mlGetStandardTTL(socketID_handle socketID,uint8_t *ttl){
1711

    
1712
        return getTTL(socketfd, ttl);
1713

    
1714
}
1715

    
1716
socketID_handle mlGetLocalSocketID(int *errorstatus){
1717

    
1718
        if (NAT_traversal == false) {
1719
                *errorstatus = 2;
1720
                return NULL;
1721
        }
1722

    
1723
        *errorstatus = 0;
1724
        return &local_socketID;
1725

    
1726
}
1727

    
1728
int mlGetExternalIP(char* external_addr){
1729

    
1730
        socketaddrgen udpgen;
1731
        struct sockaddr_in udpaddr;
1732

    
1733
        udpgen = local_socketID.external_addr;
1734
        udpaddr = udpgen.udpaddr;
1735

    
1736
        inet_ntop(AF_INET, &(udpaddr.sin_addr), external_addr,
1737
                        INET_ADDRSTRLEN);
1738

    
1739
        if (external_addr == NULL) {
1740

    
1741
        return -1;
1742

    
1743
        } else {
1744

    
1745
        return 0;
1746

    
1747
        }
1748

    
1749
}
1750

    
1751
int mlSocketIDToString(socketID_handle socketID,char* socketID_string, size_t len){
1752

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

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

    
1762
}
1763

    
1764
int mlStringToSocketID(const char* socketID_string, socketID_handle socketID){
1765

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

    
1772
        char *pch;
1773
        char *s = strdup(socketID_string);
1774

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

    
1784
        sscanf(s,"%s %d %s %d", internal_addr, &internal_port,
1785
                external_addr, &external_port);
1786

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

    
1792

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

    
1798
        free(s);
1799
        return 0;
1800

    
1801
}
1802

    
1803
int mlGetConnectionStatus(int connectionID){
1804

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

    
1811

    
1812
int mlConnectionExist(socketID_handle socketID, bool ready){
1813

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

    
1826
    return -1;
1827

    
1828
}
1829

    
1830
//Added by Robert Birke as comodity functions
1831

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

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

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

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

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

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

    
1870
        return 0;
1871
}
1872

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

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

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