Statistics
| Branch: | Revision:

grapes / som / net_helper-ml.c @ 14004304

History | View | Annotate | Download (15.4 KB)

1
/*
2
 *  Copyright (c) 2009 Marco Biazzini
3
 *
4
 *  This is free software; see lgpl-2.1.txt
5
 */
6

    
7
#include <event2/event.h>
8
#include <arpa/inet.h>
9
#include <unistd.h>
10
#include <stdlib.h>
11
#include <stdio.h>
12
#include <string.h>
13

    
14

    
15
#include "net_helper.h"
16
#include "ml.h"
17

    
18
#include "msg_types.h"/**/
19

    
20
/**
21
 * libevent pointer
22
 */
23
struct event_base *base;
24

    
25
#define NH_BUFFER_SIZE 1000
26
#define NH_PACKET_TIMEOUT {0, 500*1000}
27
#define NH_ML_INIT_TIMEOUT {1, 0}
28

    
29
static int sIdx = 0;
30
static int rIdx = 0;
31

    
32
typedef struct nodeID {
33
        socketID_handle addr;
34
        int connID;        // connection associated to this node, -1 if myself
35
        int refcnt;
36
//        int addrSize;
37
//        int addrStringSize;
38
} nodeID;
39

    
40
typedef struct msgData_cb {
41
        int bIdx;        // index of the message in the proper buffer
42
        unsigned char msgType; // message type
43
        int mSize;        // message size
44
        bool conn_cb_called;
45
        bool cancelled;
46
} msgData_cb;
47

    
48
static nodeID *me; //TODO: is it possible to get rid of this (notwithstanding ml callback)??
49
static int timeoutFired = 0;
50

    
51
// pointers to the msgs to be send
52
static uint8_t *sendingBuffer[NH_BUFFER_SIZE];
53
// pointers to the received msgs + sender nodeID
54
struct receivedB {
55
        struct nodeID *id;
56
        int len;
57
        uint8_t *data;
58
};
59
static struct receivedB receivedBuffer[NH_BUFFER_SIZE];
60
/**/ static int recv_counter =0; static int snd_counter =0;
61

    
62

    
63
/**
64
 * Look for a free slot in the received buffer and allocates it for immediate use
65
 * @return the index of a free slot in the received msgs buffer, -1 if no free slot available.
66
 */
67
static int next_R() {
68
        const int size = 1024;
69
        if (receivedBuffer[rIdx].data==NULL) {
70
                receivedBuffer[rIdx].data = malloc(size);
71
        }
72
        else {
73
                int count;
74
                for (count=0;count<NH_BUFFER_SIZE;count++) {
75
                        rIdx = (++rIdx)%NH_BUFFER_SIZE;
76
                        if (receivedBuffer[rIdx].data==NULL)
77
                                break;
78
                }
79
                if (count==NH_BUFFER_SIZE)
80
                        return -1;
81
                else {
82
                        receivedBuffer[rIdx].data = malloc(size);
83
                }
84
        }
85
        memset(receivedBuffer[rIdx].data,0,size);
86
        return rIdx;
87
}
88

    
89
/**
90
 * Look for a free slot in the sending buffer and allocates it for immediate use
91
 * @return the index of a free slot in the sending msgs buffer, -1 if no free slot available.
92
 */
93
static int next_S() {
94
        const int size = 1024;
95
        if (sendingBuffer[sIdx]==NULL) {
96
                sendingBuffer[sIdx] = malloc(size);
97
        }
98
        else {
99
                int count;
100
                for (count=0;count<NH_BUFFER_SIZE;count++) {
101
                        sIdx = (++sIdx)%NH_BUFFER_SIZE;
102
                        if (sendingBuffer[sIdx]==NULL)
103
                                break;
104
                }
105
                if (count==NH_BUFFER_SIZE)
106
                        return -1;
107
                else {
108
                        sendingBuffer[sIdx] = malloc(size);
109
                }
110
        }
111
        return sIdx;
112
}
113

    
114

    
115
/**
116
 * Callback used by ml to confirm its initialization. Create a valid self nodeID and register to receive data from remote peers.
117
 * @param local_socketID
118
 * @param errorstatus
119
 */
