Statistics
| Branch: | Revision:

ml / ml.c @ 28c32e01

History | View | Annotate | Download (52.4 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
        if(recvdatabuf[recv_id]->status == INACTIVE) {
543
                // Monitoring layer hook
544
                if(get_Recv_data_inf_cb != NULL) {
545
                        mon_data_inf recv_data_inf;
546

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

    
563
                        // send data recv callback to monitoring module
564

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

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

    
571
                recv_params rParams;
572

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

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

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

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

    
596
        int recv_id, free_recv_id = -1;
597

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

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

    
613

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

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

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

    
640

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

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

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

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

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

    
677
                                // send data recv callback to monitoring module
678

    
679
                                (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
680
                        }
681

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

    
686
                                recv_params rParams;
687

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

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

    
702
                        //clean up
703
                        free(recvdatabuf[recv_id]->recvbuf);
704
                        free(recvdatabuf[recv_id]);
705
                        recvdatabuf[recv_id] = NULL;
706
                } else { // not COMPLETE
707
                        //start time out
708
                        //TODO make timeout at least a DEFINE
709
                        struct timeval timeout = { 4, 0 };
710
                        event_base_once(base, -1, EV_TIMEOUT, &recv_timeout_cb, (void *) (long)recv_id, &timeout);
711
                }
712
        }
713
}
714

    
715
//done
716
void pmtu_timeout_cb(int fd, short event, void *arg)
717
{
718
        debug("ML: pmtu timeout called\n");
719

    
720
        int con_id = (long) arg;
721
        pmtu new_pmtusize;
722
        struct timeval timeout;
723

    
724
        if(connectbuf[con_id] == NULL) {
725
                error("ML: pmtu timeout called on non existing con_id\n");
726
                return;
727
        }
728

    
729
        if(connectbuf[con_id]->status == READY) {
730
                // nothing to do anymore
731
                return;
732
        }
733

    
734
        timeout = connectbuf[con_id]->timeout_value;
735

    
736
        if(connectbuf[con_id]->delay || connectbuf[con_id]->trials == MAX_TRIALS - 1) {
737
                double delay = timeout.tv_sec + timeout.tv_usec / 1000000.0;
738
                delay = delay * 5;
739
                timeout.tv_sec = floor(delay);
740
                timeout.tv_usec = fmod(delay, 1.0) * 1000000.0;
741
                if(connectbuf[con_id]->delay) {
742
                        connectbuf[con_id]->delay = false;
743
                        goto reschedule;
744
                }
745
        }
746

    
747
        if(connectbuf[con_id]->trials == MAX_TRIALS) {
748
                // decrement the pmtu size
749
                connectbuf[con_id]->pmtusize = pmtu_decrement(connectbuf[con_id]->pmtusize);
750
                connectbuf[con_id]->trials = 0;
751
        }
752

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

    
771
        //retry with new pmtu size
772
        connectbuf[con_id]->trials++;
773
        send_conn_msg(con_id, connectbuf[con_id]->pmtusize, connectbuf[con_id]->status);
774

    
775
reschedule:
776
        /* reschedule */
777
        event_base_once(base, -1, EV_TIMEOUT, pmtu_timeout_cb, (void *) (long)con_id, &timeout);
778
}
779

    
780
/*
781
 * decrements the mtu size
782
 */
