Statistics
| Branch: | Revision:

grapes / som / net_helper-ml.c @ 27061356

History | View | Annotate | Download (13.7 KB)

1 574aabfa MarcoBiazzini
/*
2
 *  Copyright (c) 2009 Marco Biazzini
3
 *
4 ca44152b CsabaKiraly
 *  This is free software; see lgpl-2.1.txt
5 574aabfa MarcoBiazzini
 */
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 2694dce1 MarcoBiazzini
15 574aabfa MarcoBiazzini
#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 2694dce1 MarcoBiazzini
        int refcnt;
33
//        int addrSize;
34
//        int addrStringSize;
35 574aabfa MarcoBiazzini
} 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 546f9767 AlessandroRusso
        const int size = 1024;
58 574aabfa MarcoBiazzini
        if (receivedBuffer[rIdx][0]==NULL) {
59 546f9767 AlessandroRusso
                receivedBuffer[rIdx][0] = malloc(size);
60 574aabfa MarcoBiazzini
        }
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 546f9767 AlessandroRusso
                        receivedBuffer[rIdx][0] = malloc(size);
72 574aabfa MarcoBiazzini
                }
73
        }
74 546f9767 AlessandroRusso
        memset(receivedBuffer[rIdx][0],0,size);
75 574aabfa MarcoBiazzini
        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 546f9767 AlessandroRusso
        const int size = 1024;
84 574aabfa MarcoBiazzini
        if (sendingBuffer[sIdx]==NULL) {
85 546f9767 AlessandroRusso
                sendingBuffer[sIdx] = malloc(size);
86 574aabfa MarcoBiazzini
        }
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 546f9767 AlessandroRusso
                        sendingBuffer[sIdx] = malloc(size);
98 574aabfa MarcoBiazzini
                }
99
        }
100
        return sIdx;
101
}
102
103 cd2a2a41 MarcoBiazzini
104 574aabfa MarcoBiazzini
/**
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 2694dce1 MarcoBiazzini
        //        me->addrSize = SOCKETID_SIZE;
115
        //        me->addrStringSize = SOCKETID_STRING_SIZE;
116 574aabfa MarcoBiazzini
                me->connID = -1;
117 2694dce1 MarcoBiazzini
                me->refcnt = 1;
118
        //        fprintf(stderr,"Net-helper init : received my own socket: %s.\n",node_addr(me));
119 574aabfa MarcoBiazzini
                break;
120
        case -1:
121
                //
122
                fprintf(stderr,"Net-helper init : socket error occurred in ml while creating socket\n");
123 2694dce1 MarcoBiazzini
                exit(1);
124 574aabfa MarcoBiazzini
                break;
125
        case 1:
126
                //
127
                fprintf(stderr,"Net-helper init : NAT traversal failed while creating socket\n");
128 2694dce1 MarcoBiazzini
                exit(1);
129 574aabfa MarcoBiazzini
                break;
130
        case 2:
131
            fprintf(stderr,"Net-helper init : NAT traversal timeout while creating socket\n");
132 2694dce1 MarcoBiazzini
            exit(2);
133 574aabfa MarcoBiazzini
            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 2694dce1 MarcoBiazzini
//        fprintf(stderr,"TIMEOUT!!!\n");
151 574aabfa MarcoBiazzini
//        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 2694dce1 MarcoBiazzini
//    fprintf(stderr, "Net-helper : remote peer opened the connection %d with arg = %d\n", connectionID,(int)arg);
161 574aabfa MarcoBiazzini
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
        send_params params = {0,0,0,0};
175
        send_Data(connectionID,(char *)(sendingBuffer[p->bIdx]),p->mSize,p->msgType,&params);
176
        free(sendingBuffer[p->bIdx]);
177
        sendingBuffer[p->bIdx] = NULL;
178 2694dce1 MarcoBiazzini
//        fprintf(stderr,"Net-helper: Message # %d for connection %d sent!\n ", p->bIdx,connectionID);
179 574aabfa MarcoBiazzini
        //        event_base_loopbreak(base);
180 f8686a5a CsabaKiraly
        free(p);
181 574aabfa MarcoBiazzini
}
182
183
/**
184
 * Callback called by ml when a connection error occurs
185
 * @param connectionID
186
 * @param arg
187
 */
