Statistics
| Branch: | Revision:

grapes / som / net_helper-ml.c @ 0523cf42

History | View | Annotate | Download (13.9 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
        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
//        fprintf(stderr,"Net-helper: Message # %d for connection %d sent!\n ", p->bIdx,connectionID);
179
        //        event_base_loopbreak(base);
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
                socketID_To_String(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
        register_Error_connection_cb(&connError_cb);
293
        register_Recv_connection_cb(&receive_conn_cb);
294
        init_messaging_layer(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
                        register_Recv_data_cb(&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
        to->connID = open_Connection(to->addr,&connReady_cb,p);
336
        if (to->connID<0) {
337
                free(sendingBuffer[current]);
338
                sendingBuffer[current] = NULL;
339
                fprintf(stderr,"Net-helper: Couldn't get a connection ID to send msg %d.\n ", p->bIdx);
340
                free(p);
341
                return -1;
342
        }
343
        else {
344
        //        fprintf(stderr,"Net-helper: Got a connection ID to send msg %d to %s.\n ",current,node_addr(to));
345
        //                struct timeval tout = {0,500};
346
        //                event_base_once(base,0, EV_TIMEOUT, &t_out_cb, NULL, &tout);
347
                while (sendingBuffer[current] != NULL)
348
                        event_base_loop(base,EVLOOP_ONCE);//  EVLOOP_NONBLOCK
349
//                fprintf(stderr,"Net-helper: Back from eventlib loop with status %d.\n", ok);
350
                int size = p->mSize;
351
                free(p);
352
                return size;
353
        }
354

    
355
}
356

    
357

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

    
374
        (*remote) = (nodeID*)(receivedBuffer[rIdx][1]);
375
        // retrieve a msg from the buffer
376
        memcpy(buffer_ptr, (receivedBuffer[rIdx][0])+sizeof(int), buffer_size);
377
        int size = (int)(*(receivedBuffer[rIdx][0]));
378
        free(receivedBuffer[rIdx][0]);
379
        receivedBuffer[rIdx][0] = NULL;
380
        receivedBuffer[rIdx][1] = NULL;
381

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

    
384
        return size;
385
}
386

    
387

    
388
int wait4data(const struct nodeID *n, struct timeval *tout) {
389

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

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

    
405

    
406

    
407

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

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

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

    
439

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

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

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

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

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

    
489
}
490

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

    
518

    
519
  return res;
520
}