120
static void init_myNodeID_cb (socketID_handle local_socketID,int errorstatus) {
121
        switch (errorstatus) {
122
        case 0:
123
                //
124
                memcpy(me->addr,local_socketID,SOCKETID_SIZE);
125
        //        me->addrSize = SOCKETID_SIZE;
126
        //        me->addrStringSize = SOCKETID_STRING_SIZE;
127
                me->connID = -1;
128
                me->refcnt = 1;
129
        //        fprintf(stderr,"Net-helper init : received my own socket: %s.\n",node_addr(me));
130
                break;
131
        case -1:
132
                //
133
                fprintf(stderr,"Net-helper init : socket error occurred in ml while creating socket\n");
134
                exit(1);
135
                break;
136
        case 1:
137
                //
138
                fprintf(stderr,"Net-helper init : NAT traversal failed while creating socket\n");
139
                exit(1);
140
                break;
141
        case 2:
142
            fprintf(stderr,"Net-helper init : NAT traversal timeout while creating socket\n");
143
            fprintf(stderr,"Net-helper init : Retrying without STUN\n");
144
            mlSetStunServer(0,NULL);
145
            break;
146
        default :        // should never happen
147
                //
148
                fprintf(stderr,"Net-helper init : Unknown error in ml while creating socket\n");
149
        }
150

    
151
}
152

    
153
/**
154
 * Timeout callback to be set in the eventlib loop as needed
155
 * @param socket
156
 * @param flag
157
 * @param arg
158
 */
159
static void t_out_cb (int socket, short flag, void* arg) {
160

    
161
        timeoutFired = 1;
162
//        fprintf(stderr,"TIMEOUT!!!\n");
163
//        event_base_loopbreak(base);
164
}
165

    
166
/**
167
 * Callback called by ml when a remote node ask for a connection
168
 * @param connectionID
169
 * @param arg
170
 */
171
static void receive_conn_cb(int connectionID, void *arg) {
172
//    fprintf(stderr, "Net-helper : remote peer opened the connection %d with arg = %d\n", connectionID,(int)arg);
173

    
174
}
175

    
176
void free_sending_buffer(int i)
177
{
178
        free(sendingBuffer[i]);
179
        sendingBuffer[i] = NULL;
180
}
181

    
182
/**
183
 * Callback called by the ml when a connection is ready to be used to send data to a remote peer
184
 * @param connectionID
185
 * @param arg
186
 */
187
static void connReady_cb (int connectionID, void *arg) {
188

    
189
        msgData_cb *p;
190
        p = (msgData_cb *)arg;
191
        if (p == NULL) return;
192
        if (p->cancelled) {
193
            free(p);
194
            return;
195
        }
196
        mlSendData(connectionID,(char *)(sendingBuffer[p->bIdx]),p->mSize,p->msgType,NULL);
197
/**/char mt = ((char*)sendingBuffer[p->bIdx])[0]; ++snd_counter;
198
        if (mt!=MSG_TYPE_TOPOLOGY &&
199
                mt!=MSG_TYPE_CHUNK && mt!=MSG_TYPE_SIGNALLING) {
200
                        fprintf(stderr,"Net-helper ERROR! Sent message # %d of type %c and size %d\n",
201
                                snd_counter,mt+'0', p->mSize);}
202
        free_sending_buffer(p->bIdx);
203
//        fprintf(stderr,"Net-helper: Message # %d for connection %d sent!\n ", p->bIdx,connectionID);
204
        //        event_base_loopbreak(base);
205
        p->conn_cb_called = true;
206
}
207

    
208
/**
209
 * Callback called by ml when a connection error occurs
210
 * @param connectionID
211
 * @param arg
212
 */
