Statistics
| Branch: | Revision:

streamers / net_helper-ml.c @ c7638574

History | View | Annotate | Download (14.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
#include "ml_helpers.h"
18

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

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

    
26
#define NH_BUFFER_SIZE 100
27

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

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

    
39
typedef struct msgData_cb {
40
        int bIdx;        // index of the message in the proper buffer
41
        unsigned char msgType; // message type
42
        int mSize;        // message size
43
} msgData_cb;
44

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

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

    
59

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

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

    
111

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

    
148
}
149

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

    
158
        timeoutFired = 1;
159
//        fprintf(stderr,"TIMEOUT!!!\n");
160
//        event_base_loopbreak(base);
161
}
162

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

    
171
}
172

    
173
/**
174
 * Callback called by the ml when a connection is ready to be used to send data to a remote peer
175
 * @param connectionID
176
 * @param arg
177
 */
178
static void connReady_cb (int connectionID, void *arg) {
179

    
180
        msgData_cb *p;
181
        p = (msgData_cb *)arg;
182
        if (p == NULL) return;
183
        mlSendData(connectionID,(char *)(sendingBuffer[p->bIdx]),p->mSize,p->msgType,NULL);
184
/**/char mt = ((char*)sendingBuffer[p->bIdx])[0]; ++snd_counter;
185
        if (mt!=MSG_TYPE_TOPOLOGY &&
186
                mt!=MSG_TYPE_CHUNK && mt!=MSG_TYPE_SIGNALLING) {
187
                        fprintf(stderr,"Net-helper ERROR! Sent message # %d of type %c and size %d\n",
188
                                snd_counter,mt+'0', p->mSize);}
189
        free(sendingBuffer[p->bIdx]);
190
        sendingBuffer[p->bIdx] = NULL;
191
//        fprintf(stderr,"Net-helper: Message # %d for connection %d sent!\n ", p->bIdx,connectionID);
192
        //        event_base_loopbreak(base);
193
        free(p);
194
}
195

    
196
/**
197
 * Callback called by ml when a connection error occurs
198
 * @param connectionID
199
 * @param arg
200
 */
201
static void connError_cb (int connectionID, void *arg) {
202
        // simply get rid of the msg in the buffer....
203
        msgData_cb *p;
204
        p = (msgData_cb *)arg;
205
        if (p != NULL) {
206
                fprintf(stderr,"Net-helper: Connection %d could not be established to send msg %d.\n ", connectionID,p->bIdx);
207
                free(sendingBuffer[p->bIdx]);
208
                sendingBuffer[p->bIdx] = NULL;
209
                free(p);//p->mSize = -1;
210
        }
211
        //        event_base_loopbreak(base);
212
}
213

    
214

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

    
283

    
284
struct nodeID *net_helper_init(const char *IPaddr, int port) {
285

    
286
        struct timeval tout = {1, 0};
287
        base = event_base_new();
288

    
289
        me = malloc(sizeof(nodeID));
290
        if (me == NULL) {
291
                return NULL;
292
        }
293
        memset(me,0,sizeof(nodeID));
294
        me->addr = malloc(SOCKETID_SIZE);
295
        if (me->addr == NULL) {
296
                free(me);
297
                return NULL;
298
        }
299
        memset(me->addr,0,SOCKETID_SIZE);
300
        me->connID = -10;        // dirty trick to spot later if the ml has called back ...
301
        me->refcnt = 1;
302

    
303
        int i;
304
        for (i=0;i<NH_BUFFER_SIZE;i++) {
305
                sendingBuffer[i] = NULL;
306
                receivedBuffer[i].data = NULL;
307
        }
308

    
309
        mlRegisterErrorConnectionCb(&connError_cb);
310
        mlRegisterRecvConnectionCb(&receive_conn_cb);
311
        mlInit(1,tout,port,IPaddr,3478,"stun.ekiga.net",&init_myNodeID_cb,base);
312
        while (me->connID<-1) {
313
        //        event_base_once(base,-1, EV_TIMEOUT, &t_out_cb, NULL, &tout);
314
                event_base_loop(base,EVLOOP_ONCE);
315
        }
316
        timeoutFired = 0;
317
//        fprintf(stderr,"Net-helper init : back from init!\n");
318

    
319
        return me;
320
}
321

    
322

    
323
void bind_msg_type (unsigned char msgtype) {
324

    
325
                        mlRegisterRecvDataCb(&recv_data_cb,msgtype);
326
}
327

    
328

    
329
/**
330
 * Called by the application to send data to a remote peer
331
 * @param from
332
 * @param to
333
 * @param buffer_ptr
334
 * @param buffer_size
335
 * @return The dimension of the buffer or -1 if a connection error occurred.
336
 */