188
static void connError_cb (int connectionID, void *arg) {
189
        // simply get rid of the msg in the buffer....
190
        msgData_cb *p;
191
        p = (msgData_cb *)arg;
192
        if (p != NULL) {
193
                fprintf(stderr,"Net-helper: Connection %d could not be established to send msg %d.\n ", connectionID,p->bIdx);
194
                free(sendingBuffer[p->bIdx]);
195
                sendingBuffer[p->bIdx] = NULL;
196 546f9767 AlessandroRusso
                p->mSize = -1;
197 574aabfa MarcoBiazzini
        }
198
        //        event_base_loopbreak(base);
199
}
200
201 cd2a2a41 MarcoBiazzini
202 574aabfa MarcoBiazzini
/**
203
 * Callback to receive data from ml
204
 * @param buffer
205
 * @param buflen
206
 * @param msgtype
207
 * @param arg
208
 */
209
static void recv_data_cb(char *buffer, int buflen, unsigned char msgtype, recv_params *arg) {
210
// TODO: lacks a void* arg... moreover: recv_params has a msgtype, but there is also a msgtype explicit argument...
211
//        fprintf(stderr, "Net-helper : called back with some news...\n");
212 2694dce1 MarcoBiazzini
        char str[SOCKETID_STRING_SIZE];
213 574aabfa MarcoBiazzini
        if (arg->remote_socketID != NULL)
214
                socketID_To_String(arg->remote_socketID,str,SOCKETID_STRING_SIZE);
215
        else
216
                sprintf(str,"!Unknown!");
217
        if (arg->nrMissingBytes || !arg->firstPacketArrived) {
218
            fprintf(stderr, "Net-helper : corrupted message arrived from %s\n",str);
219
        }
220
        else {
221 2694dce1 MarcoBiazzini
        //        fprintf(stderr, "Net-helper : message arrived from %s\n",str);
222 574aabfa MarcoBiazzini
                // buffering the received message only if possible, otherwise ignore it...
223
                int index = next_R();
224
                if (index >=0) {
225
                //        receivedBuffer[index][0] = malloc(buflen);
226
                        if (receivedBuffer[index][0] == NULL) {
227
                                fprintf(stderr, "Net-helper : memory error while creating a new message buffer \n");
228
                                return;
229
                        }
230
                        // creating a new sender nodedID
231
                        receivedBuffer[index][1] = malloc(sizeof(nodeID));
232
                        if (receivedBuffer[index][1]==NULL) {
233
                                free (receivedBuffer[index][0]);
234
                                receivedBuffer[index][0] = NULL;
235
                                fprintf(stderr, "Net-helper : memory error while creating a new nodeID. Message from %s is lost.\n", str);
236
                                return;
237
                        }
238
                        else {
239 2694dce1 MarcoBiazzini
                                memset(receivedBuffer[index][1], 0, sizeof(struct nodeID));
240 574aabfa MarcoBiazzini
                                nodeID *remote; remote = (nodeID*)(receivedBuffer[index][1]);
241 2694dce1 MarcoBiazzini
                                receivedBuffer[index][0] = realloc(receivedBuffer[index][0],buflen+sizeof(int));
242 546f9767 AlessandroRusso
                                memset(receivedBuffer[index][0],0,buflen+sizeof(int));
243
                                memcpy(receivedBuffer[index][0],&buflen,sizeof(int));
244
                                //*(receivedBuffer[index][0]) = buflen;
245 2694dce1 MarcoBiazzini
                                memcpy((receivedBuffer[index][0])+sizeof(int),buffer,buflen);
246 574aabfa MarcoBiazzini
                                  // get the socketID of the sender
247
                                remote->addr = malloc(SOCKETID_SIZE);
248
                                if (remote->addr == NULL) {
249
                                          free (remote);
250
                                          fprintf(stderr, "Net-helper : memory error while creating a new nodeID \n");
251
                                          return;
252
                                }
253
                                else {
254 2694dce1 MarcoBiazzini
                                        memset(remote->addr, 0, SOCKETID_SIZE);
255 574aabfa MarcoBiazzini
                                        memcpy(remote->addr, arg->remote_socketID ,SOCKETID_SIZE);
256 2694dce1 MarcoBiazzini
                                //        remote->addrSize = SOCKETID_SIZE;
257
                                //        remote->addrStringSize = SOCKETID_STRING_SIZE;
258 574aabfa MarcoBiazzini
                                        remote->connID = arg->connectionID;
259 2694dce1 MarcoBiazzini
                                        remote->refcnt = 1;
260 574aabfa MarcoBiazzini
                                }
261
                        }
262
                }
263
  }
264
//        event_base_loopbreak(base);
265
}
266
267 cd2a2a41 MarcoBiazzini
268 8c435a0b AlessandroRusso
struct nodeID *net_helper_init(const char *IPaddr, int port) {
269 574aabfa MarcoBiazzini
270
        struct timeval tout = {1, 0};
271
        base = event_base_new();
272
273
        me = malloc(sizeof(nodeID));
274
        if (me == NULL) {
275
                return NULL;
276
        }
277 2694dce1 MarcoBiazzini
        memset(me,0,sizeof(nodeID));
278 574aabfa MarcoBiazzini
        me->addr = malloc(SOCKETID_SIZE);
279
        if (me->addr == NULL) {
280
                free(me);
281
                return NULL;
282
        }
283 2694dce1 MarcoBiazzini
        memset(me->addr,0,SOCKETID_SIZE);
284
        me->connID = -10;        // dirty trick to spot later if the ml has called back ...
285
        me->refcnt = 1;
286 574aabfa MarcoBiazzini
287
        int i;
288
        for (i=0;i<NH_BUFFER_SIZE;i++) {
289
                sendingBuffer[i] = NULL;
290
                receivedBuffer[i][0] = NULL;
291
        }
292
293
        register_Error_connection_cb(&connError_cb);
294
        register_Recv_connection_cb(&receive_conn_cb);
295
        init_messaging_layer(1,tout,port,IPaddr,0,NULL,&init_myNodeID_cb,base);
296 2694dce1 MarcoBiazzini
        while (me->connID<-1) {
297
        //        event_base_once(base,-1, EV_TIMEOUT, &t_out_cb, NULL, &tout);
298
                event_base_loop(base,EVLOOP_ONCE);
299
        }
300
        timeoutFired = 0;
301 574aabfa MarcoBiazzini
//        fprintf(stderr,"Net-helper init : back from init!\n");
302 2694dce1 MarcoBiazzini
303 574aabfa MarcoBiazzini
        return me;
304
}
305
306
307 c95c6af7 MarcoBiazzini
void bind_msg_type (unsigned char msgtype) {
308
309
                        register_Recv_data_cb(&recv_data_cb,msgtype);
310 8c435a0b AlessandroRusso
}
311
312
313 574aabfa MarcoBiazzini
/**
314
 * Called by the application to send data to a remote peer
315
 * @param from
316
 * @param to
317
 * @param buffer_ptr
318
 * @param buffer_size
319 2694dce1 MarcoBiazzini
 * @return The dimension of the buffer or -1 if a connection error occurred.
320 574aabfa MarcoBiazzini
 */
