Statistics
| Branch: | Revision:

grapes / som / net_helper-ml.c @ 14922983

History | View | Annotate | Download (13.7 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
/**
20
 * libevent pointer
21
 */
22
struct event_base *base;
23

    
24
#define NH_BUFFER_SIZE 100
25

    
26
static int sIdx = 0;
27
static int rIdx = 0;
28

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

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

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

    
46
// pointers to the msgs to be send
47
static uint8_t *sendingBuffer[NH_BUFFER_SIZE];
48
// pointers to the received msgs + sender nodeID
49
static uint8_t *receivedBuffer[NH_BUFFER_SIZE][2];
50

    
51

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

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

    
103

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

    
139
}
140

    
141
/**
142
 * Timeout callback to be set in the eventlib loop as needed
143
 * @param socket
144
 * @param flag
145
 * @param arg
146
 */
147
static void t_out_cb (int socket, short flag, void* arg) {
148

    
149
        timeoutFired = 1;
150
//        fprintf(stderr,"TIMEOUT!!!\n");
151
//        event_base_loopbreak(base);
152
}
153

    
154
/**
155
 * Callback called by ml when a remote node ask for a connection
156
 * @param connectionID
157
 * @param arg
158
 */
159
static void receive_conn_cb(int connectionID, void *arg) {
160
//    fprintf(stderr, "Net-helper : remote peer opened the connection %d with arg = %d\n", connectionID,(int)arg);
161

    
162
}
163

    
164
/**
165
 * Callback called by the ml when a connection is ready to be used to send data to a remote peer
166
 * @param connectionID
167
 * @param arg
168
 */
169
static void connReady_cb (int connectionID, void *arg) {
170

    
171
        msgData_cb *p;
172
        p = (msgData_cb *)arg;
173
        if (p == NULL) return;
174
        mlSendData(connectionID,(char *)(sendingBuffer[p->bIdx]),p->mSize,p->msgType,NULL);
175
        free(sendingBuffer[p->bIdx]);
176
        sendingBuffer[p->bIdx] = NULL;
177
//        fprintf(stderr,"Net-helper: Message # %d for connection %d sent!\n ", p->bIdx,connectionID);
178
        //        event_base_loopbreak(base);
179
        free(p);
180
}
181

    
182
/**
183
 * Callback called by ml when a connection error occurs
184
 * @param connectionID
185
 * @param arg
186
 */
187
static void connError_cb (int connectionID, void *arg) {
188
        // simply get rid of the msg in the buffer....
189
        msgData_cb *p;
190
        p = (msgData_cb *)arg;
191
        if (p != NULL) {
192
                fprintf(stderr,"Net-helper: Connection %d could not be established to send msg %d.\n ", connectionID,p->bIdx);
193
                free(sendingBuffer[p->bIdx]);
194
                sendingBuffer[p->bIdx] = NULL;
195
                p->mSize = -1;
196
        }
197
        //        event_base_loopbreak(base);
198
}
199

    
200

    
201
/**
202
 * Callback to receive data from ml
203
 * @param buffer
204
 * @param buflen
205
 * @param msgtype
206
 * @param arg
207
 */