337
int send_to_peer(const struct nodeID *from, struct nodeID *to, const uint8_t *buffer_ptr, int buffer_size)
338
{
339
        // if buffer is full, discard the message and return an error flag
340
        int index = next_S();
341
        if (index<0) {
342
                // free(buffer_ptr);
343
                return -1;
344
        }
345
        sendingBuffer[index] = realloc(sendingBuffer[index],buffer_size);
346
        memset(sendingBuffer[index],0,buffer_size);
347
        memcpy(sendingBuffer[index],buffer_ptr,buffer_size);
348
        // free(buffer_ptr);
349
        msgData_cb *p = malloc(sizeof(msgData_cb));
350
        p->bIdx = index; p->mSize = buffer_size; p->msgType = (unsigned char)buffer_ptr[0];
351
        int current = p->bIdx;
352
        send_params params = {0,0,0,0};
353
        to->connID = mlOpenConnection(to->addr,&connReady_cb,p, params);
354
        if (to->connID<0) {
355
                free(sendingBuffer[current]);
356
                sendingBuffer[current] = NULL;
357
                fprintf(stderr,"Net-helper: Couldn't get a connection ID to send msg %d.\n ", p->bIdx);
358
                free(p);
359
                return -1;
360
        }
361
        else {
362
                return buffer_size; //p->mSize;
363
        }
364

    
365
}
366

    
367

    
368
/**
369
 * Called by an application to receive data from remote peers
370
 * @param local
371
 * @param remote
372
 * @param buffer_ptr
373
 * @param buffer_size
374
 * @return The number of received bytes or -1 if some error occurred.
375
 */