321
int send_to_peer(const struct nodeID *from, struct nodeID *to, const uint8_t *buffer_ptr, int buffer_size)
322
{
323
        // if buffer is full, discard the message and return an error flag
324
        int index = next_S();
325
        if (index<0) {
326
                // free(buffer_ptr);
327
                return -1;
328
        }
329 546f9767 AlessandroRusso
        sendingBuffer[index] = realloc(sendingBuffer[index],buffer_size);
330
        memset(sendingBuffer[index],0,buffer_size);
331 574aabfa MarcoBiazzini
        memcpy(sendingBuffer[index],buffer_ptr,buffer_size);
332
        // free(buffer_ptr);
333
        msgData_cb *p = malloc(sizeof(msgData_cb));
334
        p->bIdx = index; p->mSize = buffer_size; p->msgType = (unsigned char)buffer_ptr[0];
335
        int current = p->bIdx;
336
        to->connID = open_Connection(to->addr,&connReady_cb,p);
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 2694dce1 MarcoBiazzini
                free(p);
342
                return -1;
343 574aabfa MarcoBiazzini
        }
344
        else {
345 27061356 MarcoBiazzini
                return buffer_size; //p->mSize;
346 574aabfa MarcoBiazzini
        }
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 871ae532 CsabaKiraly
        int size;
362 574aabfa MarcoBiazzini
        // 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 871ae532 CsabaKiraly
        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 574aabfa MarcoBiazzini
        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 2694dce1 MarcoBiazzini
        return size;
383 574aabfa MarcoBiazzini
}
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 2694dce1 MarcoBiazzini
//        remote->addrSize = SOCKETID_SIZE;
417
//        remote->addrStringSize = SOCKETID_STRING_SIZE;
418 574aabfa MarcoBiazzini
        remote->addr = getRemoteSocketID(rem_IP, rem_port);
419
        remote->connID = open_Connection(remote->addr,&connReady_cb,NULL);
420 2694dce1 MarcoBiazzini
        remote->refcnt = 1;
421 574aabfa MarcoBiazzini
        return remote;