208
static void recv_data_cb(char *buffer, int buflen, unsigned char msgtype, recv_params *arg) {
209
// TODO: lacks a void* arg... moreover: recv_params has a msgtype, but there is also a msgtype explicit argument...
210
//        fprintf(stderr, "Net-helper : called back with some news...\n");
211
        char str[SOCKETID_STRING_SIZE];
212
        if (arg->remote_socketID != NULL)
213
                mlSocketIDToString(arg->remote_socketID,str,SOCKETID_STRING_SIZE);
214
        else
215
                sprintf(str,"!Unknown!");
216
        if (arg->nrMissingBytes || !arg->firstPacketArrived) {
217
            fprintf(stderr, "Net-helper : corrupted message arrived from %s\n",str);
218
        }
219
        else {
220
        //        fprintf(stderr, "Net-helper : message arrived from %s\n",str);
221
                // buffering the received message only if possible, otherwise ignore it...
222
                int index = next_R();
223
                if (index >=0) {
224
                //        receivedBuffer[index][0] = malloc(buflen);
225
                        if (receivedBuffer[index][0] == NULL) {
226
                                fprintf(stderr, "Net-helper : memory error while creating a new message buffer \n");
227
                                return;
228
                        }
229
                        // creating a new sender nodedID
230
                        receivedBuffer[index][1] = malloc(sizeof(nodeID));
231
                        if (receivedBuffer[index][1]==NULL) {
232
                                free (receivedBuffer[index][0]);
233
                                receivedBuffer[index][0] = NULL;
234
                                fprintf(stderr, "Net-helper : memory error while creating a new nodeID. Message from %s is lost.\n", str);
235
                                return;
236
                        }
237
                        else {
238
                                memset(receivedBuffer[index][1], 0, sizeof(struct nodeID));
239
                                nodeID *remote; remote = (nodeID*)(receivedBuffer[index][1]);
240
                                receivedBuffer[index][0] = realloc(receivedBuffer[index][0],buflen+sizeof(int));
241
                                memset(receivedBuffer[index][0],0,buflen+sizeof(int));
242
                                memcpy(receivedBuffer[index][0],&buflen,sizeof(int));
243
                                //*(receivedBuffer[index][0]) = buflen;
244
                                memcpy((receivedBuffer[index][0])+sizeof(int),buffer,buflen);
245
                                  // get the socketID of the sender
246
                                remote->addr = malloc(SOCKETID_SIZE);
247
                                if (remote->addr == NULL) {
248
                                          free (remote);
249
                                          fprintf(stderr, "Net-helper : memory error while creating a new nodeID \n");
250
                                          return;
251
                                }
252
                                else {
253
                                        memset(remote->addr, 0, SOCKETID_SIZE);
254
                                        memcpy(remote->addr, arg->remote_socketID ,SOCKETID_SIZE);
255
                                //        remote->addrSize = SOCKETID_SIZE;
256
                                //        remote->addrStringSize = SOCKETID_STRING_SIZE;
257
                                        remote->connID = arg->connectionID;
258
                                        remote->refcnt = 1;
259
                                }
260
                        }
261
                }
262
  }
263
//        event_base_loopbreak(base);
264
}
265

    
266

    
267
struct nodeID *net_helper_init(const char *IPaddr, int port) {
268

    
269
        struct timeval tout = {1, 0};
270
        base = event_base_new();
271

    
272
        me = malloc(sizeof(nodeID));
273
        if (me == NULL) {
274
                return NULL;
275
        }
276
        memset(me,0,sizeof(nodeID));
277
        me->addr = malloc(SOCKETID_SIZE);
278
        if (me->addr == NULL) {
279
                free(me);
280
                return NULL;
281
        }
282
        memset(me->addr,0,SOCKETID_SIZE);
283
        me->connID = -10;        // dirty trick to spot later if the ml has called back ...
284
        me->refcnt = 1;
285

    
286
        int i;
287
        for (i=0;i<NH_BUFFER_SIZE;i++) {
288
                sendingBuffer[i] = NULL;
289
                receivedBuffer[i][0] = NULL;
290
        }
291

    
292
        mlRegisterErrorConnectionCb(&connError_cb);
293
        mlRegisterRecvConnectionCb(&receive_conn_cb);
294
        mlInit(1,tout,port,IPaddr,0,NULL,&init_myNodeID_cb,base);
295
        while (me->connID<-1) {
296
        //        event_base_once(base,-1, EV_TIMEOUT, &t_out_cb, NULL, &tout);
297
                event_base_loop(base,EVLOOP_ONCE);
298
        }
299
        timeoutFired = 0;
300
//        fprintf(stderr,"Net-helper init : back from init!\n");
301

    
302
        return me;
303
}
304

    
305

    
306
void bind_msg_type (unsigned char msgtype) {
307

    
308
                        mlRegisterRecvDataCb(&recv_data_cb,msgtype);
309
}
310

    
311

    
312
/**
313
 * Called by the application to send data to a remote peer
314
 * @param from
315
 * @param to
316
 * @param buffer_ptr
317
 * @param buffer_size
318
 * @return The dimension of the buffer or -1 if a connection error occurred.
319
 */