783
pmtu pmtu_decrement(pmtu pmtusize)
784
{
785
        pmtu pmtu_return_size;
786
        switch(pmtusize) {
787
        case MAX:
788
                return DSL;
789
        case DSL:
790
                return DSLMEDIUM;
791
        case DSLMEDIUM:
792
                return DSLSLIM;
793
        case DSLSLIM:
794
                return BELOWDSL;
795
        case BELOWDSL:
796
                return MIN;
797
        default:
798
                return ERROR;
799
        }
800
}
801

    
802
void pmtu_error_cb_th(char *msg, int msglen)
803
{
804
        debug("ML: pmtu_error callback called msg_size: %d\n",msglen);
805
        //TODO debug
806
        return;
807

    
808
    char *msgbufptr = NULL;
809
    int msgtype;
810
    int connectionID;
811
    pmtu pmtusize;
812
    pmtu new_pmtusize;
813
    int dead = 0;
814

    
815
    // check the packettype
816
    msgbufptr = &msg[0];
817

    
818
    // check the msgtype
819
    msgbufptr = &msg[1];
820
    memcpy(&msgtype, msgbufptr, 4);
821

    
822
    if (msgtype == 0) {
823

    
824
        // get the connectionID
825
        msgbufptr = &msg[5];
826
        memcpy(&connectionID, msgbufptr, 4);
827

    
828
        int msgtype_c = connectbuf[connectionID]->status;
829
//        pmtusize = connectbuf[connectionID]->pmtutrysize;
830

    
831
        if (msgtype_c != msgtype) {
832
            dead = 1;
833
        }
834

    
835

    
836
    } else if (msgtype == 1) {
837

    
838
        // read the connectionID
839
        msgbufptr = &msg[9];
840
        memcpy(&connectionID, msgbufptr, 4);
841

    
842
        int msgtype_c = connectbuf[connectionID]->status;
843
//        pmtusize = connectbuf[connectionID]->pmtutrysize;
844

    
845
        if (msgtype_c != msgtype) {
846
            dead = 1;
847
        }
848

    
849
    }
850
    // decrement the pmtu size
851
    new_pmtusize = pmtu_decrement(pmtusize);
852

    
853
//    connectbuf[connectionID]->pmtutrysize = new_pmtusize;
854

    
855
    if (new_pmtusize == ERROR) {
856
                error("ML:  Could not create connection with connectionID %i !\n",
857
                        connectionID);
858

    
859
                if(failed_Connection_cb != NULL)
860
                        (failed_Connection_cb) (connectionID, NULL);
861
                // set the message type to a non existent message
862
                msgtype = 2;
863
                // delete the connection entry
864
                 mlCloseConnection(connectionID);
865
        }
866

    
867
    if (msgtype == 0 && dead != 1) {
868

    
869
        // stop the timeout event
870
        // timeout_del(connectbuf[connectionID]->timeout);
871
        /*
872
         * libevent2
873
         */
874

    
875
        // event_del(connectbuf[connectionID]->timeout);
876

    
877

    
878
        // create and send a connection message
879
//         create_conn_msg(new_pmtusize, connectionID,
880
//                         &local_socketID, INVITE);
881

    
882
//        send_conn_msg(connectionID, new_pmtusize);
883

    
884
        // set a timeout event for the pmtu discovery
885
        // timeout_set(connectbuf[connectionID]->timeout,pmtu_timeout_cb,(void
886
        // *)&connectionID);
887

    
888
        // timeout_add(connectbuf[connectionID]->timeout,&connectbuf[connectionID]->timeout_value);
889

    
890
        /*
891
         * libevent2
892
         */
893

    
894
        struct event *ev;
895
        ev = evtimer_new(base, pmtu_timeout_cb,
896
                         (void *) connectbuf[connectionID]);
897

    
898
        // connectbuf[connectionID]->timeout = ev;
899

    
900
        event_add(ev, &connectbuf[connectionID]->timeout_value);
901

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

    
904
        // stop the timeout event
905
        // timeout_del(connectbuf[connectionID]->timeout);
906

    
907
        /*
908
         * libevent2
909
         */
910
        // info("still here 11 \n");
911
        // printf("ev %d \n",connectbuf[connectionID]->timeout);
912
        // event_del(connectbuf[connectionID]->timeout );
913
        // evtimer_del(connectbuf[connectionID]->timeout );
914

    
915

    
916
//         // create and send a connection message
917
//         create_conn_msg(new_pmtusize,
918
//                         connectbuf[connectionID]->connectionID,
919
//                         NULL, CONNECT);
920

    
921
        //send_conn_msg(connectionID, new_pmtusize);
922

    
923
        // set a timeout event for the pmtu discovery
924
        // timeout_set(connectbuf[connectionID]->timeout,pmtu_timeout_cb,(void
925
        // *)&connectionID);
926
        // timeout_add(connectbuf[connectionID]->timeout,&connectbuf[connectionID]->timeout_value);
927

    
928
        /*
929
         * libevent2
930
         */
931
        // struct event *ev;
932
        // ev = evtimer_new(base,pmtu_timeout_cb, (void
933
        // *)connectbuf[connectionID]);
934
        // connectbuf[connectionID]->timeout = ev;
935
        // event_add(ev,&connectbuf[connectionID]->timeout_value);
936

    
937
    }
938
}
939

    
940
/*
941
 * what to do once a packet arrived if it is a conn packet send it to
942
 * recv_conn handler if it is a data packet send it to the recv_data
943
 * handler
944
 */
945

    
946
//done --
947
void recv_pkg(int fd, short event, void *arg)
948
{
949
        debug("ML: recv_pkg called\n");
950

    
951
        struct msg_header *msg_h;
952
        char msgbuf[MAX];
953
        char *bufptr = msgbuf;
954
        int ttl;
955
        struct sockaddr_in recv_addr;
956
        pmtu recvSize = MAX;
957
        int msg_size;
958

    
959
        recvPacket(fd, msgbuf, &recvSize, &recv_addr, pmtu_error_cb_th, &ttl);
960

    
961

    
962
        // check if it is not just an ERROR message
963
        if(recvSize < 0)
964
                return;
965

    
966
        // @TODO check if this simplistic STUN message recognition really always works, probably not
967
        unsigned short stun_bind_response = 0x0101;
968
        unsigned short * msgspot = (unsigned short *) msgbuf;
969
        if (*msgspot == stun_bind_response) {
970
                debug("ML: recv_pkg: parse stun message called\n");
971
                recv_stun_msg(msgbuf, recvSize);
972
                return;
973
        }
974

    
975
        msg_h = (struct msg_header *) msgbuf;
976
        bufptr += MSG_HEADER_SIZE + msg_h->len_mon_packet_hdr;
977
        msg_size = recvSize - MSG_HEADER_SIZE - msg_h->len_mon_packet_hdr;
978

    
979

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

    
1005

    
1006
        switch(msg_h->msg_type) {
1007
                case ML_CON_MSG:
1008
                        debug("ML: received conn pkg\n");
1009
                        recv_conn_msg(msg_h, bufptr, msg_size);
1010
                        break;
1011
                default:
1012
                        if(msg_h->msg_type < 127) {
1013
                                debug("ML: received data pkg\n");
1014
                                recv_data_msg(msg_h, bufptr, msg_size);
1015
                                break;
1016
                        }
1017
                        debug("ML: unrecognised msg_type\n");
1018
                        break;
1019
        }
1020
}
1021

    
1022
/*
1023
 * compare the external IP address of two socketIDs
1024
 */