213
static void connError_cb (int connectionID, void *arg) {
214
        // simply get rid of the msg in the buffer....
215
        msgData_cb *p;
216
        p = (msgData_cb *)arg;
217
        if (p != NULL) {
218
                fprintf(stderr,"Net-helper: Connection %d could not be established to send msg %d.\n ", connectionID,p->bIdx);
219
                if (p->cancelled) {
220
                        free(p);//p->mSize = -1;
221
                } else {
222
                        p->conn_cb_called = true;
223
                }
224
        }
225
        //        event_base_loopbreak(base);
226
}
227

    
228

    
229
/**
230
 * Callback to receive data from ml
231
 * @param buffer
232
 * @param buflen
233
 * @param msgtype
234
 * @param arg
235
 */
236
static void recv_data_cb(char *buffer, int buflen, unsigned char msgtype, recv_params *arg) {
237
// TODO: lacks a void* arg... moreover: recv_params has a msgtype, but there is also a msgtype explicit argument...
238
//        fprintf(stderr, "Net-helper : called back with some news...\n");
239
/**/ ++recv_counter;
240
        char str[SOCKETID_STRING_SIZE];
241
        if (arg->remote_socketID != NULL)
242
                mlSocketIDToString(arg->remote_socketID,str,SOCKETID_STRING_SIZE);
243
        else
244
                sprintf(str,"!Unknown!");
245
        if (arg->nrMissingBytes || !arg->firstPacketArrived) {
246
            fprintf(stderr, "Net-helper : corrupted message arrived from %s\n",str);
247
/**/    fprintf(stderr, "\tMessage # %d -- Message type: %hhd -- Missing # %d bytes%s\n",
248
                        recv_counter, buffer[0],arg->nrMissingBytes, arg->firstPacketArrived?"":", Missing first!");
249
        }
250
        else {
251
        //        fprintf(stderr, "Net-helper : message arrived from %s\n",str);
252
                // buffering the received message only if possible, otherwise ignore it...
253
                int index = next_R();
254
                if (index >=0) {
255
                //        receivedBuffer[index][0] = malloc(buflen);
256
                        if (receivedBuffer[index].data == NULL) {
257
                                fprintf(stderr, "Net-helper : memory error while creating a new message buffer \n");
258
                                return;
259
                        }
260
                        // creating a new sender nodedID
261
                        receivedBuffer[index].id = malloc(sizeof(nodeID));
262
                        if (receivedBuffer[index].id==NULL) {
263
                                free (receivedBuffer[index].data);
264
                                receivedBuffer[index].data = NULL;
265
                                fprintf(stderr, "Net-helper : memory error while creating a new nodeID. Message from %s is lost.\n", str);
266
                                return;
267
                        }
268
                        else {
269
                                memset(receivedBuffer[index].id, 0, sizeof(struct nodeID));
270
                                nodeID *remote = receivedBuffer[index].id;
271
                                receivedBuffer[index].data = realloc(receivedBuffer[index].data,buflen);
272
                                memset(receivedBuffer[index].data,0,buflen);
273
                                receivedBuffer[index].len = buflen;
274
                                //*(receivedBuffer[index][0]) = buflen;
275
                                memcpy(receivedBuffer[index].data,buffer,buflen);
276
                                  // get the socketID of the sender
277
                                remote->addr = malloc(SOCKETID_SIZE);
278
                                if (remote->addr == NULL) {
279
                                          free (remote);
280
                                          fprintf(stderr, "Net-helper : memory error while creating a new nodeID \n");
281
                                          return;
282
                                }
283
                                else {
284
                                        memset(remote->addr, 0, SOCKETID_SIZE);
285
                                        memcpy(remote->addr, arg->remote_socketID ,SOCKETID_SIZE);
286
                                //        remote->addrSize = SOCKETID_SIZE;
287
                                //        remote->addrStringSize = SOCKETID_STRING_SIZE;
288
                                        remote->connID = arg->connectionID;
289
                                        remote->refcnt = 1;
290
                                }
291
                        }
292
                }
293
  }
294
//        event_base_loopbreak(base);
295
}
296

    
297

    
298
struct nodeID *net_helper_init(const char *IPaddr, int port) {
299

    
300
        struct timeval tout = NH_ML_INIT_TIMEOUT;
301
        int s;
302
        base = event_base_new();
303

    
304
        me = malloc(sizeof(nodeID));
305
        if (me == NULL) {
306
                return NULL;
307
        }
308
        memset(me,0,sizeof(nodeID));
309
        me->addr = malloc(SOCKETID_SIZE);
310
        if (me->addr == NULL) {
311
                free(me);
312
                return NULL;
313
        }
314
        memset(me->addr,0,SOCKETID_SIZE);
315
        me->connID = -10;        // dirty trick to spot later if the ml has called back ...
316
        me->refcnt = 1;
317

    
318
        int i;
319
        for (i=0;i<NH_BUFFER_SIZE;i++) {
320
                sendingBuffer[i] = NULL;
321
                receivedBuffer[i].data = NULL;
322
        }
323

    
324
        mlRegisterErrorConnectionCb(&connError_cb);
325
        mlRegisterRecvConnectionCb(&receive_conn_cb);
326
        s = mlInit(1,tout,port,IPaddr,3478,"stun.ekiga.net",&init_myNodeID_cb,base);
327
        if (s < 0) {
328
                fprintf(stderr, "Net-helper : error initializing ML!\n");
329
                free(me);
330
                return NULL;
331
        }
332

    
333
        while (me->connID<-1) {
334
        //        event_base_once(base,-1, EV_TIMEOUT, &t_out_cb, NULL, &tout);
335
                event_base_loop(base,EVLOOP_ONCE);
336
        }
337
        timeoutFired = 0;
338
//        fprintf(stderr,"Net-helper init : back from init!\n");
339

    
340
        return me;
341
}
342

    
343

    
344
void bind_msg_type (unsigned char msgtype) {
345

    
346
                        mlRegisterRecvDataCb(&recv_data_cb,msgtype);
347
}
348

    
349

    
350
void send_to_peer_cb(int fd, short event, void *arg)
351
{
352
        msgData_cb *p = (msgData_cb *) arg;
353
        if (p->conn_cb_called) {
354
                free(p);
355
        }
356
        else { //don't send it anymore
357
                free_sending_buffer(p->bIdx);
358
                p->cancelled = true;
359
                // don't free p, the other timeout will do it
360
        }
361
}
362

    
363
/**
364
 * Called by the application to send data to a remote peer
365
 * @param from
366
 * @param to
367
 * @param buffer_ptr
368
 * @param buffer_size
369
 * @return The dimension of the buffer or -1 if a connection error occurred.
370
 */