320
int send_to_peer(const struct nodeID *from, struct nodeID *to, const uint8_t *buffer_ptr, int buffer_size)
321
{
322
        // if buffer is full, discard the message and return an error flag
323
        int index = next_S();
324
        if (index<0) {
325
                // free(buffer_ptr);
326
                return -1;
327
        }
328
        sendingBuffer[index] = realloc(sendingBuffer[index],buffer_size);
329
        memset(sendingBuffer[index],0,buffer_size);
330
        memcpy(sendingBuffer[index],buffer_ptr,buffer_size);
331
        // free(buffer_ptr);
332
        msgData_cb *p = malloc(sizeof(msgData_cb));
333
        p->bIdx = index; p->mSize = buffer_size; p->msgType = (unsigned char)buffer_ptr[0];
334
        int current = p->bIdx;
335
        send_params params = {0,0,0,0};
336
        to->connID = mlOpenConnection(to->addr,&connReady_cb,p, params);
337
        if (to->connID<0) {
338
                free(sendingBuffer[current]);
339
                sendingBuffer[current] = NULL;
340
                fprintf(stderr,"Net-helper: Couldn't get a connection ID to send msg %d.\n ", p->bIdx);
341
                free(p);
342
                return -1;
343
        }
344
        else {
345
                return buffer_size; //p->mSize;
346
        }
347

    
348
}
349

    
350

    
351
/**
352
 * Called by an application to receive data from remote peers
353
 * @param local
354
 * @param remote
355
 * @param buffer_ptr
356
 * @param buffer_size
357
 * @return The number of received bytes or -1 if some error occurred.
358
 */
