Statistics
| Branch: | Revision:

streamers / net_helper-ml.c @ 7b017ba0

History | View | Annotate | Download (13.8 KB)

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

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

    
15

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

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

    
25
#define NH_BUFFER_SIZE 100
26
#define NH_MSG_MAXSIZE 1024
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
static uint8_t *receivedBuffer[NH_BUFFER_SIZE][2];
52

    
53

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

    
79
/**
80
 * Look for a free slot in the sending buffer and allocates it for immediate use
81
 * @return the index of a free slot in the sending msgs buffer, -1 if no free slot available.
82
 */
83
static int next_S() {
84
        if (sendingBuffer[sIdx]==NULL) {
85
                sendingBuffer[sIdx] = malloc(NH_MSG_MAXSIZE);
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(NH_MSG_MAXSIZE);
98
                }
99
        }
100
        memset(sendingBuffer[sIdx],0,NH_MSG_MAXSIZE);
101
        return sIdx;
102
}
103

    
104

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

    
140
}
141

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

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

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

    
163
}
164

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

    
172
        msgData_cb *p;
173
        p = (msgData_cb *)arg;
174
        if (p == NULL) return;
175
        send_params params = {0,0,0,0};
176
        send_Data(connectionID,(char *)(sendingBuffer[p->bIdx]),p->mSize,p->msgType,&params);
177
        free(sendingBuffer[p->bIdx]);
178
        sendingBuffer[p->bIdx] = NULL;
179
//        fprintf(stderr,"Net-helper: Message # %d for connection %d sent!\n ", p->bIdx,connectionID);
180
        //        event_base_loopbreak(base);
181
}
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
                free(p);
197
        }
198
        //        event_base_loopbreak(base);
199
}
200

    
201

    
202
/**
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
        char str[SOCKETID_STRING_SIZE];
213
        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
        //        fprintf(stderr, "Net-helper : message arrived from %s\n",str);
222
                // 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
                                memset(receivedBuffer[index][1], 0, sizeof(struct nodeID));
240
                                nodeID *remote; remote = (nodeID*)(receivedBuffer[index][1]);
241
                                receivedBuffer[index][0] = realloc(receivedBuffer[index][0],buflen+sizeof(int));
242
                                *(receivedBuffer[index][0]) = buflen;
243
                                memcpy((receivedBuffer[index][0])+sizeof(int),buffer,buflen);
244
                                  // get the socketID of the sender
245
                                remote->addr = malloc(SOCKETID_SIZE);
246
                                if (remote->addr == NULL) {
247
                                          free (remote);
248
                                          fprintf(stderr, "Net-helper : memory error while creating a new nodeID \n");
249
                                          return;
250
                                }
251
                                else {
252
                                        memset(remote->addr, 0, SOCKETID_SIZE);
253
                                        memcpy(remote->addr, arg->remote_socketID ,SOCKETID_SIZE);
254
                                //        remote->addrSize = SOCKETID_SIZE;
255
                                //        remote->addrStringSize = SOCKETID_STRING_SIZE;
256
                                        remote->connID = arg->connectionID;
257
                                        remote->refcnt = 1;
258
                                }
259
                        }
260
                }
261
  }
262
//        event_base_loopbreak(base);
263
}
264

    
265

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

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

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

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

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

    
301
        return me;
302
}
303

    
304

    
305
void bind_msg_types (unsigned char msgtypes[], int msgtypes_len) {
306
        int i;
307
        for (i=0;i<msgtypes_len;i++) {
308
                        register_Recv_data_cb(&recv_data_cb,msgtypes[i]);
309
        }
310
}
311

    
312

    
313
/**
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
 * @return The dimension of the buffer or -1 if a connection error occurred.
320
 */
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
        memcpy(sendingBuffer[index],buffer_ptr,buffer_size);
330
        // free(buffer_ptr);
331
        msgData_cb *p = malloc(sizeof(msgData_cb));
332
        p->bIdx = index; p->mSize = buffer_size; p->msgType = (unsigned char)buffer_ptr[0];
333
        int current = p->bIdx;
334
        to->connID = open_Connection(to->addr,&connReady_cb,p);
335
        if (to->connID<0) {
336
                free(sendingBuffer[current]);
337
                sendingBuffer[current] = NULL;
338
                fprintf(stderr,"Net-helper: Couldn't get a connection ID to send msg %d.\n ", p->bIdx);
339
                free(p);
340
                return -1;
341
        }
342
        else {
343
        //        fprintf(stderr,"Net-helper: Got a connection ID to send msg %d to %s.\n ",current,node_addr(to));
344
        //                struct timeval tout = {0,500};
345
        //                event_base_once(base,0, EV_TIMEOUT, &t_out_cb, NULL, &tout);
346
                while (sendingBuffer[current] != NULL)
347
                        event_base_loop(base,EVLOOP_ONCE);//  EVLOOP_NONBLOCK
348
//                fprintf(stderr,"Net-helper: Back from eventlib loop with status %d.\n", ok);
349
                free(p);
350
                return buffer_size;
351
        }
352

    
353
}
354

    
355

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

    
372
        (*remote) = (nodeID*)(receivedBuffer[rIdx][1]);
373
        // retrieve a msg from the buffer
374
        memcpy(buffer_ptr, (receivedBuffer[rIdx][0])+sizeof(int), buffer_size);
375
        int size = (int)(*(receivedBuffer[rIdx][0]));
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
        remote->connID = open_Connection(remote->addr,&connReady_cb,NULL);
420
        remote->refcnt = 1;
421
        return remote;
422
}
423

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

    
427
//        close_Connection(n->connID);
428
//        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
}
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
struct nodeID *nodeid_dup(struct nodeID *s)
450
{
451
//  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
}
472

    
473
int nodeid_equal(const struct nodeID *s1, const struct nodeID *s2)
474
{
475
        return (compare_socketIDs(s1->addr,s2->addr) == 0);
476
}
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
  //fprintf(stderr,"Dumping nodeID : ho scritto %s (%d bytes)\n",b, strlen((char *)b));
482
  return 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
}
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
          memset(res,0,sizeof(struct nodeID));
495
          res->addr = malloc(SOCKETID_SIZE);
496
          if (res->addr != NULL) {
497
                  memset(res->addr,0,SOCKETID_SIZE);
498
                  //memcpy(res->addr, b, SOCKETID_SIZE);
499
                  //*len = SOCKETID_SIZE;
500
                  *len = strlen((char*)b);
501
                  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
                  res->connID = -1;
506
                  res->refcnt = 1;
507
          }
508
          else {
509
                  free(res);
510
                  res = NULL;
511
                  // TODO: what about *len in this case???
512
                  fprintf(stderr,"Net-helper : Error while 'undumping' nodeID...\n");
513
          }
514
  }
515

    
516

    
517
  return res;
518
}