Statistics
| Branch: | Revision:

ml / ml.c @ 9a20e619

History | View | Annotate | Download (59 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
/*
82
 * timeout before thinking that the STUN server can't be connected
83
 */
84
#define NAT_TRAVERSAL_TIMEOUT { 1, 0 }
85

    
86
/*
87
 * timeout before thinking of an mtu problem (check MAX_TRIALS as well)
88
 */
89
#define PMTU_TIMEOUT { 0, 250000 }
90

    
91
/*
92
 * retry sending connection messages this many times before reducing pmtu
93
 */
94
#define MAX_TRIALS 3
95

    
96
/*
97
 * default timeout value between the first and the last received packet of a message
98
 */
99
#define RECV_TIMEOUT_DEFAULT { 2, 0 }
100

    
101
/*
102
 * global variables
103
 */
104
/*
105
 * define a buffer of pointers to connect structures
106
 */
107
connect_data *connectbuf[CONNECTBUFSIZE];
108

    
109
/*
110
 * define a pointer buffer with pointers to recv_data structures
111
 */
112
recvdata *recvdatabuf[RECVDATABUFSIZE];
113

    
114
/*
115
 * define a pointer buffer for message multiplexing
116
 */
117
receive_data_cb recvcbbuf[MSGMULTIPLEXSIZE];
118

    
119
/*
120
 * stun server address
121
 */
122
struct sockaddr_in stun_server;
123

    
124
/*
125
 * receive timeout
126
 */
127
static struct timeval recv_timeout = RECV_TIMEOUT_DEFAULT;
128

    
129
/*
130
 * boolean NAT traversal successful if true
131
 */
132
boolean NAT_traversal;
133

    
134
/*
135
 * file descriptor for local socket
136
 */
137
evutil_socket_t socketfd;
138

    
139
/*
140
 * local socketID
141
 */
142
socket_ID local_socketID;
143

    
144
socketID_handle loc_socketID = &local_socketID;
145

    
146
/*
147
 * callback function pointers
148
 */
149
/*
150
 * monitoring module callbacks
151
 */
152
get_recv_pkt_inf_cb get_Recv_pkt_inf_cb = NULL;
153
get_send_pkt_inf_cb get_Send_pkt_inf_cb = NULL;
154
set_monitoring_header_pkt_cb set_Monitoring_header_pkt_cb = NULL;
155
get_recv_data_inf_cb get_Recv_data_inf_cb = NULL;
156
get_send_data_inf_cb get_Send_data_inf_cb = NULL;
157
set_monitoring_header_data_cb set_Monitoring_header_data_cb = NULL;
158
/*
159
 * connection callbacks
160
 */
161
receive_connection_cb receive_Connection_cb = NULL;
162
connection_failed_cb failed_Connection_cb = NULL;
163
/*
164
 * local socketID callback
165
 */
166
receive_localsocketID_cb receive_SocketID_cb;
167

    
168
/*
169
 * boolean that defines if received data is transmitted to the upper layer
170
 * via callback or via upper layer polling
171
 */
172
boolean recv_data_callback;
173

    
174
/*
175
 * helper function to get rid of a warning
176
 */
177
int min(int a, int b) {
178
        if (a > b) return b;
179
        return a;
180
}
181

    
182
/*
183
 * convert a socketID to a string. It uses a static buffer, so either strdup is needed, or the string will get lost!
184
 */
185
const char *conid_to_string(int con_id)
186
{
187
        static char s[INET_ADDRSTRLEN+1+5+1+INET_ADDRSTRLEN+1+5+1];
188
        mlSocketIDToString(&connectbuf[con_id]->external_socketID, s, sizeof(s));
189
        return s;
190
}
191

    
192
void register_recv_localsocketID_cb(receive_localsocketID_cb local_socketID_cb)
193
{
194
        if (local_socketID_cb == NULL)
195
                error("ML : Register receive_localsocketID_cb: NULL ptr \n");
196
        else
197
        receive_SocketID_cb = local_socketID_cb;
198
}
199

    
200

    
201
//void keep_connection_alive(const int connectionID)
202
//{
203
//
204
//    // to be done with the NAT traversal
205
//    // send a message over the wire
206
//    printf("\n");
207
//
208
//}
209

    
210
void unsetStunServer()
211
{
212
        stun_server.sin_addr.s_addr = INADDR_NONE;
213
}
214

    
215
bool isStunDefined()
216
{
217
        return stun_server.sin_addr.s_addr != INADDR_NONE;
218
}
219

    
220
void send_msg(int con_id, int msg_type, char* msg, int msg_len, bool truncable, send_params * sParams) {
221
        socketaddrgen udpgen;
222
        bool retry;
223
        int pkt_len, offset;
224
        struct iovec iov[4];
225

    
226
        char h_pkt[MON_HEADER_SPACE];
227
        char h_data[MON_HEADER_SPACE];
228

    
229
        struct msg_header msg_h;
230

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

    
233
        iov[0].iov_base = &msg_h;
234
        iov[0].iov_len = MSG_HEADER_SIZE;
235

    
236
        msg_h.local_con_id = con_id;
237
        msg_h.remote_con_id = connectbuf[con_id]->external_connectionID;
238
        msg_h.msg_type = msg_type;
239
        msg_h.msg_seq_num = connectbuf[con_id]->seqnr++;
240

    
241

    
242
        iov[1].iov_len = iov[2].iov_len = 0;
243
        iov[1].iov_base = h_pkt;
244
        iov[2].iov_base = h_data;
245

    
246

    
247
        if (connectbuf[con_id]->internal_connect)
248
                udpgen = connectbuf[con_id]->external_socketID.internal_addr;
249
        else
250
                udpgen = connectbuf[con_id]->external_socketID.external_addr;
251

    
252
        do{
253
                offset = 0;
254
                retry = false;
255
                // Monitoring layer hook
256
                if(set_Monitoring_header_data_cb != NULL) {
257
                        iov[2].iov_len = ((set_Monitoring_header_data_cb) (&(connectbuf[con_id]->external_socketID), msg_type));
258
                }
259
                msg_h.len_mon_data_hdr = iov[2].iov_len;
260

    
261
                if(get_Send_data_inf_cb != NULL && iov[2].iov_len != 0) {
262
                        mon_data_inf sd_data_inf;
263

    
264
                        sd_data_inf.remote_socketID = &(connectbuf[con_id]->external_socketID);
265
                        sd_data_inf.buffer = msg;
266
                        sd_data_inf.bufSize = msg_len;
267
                        sd_data_inf.msgtype = msg_type;
268
                        sd_data_inf.monitoringDataHeader = iov[2].iov_base;
269
                        sd_data_inf.monitoringDataHeaderLen = iov[2].iov_len;
270
                        sd_data_inf.priority = sParams->priority;
271
                        sd_data_inf.padding = sParams->padding;
272
                        sd_data_inf.confirmation = sParams->confirmation;
273
                        sd_data_inf.reliable = sParams->reliable;
274
                        memset(&sd_data_inf.arrival_time, 0, sizeof(struct timeval));
275

    
276
                        (get_Send_data_inf_cb) ((void *) &sd_data_inf);
277
                }
278

    
279
                do {
280
                        if(set_Monitoring_header_pkt_cb != NULL) {
281
                                iov[1].iov_len = (set_Monitoring_header_pkt_cb) (&(connectbuf[con_id]->external_socketID), msg_type);
282
                        }
283
                        pkt_len = min(connectbuf[con_id]->pmtusize - iov[2].iov_len - iov[1].iov_len - iov[0].iov_len, msg_len - offset) ;
284

    
285
                        iov[3].iov_len = pkt_len;
286
                        iov[3].iov_base = msg + offset;
287

    
288
                        //fill header
289
                        msg_h.len_mon_packet_hdr = iov[1].iov_len;
290
                        msg_h.offset = offset;
291
                        msg_h.msg_length = truncable ? pkt_len : msg_len;
292

    
293
                        //monitoring layer hook
294
                        if(get_Send_pkt_inf_cb != NULL && iov[1].iov_len) {
295
                                mon_pkt_inf pkt_info;
296

    
297
                                pkt_info.remote_socketID = &(connectbuf[con_id]->external_socketID);
298
                                pkt_info.buffer = msg + offset;
299
                                pkt_info.bufSize = pkt_len;
300
                                pkt_info.msgtype = msg_type;
301
                                pkt_info.dataID = connectbuf[con_id]->seqnr;
302
                                pkt_info.offset = offset;
303
                                pkt_info.datasize = msg_len;
304
                                pkt_info.monitoringHeaderLen = iov[1].iov_len;
305
                                pkt_info.monitoringHeader = iov[1].iov_base;
306
                                pkt_info.ttl = -1;
307
                                memset(&(pkt_info.arrival_time),0,sizeof(struct timeval));
308

    
309
                                (get_Send_pkt_inf_cb) ((void *) &pkt_info);
310
                        }
311

    
312
                        debug("ML: sending packet to %s with rconID:%d lconID:%d\n", conid_to_string(con_id), msg_h.remote_con_id, msg_h.local_con_id);
313
                        switch(sendPacket(socketfd, iov, 4, &udpgen.udpaddr)) {
314
                                case MSGLEN:
315
                                        info("ML: sending message failed, reducing MTU from %d to %d (to:%s conID:%d lconID:%d msgsize:%d offset:%d)\n", connectbuf[con_id]->pmtusize, pmtu_decrement(connectbuf[con_id]->pmtusize), conid_to_string(con_id), msg_h.remote_con_id, msg_h.local_con_id, msg_len, offset);
316
                                        // TODO: pmtu decremented here, but not in the "truncable" packet. That is currently resent without changing the claimed pmtu. Might need to be changed.
317
                                        connectbuf[con_id]->pmtusize = pmtu_decrement(connectbuf[con_id]->pmtusize);
318
                                        if (connectbuf[con_id]->pmtusize > 0) {
319
                                                connectbuf[con_id]->delay = true;
320
                                                retry = true;
321
                                        }
322
                                        offset = msg_len + msg_h.len_mon_data_hdr; // exit the while
323
                                        break;
324
                                case FAILURE:
325
                                        info("ML: sending message failed (to:%s conID:%d lconID:%d msgsize:%d offset:%d)\n", conid_to_string(con_id), msg_h.remote_con_id, msg_h.local_con_id, msg_len, offset);
326
                                        offset = msg_len + msg_h.len_mon_data_hdr; // exit the while
327
                                        break;
328
                                case OK:
329
                                        //update
330
                                        offset += pkt_len + iov[2].iov_len;
331
                                        //transmit data header only in the first packet
332
                                        iov[2].iov_len = 0;
333
                                        break;
334
                        }
335
                } while(offset != msg_len + msg_h.len_mon_data_hdr && !truncable);
336
        } while(retry);
337
}
338

    
339
void pmtu_timeout_cb(int fd, short event, void *arg);
340

    
341
void reschedule_conn_msg(int con_id)
342
{
343
        if (connectbuf[con_id]->timeout_event) {
344
                /* delete old timout */        
345
                event_del(connectbuf[con_id]->timeout_event);
346
                event_free(connectbuf[con_id]->timeout_event);
347
        }
348
        connectbuf[con_id]->timeout_event = event_new(base, -1, EV_TIMEOUT, &pmtu_timeout_cb, (void *) (long)con_id);
349
        evtimer_add(connectbuf[con_id]->timeout_event, &connectbuf[con_id]->timeout_value);
350
}
351

    
352
void send_conn_msg(int con_id, int buf_size, int command_type)
353
{
354
        if (buf_size < sizeof(struct conn_msg)) {
355
                error("ML: requested connection message size is too small\n");
356
                return;
357
        }
358

    
359
        if(connectbuf[con_id]->ctrl_msg_buf == NULL) {
360
                connectbuf[con_id]->ctrl_msg_buf = malloc(buf_size);
361
                memset(connectbuf[con_id]->ctrl_msg_buf, 0, buf_size);
362
        }
363

    
364
        if(connectbuf[con_id]->ctrl_msg_buf == NULL) {
365
                error("ML: can not allocate memory for connection message\n");
366
                return;
367
        }
368

    
369
        struct conn_msg *msg_header = (struct conn_msg*) connectbuf[con_id]->ctrl_msg_buf;
370

    
371
        msg_header->comand_type = command_type;
372
        msg_header->pmtu_size = connectbuf[con_id]->pmtusize;
373

    
374
        memcpy(&(msg_header->sock_id), loc_socketID, sizeof(socket_ID));
375

    
376
        send_msg(con_id, ML_CON_MSG, connectbuf[con_id]->ctrl_msg_buf, buf_size, true, &(connectbuf[con_id]->defaultSendParams));
377
}
378

    
379
void send_conn_msg_with_pmtu_discovery(int con_id, int buf_size, int command_type)
380
{
381
        struct timeval tout = PMTU_TIMEOUT;
382
        connectbuf[con_id]->timeout_value = tout;
383
        connectbuf[con_id]->trials = 1;
384
        send_conn_msg(con_id, buf_size, command_type);
385
        reschedule_conn_msg(con_id);
386
}
387

    
388
void resend_conn_msg(int con_id)
389
{
390
        connectbuf[con_id]->trials++;
391
        send_conn_msg(con_id, connectbuf[con_id]->pmtusize, connectbuf[con_id]->status);
392
        reschedule_conn_msg(con_id);
393
}
394

    
395
void
396
recv_conn_msg(struct msg_header *msg_h, char *msgbuf, int msg_size)
397
{
398
        struct conn_msg *con_msg;
399
        int free_con_id, con_id;
400

    
401
        time_t now = time(NULL);
402
        double timediff = 0.0;
403
        char str[1000];
404

    
405
        // Monitoring layer hook
406
        if(get_Recv_data_inf_cb != NULL && msg_h->len_mon_data_hdr != 0) {
407
                // update pointer to the real data
408
                msgbuf += msg_h->len_mon_data_hdr;
409
                msg_size -= msg_h->len_mon_data_hdr;
410
                con_msg = (struct conn_msg *)msgbuf;
411

    
412
                mon_data_inf recv_data_inf;
413
                recv_data_inf.remote_socketID = &(con_msg->sock_id);
414
                recv_data_inf.buffer = msgbuf;
415
                recv_data_inf.bufSize = msg_size;
416
                recv_data_inf.msgtype = msg_h->msg_type;
417
                recv_data_inf.monitoringDataHeaderLen = msg_h->len_mon_data_hdr;
418
                recv_data_inf.monitoringDataHeader = msg_h->len_mon_data_hdr ? msgbuf : NULL;
419
                gettimeofday(&recv_data_inf.arrival_time, NULL);
420
                recv_data_inf.firstPacketArrived = true;
421
                recv_data_inf.recvFragments = 1;
422
                recv_data_inf.priority = false;
423
                recv_data_inf.padding = false;
424
                recv_data_inf.confirmation = false;
425
                recv_data_inf.reliable = false;
426

    
427
                // send data recv callback to monitoring module
428
                (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
429
        } else {
430
                con_msg = (struct conn_msg *) msgbuf;
431
        }
432

    
433
        //decode sock_id for debug messages
434
        mlSocketIDToString(&con_msg->sock_id,str,999);
435

    
436
        // check the connection command type
437
        switch (con_msg->comand_type) {
438
                /*
439
                * if INVITE: enter a new socket make new entry in connect array
440
                * send an ok
441
                */
442
                case INVITE:
443
                        info("ML: received INVITE from %s (size:%d)\n", str, msg_size);
444
                        /*
445
                        * check if another connection for the external connectionID exist
446
                        * that was established within the last 2 seconds
447
                        */
448
                        free_con_id = -1;
449
                        for (con_id = 0; con_id < CONNECTBUFSIZE; con_id++) {
450
                                if (connectbuf[con_id] != NULL) {
451
                                        if (mlCompareSocketIDs(&(connectbuf[con_id]->external_socketID), &(con_msg->sock_id)) == 0) {
452
                                                //timediff = difftime(now, connectbuf[con_id]->starttime);        //TODO: why this timeout? Shouldn't the connection be closed instead if there is a timeout?
453
                                                //if (timediff < 2)
454
                                                //update remote connection ID
455
                                                if (connectbuf[con_id]->external_connectionID != msg_h->local_con_id) {
456
                                                        warn("ML: updating remote connection ID for %s: from %d to %d\n",str, connectbuf[con_id]->external_connectionID, msg_h->local_con_id);
457
                                                        connectbuf[con_id]->external_connectionID = msg_h->local_con_id;
458
                                                }
459
                                                break;
460
                                        }
461
                                } else if(free_con_id == -1)
462
                                        free_con_id = con_id;
463
                        }
464

    
465
                        if (con_id == CONNECTBUFSIZE) {
466
                                // create an entry in the connecttrybuf
467
                                if(free_con_id == -1) {
468
                                        error("ML: no new connect_buf available\n");
469
                                        return;
470
                                }
471
                                connectbuf[free_con_id] = (connect_data *) malloc(sizeof(connect_data));
472
                                memset(connectbuf[free_con_id],0,sizeof(connect_data));
473
                                connectbuf[free_con_id]->connection_head = connectbuf[free_con_id]->connection_last = NULL;
474
                                connectbuf[free_con_id]->starttime = time(NULL);
475
                                memcpy(&(connectbuf[free_con_id]->external_socketID), &(con_msg->sock_id), sizeof(socket_ID));
476
                                connectbuf[free_con_id]->pmtusize = con_msg->pmtu_size;        // bootstrap pmtu from the other's size. Not strictly needed, but a good hint
477
                                connectbuf[free_con_id]->timeout_event = NULL;
478
                                connectbuf[free_con_id]->external_connectionID = msg_h->local_con_id;
479
                                connectbuf[free_con_id]->internal_connect =
480
                                        !compare_external_address_socketIDs(&(con_msg->sock_id), loc_socketID);
481
                                con_id = free_con_id;
482
                        }
483

    
484
                        //if(connectbuf[con_id]->status <= CONNECT) { //TODO: anwer anyway. Why the outher would invite otherwise?
485
                                //update status and send back answer
486
                                connectbuf[con_id]->status = CONNECT;
487
                                send_conn_msg_with_pmtu_discovery(con_id, con_msg->pmtu_size, CONNECT);
488
                        //}
489
                        break;
490
                case CONNECT:
491
                        info("ML: received CONNECT from %s (size:%d)\n", str, msg_size);
492

    
493
                        if(msg_h->remote_con_id != -1 && connectbuf[msg_h->remote_con_id] == NULL) {
494
                                error("ML: received CONNECT for inexistent connection rconID:%d\n",msg_h->remote_con_id);
495
                                return;
496
                        }
497

    
498
                        /*
499
                        * check if the connection status is not already 1 or 2
500
                        */
501
                        if (connectbuf[msg_h->remote_con_id]->status == INVITE) {
502
                                // set the external connectionID
503
                                connectbuf[msg_h->remote_con_id]->external_connectionID = msg_h->local_con_id;
504
                                // change status con_msg the connection_data
505
                                connectbuf[msg_h->remote_con_id]->status = READY;
506
                                // change pmtusize in the connection_data: not needed. receiving a CONNECT means our INVITE went through. So why change pmtu?
507
                                //connectbuf[msg_h->remote_con_id]->pmtusize = con_msg->pmtu_size;
508

    
509
                                // send the READY
510
                                send_conn_msg_with_pmtu_discovery(msg_h->remote_con_id, con_msg->pmtu_size, READY);
511

    
512
                                if (receive_Connection_cb != NULL)
513
                                        (receive_Connection_cb) (msg_h->remote_con_id, NULL);
514

    
515
                                // call all registered callbacks
516
                                while(connectbuf[msg_h->remote_con_id]->connection_head != NULL) {
517
                                        struct receive_connection_cb_list *temp;
518
                                        temp = connectbuf[msg_h->remote_con_id]->connection_head;
519
                                        (temp->connection_cb) (msg_h->remote_con_id, temp->arg);
520
                                        connectbuf[msg_h->remote_con_id]->connection_head = temp->next;
521
                                        free(temp);
522
                                }
523
                                connectbuf[msg_h->remote_con_id]->connection_head =
524
                                        connectbuf[msg_h->remote_con_id]->connection_last = NULL;
525
                        } else {
526
                                // send the READY
527
                                send_conn_msg_with_pmtu_discovery(msg_h->remote_con_id, con_msg->pmtu_size, READY);
528
                        }
529

    
530
                        debug("ML: active connection established\n");
531
                        break;
532

    
533
                        /*
534
                        * if READY: find the entry in the connection array set the
535
                        * connection active change the pmtu size
536
                        */
537
                case READY:
538
                        info("ML: received READY from %s (size:%d)\n", str, msg_size);
539
                        if(connectbuf[msg_h->remote_con_id] == NULL) {
540
                                error("ML: received READY for inexistent connection\n");
541
                                return;
542
                        }
543
                        /*
544
                        * checks if the connection is not already established
545
                        */
546
                        if (connectbuf[msg_h->remote_con_id]->status == CONNECT) {
547
                                // change status of the connection
548
                                connectbuf[msg_h->remote_con_id]->status = READY;
549
                                // change pmtusize: not needed. pmtu doesn't have to be symmetric
550
                                //connectbuf[msg_h->remote_con_id]->pmtusize = con_msg->pmtu_size;
551

    
552
                                if (receive_Connection_cb != NULL)
553
                                        (receive_Connection_cb) (msg_h->remote_con_id, NULL);
554

    
555
                                while(connectbuf[msg_h->remote_con_id]->connection_head != NULL) {
556
                                        struct receive_connection_cb_list *temp;
557
                                        temp = connectbuf[msg_h->remote_con_id]->connection_head;
558
                                        (temp->connection_cb) (msg_h->remote_con_id, temp->arg);
559
                                        connectbuf[msg_h->remote_con_id]->connection_head = temp->next;
560
                                        free(temp);
561
                                }
562
                                connectbuf[msg_h->remote_con_id]->connection_head =
563
                                        connectbuf[msg_h->remote_con_id]->connection_last = NULL;
564
                                debug("ML: passive connection established\n");
565
                        }
566
                        break;
567
        }
568
}
569

    
570
void recv_stun_msg(char *msgbuf, int recvSize)
571
{
572
        /*
573
        * create empty stun message struct
574
        */
575
        StunMessage resp;
576
        memset(&resp, 0, sizeof(StunMessage));
577
        /*
578
        * parse the message
579
        */
580
        int returnValue = 0;
581
        returnValue = recv_stun_message(msgbuf, recvSize, &resp);
582

    
583
        if (returnValue == 0) {
584
                /*
585
                * read the reflexive Address into the local_socketID
586
                */
587
                struct sockaddr_in reflexiveAddr;
588
                reflexiveAddr.sin_family = AF_INET;
589
                reflexiveAddr.sin_addr.s_addr = htonl(resp.mappedAddress.ipv4.addr);
590
                reflexiveAddr.sin_port = htons(resp.mappedAddress.ipv4.port);
591
                socketaddrgen reflexiveAddres;
592
                reflexiveAddres.udpaddr = reflexiveAddr;
593
                local_socketID.external_addr = reflexiveAddres;
594
                NAT_traversal = true;
595
                // callback to the upper layer indicating that the socketID is now
596
                // ready to use
597
                (receive_SocketID_cb) (&local_socketID, 0);
598
        }
599
}
600

    
601
//done
602
void recv_timeout_cb(int fd, short event, void *arg)
603
{
604
        int recv_id = (long) arg;
605
        debug("ML: recv_timeout_cb called. Timeout for id:%d\n",recv_id);
606

    
607
        if (recvdatabuf[recv_id] == NULL) {
608
                return;
609
        }
610

    
611

    
612
/*        if(recvdatabuf[recv_id]->status == ACTIVE) {
613
                //TODO make timeout at least a DEFINE
614
                struct timeval timeout = { 4, 0 };
615
                recvdatabuf[recv_id]->status = INACTIVE;
616
                event_base_once(base, -1, EV_TIMEOUT, recv_timeout_cb,
617
                        arg, &timeout);
618
                return;
619
        }
620
*/
621

    
622
        if(recvdatabuf[recv_id]->status == ACTIVE) {
623
                // Monitoring layer hook
624
                if(get_Recv_data_inf_cb != NULL) {
625
                        mon_data_inf recv_data_inf;
626

    
627
                        recv_data_inf.remote_socketID =
628
                                        &(connectbuf[recvdatabuf[recv_id]->connectionID]->external_socketID);
629
                        recv_data_inf.buffer = recvdatabuf[recv_id]->recvbuf;
630
                        recv_data_inf.bufSize = recvdatabuf[recv_id]->bufsize;
631
                        recv_data_inf.msgtype = recvdatabuf[recv_id]->msgtype;
632
                        recv_data_inf.monitoringDataHeaderLen = recvdatabuf[recv_id]->monitoringDataHeaderLen;
633
                        recv_data_inf.monitoringDataHeader = recvdatabuf[recv_id]->monitoringDataHeaderLen ?
634
                                recvdatabuf[recv_id]->recvbuf : NULL;
635
                        gettimeofday(&recv_data_inf.arrival_time, NULL);
636
                        recv_data_inf.firstPacketArrived = recvdatabuf[recv_id]->firstPacketArrived;
637
                        recv_data_inf.recvFragments = recvdatabuf[recv_id]->recvFragments;
638
                        recv_data_inf.priority = false;
639
                        recv_data_inf.padding = false;
640
                        recv_data_inf.confirmation = false;
641
                        recv_data_inf.reliable = false;
642

    
643
                        // send data recv callback to monitoring module
644

    
645
                        (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
646
                }
647

    
648
                // Get the right callback
649
                receive_data_cb receive_data_callback = recvcbbuf[recvdatabuf[recv_id]->msgtype];
650

    
651
                recv_params rParams;
652

    
653
                rParams.nrMissingBytes = recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->arrivedBytes;
654
                rParams.recvFragments = recvdatabuf[recv_id]->recvFragments;
655
                rParams.msgtype = recvdatabuf[recv_id]->msgtype;
656
                rParams.connectionID = recvdatabuf[recv_id]->connectionID;
657
                rParams.remote_socketID =
658
                        &(connectbuf[recvdatabuf[recv_id]->connectionID]->external_socketID);
659
                rParams.firstPacketArrived = recvdatabuf[recv_id]->firstPacketArrived;
660

    
661
                (receive_data_callback) (recvdatabuf[recv_id]->recvbuf + recvdatabuf[recv_id]->monitoringDataHeaderLen, recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->monitoringDataHeaderLen,
662
                        recvdatabuf[recv_id]->msgtype, &rParams);
663

    
664
                //clean up
665
                free(recvdatabuf[recv_id]->recvbuf);
666
                free(recvdatabuf[recv_id]);
667
                recvdatabuf[recv_id] = NULL;
668
        }
669
}
670

    
671
// process a single recv data message
672
void recv_data_msg(struct msg_header *msg_h, char *msgbuf, int bufsize)
673
{
674
        debug("ML: received packet of size %d with rconID:%d lconID:%d type:%d offset:%d\n",bufsize,msg_h->remote_con_id,msg_h->local_con_id,msg_h->msg_type,msg_h->offset);
675

    
676
        int recv_id, free_recv_id = -1;
677

    
678
        if(connectbuf[msg_h->remote_con_id] == NULL) {
679
                debug("ML: Received a message not related to any opened connection!\n");
680
                return;
681
        }
682

    
683
        // check if a recv_data exist and enter data
684
        for (recv_id = 0; recv_id < RECVDATABUFSIZE; recv_id++)
685
                if (recvdatabuf[recv_id] != NULL) {
686
                        if (msg_h->remote_con_id == recvdatabuf[recv_id]->connectionID &&
687
                                        msg_h->msg_seq_num == recvdatabuf[recv_id]->seqnr)
688
                                                break;
689
                } else
690
                        if(free_recv_id == -1)
691
                                free_recv_id = recv_id;
692

    
693

    
694
        if(recv_id == RECVDATABUFSIZE) {
695
                //no recv_data found: create one
696
                recv_id = free_recv_id;
697
                recvdatabuf[recv_id] = (recvdata *) malloc(sizeof(recvdata));
698
                memset(recvdatabuf[recv_id], 0, sizeof(recvdata));
699
                recvdatabuf[recv_id]->connectionID = msg_h->remote_con_id;
700
                recvdatabuf[recv_id]->seqnr = msg_h->msg_seq_num;
701
                recvdatabuf[recv_id]->monitoringDataHeaderLen = msg_h->len_mon_data_hdr;
702
                recvdatabuf[recv_id]->bufsize = msg_h->msg_length + msg_h->len_mon_data_hdr;
703
                recvdatabuf[recv_id]->recvbuf = (char *) malloc(recvdatabuf[recv_id]->bufsize);
704
                /*
705
                * read the timeout data and set it
706
                */
707
                recvdatabuf[recv_id]->timeout_value = recv_timeout;
708
                recvdatabuf[recv_id]->timeout_event = NULL;
709
                recvdatabuf[recv_id]->recvID = recv_id;
710
                recvdatabuf[recv_id]->starttime = time(NULL);
711
                recvdatabuf[recv_id]->msgtype = msg_h->msg_type;
712

    
713
                // fill the buffer with zeros
714
                memset(recvdatabuf[recv_id]->recvbuf, 0, msg_h->msg_length);
715
                debug(" new @ id:%d\n",recv_id);
716
        } else {        //message structure already exists, no need to create new
717
                debug(" found @ id:%d (arrived before this packet: bytes:%d fragments%d\n",recv_id, recvdatabuf[recv_id]->arrivedBytes, recvdatabuf[recv_id]->recvFragments);
718
        }
719

    
720
        if (msg_h->offset == 0)
721
                recvdatabuf[recv_id]->firstPacketArrived = 1;
722

    
723

    
724
        // increment fragmentnr
725
        recvdatabuf[recv_id]->recvFragments++;
726
        // increment the arrivedBytes
727
        recvdatabuf[recv_id]->arrivedBytes += bufsize;
728

    
729
        // enter the data into the buffer
730
        memcpy(recvdatabuf[recv_id]->recvbuf + msg_h->offset, msgbuf, bufsize);
731

    
732
        //TODO very basic checkif all fragments arrived: has to be reviewed
733
        if(recvdatabuf[recv_id]->arrivedBytes == recvdatabuf[recv_id]->bufsize)
734
                recvdatabuf[recv_id]->status = COMPLETE; //buffer full -> msg completly arrived
735
        else
736
                recvdatabuf[recv_id]->status = ACTIVE;
737

    
738
        if (recv_data_callback) {
739
                if(recvdatabuf[recv_id]->status == COMPLETE) {
740
                        // Monitoring layer hook
741
                        if(get_Recv_data_inf_cb != NULL) {
742
                                mon_data_inf recv_data_inf;
743

    
744
                                recv_data_inf.remote_socketID =
745
                                         &(connectbuf[recvdatabuf[recv_id]->connectionID]->external_socketID);
746
                                recv_data_inf.buffer = recvdatabuf[recv_id]->recvbuf;
747
                                recv_data_inf.bufSize = recvdatabuf[recv_id]->bufsize;
748
                                recv_data_inf.msgtype = recvdatabuf[recv_id]->msgtype;
749
                                recv_data_inf.monitoringDataHeaderLen = recvdatabuf[recv_id]->monitoringDataHeaderLen;
750
                                recv_data_inf.monitoringDataHeader = recvdatabuf[recv_id]->monitoringDataHeaderLen ?
751
                                        recvdatabuf[recv_id]->recvbuf : NULL;
752
                                gettimeofday(&recv_data_inf.arrival_time, NULL);
753
                                recv_data_inf.firstPacketArrived = recvdatabuf[recv_id]->firstPacketArrived;
754
                                recv_data_inf.recvFragments = recvdatabuf[recv_id]->recvFragments;
755
                                recv_data_inf.priority = false;
756
                                recv_data_inf.padding = false;
757
                                recv_data_inf.confirmation = false;
758
                                recv_data_inf.reliable = false;
759

    
760
                                // send data recv callback to monitoring module
761

    
762
                                (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
763
                        }
764

    
765
                        // Get the right callback
766
                        receive_data_cb receive_data_callback = recvcbbuf[msg_h->msg_type];
767
                        if (receive_data_callback) {
768

    
769
                                recv_params rParams;
770

    
771
                                rParams.nrMissingBytes = recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->arrivedBytes;
772
                                rParams.recvFragments = recvdatabuf[recv_id]->recvFragments;
773
                                rParams.msgtype = recvdatabuf[recv_id]->msgtype;
774
                                rParams.connectionID = recvdatabuf[recv_id]->connectionID;
775
                                rParams.remote_socketID =
776
                                        &(connectbuf[recvdatabuf[recv_id]->connectionID]->external_socketID);
777

    
778
                                char str[1000];
779
                                mlSocketIDToString(rParams.remote_socketID,str,999);
780
                                debug("ML: received message from conID:%d, %s\n",recvdatabuf[recv_id]->connectionID,str);
781
                                rParams.firstPacketArrived = recvdatabuf[recv_id]->firstPacketArrived;
782

    
783
                                (receive_data_callback) (recvdatabuf[recv_id]->recvbuf + recvdatabuf[recv_id]->monitoringDataHeaderLen, recvdatabuf[recv_id]->bufsize - recvdatabuf[recv_id]->monitoringDataHeaderLen,
784
                                        recvdatabuf[recv_id]->msgtype, (void *) &rParams);
785
                        } else {
786
                            warn("ML: callback not initialized for this message type: %d!\n",msg_h->msg_type);
787
                        }
788

    
789
                        //clean up
790
                        if (recvdatabuf[recv_id]->timeout_event) {
791
                                int ret;
792
                                debug("ML: freeing timeout for %d",recv_id);
793
                                ret = event_del(recvdatabuf[recv_id]->timeout_event);
794
                                event_free(recvdatabuf[recv_id]->timeout_event);
795
                                recvdatabuf[recv_id]->timeout_event = NULL;
796
                                debug(" ret: %d\n",ret);
797
                        } else {
798
                                debug("ML: received in 1 packet\n",recv_id);
799
                        }
800
                        free(recvdatabuf[recv_id]->recvbuf);
801
                        free(recvdatabuf[recv_id]);
802
                        recvdatabuf[recv_id] = NULL;
803
                } else { // not COMPLETE
804
                        if (!recvdatabuf[recv_id]->timeout_event) {
805
                                //start time out
806
                                //TODO make timeout at least a DEFINE
807
                                recvdatabuf[recv_id]->timeout_event = event_new(base, -1, EV_TIMEOUT, &recv_timeout_cb, (void *) (long)recv_id);
808
                                evtimer_add(recvdatabuf[recv_id]->timeout_event, &recv_timeout);
809
                        }
810
                }
811
        }
812
}
813

    
814
//done
815
void pmtu_timeout_cb(int fd, short event, void *arg)
816
{
817

    
818
        int con_id = (long) arg;
819
        pmtu new_pmtusize;
820

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

    
823
        if(connectbuf[con_id] == NULL) {
824
                error("ML: pmtu timeout called on non existing con_id\n");
825
                return;
826
        }
827

    
828
        if(connectbuf[con_id]->status == READY) {
829
                // nothing to do anymore
830
                event_del(connectbuf[con_id]->timeout_event);
831
                event_free(connectbuf[con_id]->timeout_event);
832
                connectbuf[con_id]->timeout_event = NULL;
833
                return;
834
        }
835

    
836
        info("ML: pmtu timeout while connecting(to:%s lcon:%d status:%d size:%d trial:%d tout:%ld.%06ld)\n",conid_to_string(con_id), con_id, connectbuf[con_id]->status, connectbuf[con_id]->pmtusize, connectbuf[con_id]->trials, connectbuf[con_id]->timeout_value.tv_sec, connectbuf[con_id]->timeout_value.tv_usec);
837

    
838
        if(connectbuf[con_id]->delay || connectbuf[con_id]->trials == MAX_TRIALS - 1) {
839
                double delay = connectbuf[con_id]->timeout_value.tv_sec + connectbuf[con_id]->timeout_value.tv_usec / 1000000.0;
840
                delay = delay * 2;
841
                info("\tML: increasing pmtu timeout to %f sec\n", delay);
842
                connectbuf[con_id]->timeout_value.tv_sec = floor(delay);
843
                connectbuf[con_id]->timeout_value.tv_usec = fmod(delay, 1.0) * 1000000.0;
844
                if(connectbuf[con_id]->delay) {
845
                        connectbuf[con_id]->delay = false;
846
                        reschedule_conn_msg(con_id);
847
                }
848
        }
849

    
850
        if(connectbuf[con_id]->trials == MAX_TRIALS) {
851
                // decrement the pmtu size
852
                struct timeval tout = PMTU_TIMEOUT;
853
                info("\tML: decreasing pmtu estimate from %d to %d\n", connectbuf[con_id]->pmtusize, pmtu_decrement(connectbuf[con_id]->pmtusize));
854
                connectbuf[con_id]->pmtusize = pmtu_decrement(connectbuf[con_id]->pmtusize);
855
                connectbuf[con_id]->timeout_value = tout; 
856
                connectbuf[con_id]->trials = 0;
857
        }
858

    
859
        //error in PMTU discovery?
860
        if (connectbuf[con_id]->pmtusize == ERROR) {
861
                if (connectbuf[con_id]->internal_connect == true) {
862
                        //as of now we tried directly connecting, now let's try trough the NAT
863
                        connectbuf[con_id]->internal_connect = false;
864
                        connectbuf[con_id]->pmtusize = MAX;
865
                } else {
866
                        //nothing to do we have to give up
867
                        error("ML: Could not create connection with connectionID %i!\n",con_id);
868
                        // envoke the callback for failed connection establishment
869
                        if(failed_Connection_cb != NULL)
870
                                (failed_Connection_cb) (con_id, NULL);
871
                        // delete the connection entry
872
                        mlCloseConnection(con_id);
873
                        return;
874
                }
875
        }
876

    
877
        //retry
878
        resend_conn_msg(con_id);
879
}
880

    
881

    
882
int schedule_pmtu_timeout(int con_id)
883
{
884
        if (! connectbuf[con_id]->timeout_event) {
885
                struct timeval tout = PMTU_TIMEOUT;
886
                connectbuf[con_id]->timeout_value = tout;
887
                connectbuf[con_id]->trials = 1;
888
                connectbuf[con_id]->timeout_event = event_new(base, -1, EV_TIMEOUT, &pmtu_timeout_cb, (void *) (long)con_id);
889
                evtimer_add(connectbuf[con_id]->timeout_event, &connectbuf[con_id]->timeout_value);
890
        }
891
}
892

    
893
/*
894
 * decrements the mtu size
895
 */
896
pmtu pmtu_decrement(pmtu pmtusize)
897
{
898
        pmtu pmtu_return_size;
899
        switch(pmtusize) {
900
        case MAX:
901
                return DSL;
902
        case DSL:
903
                return DSLMEDIUM;
904
        case DSLMEDIUM:
905
                return DSLSLIM;
906
        case DSLSLIM:
907
                return BELOWDSL;
908
        case BELOWDSL:
909
                return MIN;
910
        case MIN:
911
                return ERROR;
912
        default:
913
                warn("ML: strange pmtu size encountered:%d, changing to some safe value:%d\n", pmtusize, MIN);
914
                return MIN;
915
        }
916
}
917

    
918
// called when an ICMP pmtu error message (type 3, code 4) is received
919
void pmtu_error_cb_th(char *msg, int msglen)
920
{
921
        debug("ML: pmtu_error callback called msg_size: %d\n",msglen);
922
        //TODO debug
923
        return;
924

    
925
    char *msgbufptr = NULL;
926
    int msgtype;
927
    int connectionID;
928
    pmtu pmtusize;
929
    pmtu new_pmtusize;
930
    int dead = 0;
931

    
932
    // check the packettype
933
    msgbufptr = &msg[0];
934

    
935
    // check the msgtype
936
    msgbufptr = &msg[1];
937
    memcpy(&msgtype, msgbufptr, 4);
938

    
939
    if (msgtype == 0) {
940

    
941
        // get the connectionID
942
        msgbufptr = &msg[5];
943
        memcpy(&connectionID, msgbufptr, 4);
944

    
945
        int msgtype_c = connectbuf[connectionID]->status;
946
//        pmtusize = connectbuf[connectionID]->pmtutrysize;
947

    
948
        if (msgtype_c != msgtype) {
949
            dead = 1;
950
        }
951

    
952

    
953
    } else if (msgtype == 1) {
954

    
955
        // read the connectionID
956
        msgbufptr = &msg[9];
957
        memcpy(&connectionID, msgbufptr, 4);
958

    
959
        int msgtype_c = connectbuf[connectionID]->status;
960
//        pmtusize = connectbuf[connectionID]->pmtutrysize;
961

    
962
        if (msgtype_c != msgtype) {
963
            dead = 1;
964
        }
965

    
966
    }
967
    // decrement the pmtu size
968
    new_pmtusize = pmtu_decrement(pmtusize);
969

    
970
//    connectbuf[connectionID]->pmtutrysize = new_pmtusize;
971

    
972
    if (new_pmtusize == ERROR) {
973
                error("ML:  Could not create connection with connectionID %i !\n",
974
                        connectionID);
975

    
976
                if(failed_Connection_cb != NULL)
977
                        (failed_Connection_cb) (connectionID, NULL);
978
                // set the message type to a non existent message
979
                msgtype = 2;
980
                // delete the connection entry
981
                 mlCloseConnection(connectionID);
982
        }
983

    
984
    if (msgtype == 0 && dead != 1) {
985

    
986
        // stop the timeout event
987
        // timeout_del(connectbuf[connectionID]->timeout);
988
        /*
989
         * libevent2
990
         */
991

    
992
        // event_del(connectbuf[connectionID]->timeout);
993

    
994

    
995
        // create and send a connection message
996
//         create_conn_msg(new_pmtusize, connectionID,
997
//                         &local_socketID, INVITE);
998

    
999
//        send_conn_msg(connectionID, new_pmtusize);
1000

    
1001
        // set a timeout event for the pmtu discovery
1002
        // timeout_set(connectbuf[connectionID]->timeout,pmtu_timeout_cb,(void
1003
        // *)&connectionID);
1004

    
1005
        // timeout_add(connectbuf[connectionID]->timeout,&connectbuf[connectionID]->timeout_value);
1006

    
1007
        /*
1008
         * libevent2
1009
         */
1010

    
1011
        struct event *ev;
1012
        ev = evtimer_new(base, pmtu_timeout_cb,
1013
                         (void *) connectbuf[connectionID]);
1014

    
1015
        // connectbuf[connectionID]->timeout = ev;
1016

    
1017
        event_add(ev, &connectbuf[connectionID]->timeout_value);
1018

    
1019
    } else if (msgtype == 1 && dead != 1) {
1020

    
1021
        // stop the timeout event
1022
        // timeout_del(connectbuf[connectionID]->timeout);
1023

    
1024
        /*
1025
         * libevent2
1026
         */
1027
        // info("still here 11 \n");
1028
        // printf("ev %d \n",connectbuf[connectionID]->timeout);
1029
        // event_del(connectbuf[connectionID]->timeout );
1030
        // evtimer_del(connectbuf[connectionID]->timeout );
1031

    
1032

    
1033
//         // create and send a connection message
1034
//         create_conn_msg(new_pmtusize,
1035
//                         connectbuf[connectionID]->connectionID,
1036
//                         NULL, CONNECT);
1037

    
1038
        //send_conn_msg(connectionID, new_pmtusize);
1039

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

    
1045
        /*
1046
         * libevent2
1047
         */
1048
        // struct event *ev;
1049
        // ev = evtimer_new(base,pmtu_timeout_cb, (void
1050
        // *)connectbuf[connectionID]);
1051
        // connectbuf[connectionID]->timeout = ev;
1052
        // event_add(ev,&connectbuf[connectionID]->timeout_value);
1053

    
1054
    }
1055
}
1056

    
1057
/*
1058
 * what to do once a packet arrived if it is a conn packet send it to
1059
 * recv_conn handler if it is a data packet send it to the recv_data
1060
 * handler
1061
 */
1062

    
1063
//done --
1064
void recv_pkg(int fd, short event, void *arg)
1065
{
1066
        debug("ML: recv_pkg called\n");
1067

    
1068
        struct msg_header *msg_h;
1069
        char msgbuf[MAX];
1070
        pmtu recvSize = MAX;
1071
        char *bufptr = msgbuf;
1072
        int ttl;
1073
        struct sockaddr_in recv_addr;
1074
        int msg_size;
1075

    
1076
        recvPacket(fd, msgbuf, &recvSize, &recv_addr, pmtu_error_cb_th, &ttl);
1077

    
1078

    
1079
        // check if it is not just an ERROR message
1080
        if(recvSize < 0)
1081
                return;
1082

    
1083
        // @TODO check if this simplistic STUN message recognition really always works, probably not
1084
        unsigned short stun_bind_response = 0x0101;
1085
        unsigned short * msgspot = (unsigned short *) msgbuf;
1086
        if (*msgspot == stun_bind_response) {
1087
                debug("ML: recv_pkg: parse stun message called\n");
1088
                recv_stun_msg(msgbuf, recvSize);
1089
                return;
1090
        }
1091

    
1092
        msg_h = (struct msg_header *) msgbuf;
1093
        bufptr += MSG_HEADER_SIZE + msg_h->len_mon_packet_hdr;
1094
        msg_size = recvSize - MSG_HEADER_SIZE - msg_h->len_mon_packet_hdr;
1095

    
1096

    
1097
        if(get_Recv_pkt_inf_cb != NULL && msg_h->len_mon_packet_hdr != 0) {
1098
                mon_pkt_inf msginfNow;
1099
                msginfNow.monitoringHeaderLen = msg_h->len_mon_packet_hdr;
1100
                msginfNow.monitoringHeader = msg_h->len_mon_packet_hdr ? &msgbuf[0] + MSG_HEADER_SIZE : NULL;
1101
                //TODO rethink this ...
1102
                if(msg_h->msg_type == ML_CON_MSG) {
1103
                        struct conn_msg *c_msg = (struct conn_msg *) bufptr;
1104
                        msginfNow.remote_socketID = &(c_msg->sock_id);
1105
                }
1106
                else if(connectbuf[msg_h->remote_con_id] == NULL) {
1107
                        error("ML: received pkg called with non existent connection\n");
1108
                        return;
1109
                } else
1110
                        msginfNow.remote_socketID = &(connectbuf[msg_h->remote_con_id]->external_socketID);
1111
                msginfNow.buffer = bufptr;
1112
                msginfNow.bufSize = recvSize;
1113
                msginfNow.msgtype = msg_h->msg_type;
1114
                msginfNow.ttl = ttl;
1115
                msginfNow.dataID = msg_h->msg_seq_num;
1116
                msginfNow.offset = msg_h->offset;
1117
                msginfNow.datasize = msg_h->msg_length;
1118
                gettimeofday(&msginfNow.arrival_time, NULL);
1119
                (get_Recv_pkt_inf_cb) ((void *) &msginfNow);
1120
        }
1121

    
1122

    
1123
        switch(msg_h->msg_type) {
1124
                case ML_CON_MSG:
1125
                        debug("ML: received conn pkg\n");
1126
                        recv_conn_msg(msg_h, bufptr, msg_size);
1127
                        break;
1128
                default:
1129
                        if(msg_h->msg_type < 127) {
1130
                                debug("ML: received data pkg\n");
1131
                                recv_data_msg(msg_h, bufptr, msg_size);
1132
                                break;
1133
                        }
1134
                        debug("ML: unrecognised msg_type\n");
1135
                        break;
1136
        }
1137
}
1138

    
1139
/*
1140
 * compare the external IP address of two socketIDs
1141
 */
1142
int
1143
compare_external_address_socketIDs(socketID_handle sock1, socketID_handle sock2)
1144
{
1145
        if( sock1->external_addr.udpaddr.sin_addr.s_addr == sock2->external_addr.udpaddr.sin_addr.s_addr)
1146
                return 0;
1147
        return 1;
1148
}
1149

    
1150
void try_stun();
1151

    
1152
/*
1153
 * the timeout of the NAT traversal
1154
 */
1155
void nat_traversal_timeout(int fd, short event, void *arg)
1156
{
1157
        if (NAT_traversal == false) {
1158
                debug("ML: NAT traversal request re-send\n");
1159
                if(receive_SocketID_cb)
1160
                        (receive_SocketID_cb) (&local_socketID, 2);
1161
                try_stun();
1162
        }
1163
}
1164

    
1165
//return IP address, or INADDR_NONE if can't resolve
1166
unsigned long resolve(const char *ipaddr)
1167
{
1168
        struct hostent *h = gethostbyname(ipaddr);
1169
        if (!h) {
1170
                error("ML: Unable to resolve host name %s\n", ipaddr);
1171
                return INADDR_NONE;
1172
        }
1173
        unsigned long *addr = (unsigned long *) (h->h_addr);
1174
        return *addr;
1175
}
1176

    
1177

    
1178
/*
1179
 * returns the file descriptor, or <0 on error. The ipaddr can be a null
1180
 * pointer. Then all available ipaddr on the machine are choosen.
1181
 */
1182
int create_socket(const int port, const char *ipaddr)
1183
{
1184
        struct sockaddr_in udpaddr;
1185
        udpaddr.sin_family = AF_INET;
1186
        if (ipaddr == NULL) {
1187
                /*
1188
                * try to guess the local IP address
1189
                */
1190
                const char *ipaddr_iface = mlAutodetectIPAddress();
1191
                if (ipaddr_iface) {
1192
                        udpaddr.sin_addr.s_addr = inet_addr(ipaddr_iface);
1193
                } else {
1194
                        udpaddr.sin_addr.s_addr = INADDR_ANY;
1195
                }
1196
        } else {
1197
                udpaddr.sin_addr.s_addr = inet_addr(ipaddr);
1198
        }
1199
        udpaddr.sin_port = htons(port);
1200

    
1201
        socketaddrgen udpgen;
1202
        memset(&udpgen,0,sizeof(socketaddrgen));        //this will be sent over the net, so set it to 0
1203
        udpgen.udpaddr = udpaddr;
1204
        local_socketID.internal_addr = udpgen;
1205

    
1206
        socketfd = createSocket(port, ipaddr);
1207
        if (socketfd < 0){
1208
                return socketfd;
1209
        }
1210

    
1211
        struct event *ev;
1212
        ev = event_new(base, socketfd, EV_READ | EV_PERSIST, recv_pkg, NULL);
1213

    
1214
        event_add(ev, NULL);
1215

    
1216
        try_stun();
1217

    
1218
        return socketfd;
1219
}
1220

    
1221
/*
1222
 * try to figure out external IP using STUN, if defined
1223
 */
1224
void try_stun()
1225
{
1226
        if (isStunDefined()) {
1227
                /*
1228
                * send the NAT traversal STUN request
1229
                */
1230
                 send_stun_request(socketfd, &stun_server);
1231

    
1232
                /*
1233
                * enter a NAT traversal timeout that takes care of retransmission
1234
                */
1235
                struct event *ev1;
1236
                struct timeval timeout_value_NAT_traversal = NAT_TRAVERSAL_TIMEOUT;
1237
                ev1 = evtimer_new(base, nat_traversal_timeout, NULL);
1238
                event_add(ev1, &timeout_value_NAT_traversal);
1239

    
1240
                NAT_traversal = false;
1241
        } else {
1242
                /*
1243
                * Assume we have accessibility and copy internal address to external one
1244
                */
1245
                local_socketID.external_addr = local_socketID.internal_addr;
1246
                NAT_traversal = true; // @TODO: this is not really NAT traversal, but a flag that init is over
1247
                // callback to the upper layer indicating that the socketID is now
1248
                // ready to use
1249
                if(receive_SocketID_cb)
1250
                        (receive_SocketID_cb) (&local_socketID, 0); //success
1251
        }
1252
}
1253

    
1254
/**************************** END OF INTERNAL ***********************/
1255

    
1256
/**************************** MONL functions *************************/
1257

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

    
1260
        base = (struct event_base *) arg;
1261
        recv_data_callback = recv_data_cb;
1262
        mlSetRecvTimeout(timeout_value);
1263
        if (stun_ipaddr) {
1264
                 mlSetStunServer(stun_port, stun_ipaddr);
1265
        } else {
1266

    
1267
        }
1268
        register_recv_localsocketID_cb(local_socketID_cb);
1269
        return create_socket(port, ipaddr);
1270
}
1271

    
1272
/* register callbacks  */
1273
void mlRegisterGetRecvPktInf(get_recv_pkt_inf_cb recv_pkt_inf_cb){
1274

    
1275
        if (recv_pkt_inf_cb == NULL)
1276
                error("ML: Register get_recv_pkt_inf_cb failed: NULL ptr  \n");
1277
        else
1278
                get_Recv_pkt_inf_cb = recv_pkt_inf_cb;
1279

    
1280
}
1281

    
1282
void mlRegisterGetSendPktInf(get_send_pkt_inf_cb  send_pkt_inf_cb){
1283

    
1284
        if (send_pkt_inf_cb == NULL)
1285
                error("ML: Register get_send_pkt_inf_cb: NULL ptr  \n");
1286
        else
1287
                get_Send_pkt_inf_cb = send_pkt_inf_cb;
1288

    
1289
}
1290

    
1291

    
1292
void mlRegisterSetMonitoringHeaderPktCb(set_monitoring_header_pkt_cb monitoring_header_pkt_cb ){
1293

    
1294
        if (monitoring_header_pkt_cb == NULL)
1295
                error("ML: Register set_monitoring_header_pkt_cb: NULL ptr  \n");
1296
        else
1297
                set_Monitoring_header_pkt_cb = monitoring_header_pkt_cb;
1298

    
1299
}
1300

    
1301
void mlRegisterGetRecvDataInf(get_recv_data_inf_cb recv_data_inf_cb){
1302

    
1303
        if (recv_data_inf_cb == NULL)
1304
                error("ML: Register get_recv_data_inf_cb: NULL ptr  \n");
1305
        else
1306
                get_Recv_data_inf_cb = recv_data_inf_cb;
1307

    
1308
}
1309

    
1310
void mlRegisterGetSendDataInf(get_send_data_inf_cb  send_data_inf_cb){
1311

    
1312
        if (send_data_inf_cb == NULL)
1313
                error("ML: Register get_send_data_inf_cb: NULL ptr  \n");
1314
        else
1315
                get_Send_data_inf_cb = send_data_inf_cb;
1316

    
1317
}
1318

    
1319
void mlRegisterSetMonitoringHeaderDataCb(set_monitoring_header_data_cb monitoring_header_data_cb){
1320

    
1321
        if (monitoring_header_data_cb == NULL)
1322
                error("ML: Register set_monitoring_header_data_cb : NULL ptr  \n");
1323
        else
1324
        set_Monitoring_header_data_cb = monitoring_header_data_cb;
1325

    
1326
}
1327

    
1328
void mlSetRecvTimeout(struct timeval timeout_value){
1329

    
1330
        recv_timeout = timeout_value;
1331

    
1332
}
1333

    
1334
int mlGetStandardTTL(socketID_handle socketID,uint8_t *ttl){
1335

    
1336
        return getTTL(socketfd, ttl);
1337

    
1338
}
1339

    
1340
socketID_handle mlGetLocalSocketID(int *errorstatus){
1341

    
1342
        if (NAT_traversal == false) {
1343
                *errorstatus = 2;
1344
                return NULL;
1345
        }
1346

    
1347
        *errorstatus = 0;
1348
        return &local_socketID;
1349

    
1350
}
1351

    
1352

    
1353
/**************************** END of MONL functions *************************/
1354

    
1355
/**************************** GENERAL functions *************************/
1356

    
1357
void mlRegisterRecvConnectionCb(receive_connection_cb recv_conn_cb){
1358

    
1359
        if (recv_conn_cb == NULL)
1360
                error("ML: Register receive_connection_cb: NULL ptr  \n");
1361
        else
1362
                receive_Connection_cb = recv_conn_cb;
1363

    
1364
}
1365

    
1366
void mlRegisterErrorConnectionCb(connection_failed_cb conn_failed){
1367

    
1368
        if (conn_failed == NULL)
1369
                error("ML: Register connection_failed_cb: NULL ptr  \n");
1370
        else
1371
        failed_Connection_cb = conn_failed;
1372

    
1373
}
1374

    
1375
void mlRegisterRecvDataCb(receive_data_cb data_cb,unsigned char msgtype){
1376

    
1377
    if (msgtype > 126) {
1378

    
1379
            error
1380
            ("ML: Could not register recv_data callback. Msgtype is greater then 126 \n");
1381

    
1382
    }
1383

    
1384
    if (data_cb == NULL) {
1385

    
1386
            error("ML: Register receive data callback: NUll ptr \n ");
1387

    
1388
    } else {
1389

    
1390
        recvcbbuf[msgtype] = data_cb;
1391

    
1392
    }
1393

    
1394
}
1395

    
1396
void mlCloseSocket(socketID_handle socketID){
1397

    
1398
        free(socketID);
1399

    
1400
}
1401

    
1402
void keepalive_fn(evutil_socket_t fd, short what, void *arg) {
1403
        socketID_handle peer = arg;
1404

    
1405
        int con_id = mlConnectionExist(peer, false);
1406
        if (con_id < 0 || connectbuf[con_id]->defaultSendParams.keepalive <= 0) {
1407
                /* Connection fell from under us or keepalive was disabled */
1408
                free(arg);
1409
                return;
1410
        }
1411

    
1412
        /* do what we gotta do */
1413
        if ( connectbuf[con_id]->status == READY) {
1414
                char keepaliveMsg[32] = "";
1415
                sprintf(keepaliveMsg, "KEEPALIVE %d", connectbuf[con_id]->keepalive_seq++);
1416
                send_msg(con_id, MSG_TYPE_ML_KEEPALIVE, keepaliveMsg, 1 + strlen(keepaliveMsg), false, 
1417
                        &(connectbuf[con_id]->defaultSendParams));
1418
        }
1419

    
1420
        /* re-schedule */
1421
        struct timeval t = { 0,0 };
1422
        t.tv_sec = connectbuf[con_id]->defaultSendParams.keepalive;
1423
        if (connectbuf[con_id]->defaultSendParams.keepalive) 
1424
                event_base_once(base, -1, EV_TIMEOUT, keepalive_fn, peer, &t);
1425
}
1426

    
1427
void setupKeepalive(int conn_id) {
1428
        /* Save the peer's address for us */
1429
        socketID_handle peer = malloc(sizeof(socket_ID));
1430
        memcpy(peer, &connectbuf[conn_id]->external_socketID, sizeof(socket_ID));
1431

    
1432
        struct timeval t = { 0,0 };
1433
        t.tv_sec = connectbuf[conn_id]->defaultSendParams.keepalive;
1434

    
1435
        if (connectbuf[conn_id]->defaultSendParams.keepalive) 
1436
                event_base_once(base, -1, EV_TIMEOUT, keepalive_fn, peer, &t);
1437
}
1438

    
1439
/* connection functions */
1440
int mlOpenConnection(socketID_handle external_socketID,receive_connection_cb connection_cb,void *arg, const send_params defaultSendParams){
1441

    
1442
        int con_id;
1443
        if (external_socketID == NULL) {
1444
                error("ML: cannot open connection: one of the socketIDs is NULL\n");
1445
                return -1;
1446
        }
1447
        if (NAT_traversal == false) {
1448
                error("ML: cannot open connection: NAT traversal for socketID still in progress\n");
1449
                return -1;
1450
        }
1451
        if (connection_cb == NULL) {
1452
                error("ML: cannot open connection: connection_cb is NULL\n");
1453
                return -1;
1454
        }
1455

    
1456
        // check if that connection already exist
1457

    
1458
        con_id = mlConnectionExist(external_socketID, false);
1459
        if (con_id >= 0) {
1460
                // overwrite defaultSendParams
1461
                bool newKeepalive = 
1462
                        connectbuf[con_id]->defaultSendParams.keepalive == 0 && defaultSendParams.keepalive != 0;
1463
                connectbuf[con_id]->defaultSendParams = defaultSendParams;
1464
                if (newKeepalive) setupKeepalive(con_id);
1465
                // if so check if it is ready to use
1466
                if (connectbuf[con_id]->status == READY) {
1467
                                // if so use the callback immediately
1468
                                (connection_cb) (con_id, arg);
1469

    
1470
                // otherwise just write the connection cb and the arg pointer
1471
                // into the connection struct
1472
                } else {
1473
                        struct receive_connection_cb_list *temp;
1474
                        temp = malloc(sizeof(struct receive_connection_cb_list));
1475
                        temp->next = NULL;
1476
                        temp->connection_cb = connection_cb;
1477
                        temp->arg = arg;
1478
                        if(connectbuf[con_id]->connection_last != NULL) {
1479
                                connectbuf[con_id]->connection_last->next = temp;
1480
                                connectbuf[con_id]->connection_last = temp;
1481
                        } else
1482
                                connectbuf[con_id]->connection_last = connectbuf[con_id]->connection_head = temp;
1483
                }
1484
                return con_id;
1485
        }
1486
        // make entry in connection_establishment array
1487
        for (con_id = 0; con_id < CONNECTBUFSIZE; con_id++) {
1488
                if (connectbuf[con_id] == NULL) {
1489
                        connectbuf[con_id] = (connect_data *) malloc(sizeof(connect_data));
1490
                        memset(connectbuf[con_id],0,sizeof(connect_data));
1491
                        connectbuf[con_id]->starttime = time(NULL);
1492
                        memcpy(&connectbuf[con_id]->external_socketID, external_socketID, sizeof(socket_ID));
1493
                        connectbuf[con_id]->pmtusize = DSLSLIM;
1494
                        connectbuf[con_id]->timeout_event = NULL;
1495
                        connectbuf[con_id]->status = INVITE;
1496
                        connectbuf[con_id]->seqnr = 0;
1497
                        connectbuf[con_id]->internal_connect = !compare_external_address_socketIDs(external_socketID, &local_socketID);
1498
                        connectbuf[con_id]->connectionID = con_id;
1499

    
1500
                        connectbuf[con_id]->connection_head = connectbuf[con_id]->connection_last = malloc(sizeof(struct receive_connection_cb_list));
1501
                        connectbuf[con_id]->connection_last->next = NULL;
1502
                        connectbuf[con_id]->connection_last->connection_cb = connection_cb;
1503
                        connectbuf[con_id]->connection_last->arg = arg;
1504
                        connectbuf[con_id]->external_connectionID = -1;
1505

    
1506
                        connectbuf[con_id]->defaultSendParams = defaultSendParams;
1507
                        if (defaultSendParams.keepalive) setupKeepalive(con_id);
1508
                        break;
1509
                }
1510
        } //end of for
1511

    
1512
        if (con_id == CONNECTBUFSIZE) {
1513
                error("ML: Could not open connection: connection buffer full\n");
1514
                return -1;
1515
        }
1516

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

    
1521
        return con_id;
1522

    
1523
}
1524

    
1525
void mlCloseConnection(const int connectionID){
1526

    
1527
        // remove it from the connection array
1528
        if(connectbuf[connectionID]) {
1529
                if(connectbuf[connectionID]->ctrl_msg_buf) {
1530
                        free(connectbuf[connectionID]->ctrl_msg_buf);
1531
                }
1532
                // remove related events
1533
                if (connectbuf[connectionID]->timeout_event) {
1534
                        event_del(connectbuf[connectionID]->timeout_event);
1535
                        event_free(connectbuf[connectionID]->timeout_event);
1536
                        connectbuf[connectionID]->timeout_event = NULL;
1537
                }
1538
                free(connectbuf[connectionID]);
1539
                connectbuf[connectionID] = NULL;
1540
        }
1541

    
1542
}
1543

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

    
1546
        if (connectionID < 0) {
1547
                error("ML: send data failed: connectionID does not exist\n");
1548
                return;
1549
        }
1550

    
1551
        if (connectbuf[connectionID] == NULL) {
1552
                error("ML: send data failed: connectionID does not exist\n");
1553
                return;
1554
        }
1555
        if (connectbuf[connectionID]->status != READY) {
1556
            error("ML: send data failed: connection is not active\n");
1557
            return;
1558
        }
1559

    
1560
        if (sParams == NULL) {
1561
                sParams = &(connectbuf[connectionID]->defaultSendParams);
1562
        }
1563

    
1564
        send_msg(connectionID, msgtype, sendbuf, bufsize, false, sParams);
1565

    
1566
}
1567

    
1568
/* transmit data functions  */
1569
int mlSendAllData(const int connectionID,send_all_data_container *container,int nr_entries,unsigned char msgtype,send_params *sParams){
1570

    
1571
    if (nr_entries < 1 || nr_entries > 5) {
1572

    
1573
        error
1574
            ("ML : sendALlData : nr_enties is not between 1 and 5 \n ");
1575
        return 0;
1576

    
1577
    } else {
1578

    
1579
        if (nr_entries == 1) {
1580

    
1581
                mlSendData(connectionID, container->buffer_1,
1582
                      container->length_1, msgtype, sParams);
1583

    
1584
            return 1;
1585

    
1586
        } else if (nr_entries == 2) {
1587

    
1588
            int buflen = container->length_1 + container->length_2;
1589
            char buf[buflen];
1590
            memcpy(buf, container->buffer_1, container->length_1);
1591
            memcpy(&buf[container->length_1], container->buffer_2,
1592
                   container->length_2);
1593
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1594

    
1595
            return 1;
1596

    
1597
        } else if (nr_entries == 3) {
1598

    
1599
            int buflen =
1600
                container->length_1 + container->length_2 +
1601
                container->length_3;
1602
            char buf[buflen];
1603
            memcpy(buf, container->buffer_1, container->length_1);
1604
            memcpy(&buf[container->length_1], container->buffer_2,
1605
                   container->length_2);
1606
            memcpy(&buf[container->length_2], container->buffer_3,
1607
                   container->length_3);
1608
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1609

    
1610

    
1611
            return 1;
1612

    
1613
        } else if (nr_entries == 4) {
1614

    
1615
            int buflen =
1616
                container->length_1 + container->length_2 +
1617
                container->length_3 + container->length_4;
1618
            char buf[buflen];
1619
            memcpy(buf, container->buffer_1, container->length_1);
1620
            memcpy(&buf[container->length_1], container->buffer_2,
1621
                   container->length_2);
1622
            memcpy(&buf[container->length_2], container->buffer_3,
1623
                   container->length_3);
1624
            memcpy(&buf[container->length_3], container->buffer_4,
1625
                   container->length_4);
1626
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1627

    
1628
            return 1;
1629

    
1630
        } else {
1631

    
1632
            int buflen =
1633
                container->length_1 + container->length_2 +
1634
                container->length_3 + container->length_4 +
1635
                container->length_5;
1636
            char buf[buflen];
1637
            memcpy(buf, container->buffer_1, container->length_1);
1638
            memcpy(&buf[container->length_1], container->buffer_2,
1639
                   container->length_2);
1640
            memcpy(&buf[container->length_2], container->buffer_3,
1641
                   container->length_3);
1642
            memcpy(&buf[container->length_3], container->buffer_4,
1643
                   container->length_4);
1644
            memcpy(&buf[container->length_4], container->buffer_5,
1645
                   container->length_5);
1646
            mlSendData(connectionID, buf, buflen, msgtype, sParams);
1647

    
1648
            return 1;
1649
        }
1650

    
1651
    }
1652

    
1653
}
1654

    
1655
int mlRecvData(const int connectionID,char *recvbuf,int *bufsize,recv_params *rParams){
1656

    
1657
        //TODO yet to be converted
1658
        return 0;
1659
#if 0
1660
        if (rParams == NULL) {
1661
                error("ML: recv_data failed: recv_params is a NULL ptr\n");
1662
                return 0;
1663
    } else {
1664

1665
        info("ML: recv data called \n");
1666

1667
        int i = 0;
1668
        int returnValue = 0;
1669
        double timeout = (double) recv_timeout.tv_sec;
1670
        time_t endtime = time(NULL);
1671

1672
        for (i = 0; i < RECVDATABUFSIZE; i++) {
1673

1674
            if (recvdatabuf[i] != NULL) {
1675

1676
                if (recvdatabuf[i]->connectionID == connectionID) {
1677

1678
                    info("ML: recv data has entry  \n");
1679

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

1682
                    // check if the specified connection has data and it
1683
                    // is complete
1684
                    // check the data seqnr
1685
                    // if(connectionID == recvdatabuf[i]->connectionID &&
1686
                    // 1 == recvdatabuf[i]->status){
1687

1688
                    if (1 == recvdatabuf[i]->status) {
1689

1690
                        // info("transmissionHandler: recv_data set is
1691
                        // complete \n" );
1692

1693
                        // debug("debud \n");
1694

1695
                        // exchange the pointers
1696
                        int buffersize = 0;
1697
                        buffersize = recvdatabuf[i]->bufsize;
1698
                        *bufsize = buffersize;
1699
                        // recvbuf = recvdatabuf[i]->recvbuf;
1700

1701
                        // info("buffersize %d \n",buffersize);
1702
                        memcpy(recvbuf, recvdatabuf[i]->recvbuf,
1703
                               buffersize);
1704
                        // debug(" recvbuf %s \n",recvbuf );
1705

1706
//                         double nrMissFrags =
1707
//                             (double) recvdatabuf[i]->nrFragments /
1708
//                             (double) recvdatabuf[i]->recvFragments;
1709
//                         int nrMissingFragments = (int) ceil(nrMissFrags);
1710

1711
//                        rParams->nrMissingFragments = nrMissingFragments;
1712
//                         rParams->nrFragments = recvdatabuf[i]->nrFragments;
1713
                        rParams->msgtype = recvdatabuf[i]->msgtype;
1714
                        rParams->connectionID =
1715
                            recvdatabuf[i]->connectionID;
1716

1717
                        // break from the loop
1718
                        // debug(" recvbuf %s \n ",recvbuf);
1719

1720
                        // double nrMissFrags =
1721
                        // (double)recvdatabuf[i]->nrFragments /
1722
                        // (double)recvdatabuf[i]->recvFragments;
1723
                        // int nrMissingFragments =
1724
                        // (int)ceil(nrMissFrags);
1725

1726
                        if(get_Recv_data_inf_cb != NULL) {
1727
                                mon_data_inf recv_data_inf;
1728

1729
                                recv_data_inf.remote_socketID = &(connectbuf[connectionID]->external_socketID);
1730
                                recv_data_inf.buffer = recvdatabuf[i]->recvbuf;
1731
                                recv_data_inf.bufSize = recvdatabuf[i]->bufsize;
1732
                                recv_data_inf.msgtype = recvdatabuf[i]->msgtype;
1733
//                                 recv_data_inf.monitoringHeaderType = recvdatabuf[i]->monitoringHeaderType;
1734
//                                 recv_data_inf.monitoringDataHeader = recvdatabuf[i]->monitoringDataHeader;
1735
                                gettimeofday(&recv_data_inf.arrival_time, NULL);
1736
                                recv_data_inf.firstPacketArrived = recvdatabuf[i]->firstPacketArrived;
1737
                                recv_data_inf.nrMissingFragments = nrMissingFragments;
1738
                                recv_data_inf.nrFragments = recvdatabuf[i]->nrFragments;
1739
                                recv_data_inf.priority = false;
1740
                                recv_data_inf.padding = false;
1741
                                recv_data_inf.confirmation = false;
1742
                                recv_data_inf.reliable = false;
1743

1744
                                // send data recv callback to monitoring module
1745

1746
                                (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
1747
                        }
1748

1749

1750
                        // free the allocated memory
1751
                        free(recvdatabuf[i]);
1752
                        recvdatabuf[i] = NULL;
1753

1754
                        returnValue = 1;
1755
                        break;
1756

1757
                    }
1758

1759
                    if (recvdatabuf[i] != NULL) {
1760

1761
                        if (timepass > timeout) {
1762

1763
                            info("ML: recv_data timeout called  \n");
1764

1765
                            // some data about the missing chunks should
1766
                            // be added here
1767
                            // exchange the pointers
1768
                            int buffersize = 0;
1769
                            buffersize = recvdatabuf[i]->bufsize;
1770
                            *bufsize = buffersize;
1771
                            // recvbuf = recvdatabuf[i]->recvbuf;
1772

1773
                            double nrMissFrags =
1774
                                (double) recvdatabuf[i]->nrFragments /
1775
                                (double) recvdatabuf[i]->recvFragments;
1776
                            int nrMissingFragments =
1777
                                (int) ceil(nrMissFrags);
1778

1779
                            // debug(" recvbuf %s \n",recvbuf );
1780

1781
                            memcpy(recvbuf, recvdatabuf[i]->recvbuf,
1782
                                   buffersize);
1783

1784
                            rParams->nrMissingFragments =
1785
                                nrMissingFragments;
1786
                            rParams->nrFragments =
1787
                                recvdatabuf[i]->nrFragments;
1788
                            rParams->msgtype = recvdatabuf[i]->msgtype;
1789
                            rParams->connectionID =
1790
                                recvdatabuf[i]->connectionID;
1791

1792
                                if(get_Recv_data_inf_cb != NULL) {
1793
                                        mon_data_inf recv_data_inf;
1794

1795
                                        recv_data_inf.remote_socketID = &(connectbuf[connectionID]->external_socketID);
1796
                                        recv_data_inf.buffer = recvdatabuf[i]->recvbuf;
1797
                                        recv_data_inf.bufSize = recvdatabuf[i]->bufsize;
1798
                                        recv_data_inf.msgtype = recvdatabuf[i]->msgtype;
1799
                                        recv_data_inf.monitoringHeaderType = recvdatabuf[i]->monitoringHeaderType;
1800
                                        recv_data_inf.monitoringDataHeader = recvdatabuf[i]->monitoringDataHeader;
1801
                                        gettimeofday(&recv_data_inf.arrival_time, NULL);
1802
                                        recv_data_inf.firstPacketArrived = recvdatabuf[i]->firstPacketArrived;
1803
                                        recv_data_inf.nrMissingFragments = nrMissingFragments;
1804
                                        recv_data_inf.nrFragments = recvdatabuf[i]->nrFragments;
1805
                                        recv_data_inf.priority = false;
1806
                                        recv_data_inf.padding = false;
1807
                                        recv_data_inf.confirmation = false;
1808
                                        recv_data_inf.reliable = false;
1809

1810
                                        // send data recv callback to monitoring module
1811

1812
                                        (get_Recv_data_inf_cb) ((void *) &recv_data_inf);
1813
                                }
1814

1815
                            // free the allocated memory
1816
                            free(recvdatabuf[i]);
1817
                            recvdatabuf[i] = NULL;
1818

1819
                            returnValue = 1;
1820
                            break;
1821

1822
                        }
1823
                    }
1824

1825
                }
1826

1827
            }
1828
            // debug("2 recvbuf %s \n ",recvbuf);
1829
        }
1830
        return returnValue;
1831
    }
1832
#endif
1833

    
1834
}
1835

    
1836
int mlSocketIDToString(socketID_handle socketID,char* socketID_string, size_t len){
1837

    
1838
        char internal_addr[INET_ADDRSTRLEN];
1839
        char external_addr[INET_ADDRSTRLEN];
1840
        inet_ntop(AF_INET, &(socketID->internal_addr.udpaddr.sin_addr.s_addr), internal_addr, INET_ADDRSTRLEN);
1841
        inet_ntop(AF_INET, &(socketID->external_addr.udpaddr.sin_addr.s_addr), external_addr, INET_ADDRSTRLEN);
1842

    
1843
        snprintf(socketID_string,len,"%s:%d-%s:%d", internal_addr, ntohs(socketID->internal_addr.udpaddr.sin_port),
1844
                external_addr,        ntohs(socketID->external_addr.udpaddr.sin_port));
1845
        return 0;
1846

    
1847
}
1848

    
1849
int mlStringToSocketID(const char* socketID_string, socketID_handle socketID){
1850

    
1851
        //@TODO add checks against malformed string
1852
        char external_addr[INET_ADDRSTRLEN];
1853
        int external_port;
1854
        char internal_addr[INET_ADDRSTRLEN];
1855
        int internal_port;
1856

    
1857
        char *pch;
1858
        char *s = strdup(socketID_string);
1859

    
1860
        //replace ':' with a blank
1861
        pch=strchr(s,':');
1862
        while (pch!=NULL){
1863
                                *pch = ' ';
1864
                pch=strchr(pch+1,':');
1865
        }
1866
        pch=strchr(s,'-');
1867
        if(pch) *pch = ' ';
1868

    
1869
        sscanf(s,"%s %d %s %d", internal_addr, &internal_port,
1870
                external_addr, &external_port);
1871

    
1872
        if(inet_pton(AF_INET, internal_addr, &(socketID->internal_addr.udpaddr.sin_addr)) == 0)
1873
                return EINVAL;
1874
        socketID->internal_addr.udpaddr.sin_family = AF_INET;
1875
        socketID->internal_addr.udpaddr.sin_port = htons(internal_port);
1876

    
1877

    
1878
        if(inet_pton(AF_INET, external_addr, &(socketID->external_addr.udpaddr.sin_addr)) ==0)
1879
                return EINVAL;
1880
        socketID->external_addr.udpaddr.sin_family = AF_INET;
1881
        socketID->external_addr.udpaddr.sin_port = htons(external_port);
1882

    
1883
        free(s);
1884
        return 0;
1885

    
1886
}
1887

    
1888
int mlGetConnectionStatus(int connectionID){
1889

    
1890
        if(connectbuf[connectionID])
1891
                return connectbuf[connectionID]->status == READY;
1892
        return -1;
1893
    
1894
}
1895

    
1896

    
1897
int mlConnectionExist(socketID_handle socketID, bool ready){
1898

    
1899
    /*
1900
     * check if another connection for the external connectionID exist
1901
     * that was established \ within the last 2 seconds
1902
     */
1903
        int i;
1904
        for (i = 0; i < CONNECTBUFSIZE; i++)
1905
                if (connectbuf[i] != NULL)
1906
                        if (mlCompareSocketIDs(&(connectbuf[i]->external_socketID), socketID) == 0) {
1907
                                if (ready) return (connectbuf[i]->status == READY ? i : -1);;
1908
                                return i;
1909
                                }
1910

    
1911
    return -1;
1912

    
1913
}
1914

    
1915
//Added by Robert Birke as comodity functions
1916

    
1917
//int mlPrintSocketID(socketID_handle socketID) {
1918
//        char str[SOCKETID_STRING_SIZE];
1919
//        mlSocketIDToString(socketID, str, sizeof(str));
1920
//        printf(stderr,"int->%s<-ext\n",str);
1921
//}
1922

    
1923
/*
1924
 * hash code of a socketID
1925
 * TODO might think of a better way
1926
 */
1927
int mlHashSocketID(socketID_handle sock) {
1928
    return sock->internal_addr.udpaddr.sin_port +
1929
                          sock->external_addr.udpaddr.sin_port;
1930
}
1931

    
1932
int mlCompareSocketIDs(socketID_handle sock1, socketID_handle sock2) {
1933
        /*
1934
        * compare internal addr
1935
        */
1936
        if (sock1->internal_addr.udpaddr.sin_addr.s_addr !=
1937
            sock2->internal_addr.udpaddr.sin_addr.s_addr)
1938
                        return 1;
1939

    
1940
        if (sock1->internal_addr.udpaddr.sin_port !=
1941
                 sock2->internal_addr.udpaddr.sin_port)
1942
                        return 1;
1943

    
1944
        /*
1945
        * compare external addr
1946
        */
1947
        if (sock1->external_addr.udpaddr.sin_addr.s_addr !=
1948
            sock2->external_addr.udpaddr.sin_addr.s_addr)
1949
                        return 1;
1950

    
1951
        if (sock1->external_addr.udpaddr.sin_port !=
1952
                 sock2->external_addr.udpaddr.sin_port)
1953
                        return 1;
1954

    
1955
        return 0;
1956
}
1957

    
1958
int mlCompareSocketIDsByPort(socketID_handle sock1, socketID_handle sock2)
1959
{ 
1960
        if (sock1->internal_addr.udpaddr.sin_port !=
1961
                 sock2->internal_addr.udpaddr.sin_port)
1962
                        return 1;
1963

    
1964
        if (sock1->external_addr.udpaddr.sin_port !=
1965
                 sock2->external_addr.udpaddr.sin_port)
1966
                        return 1;
1967
        return 0;
1968
}
1969

    
1970
int mlGetPathMTU(int ConnectionId) {
1971
        if(ConnectionId < 0 || ConnectionId >= CONNECTBUFSIZE)
1972
                return -1;
1973
        if (connectbuf[ConnectionId] != NULL)
1974
                return connectbuf[ConnectionId]->pmtusize;
1975
        return -1;
1976
}
1977

    
1978
/**************************** END of GENERAL functions *************************/
1979

    
1980
/**************************** NAT functions *************************/
1981

    
1982
/* setter  */
1983
void mlSetStunServer(const int port,const char *ipaddr){
1984

    
1985
        stun_server.sin_family = AF_INET;
1986
        if (ipaddr == NULL)
1987
                stun_server.sin_addr.s_addr = htonl(INADDR_NONE);
1988
        else
1989
                stun_server.sin_addr.s_addr = resolve(ipaddr);
1990
        stun_server.sin_port = htons(port);
1991

    
1992
}
1993

    
1994
int mlGetExternalIP(char* external_addr){
1995

    
1996
        socketaddrgen udpgen;
1997
        struct sockaddr_in udpaddr;
1998

    
1999
        udpgen = local_socketID.external_addr;
2000
        udpaddr = udpgen.udpaddr;
2001

    
2002
        inet_ntop(AF_INET, &(udpaddr.sin_addr), external_addr,
2003
                        INET_ADDRSTRLEN);
2004

    
2005
        if (external_addr == NULL) {
2006

    
2007
        return -1;
2008

    
2009
        } else {
2010

    
2011
        return 0;
2012

    
2013
        }
2014

    
2015
}
2016

    
2017
/**************************** END of NAT functions *************************/