1025
int
1026
compare_external_address_socketIDs(socketID_handle sock1, socketID_handle sock2)
1027
{
1028
        if( sock1->external_addr.udpaddr.sin_addr.s_addr == sock2->external_addr.udpaddr.sin_addr.s_addr)
1029
                return 0;
1030
        return 1;
1031
}
1032

    
1033
void try_stun();
1034

    
1035
/*
1036
 * the timeout of the NAT traversal
1037
 */
1038
void nat_traversal_timeout(int fd, short event, void *arg)
1039
{
1040
        if (NAT_traversal == false) {
1041
                debug("ML: NAT traversal request re-send\n");
1042
                if(receive_SocketID_cb)
1043
                        (receive_SocketID_cb) (&local_socketID, 2);
1044
                try_stun();
1045
        }
1046
}
1047

    
1048
unsigned long resolve(const char *ipaddr)
1049
{
1050
        struct hostent *h = gethostbyname(ipaddr);
1051
        if (!h) {
1052
                error("ML: Unable to resolve host name %s\n", ipaddr);
1053
        exit(-1);
1054
    }
1055
    unsigned long *addr = (unsigned long *) (h->h_addr);
1056
    return *addr;
1057
}
1058

    
1059

    
1060
/*
1061
 * returns a handle to the socketID struct the ipaddr can be a null
1062
 * pointer. Then all available ipaddr on the machine are choosen.
1063
 */
1064
void create_socket(const int port, const char *ipaddr)
1065
{
1066
        struct sockaddr_in udpaddr;
1067
        udpaddr.sin_family = AF_INET;
1068
        if (ipaddr == NULL) {
1069
                /*
1070
                * try to guess the local IP address
1071
                */
1072
                const char *ipaddr_iface = mlAutodetectIPAddress();
1073
                if (ipaddr_iface) {
1074
                        udpaddr.sin_addr.s_addr = inet_addr(ipaddr_iface);
1075
                } else {
1076
                        udpaddr.sin_addr.s_addr = INADDR_ANY;
1077
                }
1078
        } else {
1079
                udpaddr.sin_addr.s_addr = inet_addr(ipaddr);
1080
        }
1081
        udpaddr.sin_port = htons(port);
1082

    
1083
        socketaddrgen udpgen;
1084
        memset(&udpgen,0,sizeof(socketaddrgen));        //this will be sent over the net, so set it to 0
1085
        udpgen.udpaddr = udpaddr;
1086
        local_socketID.internal_addr = udpgen;
1087

    
1088
        socketfd = createSocket(port, ipaddr);
1089

    
1090
        struct event *ev;
1091
        ev = event_new(base, socketfd, EV_READ | EV_PERSIST, recv_pkg, NULL);
1092

    
1093
        event_add(ev, NULL);
1094

    
1095
        try_stun();
1096
}
1097

    
1098
/*
1099
 * try to figure out external IP using STUN, if defined
1100
 */