371
int send_to_peer(const struct nodeID *from, struct nodeID *to, const uint8_t *buffer_ptr, int buffer_size)
372
{
373
        // if buffer is full, discard the message and return an error flag
374
        int index = next_S();
375
        if (index<0) {
376
                // free(buffer_ptr);
377
                fprintf(stderr,"Net-helper: buffer full\n ");
378
                return -1;
379
        }
380
        sendingBuffer[index] = realloc(sendingBuffer[index],buffer_size);
381
        memset(sendingBuffer[index],0,buffer_size);
382
        memcpy(sendingBuffer[index],buffer_ptr,buffer_size);
383
        // free(buffer_ptr);
384
        msgData_cb *p = malloc(sizeof(msgData_cb));
385
        p->bIdx = index; p->mSize = buffer_size; p->msgType = (unsigned char)buffer_ptr[0]; p->conn_cb_called = false; p->cancelled = false;
386
        int current = p->bIdx;
387
        send_params params = {0,0,0,0};
388
        to->connID = mlOpenConnection(to->addr,&connReady_cb,p, params);
389
        if (to->connID<0) {
390
                free_sending_buffer(current);
391
                fprintf(stderr,"Net-helper: Couldn't get a connection ID to send msg %d.\n ", p->bIdx);
392
                free(p);
393
                return -1;
394
        }
395
        else {
396
                struct timeval timeout = NH_PACKET_TIMEOUT;
397
                event_base_once(base, -1, EV_TIMEOUT, send_to_peer_cb, (void *) p, &timeout);
398
                return buffer_size; //p->mSize;
399
        }
400

    
401
}
402

    
403

    
404
/**
405
 * Called by an application to receive data from remote peers
406
 * @param local
407
 * @param remote
408
 * @param buffer_ptr
409
 * @param buffer_size
410
 * @return The number of received bytes or -1 if some error occurred.
411
 */