376
int recv_from_peer(const struct nodeID *local, struct nodeID **remote, uint8_t *buffer_ptr, int buffer_size)
377
{
378
        int size;
379
        // this should never happen... if it does, index handling is faulty...
380
        if (receivedBuffer[rIdx].id==NULL) {
381
                fprintf(stderr, "Net-helper : memory error while creating a new nodeID \n");
382
                return -1;
383
        }
384

    
385
        (*remote) = receivedBuffer[rIdx].id;
386
        // retrieve a msg from the buffer
387
        size = receivedBuffer[rIdx].len;
388
        if (size>buffer_size) {
389
                fprintf(stderr, "Net-helper : recv_from_peer: buffer too small (size:%d > buffer_size: %d)!\n",size,buffer_size);
390
                return -1;
391
        }
392
        memcpy(buffer_ptr, receivedBuffer[rIdx].data, size);
393
        free(receivedBuffer[rIdx].data);
394
        receivedBuffer[rIdx].data = NULL;
395
        receivedBuffer[rIdx].id = NULL;
396

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

    
399
        return size;
400
}
401

    
402

    
403
int wait4data(const struct nodeID *n, struct timeval *tout) {
404

    
405
//        fprintf(stderr,"Net-helper : Waiting for data to come...\n");
406
        event_base_once(base,-1, EV_TIMEOUT, &t_out_cb, NULL, tout);
407
        while(receivedBuffer[rIdx].data==NULL && timeoutFired==0) {
408
        //        event_base_dispatch(base);
409
                event_base_loop(base,EVLOOP_ONCE);
410
        }
411
        timeoutFired = 0;
412
//        fprintf(stderr,"Back from eventlib loop.\n");
413

    
414
        if (receivedBuffer[rIdx].data!=NULL)
415
                return 1;
416
        else
417
                return 0;
418
}
419

    
420

    
421

    
422

    
423
struct nodeID *create_node(const char *rem_IP, int rem_port) {
424
        struct nodeID *remote = malloc(sizeof(nodeID));
425
        if (remote == NULL) {
426
                return NULL;
427
        }
428
//        remote->addr = malloc(sizeof(SOCKETID_SIZE));
429
//        if (remote->addr == NULL) {
430
//                free(remote);
431
//                return NULL;
432
//        }
433
//        remote->addrSize = SOCKETID_SIZE;
434
//        remote->addrStringSize = SOCKETID_STRING_SIZE;
435
        remote->addr = getRemoteSocketID(rem_IP, rem_port);
436
        send_params params = {0,0,0,0};
437
        remote->connID = mlOpenConnection(remote->addr,&connReady_cb,NULL, params);
438
        remote->refcnt = 1;
439
        return remote;
440
}
441

    
442
// TODO: check why closing the connection is annoying for the ML
443
void nodeid_free(struct nodeID *n) {
444

    
445
//        mlCloseConnection(n->connID);
446
//        mlCloseSocket(n->addr);
447
//        free(n);
448
        if (n && (--(n->refcnt) == 0)) {
449
        //        mlCloseConnection(n->connID);
450
                mlCloseSocket(n->addr);
451
                free(n);
452
        }
453
}
454

    
455

    
456
const char *node_addr(const struct nodeID *s)
457
{
458
  static char addr[256];
459
  // TODO: mlSocketIDToString always return 0 !!!
460
  int r = mlSocketIDToString(s->addr,addr,256);
461
  if (!r)
462
          return addr;
463
  else
464
          return "";
465
}
466

    
467
struct nodeID *nodeid_dup(struct nodeID *s)
468
{
469
//  struct nodeID *res;
470
//
471
//  res = malloc(sizeof(struct nodeID));
472
//  if (res != NULL) {
473
//          res->addr = malloc(SOCKETID_SIZE);
474
//          if (res->addr != NULL) {
475
//                 memcpy(res->addr, s->addr, SOCKETID_SIZE);
476
//        //         res->addrSize = SOCKETID_SIZE;
477
//        //         res->addrStringSize = SOCKETID_STRING_SIZE;
478
//                 res->connID = s->connID;
479
//          }
480
//          else {
481
//                free(res);
482
//                res = NULL;
483
//                fprintf(stderr,"Net-helper : Error while duplicating nodeID...\n");
484
//          }
485
//  }
486
//        return res;
487
        s->refcnt++;
488
        return s;
489
}
490

    
491
int nodeid_equal(const struct nodeID *s1, const struct nodeID *s2)
492
{
493
        return (mlCompareSocketIDs(s1->addr,s2->addr) == 0);
494
}
495

    
496
int nodeid_dump(uint8_t *b, const struct nodeID *s)
497
{
498
  mlSocketIDToString(s->addr,(char *)b,SOCKETID_STRING_SIZE);
499
  //fprintf(stderr,"Dumping nodeID : ho scritto %s (%d bytes)\n",b, strlen((char *)b));
500

    
501
//        memcpy(b, s->addr,SOCKETID_SIZE);//sizeof(struct sockaddr_in6)*2
502
//        return SOCKETID_SIZE;//sizeof(struct sockaddr_in6)*2;
503

    
504
  return 1 + strlen((char *)b);        //terminating \0 IS included in the size
505
}
506

    
507
struct nodeID *nodeid_undump(const uint8_t *b, int *len)
508
{
509
  struct nodeID *res;
510
  res = malloc(sizeof(struct nodeID));
511
  if (res != NULL) {
512
          memset(res,0,sizeof(struct nodeID));
513
          res->addr = malloc(SOCKETID_SIZE);
514
          if (res->addr != NULL) {
515
                  memset(res->addr,0,SOCKETID_SIZE);
516
                  //memcpy(res->addr, b, SOCKETID_SIZE);
517
                  //*len = SOCKETID_SIZE;
518
                  *len = strlen((char*)b) + 1;
519
                  mlStringToSocketID((char *)b,res->addr);
520
        //          fprintf(stderr,"Node undumped : %s\n",node_addr(res));
521
        //          res->addrSize = SOCKETID_SIZE;
522
        //          res->addrStringSize = SOCKETID_STRING_SIZE;
523
                  res->connID = -1;
524
                  res->refcnt = 1;
525
          }
526
          else {
527
                  free(res);
528
                  res = NULL;
529
                  // TODO: what about *len in this case???
530
                  fprintf(stderr,"Net-helper : Error while 'undumping' nodeID...\n");
531
          }
532
  }
533

    
534

    
535
  return res;
536
}