1101
void try_stun()
1102
{
1103
        if (isStunDefined()) {
1104
                /*
1105
                * send the NAT traversal STUN request
1106
                */
1107
                 send_stun_request(socketfd, &stun_server);
1108

    
1109
                /*
1110
                * enter a NAT traversal timeout that takes care of retransmission
1111
                */
1112
                struct event *ev1;
1113
                struct timeval timeout_value_NAT_traversal = { 2, 0 };
1114
                ev1 = evtimer_new(base, nat_traversal_timeout, NULL);
1115
                event_add(ev1, &timeout_value_NAT_traversal);
1116

    
1117
                NAT_traversal = false;
1118
        } else {
1119
                /*
1120
                * Assume we have accessibility and copy internal address to external one
1121
                */
1122
                local_socketID.external_addr = local_socketID.internal_addr;
1123
                NAT_traversal = true; // @TODO: this is not really NAT traversal, but a flag that init is over
1124
                // callback to the upper layer indicating that the socketID is now
1125
                // ready to use
1126
                if(receive_SocketID_cb)
1127
                        (receive_SocketID_cb) (&local_socketID, 0); //success
1128
        }
1129
}
1130

    
1131
/**************************** END OF INTERNALS ***********************/
1132

    
1133
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){
1134

    
1135
        base = (struct event_base *) arg;
1136
        recv_data_callback = recv_data_cb;
1137
        mlSetRecvTimeout(timeout_value);
1138
        if (stun_ipaddr) {
1139
                 mlSetStunServer(stun_port, stun_ipaddr);
1140
        } else {
1141

    
1142
        }
1143
        register_recv_localsocketID_cb(local_socketID_cb);
1144
        create_socket(port, ipaddr);
1145

    
1146
}
1147

    
1148
/* register callbacks  */
1149
void mlRegisterGetRecvPktInf(get_recv_pkt_inf_cb recv_pkt_inf_cb){
1150

    
1151
        if (recv_pkt_inf_cb == NULL)
1152
                error("ML: Register get_recv_pkt_inf_cb failed: NULL ptr  \n");
1153
        else
1154
                get_Recv_pkt_inf_cb = recv_pkt_inf_cb;
1155

    
1156
}
1157

    
1158
void mlRegisterGetSendPktInf(get_send_pkt_inf_cb  send_pkt_inf_cb){
1159

    
1160
        if (send_pkt_inf_cb == NULL)
1161
                error("ML: Register get_send_pkt_inf_cb: NULL ptr  \n");
1162
        else
1163
                get_Send_pkt_inf_cb = send_pkt_inf_cb;
1164

    
1165
}
1166

    
1167

    
1168
void mlRegisterSetMonitoringHeaderPktCb(set_monitoring_header_pkt_cb monitoring_header_pkt_cb ){
1169

    
1170
        if (monitoring_header_pkt_cb == NULL)
1171
                error("ML: Register set_monitoring_header_pkt_cb: NULL ptr  \n");
1172
        else
1173
                set_Monitoring_header_pkt_cb = monitoring_header_pkt_cb;
1174

    
1175
}
1176

    
1177
void mlRegisterGetRecvDataInf(get_recv_data_inf_cb recv_data_inf_cb){
1178

    
1179
        if (recv_data_inf_cb == NULL)
1180
                error("ML: Register get_recv_data_inf_cb: NULL ptr  \n");
1181
        else
1182
                get_Recv_data_inf_cb = recv_data_inf_cb;
1183

    
1184
}
1185

    
1186
void mlRegisterGetSendDataInf(get_send_data_inf_cb  send_data_inf_cb){
1187

    
1188
        if (send_data_inf_cb == NULL)
1189
                error("ML: Register get_send_data_inf_cb: NULL ptr  \n");
1190
        else
1191
                get_Send_data_inf_cb = send_data_inf_cb;
1192

    
1193
}
1194

    
1195
void mlRegisterSetMonitoringHeaderDataCb(set_monitoring_header_data_cb monitoring_header_data_cb){
1196

    
1197
        if (monitoring_header_data_cb == NULL)
1198
                error("ML: Register set_monitoring_header_data_cb : NULL ptr  \n");
1199
        else
1200
        set_Monitoring_header_data_cb = monitoring_header_data_cb;
1201

    
1202
}
1203

    
1204
void mlRegisterRecvConnectionCb(receive_connection_cb recv_conn_cb){
1205

    
1206
        if (recv_conn_cb == NULL)
1207
                error("ML: Register receive_connection_cb: NULL ptr  \n");
1208
        else
1209
                receive_Connection_cb = recv_conn_cb;
1210

    
1211
}
1212

    
1213
void mlRegisterErrorConnectionCb(connection_failed_cb conn_failed){
1214

    
1215
        if (conn_failed == NULL)
1216
                error("ML: Register connection_failed_cb: NULL ptr  \n");
1217
        else
1218
        failed_Connection_cb = conn_failed;
1219

    
1220
}
1221

    
1222
void mlRegisterRecvDataCb(receive_data_cb data_cb,unsigned char msgtype){
1223

    
1224
    if (msgtype > 126) {
1225

    
1226
            error
1227
            ("ML: Could not register recv_data callback. Msgtype is greater then 126 \n");
1228

    
1229
    }
1230

    
1231
    if (data_cb == NULL) {
1232

    
1233
            error("ML: Register receive data callback: NUll ptr \n ");
1234

    
1235
    } else {
1236

    
1237
        recvcbbuf[msgtype] = data_cb;
1238

    
1239
    }
1240

    
1241
}
1242

    
1243
void mlCloseSocket(socketID_handle socketID){
1244

    
1245
        free(socketID);
1246

    
1247
}
1248

    
1249
void keepalive_fn(evutil_socket_t fd, short what, void *arg) {
1250
        socketID_handle peer = arg;
1251

    
1252
        int con_id = mlConnectionExist(peer, false);
1253
        if (con_id < 0 || connectbuf[con_id]->defaultSendParams.keepalive <= 0) {
1254
                /* Connection fell from under us or keepalive was disabled */
1255
                free(arg);
1256
                return;
1257
        }
1258

    
1259
        /* do what we gotta do */
1260
        if ( connectbuf[con_id]->status == READY) {
1261
                char keepaliveMsg[32] = "";
1262
                sprintf(keepaliveMsg, "KEEPALIVE %d", connectbuf[con_id]->keepalive_seq++);
1263
                send_msg(con_id, MSG_TYPE_ML_KEEPALIVE, keepaliveMsg, 1 + strlen(keepaliveMsg), false, 
1264
                        &(connectbuf[con_id]->defaultSendParams));
1265
        }
1266

    
1267
        /* re-schedule */
1268
        struct timeval t = { 0,0 };
1269
        t.tv_sec = time(NULL) + connectbuf[con_id]->defaultSendParams.keepalive;
1270

    
1271
        event_base_once(base, -1, EV_TIMEOUT, keepalive_fn, peer, &t);
1272
}
1273

    
1274
void setupKeepalive(int conn_id) {
1275
        /* Save the peer's address for us */
1276
        socketID_handle peer = malloc(sizeof(socket_ID));
1277
        memcpy(peer, &connectbuf[conn_id]->external_socketID, sizeof(socket_ID));
1278

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

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

    
1285
/* connection functions */
1286
int mlOpenConnection(socketID_handle external_socketID,receive_connection_cb connection_cb,void *arg, const send_params defaultSendParams){
1287

    
1288
        int con_id;
1289
        if (external_socketID == NULL) {
1290
                error("ML: cannot open connection: one of the socketIDs is NULL\n");
1291
                return -1;
1292
        }
1293
        if (NAT_traversal == false) {
1294
                error("ML: cannot open connection: NAT traversal for socketID still in progress\n");
1295
                return -1;
1296
        }
1297
        if (connection_cb == NULL) {
1298
                error("ML: cannot open connection: connection_cb is NULL\n");
1299
                return -1;
1300
        }
1301

    
1302
        // check if that connection already exist
1303

    
1304
        con_id = mlConnectionExist(external_socketID, false);
1305
        if (con_id >= 0) {
1306
                // overwrite defaultSendParams
1307
                bool newKeepalive = 
1308
                        connectbuf[con_id]->defaultSendParams.keepalive == 0 && defaultSendParams.keepalive != 0;
1309
                connectbuf[con_id]->defaultSendParams = defaultSendParams;
1310
                if (newKeepalive) setupKeepalive(con_id);
1311
                // if so check if it is ready to use
1312
                if (connectbuf[con_id]->status == READY) {
1313
                                // if so use the callback immediateley
1314
                                (connection_cb) (con_id, arg);
1315

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

    
1350
                        connectbuf[con_id]->connection_head = connectbuf[con_id]->connection_last = malloc(sizeof(struct receive_connection_cb_list));
1351
                        connectbuf[con_id]->connection_last->next = NULL;
1352
                        connectbuf[con_id]->connection_last->connection_cb = connection_cb;
1353
                        connectbuf[con_id]->connection_last->arg = arg;
1354
                        connectbuf[con_id]->external_connectionID = -1;
1355

    
1356
                        connectbuf[con_id]->defaultSendParams = defaultSendParams;
1357
                        if (defaultSendParams.keepalive) setupKeepalive(con_id);
1358
                        break;
1359
                }
1360
        } //end of for
1361

    
1362
        if (con_id == CONNECTBUFSIZE) {
1363
                error("ML: Could not open connection: connection buffer full\n");
1364
                return -1;
1365
        }
1366

    
1367
        // create and send a connection message
1368
        send_conn_msg(con_id, MAX, INVITE);
1369

    
1370
        struct event *ev;
1371
        ev = evtimer_new(base, pmtu_timeout_cb, (void *) (long)con_id);
1372
        event_add(ev, &connectbuf[con_id]->timeout_value);
1373

    
1374
        return con_id;
1375

    
1376
}
1377

    
1378
void mlCloseConnection(const int connectionID){
1379

    
1380
        // remove it from the connection array
1381
        if(connectbuf[connectionID]) {
1382
                if(connectbuf[connectionID]->ctrl_msg_buf)
1383
                        free(connectbuf[connectionID]->ctrl_msg_buf);
1384
                free(connectbuf[connectionID]);
1385
                connectbuf[connectionID] = NULL;
1386
        }
1387

    
1388
}
1389

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

    
1392
        if (connectionID < 0) {
1393
                error("ML: send data failed: connectionID does not exist\n");
1394
                return;
1395
        }
1396

    
1397
        if (connectbuf[connectionID] == NULL) {
1398
                error("ML: send data failed: connectionID does not exist\n");
1399
                return;
1400
        }
1401
        if (connectbuf[connectionID]->status != READY) {
1402
            error("ML: send data failed: connection is not active\n");
1403
            return;
1404
        }
1405

    
1406
        if (sParams == NULL) {
1407
                sParams = &(connectbuf[connectionID]->defaultSendParams);
1408
        }
1409

    
1410
        send_msg(connectionID, msgtype, sendbuf, bufsize, false, sParams);
1411

    
1412
}
1413

    
1414
/* transmit data functions  */
1415
int mlSendAllData(const int connectionID,send_all_data_container *container,int nr_entries,unsigned char msgtype,send_params *sParams){
1416

    
1417
    if (nr_entries < 1 || nr_entries > 5) {
1418

    
1419
        error
1420
            ("ML : sendALlData : nr_enties is not between 1 and 5 \n ");
1421
        return 0;
1422

    
1423
    } else {
1424

    
1425
        if (nr_entries == 1) {
1426

    
1427
                mlSendData(connectionID, container->buffer_1,
1428
                      container->length_1, msgtype, sParams);
1429

    
1430
            return 1;
1431

    
1432
        } else if (nr_entries == 2) {
1433

    
1434
            int buflen = container->length_1 + container->length_2;
1435
            char buf[buflen];
1436
            memcpy(buf, container->buffer_1, container->length_1);
1437
            memcpy(&buf[container->length_1], container->buffer_2,
1438
                   container->length_2);
1439
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1440

    
1441
            return 1;
1442

    
1443
        } else if (nr_entries == 3) {
1444

    
1445
            int buflen =
1446
                container->length_1 + container->length_2 +
1447
                container->length_3;
1448
            char buf[buflen];
1449
            memcpy(buf, container->buffer_1, container->length_1);
1450
            memcpy(&buf[container->length_1], container->buffer_2,
1451
                   container->length_2);
1452
            memcpy(&buf[container->length_2], container->buffer_3,
1453
                   container->length_3);
1454
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1455

    
1456

    
1457
            return 1;
1458

    
1459
        } else if (nr_entries == 4) {
1460

    
1461
            int buflen =
1462
                container->length_1 + container->length_2 +
1463
                container->length_3 + container->length_4;
1464
            char buf[buflen];
1465
            memcpy(buf, container->buffer_1, container->length_1);
1466
            memcpy(&buf[container->length_1], container->buffer_2,
1467
                   container->length_2);
1468
            memcpy(&buf[container->length_2], container->buffer_3,
1469
                   container->length_3);
1470
            memcpy(&buf[container->length_3], container->buffer_4,
1471
                   container->length_4);
1472
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1473

    
1474
            return 1;
1475

    
1476
        } else {
1477

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

    
1494
            return 1;
1495
        }
1496

    
1497
    }
1498

    
1499
}
1500

    
1501
int mlRecvData(const int connectionID,char *recvbuf,int *bufsize,recv_params *rParams){
1502

    
1503
        //TODO yet to be converted
1504
        return 0;
1505
#if 0
1506
        if (rParams == NULL) {
1507
                error("ML: recv_data failed: recv_params is a NULL ptr\n");
1508
                return 0;
1509
    } else {
1510

1511
        info("ML: recv data called \n");
1512

1513
        int i = 0;
1514
        int returnValue = 0;
1515
        double timeout = (double) recv_timeout.tv_sec;
1516
        time_t endtime = time(NULL);
1517

1518
        for (i = 0; i < RECVDATABUFSIZE; i++) {
1519

1520
            if (recvdatabuf[i] != NULL) {
1521

1522
                if (recvdatabuf[i]->connectionID == connectionID) {
1523

1524
                    info("ML: recv data has entry  \n");
1525

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

1528
                    // check if the specified connection has data and it
1529
                    // is complete
1530
                    // check the data seqnr
1531
                    // if(connectionID == recvdatabuf[i]->connectionID &&
1532
                    // 1 == recvdatabuf[i]->status){
1533

1534
                    if (1 == recvdatabuf[i]->status) {
1535

1536
                        // info("transmissionHandler: recv_data set is
1537
                        // complete \n" );
1538

1539
                        // debug("debud \n");
1540

1541
                        // exchange the pointers
1542
                        int buffersize = 0;
1543
                        buffersize = recvdatabuf[i]->bufsize;
1544
                        *bufsize = buffersize;
1545
                        // recvbuf = recvdatabuf[i]->recvbuf;
1546

1547
                        // info("buffersize %d \n",buffersize);
1548
                        memcpy(recvbuf, recvdatabuf[i]->recvbuf,
1549
                               buffersize);
1550
                        // debug(" recvbuf %s \n",recvbuf );
1551

1552
//                         double nrMissFrags =
1553
//                             (double) recvdatabuf[i]->nrFragments /
1554
//                             (double) recvdatabuf[i]->recvFragments;
1555
//                         int nrMissingFragments = (int) ceil(nrMissFrags);
1556

1557
//                        rParams->nrMissingFragments = nrMissingFragments;
1558
//                         rParams->nrFragments = recvdatabuf[i]->nrFragments;
1559
                        rParams->msgtype = recvdatabuf[i]->msgtype;
1560
                        rParams->connectionID =
1561
                            recvdatabuf[i]->connectionID;
1562

1563
                        // break from the loop
1564
                        // debug(" recvbuf %s \n ",recvbuf);
1565

1566
                        // double nrMissFrags =
1567
                        // (double)recvdatabuf[i]->nrFragments /
1568
                        // (double)recvdatabuf[i]->recvFragments;
1569
                        // int nrMissingFragments =
1570
                        // (int)ceil(nrMissFrags);
1571

1572
                        if(get_Recv_data_inf_cb != NULL) {
1573
                                mon_data_inf recv_data_inf;
1574

1575
                                recv_data_inf.remote_socketID = &(connectbuf[connectionID]->external_socketID);
1576
                                recv_data_inf.buffer = recvdatabuf[i]->recvbuf;
1577
                                recv_data_inf.bufSize = recvdatabuf[i]->bufsize;
1578
                                recv_data_inf.msgtype = recvdatabuf[i]->msgtype;
1579
//                                 recv_data_inf.monitoringHeaderType = recvdatabuf[i]->monitoringHeaderType;
1580
//                                 recv_data_inf.monitoringDataHeader = recvdatabuf[i]->monitoringDataHeader;
1581
                                gettimeofday(&recv_data_inf.arrival_time, NULL);
1582
                                recv_data_inf.firstPacketArrived = recvdatabuf[i]->firstPacketArrived;
1583
                                recv_data_inf.nrMissingFragments = nrMissingFragments;
1584
                                recv_data_inf.nrFragments = recvdatabuf[i]->nrFragments;
1585
                                recv_data_inf.priority = false;
1586
                                recv_data_inf.padding = false;
1587
                                recv_data_inf.confirmation = false;
1588
                                recv_data_inf.reliable = false;
1589

1590
                                // send data recv callback to monitoring module
1591

1592
                                (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
1593
                        }
1594

1595

1596
                        // free the allocated memory
1597
                        free(recvdatabuf[i]);
1598
                        recvdatabuf[i] = NULL;
1599

1600
                        returnValue = 1;
1601
                        break;
1602

1603
                    }
1604

1605
                    if (recvdatabuf[i] != NULL) {
1606

1607
                        if (timepass > timeout) {
1608

1609
                            info("ML: recv_data timeout called  \n");
1610

1611
                            // some data about the missing chunks should
1612
                            // be added here
1613
                            // exchange the pointers
1614
                            int buffersize = 0;
1615
                            buffersize = recvdatabuf[i]->bufsize;
1616
                            *bufsize = buffersize;
1617
                            // recvbuf = recvdatabuf[i]->recvbuf;
1618

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

1625
                            // debug(" recvbuf %s \n",recvbuf );
1626

1627
                            memcpy(recvbuf, recvdatabuf[i]->recvbuf,
1628
                                   buffersize);
1629

1630
                            rParams->nrMissingFragments =
1631
                                nrMissingFragments;
1632
                            rParams->nrFragments =
1633
                                recvdatabuf[i]->nrFragments;
1634
                            rParams->msgtype = recvdatabuf[i]->msgtype;
1635
                            rParams->connectionID =
1636
                                recvdatabuf[i]->connectionID;
1637

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

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

1656
                                        // send data recv callback to monitoring module
1657

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

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

1665
                            returnValue = 1;
1666
                            break;
1667

1668
                        }
1669
                    }
1670

1671
                }
1672

1673
            }
1674
            // debug("2 recvbuf %s \n ",recvbuf);
1675
        }
1676
        return returnValue;
1677
    }
1678
#endif
1679

    
1680
}
1681

    
1682
/* setter  */
1683
void mlSetStunServer(const int port,const char *ipaddr){
1684

    
1685
        stun_server.sin_family = AF_INET;
1686
        if (ipaddr == NULL)
1687
                stun_server.sin_addr.s_addr = htonl(INADDR_ANY);
1688
        else
1689
                stun_server.sin_addr.s_addr = resolve(ipaddr);
1690
        stun_server.sin_port = htons(port);
1691

    
1692
}
1693

    
1694
void mlSetRecvTimeout(struct timeval timeout_value){
1695

    
1696
        recv_timeout = timeout_value;
1697

    
1698
}
1699

    
1700
int mlGetStandardTTL(socketID_handle socketID,uint8_t *ttl){
1701

    
1702
        return getTTL(socketfd, ttl);
1703

    
1704
}
1705

    
1706
socketID_handle mlGetLocalSocketID(int *errorstatus){
1707

    
1708
        if (NAT_traversal == false) {
1709
                *errorstatus = 2;
1710
                return NULL;
1711
        }
1712

    
1713
        *errorstatus = 0;
1714
        return &local_socketID;
1715

    
1716
}
1717

    
1718
int mlGetExternalIP(char* external_addr){
1719

    
1720
        socketaddrgen udpgen;
1721
        struct sockaddr_in udpaddr;
1722

    
1723
        udpgen = local_socketID.external_addr;
1724
        udpaddr = udpgen.udpaddr;
1725

    
1726
        inet_ntop(AF_INET, &(udpaddr.sin_addr), external_addr,
1727
                        INET_ADDRSTRLEN);
1728

    
1729
        if (external_addr == NULL) {
1730

    
1731
        return -1;
1732

    
1733
        } else {
1734

    
1735
        return 0;
1736

    
1737
        }
1738

    
1739
}
1740

    
1741
int mlSocketIDToString(socketID_handle socketID,char* socketID_string, size_t len){
1742

    
1743
        char internal_addr[INET_ADDRSTRLEN];
1744
        char external_addr[INET_ADDRSTRLEN];
1745
        inet_ntop(AF_INET, &(socketID->internal_addr.udpaddr.sin_addr.s_addr), internal_addr, INET_ADDRSTRLEN);
1746
        inet_ntop(AF_INET, &(socketID->external_addr.udpaddr.sin_addr.s_addr), external_addr, INET_ADDRSTRLEN);
1747

    
1748
        snprintf(socketID_string,len,"%s:%d-%s:%d", internal_addr, ntohs(socketID->internal_addr.udpaddr.sin_port),
1749
                external_addr,        ntohs(socketID->external_addr.udpaddr.sin_port));
1750
        return 0;
1751

    
1752
}
1753

    
1754
int mlStringToSocketID(const char* socketID_string, socketID_handle socketID){
1755

    
1756
        //@TODO add checks against malformed string
1757
        char external_addr[INET_ADDRSTRLEN];
1758
        int external_port;
1759
        char internal_addr[INET_ADDRSTRLEN];
1760
        int internal_port;
1761

    
1762
        char *pch;
1763
        char *s = strdup(socketID_string);
1764

    
1765
        //replace ':' with a blank
1766
        pch=strchr(s,':');
1767
        while (pch!=NULL){
1768
                                *pch = ' ';
1769
                pch=strchr(pch+1,':');
1770
        }
1771
        pch=strchr(s,'-');
1772
        if(pch) *pch = ' ';
1773

    
1774
        sscanf(s,"%s %d %s %d", internal_addr, &internal_port,
1775
                external_addr, &external_port);
1776

    
1777
        if(inet_pton(AF_INET, internal_addr, &(socketID->internal_addr.udpaddr.sin_addr)) == 0)
1778
                return EINVAL;
1779
        socketID->internal_addr.udpaddr.sin_family = AF_INET;
1780
        socketID->internal_addr.udpaddr.sin_port = htons(internal_port);
1781

    
1782

    
1783
        if(inet_pton(AF_INET, external_addr, &(socketID->external_addr.udpaddr.sin_addr)) ==0)
1784
                return EINVAL;
1785
        socketID->external_addr.udpaddr.sin_family = AF_INET;
1786
        socketID->external_addr.udpaddr.sin_port = htons(external_port);
1787

    
1788
        free(s);
1789
        return 0;
1790

    
1791
}
1792

    
1793
int mlGetConnectionStatus(int connectionID){
1794

    
1795
        if(connectbuf[connectionID])
1796
                return connectbuf[connectionID]->status == READY;
1797
        return -1;
1798
    
1799
}
1800

    
1801

    
1802
int mlConnectionExist(socketID_handle socketID, bool ready){
1803

    
1804
    /*
1805
     * check if another connection for the external connectionID exist
1806
     * that was established \ within the last 2 seconds
1807
     */
1808
        int i;
1809
        for (i = 0; i < CONNECTBUFSIZE; i++)
1810
                if (connectbuf[i] != NULL)
1811
                        if (mlCompareSocketIDs(&(connectbuf[i]->external_socketID), socketID) == 0) {
1812
                                if (ready) return (connectbuf[i]->status == READY ? i : -1);;
1813
                                return i;
1814
                                }
1815

    
1816
    return -1;
1817

    
1818
}
1819

    
1820
//Added by Robert Birke as comodity functions
1821

    
1822
//int mlPrintSocketID(socketID_handle socketID) {
1823
//        char str[SOCKETID_STRING_SIZE];
1824
//        mlSocketIDToString(socketID, str, sizeof(str));
1825
//        printf(stderr,"int->%s<-ext\n",str);
1826
//}
1827

    
1828
/*
1829
 * hash code of a socketID
1830
 * TODO might think of a better way
1831
 */
1832
int mlHashSocketID(socketID_handle sock) {
1833
    return sock->internal_addr.udpaddr.sin_port +
1834
                          sock->external_addr.udpaddr.sin_port;
1835
}
1836

    
1837
int mlCompareSocketIDs(socketID_handle sock1, socketID_handle sock2) {
1838
        /*
1839
        * compare internal addr
1840
        */
1841
        if (sock1->internal_addr.udpaddr.sin_addr.s_addr !=
1842
            sock2->internal_addr.udpaddr.sin_addr.s_addr)
1843
                        return 1;
1844

    
1845
        if (sock1->internal_addr.udpaddr.sin_port !=
1846
                 sock2->internal_addr.udpaddr.sin_port)
1847
                        return 1;
1848

    
1849
        /*
1850
        * compare external addr
1851
        */
1852
        if (sock1->external_addr.udpaddr.sin_addr.s_addr !=
1853
            sock2->external_addr.udpaddr.sin_addr.s_addr)
1854
                        return 1;
1855

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

    
1860
        return 0;
1861
}
1862

    
1863
int mlCompareSocketIDsByPort(socketID_handle sock1, socketID_handle sock2)
1864
{ 
1865
        if (sock1->internal_addr.udpaddr.sin_port !=
1866
                 sock2->internal_addr.udpaddr.sin_port)
1867
                        return 1;
1868

    
1869
        if (sock1->external_addr.udpaddr.sin_port !=
1870
                 sock2->external_addr.udpaddr.sin_port)
1871
                        return 1;
1872
        return 0;
1873
}
1874

    
1875
int mlGetPathMTU(int ConnectionId) {
1876
        if(ConnectionId < 0 || ConnectionId >= CONNECTBUFSIZE)
1877
                return -1;
1878
        if (connectbuf[ConnectionId] != NULL)
1879
                return connectbuf[ConnectionId]->pmtusize;
1880
        return -1;
1881
}