422
}
423
424
// TODO: check why closing the connection is annoying for the ML
425 dccd020d MarcoBiazzini
void nodeid_free(struct nodeID *n) {
426 2694dce1 MarcoBiazzini
427 574aabfa MarcoBiazzini
//        close_Connection(n->connID);
428 2694dce1 MarcoBiazzini
//        close_Socket(n->addr);
429
//        free(n);
430
        if (n && (--(n->refcnt) == 0)) {
431
        //        close_Connection(n->connID);
432
                close_Socket(n->addr);
433
                free(n);
434
        }
435 574aabfa MarcoBiazzini
}
436
437
438
const char *node_addr(const struct nodeID *s)
439
{
440
  static char addr[256];
441
  // TODO: socketID_To_String always return 0 !!!
442
  int r = socketID_To_String(s->addr,addr,256);
443
  if (!r)
444
          return addr;
445
  else
446
          return "";
447
}
448
449 2694dce1 MarcoBiazzini
struct nodeID *nodeid_dup(struct nodeID *s)
450 574aabfa MarcoBiazzini
{
451 2694dce1 MarcoBiazzini
//  struct nodeID *res;
452
//
453
//  res = malloc(sizeof(struct nodeID));
454
//  if (res != NULL) {
455
//          res->addr = malloc(SOCKETID_SIZE);
456
//          if (res->addr != NULL) {
457
//                 memcpy(res->addr, s->addr, SOCKETID_SIZE);
458
//        //         res->addrSize = SOCKETID_SIZE;
459
//        //         res->addrStringSize = SOCKETID_STRING_SIZE;
460
//                 res->connID = s->connID;
461
//          }
462
//          else {
463
//                free(res);
464
//                res = NULL;
465
//                fprintf(stderr,"Net-helper : Error while duplicating nodeID...\n");
466
//          }
467
//  }
468
//        return res;
469
        s->refcnt++;
470
        return s;
471 574aabfa MarcoBiazzini
}
472
473
int nodeid_equal(const struct nodeID *s1, const struct nodeID *s2)
474
{
475 2694dce1 MarcoBiazzini
        return (compare_socketIDs(s1->addr,s2->addr) == 0);
476 574aabfa MarcoBiazzini
}
477
478
int nodeid_dump(uint8_t *b, const struct nodeID *s)
479
{
480
  socketID_To_String(s->addr,(char *)b,SOCKETID_STRING_SIZE);
481 2694dce1 MarcoBiazzini
  //fprintf(stderr,"Dumping nodeID : ho scritto %s (%d bytes)\n",b, strlen((char *)b));
482 574aabfa MarcoBiazzini
483 2694dce1 MarcoBiazzini
//        memcpy(b, s->addr,SOCKETID_SIZE);//sizeof(struct sockaddr_in6)*2
484
//        return SOCKETID_SIZE;//sizeof(struct sockaddr_in6)*2;
485 574aabfa MarcoBiazzini
486 4173f623 CsabaKiraly
  return 1 + strlen((char *)b);        //terminating \0 IS included in the size
487 574aabfa MarcoBiazzini
}
488
489
struct nodeID *nodeid_undump(const uint8_t *b, int *len)
490
{
491
  struct nodeID *res;
492
  res = malloc(sizeof(struct nodeID));
493
  if (res != NULL) {
494 2694dce1 MarcoBiazzini
          memset(res,0,sizeof(struct nodeID));
495 574aabfa MarcoBiazzini
          res->addr = malloc(SOCKETID_SIZE);
496
          if (res->addr != NULL) {
497 2694dce1 MarcoBiazzini
                  memset(res->addr,0,SOCKETID_SIZE);
498
                  //memcpy(res->addr, b, SOCKETID_SIZE);
499
                  //*len = SOCKETID_SIZE;
500 4173f623 CsabaKiraly
                  *len = strlen((char*)b) + 1;
501 2694dce1 MarcoBiazzini
                  string_To_SocketID((char *)b,res->addr);
502
        //          fprintf(stderr,"Node undumped : %s\n",node_addr(res));
503
        //          res->addrSize = SOCKETID_SIZE;
504
        //          res->addrStringSize = SOCKETID_STRING_SIZE;
505 574aabfa MarcoBiazzini
                  res->connID = -1;
506 2694dce1 MarcoBiazzini
                  res->refcnt = 1;
507 574aabfa MarcoBiazzini
          }
508
          else {
509
                  free(res);
510
                  res = NULL;
511 2694dce1 MarcoBiazzini
                  // TODO: what about *len in this case???
512 574aabfa MarcoBiazzini
                  fprintf(stderr,"Net-helper : Error while 'undumping' nodeID...\n");
513
          }
514
  }
515 2694dce1 MarcoBiazzini
516 574aabfa MarcoBiazzini
517
  return res;
518
}