412
int recv_from_peer(const struct nodeID *local, struct nodeID **remote, uint8_t *buffer_ptr, int buffer_size)
413
{
414
        int size;
415
        if (receivedBuffer[rIdx].id==NULL) {        //block till first message arrives
416
                wait4data(local, NULL);
417
        }
418

    
419
        (*remote) = receivedBuffer[rIdx].id;
420
        // retrieve a msg from the buffer
421
        size = receivedBuffer[rIdx].len;
422
        if (size>buffer_size) {
423
                fprintf(stderr, "Net-helper : recv_from_peer: buffer too small (size:%d > buffer_size: %d)!\n",size,buffer_size);
424
                return -1;
425
        }
426
        memcpy(buffer_ptr, receivedBuffer[rIdx].data, size);
427
        free(receivedBuffer[rIdx].data);
428
        receivedBuffer[rIdx].data = NULL;
429
        receivedBuffer[rIdx].id = NULL;
430

    
431
//        fprintf(stderr, "Net-helper : I've got mail!!!\n");
432

    
433
        return size;
434
}
435

    
436

    
437
int wait4data(const struct nodeID *n, struct timeval *tout) {
438

    
439
//        fprintf(stderr,"Net-helper : Waiting for data to come...\n");
440
        if (tout) {        //if tout==NULL, loop wait infinitely
441
                event_base_once(base,-1, EV_TIMEOUT, &t_out_cb, NULL, tout);
442
        }
443
        while(receivedBuffer[rIdx].data==NULL && timeoutFired==0) {
444
        //        event_base_dispatch(base);
445
                event_base_loop(base,EVLOOP_ONCE);
446
        }
447
        timeoutFired = 0;
448
//        fprintf(stderr,"Back from eventlib loop.\n");
449

    
450
        if (receivedBuffer[rIdx].data!=NULL)
451
                return 1;
452
        else
453
                return 0;
454
}
455

    
456
socketID_handle getRemoteSocketID(const char *ip, int port) {
457
        char str[SOCKETID_STRING_SIZE];
458
        socketID_handle h;
459

    
460
        snprintf(str, SOCKETID_STRING_SIZE, "%s:%d-%s:%d", ip, port, ip, port);
461
        h = malloc(SOCKETID_SIZE);
462
        mlStringToSocketID(str, h);
463

    
464
        return h;
465
}
466

    
467
struct nodeID *create_node(const char *rem_IP, int rem_port) {
468
        struct nodeID *remote = malloc(sizeof(nodeID));
469
        if (remote == NULL) {
470
                return NULL;
471
        }
472
//        remote->addr = malloc(sizeof(SOCKETID_SIZE));
473
//        if (remote->addr == NULL) {
474
//                free(remote);
475
//                return NULL;
476
//        }
477
//        remote->addrSize = SOCKETID_SIZE;
478
//        remote->addrStringSize = SOCKETID_STRING_SIZE;
479
        remote->addr = getRemoteSocketID(rem_IP, rem_port);
480
        send_params params = {0,0,0,0};
481
        remote->connID = mlOpenConnection(remote->addr,&connReady_cb,NULL, params);
482
        remote->refcnt = 1;
483
        return remote;
484
}
485

    
486
// TODO: check why closing the connection is annoying for the ML
487
void nodeid_free(struct nodeID *n) {
488

    
489
//        mlCloseConnection(n->connID);
490
//        mlCloseSocket(n->addr);
491
//        free(n);
492
        if (n && (--(n->refcnt) == 0)) {
493
        //        mlCloseConnection(n->connID);
494
                mlCloseSocket(n->addr);
495
                free(n);
496
        }
497
}
498

    
499

    
500
const char *node_addr(const struct nodeID *s)
501
{
502
  static char addr[256];
503
  // TODO: mlSocketIDToString always return 0 !!!
504
  int r = mlSocketIDToString(s->addr,addr,256);
505
  if (!r)
506
          return addr;
507
  else
508
          return "";
509
}
510

    
511
struct nodeID *nodeid_dup(struct nodeID *s)
512
{
513
//  struct nodeID *res;
514
//
515
//  res = malloc(sizeof(struct nodeID));
516
//  if (res != NULL) {
517
//          res->addr = malloc(SOCKETID_SIZE);
518
//          if (res->addr != NULL) {
519
//                 memcpy(res->addr, s->addr, SOCKETID_SIZE);
520
//        //         res->addrSize = SOCKETID_SIZE;
521
//        //         res->addrStringSize = SOCKETID_STRING_SIZE;
522
//                 res->connID = s->connID;
523
//          }
524
//          else {
525
//                free(res);
526
//                res = NULL;
527
//                fprintf(stderr,"Net-helper : Error while duplicating nodeID...\n");
528
//          }
529
//  }
530
//        return res;
531
        s->refcnt++;
532
        return s;
533
}
534

    
535
int nodeid_equal(const struct nodeID *s1, const struct nodeID *s2)
536
{
537
        return (mlCompareSocketIDs(s1->addr,s2->addr) == 0);
538
}
539

    
540
int nodeid_dump(uint8_t *b, const struct nodeID *s)
541
{
542
  mlSocketIDToString(s->addr,(char *)b,SOCKETID_STRING_SIZE);
543
  //fprintf(stderr,"Dumping nodeID : ho scritto %s (%d bytes)\n",b, strlen((char *)b));
544

    
545
//        memcpy(b, s->addr,SOCKETID_SIZE);//sizeof(struct sockaddr_in6)*2
546
//        return SOCKETID_SIZE;//sizeof(struct sockaddr_in6)*2;
547

    
548
  return 1 + strlen((char *)b);        //terminating \0 IS included in the size
549
}
550

    
551
struct nodeID *nodeid_undump(const uint8_t *b, int *len)
552
{
553
  struct nodeID *res;
554
  res = malloc(sizeof(struct nodeID));
555
  if (res != NULL) {
556
          memset(res,0,sizeof(struct nodeID));
557
          res->addr = malloc(SOCKETID_SIZE);
558
          if (res->addr != NULL) {
559
                  memset(res->addr,0,SOCKETID_SIZE);
560
                  //memcpy(res->addr, b, SOCKETID_SIZE);
561
                  //*len = SOCKETID_SIZE;
562
                  *len = strlen((char*)b) + 1;
563
                  mlStringToSocketID((char *)b,res->addr);
564
        //          fprintf(stderr,"Node undumped : %s\n",node_addr(res));
565
        //          res->addrSize = SOCKETID_SIZE;
566
        //          res->addrStringSize = SOCKETID_STRING_SIZE;
567
                  res->connID = -1;
568
                  res->refcnt = 1;
569
          }
570
          else {
571
                  free(res);
572
                  res = NULL;
573
                  // TODO: what about *len in this case???
574
                  fprintf(stderr,"Net-helper : Error while 'undumping' nodeID...\n");
575
          }
576
  }
577

    
578

    
579
  return res;
580
}