359
int recv_from_peer(const struct nodeID *local, struct nodeID **remote, uint8_t *buffer_ptr, int buffer_size)
360
{
361
        int size;
362
        // this should never happen... if it does, index handling is faulty...
363
        if (receivedBuffer[rIdx][1]==NULL) {
364
                fprintf(stderr, "Net-helper : memory error while creating a new nodeID \n");
365
                return -1;
366
        }
367

    
368
        (*remote) = (nodeID*)(receivedBuffer[rIdx][1]);
369
        // retrieve a msg from the buffer
370
        size = *((int*)(receivedBuffer[rIdx][0]));
371
        if (size>buffer_size) {
372
                fprintf(stderr, "Net-helper : recv_from_peer: buffer too small (size:%d > buffer_size: %d)!\n",size,buffer_size);
373
                return -1;
374
        }
375
        memcpy(buffer_ptr, (receivedBuffer[rIdx][0])+sizeof(int), size);
376
        free(receivedBuffer[rIdx][0]);
377
        receivedBuffer[rIdx][0] = NULL;
378
        receivedBuffer[rIdx][1] = NULL;
379

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

    
382
        return size;
383
}
384

    
385

    
386
int wait4data(const struct nodeID *n, struct timeval *tout) {
387

    
388
//        fprintf(stderr,"Net-helper : Waiting for data to come...\n");
389
        event_base_once(base,-1, EV_TIMEOUT, &t_out_cb, NULL, tout);
390
        while(receivedBuffer[rIdx][0]==NULL && timeoutFired==0) {
391
        //        event_base_dispatch(base);
392
                event_base_loop(base,EVLOOP_ONCE);
393
        }
394
        timeoutFired = 0;
395
//        fprintf(stderr,"Back from eventlib loop.\n");
396

    
397
        if (receivedBuffer[rIdx][0]!=NULL)
398
                return 1;
399
        else
400
                return 0;
401
}
402

    
403

    
404

    
405

    
406
struct nodeID *create_node(const char *rem_IP, int rem_port) {
407
        struct nodeID *remote = malloc(sizeof(nodeID));
408
        if (remote == NULL) {
409
                return NULL;
410
        }
411
//        remote->addr = malloc(sizeof(SOCKETID_SIZE));
412
//        if (remote->addr == NULL) {
413
//                free(remote);
414
//                return NULL;
415
//        }
416
//        remote->addrSize = SOCKETID_SIZE;
417
//        remote->addrStringSize = SOCKETID_STRING_SIZE;
418
        remote->addr = getRemoteSocketID(rem_IP, rem_port);
419
        send_params params = {0,0,0,0};
420
        remote->connID = mlOpenConnection(remote->addr,&connReady_cb,NULL, params);
421
        remote->refcnt = 1;
422
        return remote;
423
}
424

    
425
// TODO: check why closing the connection is annoying for the ML
426
void nodeid_free(struct nodeID *n) {
427

    
428
//        mlCloseConnection(n->connID);
429
//        mlCloseSocket(n->addr);
430
//        free(n);
431
        if (n && (--(n->refcnt) == 0)) {
432
        //        mlCloseConnection(n->connID);
433
                mlCloseSocket(n->addr);
434
                free(n);
435
        }
436
}
437

    
438

    
439
const char *node_addr(const struct nodeID *s)
440
{
441
  static char addr[256];
442
  // TODO: mlSocketIDToString always return 0 !!!
443
  int r = mlSocketIDToString(s->addr,addr,256);
444
  if (!r)
445
          return addr;
446
  else
447
          return "";
448
}
449

    
450
struct nodeID *nodeid_dup(struct nodeID *s)
451
{
452
//  struct nodeID *res;
453
//
454
//  res = malloc(sizeof(struct nodeID));
455
//  if (res != NULL) {
456
//          res->addr = malloc(SOCKETID_SIZE);
457
//          if (res->addr != NULL) {
458
//                 memcpy(res->addr, s->addr, SOCKETID_SIZE);
459
//        //         res->addrSize = SOCKETID_SIZE;
460
//        //         res->addrStringSize = SOCKETID_STRING_SIZE;
461
//                 res->connID = s->connID;
462
//          }
463
//          else {
464
//                free(res);
465
//                res = NULL;
466
//                fprintf(stderr,"Net-helper : Error while duplicating nodeID...\n");
467
//          }
468
//  }
469
//        return res;
470
        s->refcnt++;
471
        return s;
472
}
473

    
474
int nodeid_equal(const struct nodeID *s1, const struct nodeID *s2)
475
{
476
        return (mlCompareSocketIDs(s1->addr,s2->addr) == 0);
477
}
478

    
479
int nodeid_dump(uint8_t *b, const struct nodeID *s)
480
{
481
  mlSocketIDToString(s->addr,(char *)b,SOCKETID_STRING_SIZE);
482
  //fprintf(stderr,"Dumping nodeID : ho scritto %s (%d bytes)\n",b, strlen((char *)b));
483

    
484
//        memcpy(b, s->addr,SOCKETID_SIZE);//sizeof(struct sockaddr_in6)*2
485
//        return SOCKETID_SIZE;//sizeof(struct sockaddr_in6)*2;
486

    
487
  return 1 + strlen((char *)b);        //terminating \0 IS included in the size
488
}
489

    
490
struct nodeID *nodeid_undump(const uint8_t *b, int *len)
491
{
492
  struct nodeID *res;
493
  res = malloc(sizeof(struct nodeID));
494
  if (res != NULL) {
495
          memset(res,0,sizeof(struct nodeID));
496
          res->addr = malloc(SOCKETID_SIZE);
497
          if (res->addr != NULL) {
498
                  memset(res->addr,0,SOCKETID_SIZE);
499
                  //memcpy(res->addr, b, SOCKETID_SIZE);
500
                  //*len = SOCKETID_SIZE;
501
                  *len = strlen((char*)b) + 1;
502
                  mlStringToSocketID((char *)b,res->addr);
503
        //          fprintf(stderr,"Node undumped : %s\n",node_addr(res));
504
        //          res->addrSize = SOCKETID_SIZE;
505
        //          res->addrStringSize = SOCKETID_STRING_SIZE;
506
                  res->connID = -1;
507
                  res->refcnt = 1;
508
          }
509
          else {
510
                  free(res);
511
                  res = NULL;
512
                  // TODO: what about *len in this case???
513
                  fprintf(stderr,"Net-helper : Error while 'undumping' nodeID...\n");
514
          }
515
  }
516

    
517

    
518
  return res;
519
}