Statistics
| Branch: | Revision:

grapes / som / net_helper-ml.c @ 7a4b65c6

History | View | Annotate | Download (15.1 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
#include <assert.h>
14

    
15

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

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

    
21

    
22
#ifdef MONL
23
#include "mon.h"
24
#include "grapes_log.h"
25
#include "repoclient.h"
26
#include "grapes.h"
27
#endif
28

    
29

    
30
/**
31
 * libevent pointer
32
 */
33
struct event_base *base;
34

    
35
#define NH_BUFFER_SIZE 1000
36
#define NH_LOOKUP_SIZE 1000
37
#define NH_PACKET_TIMEOUT {0, 500*1000}
38
#define NH_ML_INIT_TIMEOUT {1, 0}
39

    
40
static int sIdx = 0;
41
static int rIdxML = 0;        //reveive from ML to this buffer position
42
static int rIdxUp = 0;        //hand up to layer above at this buffer position
43

    
44
typedef struct nodeID {
45
        socketID_handle addr;
46
        int connID;        // connection associated to this node, -1 if myself
47
        int refcnt;
48
#ifdef MONL
49
        //n quick and dirty static vector for measures TODO: make it dinamic
50
        MonHandler mhs[20];
51
        int n_mhs;
52
#endif
53
//        int addrSize;
54
//        int addrStringSize;
55
} nodeID;
56

    
57
typedef struct msgData_cb {
58
        int bIdx;        // index of the message in the proper buffer
59
        unsigned char msgType; // message type
60
        int mSize;        // message size
61
        bool conn_cb_called;
62
        bool cancelled;
63
} msgData_cb;
64

    
65
static struct nodeID **lookup_array;
66
static int lookup_max = NH_LOOKUP_SIZE;
67
static int lookup_curr = 0;
68

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

    
72
// pointers to the msgs to be send
73
static uint8_t *sendingBuffer[NH_BUFFER_SIZE];
74
// pointers to the received msgs + sender nodeID
75
struct receivedB {
76
        struct nodeID *id;
77
        int len;
78
        uint8_t *data;
79
};
80
static struct receivedB receivedBuffer[NH_BUFFER_SIZE];
81
/**/ static int recv_counter =0; static int snd_counter =0;
82

    
83

    
84
static void connReady_cb (int connectionID, void *arg);
85
static struct nodeID *new_node(socketID_handle peer) {
86
        send_params params = {0,0,0,0};
87
        struct nodeID *res = malloc(sizeof(struct nodeID));
88
        if (!res) {
89
                 fprintf(stderr, "Net-helper : memory error\n");
90
                 return NULL;
91
        }
92
        memset(res, 0, sizeof(struct nodeID));
93

    
94
        res->addr = malloc(SOCKETID_SIZE);
95
        if (! res->addr) {
96
                free (res);
97
                fprintf(stderr, "Net-helper : memory error while creating a new nodeID \n");
98
                return NULL;
99
        }
100
        memset(res->addr, 0, SOCKETID_SIZE);
101
        memcpy(res->addr, peer ,SOCKETID_SIZE);
102

    
103
        res->refcnt = 1;
104

    
105
        res->connID = mlOpenConnection(peer, &connReady_cb, NULL, params);
106

    
107
        return res;
108
}
109

    
110

    
111
static struct nodeID **id_lookup(socketID_handle target) {
112

    
113
        int i,here=-1;
114
        for (i=0;i<lookup_curr;i++) {
115
                if (lookup_array[i] == NULL) {
116
                        if (here < 0) {
117
                                here = i;
118
                        }
119
                } else if (!mlCompareSocketIDs(lookup_array[i]->addr,target)) {
120
                        return &lookup_array[i];
121
                }
122
        }
123

    
124
        if (here == -1) {
125
                here = lookup_curr++;
126
        }
127

    
128
        if (lookup_curr > lookup_max) {
129
                lookup_max *= 2;
130
                lookup_array = realloc(lookup_array,lookup_max*sizeof(struct nodeID*));
131
        }
132

    
133
        lookup_array[here] = new_node(target);
134
        return &lookup_array[here];
135
}
136

    
137
static struct nodeID *id_lookup_dup(socketID_handle target) {
138
        return nodeid_dup(*id_lookup(target));
139
}
140

    
141

    
142
/**
143
 * Look for a free slot in the received buffer and allocates it for immediate use
144
 * @return the index of a free slot in the received msgs buffer, -1 if no free slot available.
145
 */
146
static int next_R() {
147
        if (receivedBuffer[rIdxML].data==NULL) {
148
                int ret = rIdxML;
149
                rIdxML = (rIdxML+1)%NH_BUFFER_SIZE;
150
                return ret;
151
        } else {
152
                //TODO: handle receive overload situation!
153
                return -1;
154
        }
155
}
156

    
157
/**
158
 * Look for a free slot in the sending buffer and allocates it for immediate use
159
 * @return the index of a free slot in the sending msgs buffer, -1 if no free slot available.
160
 */
161
static int next_S() {
162
        const int size = 1024;
163
        if (sendingBuffer[sIdx]==NULL) {
164
                sendingBuffer[sIdx] = malloc(size);
165
        }
166
        else {
167
                int count;
168
                for (count=0;count<NH_BUFFER_SIZE;count++) {
169
                        sIdx = (++sIdx)%NH_BUFFER_SIZE;
170
                        if (sendingBuffer[sIdx]==NULL)
171
                                break;
172
                }
173
                if (count==NH_BUFFER_SIZE)
174
                        return -1;
175
                else {
176
                        sendingBuffer[sIdx] = malloc(size);
177
                }
178
        }
179
        return sIdx;
180
}
181

    
182

    
183
/**
184
 * Callback used by ml to confirm its initialization. Create a valid self nodeID and register to receive data from remote peers.
185
 * @param local_socketID
186
 * @param errorstatus
187
 */
188
static void init_myNodeID_cb (socketID_handle local_socketID,int errorstatus) {
189
        switch (errorstatus) {
190
        case 0:
191
                me->addr = malloc(SOCKETID_SIZE);
192
                if (! me->addr) {
193
                        fprintf(stderr, "Net-helper : memory error while creating my new nodeID \n");
194
                        return;
195
                }
196

    
197
                memcpy(me->addr,local_socketID,SOCKETID_SIZE);
198
        //        me->addrSize = SOCKETID_SIZE;
199
        //        me->addrStringSize = SOCKETID_STRING_SIZE;
200
                me->connID = -1;
201
                me->refcnt = 1;
202
        //        fprintf(stderr,"Net-helper init : received my own socket: %s.\n",node_addr(me));
203
                break;
204
        case -1:
205
                //
206
                fprintf(stderr,"Net-helper init : socket error occurred in ml while creating socket\n");
207
                exit(1);
208
                break;
209
        case 1:
210
                //
211
                fprintf(stderr,"Net-helper init : NAT traversal failed while creating socket\n");
212
                exit(1);
213
                break;
214
        case 2:
215
            fprintf(stderr,"Net-helper init : NAT traversal timeout while creating socket\n");
216
            fprintf(stderr,"Net-helper init : Retrying without STUN\n");
217
            mlSetStunServer(0,NULL);
218
            break;
219
        default :        // should never happen
220
                //
221
                fprintf(stderr,"Net-helper init : Unknown error in ml while creating socket\n");
222
        }
223

    
224
}
225

    
226
/**
227
 * Timeout callback to be set in the eventlib loop as needed
228
 * @param socket
229
 * @param flag
230
 * @param arg
231
 */
232
static void t_out_cb (int socket, short flag, void* arg) {
233

    
234
        timeoutFired = 1;
235
//        fprintf(stderr,"TIMEOUT!!!\n");
236
//        event_base_loopbreak(base);
237
}
238

    
239
/**
240
 * Callback called by ml when a remote node ask for a connection
241
 * @param connectionID
242
 * @param arg
243
 */
244
static void receive_conn_cb(int connectionID, void *arg) {
245
//    fprintf(stderr, "Net-helper : remote peer opened the connection %d with arg = %d\n", connectionID,(int)arg);
246

    
247
}
248

    
249
void free_sending_buffer(int i)
250
{
251
        free(sendingBuffer[i]);
252
        sendingBuffer[i] = NULL;
253
}
254

    
255
/**
256
 * Callback called by the ml when a connection is ready to be used to send data to a remote peer
257
 * @param connectionID
258
 * @param arg
259
 */
260
static void connReady_cb (int connectionID, void *arg) {
261
        char mt;
262
        msgData_cb *p;
263
        p = (msgData_cb *)arg;
264
        if (p == NULL) return;
265
        if (p->cancelled) {
266
            free(p);
267
            return;
268
        }
269
        mlSendData(connectionID,(char *)(sendingBuffer[p->bIdx]),p->mSize,p->msgType,NULL);
270
/**/        mt = ((char*)sendingBuffer[p->bIdx])[0]; ++snd_counter;
271
        if (mt!=MSG_TYPE_TOPOLOGY &&
272
                mt!=MSG_TYPE_CHUNK && mt!=MSG_TYPE_SIGNALLING) {
273
                        fprintf(stderr,"Net-helper ERROR! Sent message # %d of type %c and size %d\n",
274
                                snd_counter,mt+'0', p->mSize);}
275
        free_sending_buffer(p->bIdx);
276
//        fprintf(stderr,"Net-helper: Message # %d for connection %d sent!\n ", p->bIdx,connectionID);
277
        //        event_base_loopbreak(base);
278
        p->conn_cb_called = true;
279
}
280

    
281
/**
282
 * Callback called by ml when a connection error occurs
283
 * @param connectionID
284
 * @param arg
285
 */
286
static void connError_cb (int connectionID, void *arg) {
287
        // simply get rid of the msg in the buffer....
288
        msgData_cb *p;
289
        p = (msgData_cb *)arg;
290
        if (p != NULL) {
291
                fprintf(stderr,"Net-helper: Connection %d could not be established to send msg %d.\n ", connectionID,p->bIdx);
292
                if (p->cancelled) {
293
                        free(p);//p->mSize = -1;
294
                } else {
295
                        p->conn_cb_called = true;
296
                }
297
        }
298
        //        event_base_loopbreak(base);
299
}
300

    
301

    
302
/**
303
 * Callback to receive data from ml
304
 * @param buffer
305
 * @param buflen
306
 * @param msgtype
307
 * @param arg
308
 */
309
static void recv_data_cb(char *buffer, int buflen, unsigned char msgtype, recv_params *arg) {
310
// TODO: lacks a void* arg... moreover: recv_params has a msgtype, but there is also a msgtype explicit argument...
311
        char str[SOCKETID_STRING_SIZE];
312
//        fprintf(stderr, "Net-helper : called back with some news...\n");
313
/**/ ++recv_counter;
314
        if (arg->remote_socketID != NULL)
315
                mlSocketIDToString(arg->remote_socketID,str,SOCKETID_STRING_SIZE);
316
        else
317
                sprintf(str,"!Unknown!");
318
        if (arg->nrMissingBytes || !arg->firstPacketArrived) {
319
            fprintf(stderr, "Net-helper : corrupted message arrived from %s\n",str);
320
/**/    fprintf(stderr, "\tMessage # %d -- Message type: %hhd -- Missing # %d bytes%s\n",
321
                        recv_counter, buffer[0],arg->nrMissingBytes, arg->firstPacketArrived?"":", Missing first!");
322
        }
323
        else {
324
        //        fprintf(stderr, "Net-helper : message arrived from %s\n",str);
325
                // buffering the received message only if possible, otherwise ignore it...
326
                int index = next_R();
327
                if (index<0) {
328
                        fprintf(stderr,"Net-helper: receive buffer full\n ");
329
                        return;
330
                } else {
331
                        receivedBuffer[index].data = malloc(buflen);
332
                        if (receivedBuffer[index].data == NULL) {
333
                                fprintf(stderr,"Net-helper: memory full, can't receive!\n ");
334
                                return;
335
                        }
336
                        receivedBuffer[index].len = buflen;
337
                        memcpy(receivedBuffer[index].data,buffer,buflen);
338
                          // save the socketID of the sender
339
                        receivedBuffer[index].id = id_lookup_dup(arg->remote_socketID);
340
                }
341
  }
342
//        event_base_loopbreak(base);
343
}
344

    
345

    
346
struct nodeID *net_helper_init(const char *IPaddr, int port) {
347

    
348
        struct timeval tout = NH_ML_INIT_TIMEOUT;
349
        int s, i;
350
        base = event_base_new();
351
        lookup_array = calloc(lookup_max,sizeof(struct nodeID *));
352

    
353
        me = malloc(sizeof(nodeID));
354
        if (me == NULL) {
355
                return NULL;
356
        }
357
        memset(me,0,sizeof(nodeID));
358
        me->connID = -10;        // dirty trick to spot later if the ml has called back ...
359
        me->refcnt = 1;
360

    
361
        for (i=0;i<NH_BUFFER_SIZE;i++) {
362
                sendingBuffer[i] = NULL;
363
                receivedBuffer[i].data = NULL;
364
        }
365

    
366
        mlRegisterErrorConnectionCb(&connError_cb);
367
        mlRegisterRecvConnectionCb(&receive_conn_cb);
368
        s = mlInit(1,tout,port,IPaddr,3478,"stun.ekiga.net",&init_myNodeID_cb,base);
369
        if (s < 0) {
370
                fprintf(stderr, "Net-helper : error initializing ML!\n");
371
                free(me);
372
                return NULL;
373
        }
374

    
375
#ifdef MONL
376
        eventbase = base;
377
        void *repoclient;
378

    
379
        // Initialize logging
380
        grapesInitLog(DCLOG_WARNING, NULL, NULL);
381

    
382
        repInit("");
383
        repoclient = repOpen("repository.napa-wine.eu:9832",60);
384
        if (repoclient == NULL) fatal("Unable to initialize repoclient");
385
        monInit(base, repoclient);
386
#endif
387

    
388
        while (me->connID<-1) {
389
        //        event_base_once(base,-1, EV_TIMEOUT, &t_out_cb, NULL, &tout);
390
                event_base_loop(base,EVLOOP_ONCE);
391
        }
392
        timeoutFired = 0;
393
//        fprintf(stderr,"Net-helper init : back from init!\n");
394

    
395
        return me;
396
}
397

    
398

    
399
void bind_msg_type (unsigned char msgtype) {
400

    
401
                        mlRegisterRecvDataCb(&recv_data_cb,msgtype);
402
}
403

    
404

    
405
void send_to_peer_cb(int fd, short event, void *arg)
406
{
407
        msgData_cb *p = (msgData_cb *) arg;
408
        if (p->conn_cb_called) {
409
                free(p);
410
        }
411
        else { //don't send it anymore
412
                free_sending_buffer(p->bIdx);
413
                p->cancelled = true;
414
                // don't free p, the other timeout will do it
415
        }
416
}
417

    
418
/**
419
 * Called by the application to send data to a remote peer
420
 * @param from
421
 * @param to
422
 * @param buffer_ptr
423
 * @param buffer_size
424
 * @return The dimension of the buffer or -1 if a connection error occurred.
425
 */
426
int send_to_peer(const struct nodeID *from, struct nodeID *to, const uint8_t *buffer_ptr, int buffer_size)
427
{
428
        msgData_cb *p;
429
        int current;
430
        send_params params = {0,0,0,0};
431

    
432
        // if buffer is full, discard the message and return an error flag
433
        int index = next_S();
434
        if (index<0) {
435
                // free(buffer_ptr);
436
                fprintf(stderr,"Net-helper: buffer full\n ");
437
                return -1;
438
        }
439
        sendingBuffer[index] = realloc(sendingBuffer[index],buffer_size);
440
        memset(sendingBuffer[index],0,buffer_size);
441
        memcpy(sendingBuffer[index],buffer_ptr,buffer_size);
442
        // free(buffer_ptr);
443
        p = malloc(sizeof(msgData_cb));
444
        p->bIdx = index; p->mSize = buffer_size; p->msgType = (unsigned char)buffer_ptr[0]; p->conn_cb_called = false; p->cancelled = false;
445
        current = p->bIdx;
446

    
447
        to->connID = mlOpenConnection(to->addr,&connReady_cb,p, params);
448
        if (to->connID<0) {
449
                free_sending_buffer(current);
450
                fprintf(stderr,"Net-helper: Couldn't get a connection ID to send msg %d.\n ", p->bIdx);
451
                free(p);
452
                return -1;
453
        }
454
        else {
455
                struct timeval timeout = NH_PACKET_TIMEOUT;
456
                event_base_once(base, -1, EV_TIMEOUT, send_to_peer_cb, (void *) p, &timeout);
457
                return buffer_size; //p->mSize;
458
        }
459

    
460
}
461

    
462

    
463
/**
464
 * Called by an application to receive data from remote peers
465
 * @param local
466
 * @param remote
467
 * @param buffer_ptr
468
 * @param buffer_size
469
 * @return The number of received bytes or -1 if some error occurred.
470
 */
471
int recv_from_peer(const struct nodeID *local, struct nodeID **remote, uint8_t *buffer_ptr, int buffer_size)
472
{
473
        int size;
474
        if (receivedBuffer[rIdxUp].data==NULL) {        //block till first message arrives
475
                wait4data(local, NULL, NULL);
476
        }
477

    
478
        assert(receivedBuffer[rIdxUp].data && receivedBuffer[rIdxUp].id);
479

    
480
        (*remote) = receivedBuffer[rIdxUp].id;
481
        // retrieve a msg from the buffer
482
        size = receivedBuffer[rIdxUp].len;
483
        if (size>buffer_size) {
484
                fprintf(stderr, "Net-helper : recv_from_peer: buffer too small (size:%d > buffer_size: %d)!\n",size,buffer_size);
485
                return -1;
486
        }
487
        memcpy(buffer_ptr, receivedBuffer[rIdxUp].data, size);
488
        free(receivedBuffer[rIdxUp].data);
489
        receivedBuffer[rIdxUp].data = NULL;
490
        receivedBuffer[rIdxUp].id = NULL;
491

    
492
        rIdxUp = (rIdxUp+1)%NH_BUFFER_SIZE;
493

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

    
496
        return size;
497
}
498

    
499

    
500
int wait4data(const struct nodeID *n, struct timeval *tout, fd_set *dummy) {
501

    
502
//        fprintf(stderr,"Net-helper : Waiting for data to come...\n");
503
        if (tout) {        //if tout==NULL, loop wait infinitely
504
                event_base_once(base,-1, EV_TIMEOUT, &t_out_cb, NULL, tout);
505
        }
506
        while(receivedBuffer[rIdxUp].data==NULL && timeoutFired==0) {
507
        //        event_base_dispatch(base);
508
                event_base_loop(base,EVLOOP_ONCE);
509
        }
510
        timeoutFired = 0;
511
//        fprintf(stderr,"Back from eventlib loop.\n");
512

    
513
        if (receivedBuffer[rIdxUp].data!=NULL)
514
                return 1;
515
        else
516
                return 0;
517
}
518

    
519
socketID_handle getRemoteSocketID(const char *ip, int port) {
520
        char str[SOCKETID_STRING_SIZE];
521
        socketID_handle h;
522

    
523
        snprintf(str, SOCKETID_STRING_SIZE, "%s:%d-%s:%d", ip, port, ip, port);
524
        h = malloc(SOCKETID_SIZE);
525
        mlStringToSocketID(str, h);
526

    
527
        return h;
528
}
529

    
530
struct nodeID *create_node(const char *rem_IP, int rem_port) {
531
        socketID_handle s;
532
        struct nodeID *remote;
533

    
534
        s = getRemoteSocketID(rem_IP, rem_port);
535
        remote = id_lookup_dup(s);
536
        free(s);
537

    
538
        return remote;
539
}
540

    
541
// TODO: check why closing the connection is annoying for the ML
542
void nodeid_free(struct nodeID *n) {
543
        if (n && (--(n->refcnt) == 1)) {
544
                struct nodeID **npos;
545

    
546
/*
547
        //        mlCloseConnection(n->connID);
548
                npos = id_lookup(n->addr);
549
                *npos = NULL;
550
                mlCloseSocket(n->addr);
551
                free(n);
552
*/
553
        }
554
}
555

    
556

    
557
const char *node_addr(const struct nodeID *s)
558
{
559
  static char addr[256];
560
  // TODO: mlSocketIDToString always return 0 !!!
561
  int r = mlSocketIDToString(s->addr,addr,256);
562
  if (!r)
563
          return addr;
564
  else
565
          return "";
566
}
567

    
568
struct nodeID *nodeid_dup(struct nodeID *s)
569
{
570
        s->refcnt++;
571
        return s;
572
}
573

    
574
int nodeid_equal(const struct nodeID *s1, const struct nodeID *s2)
575
{
576
        return (mlCompareSocketIDs(s1->addr,s2->addr) == 0);
577
}
578

    
579
int nodeid_dump(uint8_t *b, const struct nodeID *s)
580
{
581
  mlSocketIDToString(s->addr,(char *)b,SOCKETID_STRING_SIZE);
582
  //fprintf(stderr,"Dumping nodeID : ho scritto %s (%d bytes)\n",b, strlen((char *)b));
583

    
584
//        memcpy(b, s->addr,SOCKETID_SIZE);//sizeof(struct sockaddr_in6)*2
585
//        return SOCKETID_SIZE;//sizeof(struct sockaddr_in6)*2;
586

    
587
  return 1 + strlen((char *)b);        //terminating \0 IS included in the size
588
}
589

    
590
struct nodeID *nodeid_undump(const uint8_t *b, int *len)
591
{
592
  uint8_t sid[SOCKETID_SIZE];
593
  socketID_handle h = (socketID_handle) sid;
594
  mlStringToSocketID((char *)b,h);
595
  *len = strlen((char*)b) + 1;
596
  return id_lookup_dup(h);
597
}