mapiipc.c 61 KB
Newer Older
1
2
3
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
Arne Øslebø's avatar
Arne Øslebø committed
4
5
6
7
8
9
10
11
12
13
14
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <string.h>
15
#include <signal.h>
Arne Øslebø's avatar
Arne Øslebø committed
16
17
18

#include "mapiipc.h"
#include "debug.h"
19
#include "mapidflib.h"
20
#include "devgroupdb.h"
21
#include "mapi_errors.h"
Arne Øslebø's avatar
Arne Øslebø committed
22
23
24

#define HAVE_MSGHDR_MSG_CONTROL 1

25
26
27
28
29
30
31
#ifdef DIMAPI
#include <netdb.h>
#include <netinet/in.h>
#include <semaphore.h>
#include "flist.h"
#endif

32
33
34
35
36
#ifdef RECONNECT
#include <fcntl.h>
#endif

// this file contains all the client-side IPC related functions [ and functions for reconnection purposes ]
Arne Øslebø's avatar
Arne Øslebø committed
37

's avatar
   
committed
38
39
40
static int sock;
static int mapidaddr_len;
static struct sockaddr_un mapidaddr;
41
42
static char* mapidsocket = NULL;
static char* mapidsocketglobal = NULL;
Arne Øslebø's avatar
Arne Øslebø committed
43

44
45
flist_t *flowlist = NULL;

's avatar
committed
46
47
#ifdef DIMAPISSL
static SSL_CTX *ctx;
48
void sigpipe_handle();
's avatar
committed
49
50
#endif

51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#ifdef RECONNECT

#ifdef DIMAPI
int check_network_mapicommd(struct host *h);	// checks if network (mapicommd) is up. Returns 1 if network is up, 0 otherwise
void restore_network_mapicommd(struct host *h);	// restores the connection to mapicommd in case of a breakdown, using back-off mechanism
void mapi_recreate_flow(struct host *h);	// recreates all flows, that host which broke down the connection had created
void mapi_reapply_function(struct host *h);	// reapplies all functions, that host which broke down the connection had applyed
void mapi_reconnect(struct host *h);		// checks which flows of the specified host, had called mapi_connect() function
#ifdef WITH_AUTHENTICATION
void mapi_reauthenticate(struct host *h);	// checks which flows of the specified host, had called mapi_authenticate() function
#endif
void check_mapi_functions(struct host *h);	// checks all functions that can be called, when a break down happens
void mapi_get_next_packet(struct host *h);	// checks which flows of the specified host, had called mapi_get_next_pkt() function

typedef struct function_data{

	int fid;			// real fid returned from mapicommd
	mapidflib_function_def_t *fdef;	// function definition
	host_flow *hflow;		// flow of a specified host
	char args[DIMAPI_DATA_SIZE];	// function's arguments
	int index;			// need for functions that have arguments that reference to a flow

} function_data;

#endif

void restore_network_mapid(void);		// restores the connection to mapid in case of a breakdown, using back-off mechanism
void mapi_create_offline_device_mapid(void);	// this function recreates all offline devices, that have been created and not deleted
void mapi_recreate_flow_mapid(void);		// recreates all flows, on-line and off-line, that have been created and not closed
void mapi_reapply_function_mapid(void);		// reapplies all functions, that have been applyed to flows that have not been closed
void mapi_reconnect_mapid(void);		// checks which flows, had called mapi_connect() function and not mapi_close_flow()
void mapi_start_offline_device_mapid(void);	// checks which devices, had called mapi_start_offline_device() function and not mapi_delete_offline_device()
void mapi_read_results_mapid(void);		// initializes shared memory segments for new results of a function, after reconnection

typedef struct flowdescr{

	int fd;
	int file; 			// file descriptor for offline flows
	int fds[256];			// file descriptors
	int numfd;			// number of file descriptors
	char *devtype;
	char *device;
93
	int read_results_flag;
94
	int mapid_down;
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
	char *shm_base;
	pthread_mutex_t *shm_spinlock;
	flist_t *flist;
	unsigned char is_connected; 	// this should be 1 if the flow is connected, 0 otherwise
	int format;			// this should be MFF_PCAP or MFF_DAG_ERF if the flow is offline, -1 otherwise
} flowdescr_t;

typedef struct functdescr{

	int fid;
	short result_init;
	mapidflib_function_def_t *def;
	mapidflib_function_t *funct;
	void *data;
	mapi_results_t *result;
	flowdescr_t *flow;
	int numfd;
} functdescr_t;

typedef struct offline_device{
	char *path;			// specifies the name of the trace file to open
	char *previous_device;		// return value of mapi_create_offline_device (device name that should be used in mapi_start_offline_device)
	char *new_device;		// new device name (returned from mapid)
	int format;			// the format of the captured packets (MFF_PCAP or MFF_DAG_ERF)
	unsigned char is_started;	// this should be 1 if the device is started ( via mapi_start_offline_device() ), 0 otherwise
} offline_device;

flist_t *function_list = NULL;		// list which contains all applyed functions
flist_t *offline_device_list = NULL;	// list which contains all offline devices

#endif

int mapiipc_write(struct mapiipcbuf *qbuf){	// sends an IPC message to mapid

  qbuf->uid = getuid();		 // returns the real user ID of the current process
130

131
132
  if(send(sock, qbuf, sizeof(struct mapiipcbuf), MSG_NOSIGNAL) == -1){

's avatar
committed
133
    //WARNING_CMD(printf("\nsend: %s [%s:%d]\n", strerror(errno), __FILE__, __LINE__));
134
135
136
137
138
139
140

#ifdef RECONNECT
    offline_device *device = NULL;
    flist_node_t *fnode = NULL;
    flowdescr_t* flow = NULL;
    functdescr_t *fun = NULL;

's avatar
committed
141
    //printf("\n ---> Mapid is down\n");
142

143
144
145
146
147
148
149
150
151
152
153
154
155
    if(qbuf->cmd == READ_RESULT && qbuf->size == 1)	// 1st attempt after break down ...
	    return -1;
    else{
	    restore_network_mapid();
	    mapi_create_offline_device_mapid();
	    mapi_recreate_flow_mapid();
	    mapi_reapply_function_mapid();
	    mapi_reconnect_mapid();
	    mapi_start_offline_device_mapid();
	    mapi_read_results_mapid();
	    
	    // special case ( create flow for a device name returned from mapi_create_offline_device() and start/delete this device )
	    if(qbuf->cmd == CREATE_FLOW || qbuf->cmd == START_OFFLINE_DEVICE || qbuf->cmd == DELETE_OFFLINE_DEVICE){
's avatar
committed
156
		    
157
158
159
160
161
162
163
164
165
		    // find specified device in offline_device_list
		    for(fnode = flist_head(offline_device_list); fnode != NULL; fnode = flist_next(fnode)){
			    
			    device = (offline_device *)fnode->data;
			    
			    if(!strcmp(device->previous_device, (char *) qbuf->data)){
				    strncpy((char *) qbuf->data, device->new_device, DATA_SIZE);	// the new device name
				    break;
			    }
's avatar
committed
166
		    }
167
	    }
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
	    // FIXME (CLOSE_FLOW ...)
	    else if(qbuf->cmd == GET_FLOW_INFO || qbuf->cmd == GET_NEXT_FLOW_INFO || qbuf->cmd == CONNECT || qbuf->cmd == APPLY_FUNCTION){
		    flow = flist_get(flowlist, qbuf->user_fd);	// we must send the new fd of the flow, in the below send operation
		    qbuf->fd = flow->fd;
	    }
	    else if(qbuf->cmd == GET_FUNCTION_INFO || qbuf->cmd == GET_NEXT_FUNCTION_INFO){
		    flow = flist_get(flowlist, qbuf->user_fd);		// we must send the new fd of the flow, in the below send operation
		    fun = flist_get(flow->flist, qbuf->user_fid);	// and the new fid of the function
		    
		    qbuf->fd = flow->fd;
		    qbuf->fid = fun->fid;
	    }
	    else if(qbuf->cmd == READ_RESULT && qbuf->fd != -1 && qbuf->fid != -1){
		    flow = flist_get(flowlist, qbuf->user_fd);		// we must send the new fd of the flow, in the below send operation
		    fun = flist_get(flow->flist, qbuf->user_fid);	// and the new fid of the function
		    
		    qbuf->fd = flow->fd;
		    qbuf->fid = fun->fid;
	    }
's avatar
committed
187
	    
188
	    send(sock, qbuf, sizeof(struct mapiipcbuf), MSG_NOSIGNAL);
's avatar
committed
189
    }
190
#else
's avatar
committed
191
    return -1;
192
#endif
Arne Øslebø's avatar
Arne Øslebø committed
193
  }
's avatar
committed
194
  return 0;
Arne Øslebø's avatar
Arne Øslebø committed
195
196
}

's avatar
committed
197
int mapiipc_read(struct mapiipcbuf *qbuf)
Arne Øslebø's avatar
Arne Øslebø committed
198
199
200
//Reads an IPC message. Blocking call
{
  if(recv(sock, qbuf, MAX_SEND_SIZE, 0) == -1){
201
    printf("ERROR: recv (%s) [%s:%d]\n", strerror(errno), __FILE__, __LINE__);
's avatar
committed
202
    return -1;
Arne Øslebø's avatar
Arne Øslebø committed
203
  }
's avatar
committed
204
  return 0;
Arne Øslebø's avatar
Arne Øslebø committed
205
206
}

207
// Sets globals (each thread)
's avatar
committed
208
int mapiipc_set_socket_names(char *socket, char *socketglobal) {
209
210
		if(mapidsocket != NULL) free(mapidsocket);
		if(mapidsocketglobal != NULL) free(mapidsocketglobal);
's avatar
committed
211
212
213
214
		mapidsocket = strdup(socket);
		mapidsocketglobal = strdup(socketglobal);

		return 0;
215
216
}

's avatar
committed
217
int mapiipc_client_init()
Arne Øslebø's avatar
Arne Øslebø committed
218
219
220
//Initializes IPC for mapi functions
{
  if ((sock = socket(AF_LOCAL, SOCK_STREAM, 0)) == -1) {
221
    printf("ERROR: socket (%s) [%s:%d]\n", strerror(errno), __FILE__, __LINE__);
's avatar
committed
222
    return -1;
Arne Øslebø's avatar
Arne Øslebø committed
223
  }
's avatar
committed
224

225
226
  // Check that names of mapid's sockets were set
  if(mapidsocket == NULL || mapidsocketglobal == NULL) {
227
    printf("ERROR: mapiipc_client_init() - socket names not set [%s:%d]\n", __FILE__, __LINE__);
228
229
    return -1;
  }
Arne Øslebø's avatar
Arne Øslebø committed
230

231
  // construct socket (try local)
Arne Øslebø's avatar
Arne Øslebø committed
232
  mapidaddr.sun_family = AF_LOCAL;
's avatar
committed
233
  strcpy(mapidaddr.sun_path, mapidsocket);
Arne Øslebø's avatar
Arne Øslebø committed
234
235
  mapidaddr_len = sizeof mapidaddr.sun_family + strlen(mapidaddr.sun_path);

's avatar
committed
236
  if (connect(sock, (struct sockaddr *)&mapidaddr, mapidaddr_len) < 0) 
's avatar
   
committed
237
  {
238
239
240
241
    // construct socket (try global)
    strcpy(mapidaddr.sun_path, mapidsocketglobal);
    mapidaddr_len = sizeof mapidaddr.sun_family + strlen(mapidaddr.sun_path);
    if (connect(sock, (struct sockaddr *)&mapidaddr, mapidaddr_len) < 0) {
242
      printf("ERROR: connect (%s) [%s:%d]\n", strerror(errno), __FILE__, __LINE__);
243
244
245
246
    }
    else {
      return 0;
    }
's avatar
   
committed
247
  }
248
  return -1;
Arne Øslebø's avatar
Arne Øslebø committed
249
250
251
252
253
254
255
256
}

void mapiipc_client_close()
//Releases socket resources
{
  close(sock);
}

257
258
259
#ifdef DIMAPI
struct sockaddr_in remoteaddr;
flist_t *remote_flowlist=NULL;
260
sem_t stats_sem;
261

262
int mapiipc_remote_write(struct dmapiipcbuf *dbuf, struct host *h){	// sends an IPC message to mapid
's avatar
committed
263
264

#ifdef DIMAPISSL
265
266
267

#ifdef RECONNECT
	if(SSL_write(h->con, dbuf, dbuf->length) <= 0){
268
		printf("WARNING: SSL_write (%s) [%s:%d]\n", strerror(errno), __FILE__, __LINE__);
269
270
271
272
		sem_wait(&h->connection);	// lock the semaphore
	}
#else
	if(SSL_write(h->con, dbuf, dbuf->length) <= 0){
273
		printf("WARNING: SSL_write (%s) [%s:%d]\n", strerror(errno), __FILE__, __LINE__);
's avatar
committed
274
275
		return -1;
	}
276
277
278
279
280
281
282
283
#endif

#else

#ifdef RECONNECT
	// MSG_NOSIGNAL : requests not to send SIGPIPE on errors on stream oriented sockets when the other end breaks the connection
	// need in mapi_get_next_packet()
	if(send(h->sockfd, dbuf, dbuf->length, MSG_NOSIGNAL) <= 0){
's avatar
committed
284
		//WARNING_CMD( printf("send: %s [%s:%d]\n", strerror(errno), __FILE__, __LINE__) );
285
286
		sem_wait(&h->connection);	// lock the semaphore
	}
287
288
#else
	if(send(h->sockfd, dbuf, dbuf->length, 0) == -1) {
289
		printf("WARNING: send (%s) [%s:%d]\n", strerror(errno), __FILE__, __LINE__);
290
291
		return -1;
	}
292
293
#endif

's avatar
committed
294
#endif
295
	return 0;
296
297
}

's avatar
committed
298
int mapiipc_remote_write_to_all(remote_flowdescr_t* rflow)
299
300
301
{
  host_flow* hflow;
  flist_node_t* fnode;
's avatar
committed
302

303
304
305
  for (fnode=flist_head(rflow->host_flowlist); fnode!=NULL; fnode=flist_next(fnode)) {
    hflow=(host_flow*)fnode->data;
    hflow->dbuf->fd=hflow->fd;
's avatar
fix    
committed
306
    if (mapiipc_remote_write(hflow->dbuf, hflow->rhost)<0) return -1;
's avatar
committed
307
  }
308

's avatar
committed
309
  for (fnode=flist_head(rflow->host_flowlist); fnode!=NULL; fnode=flist_next(fnode)) {
310
     sem_wait(&rflow->fd_sem);
311
  }
312

's avatar
committed
313
  return 0;
314
}
315
 
316
317
318
void cleanup_handler(void *arg){  //the cleanup handler
  free(arg);
  return;
319
}
320

321
void *mapiipc_comm_thread(void *host){  // reads an IPC message - blocking call
322

323
324
325
326
  struct dmapiipcbuf* dbuf;
  remote_flowdescr_t* rflow;
  host_flow* hflow;
  int recv_bytes;
327
328
  struct mapi_stat *stat;
  flist_node_t* fnode;
's avatar
committed
329

330
331
#ifdef RECONNECT
  int check_net;
's avatar
committed
332
  struct dmapiipcbuf dbuf_;
's avatar
committed
333
#endif
334

's avatar
committed
335
  /* Guarantees that thread resources are deallocated upon return */
336
  pthread_detach(pthread_self());
337
338
339
  pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);      // enable cancellation
  pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); // changes the type of responses to cancellation requests for the calling thread
                                                            // asynchronous (cancel the calling thread as soon as the cancellation request is received)
340
  dbuf = (struct dmapiipcbuf *)malloc(sizeof(struct dmapiipcbuf));
341

342
343
344
345
346
347
  // pthread_cleanup_push() function pushes the specified cancellation cleanup handler onto
  // the cancellation cleanup stack of the calling thread. When a thread exits or is cancelled,
  // and its cancellation cleanup stack is not empty, the cleanup handlers are invoked with
  // the specified argument in last-in-first-out order from the cancellation cleanup stack
  pthread_cleanup_push(cleanup_handler, dbuf);

348
  while(1){
349

350
    if(host == NULL) break;
's avatar
committed
351

's avatar
committed
352
#ifdef DIMAPISSL
353
      	  recv_bytes = SSL_readn( ((struct host *) host)->con, dbuf, BASIC_SIZE);
354
#else
355
      	  recv_bytes = readn( ((struct host *) host)->sockfd, dbuf, BASIC_SIZE);
's avatar
committed
356
357
#endif

358
359
	  if(recv_bytes == 0){				// the peer has gone
#ifdef RECONNECT
's avatar
committed
360
	  	  //printf("\n\t--->  Mapicommd is down. Socket closed from host: %s\n", ((struct host *)host)->hostname);
361
362
363
364
365
		  check_net = check_network_mapicommd((struct host *) host);

		  if(check_net == 1)			// network is up
			  continue;
		  else{					// network is down
's avatar
committed
366
			  //printf("\nNetwork down ...\n");
367
			  restore_network_mapicommd((struct host *) host);
's avatar
committed
368
369
370
371
372
373
374

			  dbuf_.cmd = IGNORE_SLEEP;
			  dbuf_.length = BASIC_SIZE;
			  
			  if(mapiipc_remote_write(&dbuf_, (struct host *) host) < 0)	// send an IPC message to mapicommd
				  break;

375
376
377
378
379
380
			  mapi_recreate_flow((struct host *) host);
			  mapi_reapply_function((struct host *) host);
			  mapi_reconnect((struct host *) host);
#ifdef WITH_AUTHENTICATION
			  mapi_reauthenticate((struct host *) host);
#endif
's avatar
committed
381
382
383
384
385
386
			  dbuf_.cmd = IGNORE_NOTIFY;
			  dbuf_.length = BASIC_SIZE;
			  
			  if(mapiipc_remote_write(&dbuf_, (struct host *) host) < 0)	// send an IPC message to mapicommd
				  break;
			  
387
388
389
390
391
392
393
			  check_mapi_functions((struct host *) host);
			  mapi_get_next_packet((struct host *) host);
			  sem_trywait(& ((struct host *) host)->connection);	// lock the semaphore only if the semaphore is currently not locked
			  sem_post(& ((struct host *) host)->connection);	// unlock the semaphore
			  continue;
		  }
#else
394
		  check_for_read_results((struct host *) host);
395
396
397
398
399
400
		  break;
#endif
      	  }

      	  else if(recv_bytes == -1){
#ifdef RECONNECT
's avatar
committed
401
	  	  //printf("\n\t--->  Mapicommd is down. Socket closed from host: %s\n", ((struct host *)host)->hostname);
402
403
404
405
406
		  check_net = check_network_mapicommd((struct host *) host);

  		  if(check_net == 1)			// network is up
			  continue;
		  else{					// network is down
's avatar
committed
407
			  //printf("\nNetwork down ...\n");
408
			  restore_network_mapicommd((struct host *) host);
's avatar
committed
409
410
411
412
413
414
415

			  dbuf_.cmd = IGNORE_SLEEP;
			  dbuf_.length = BASIC_SIZE;
			  
			  if(mapiipc_remote_write(&dbuf_, (struct host *) host) < 0)	// send an IPC message to mapicommd
				  break;

416
417
418
419
420
421
			  mapi_recreate_flow((struct host *) host);
			  mapi_reapply_function((struct host *) host);
			  mapi_reconnect((struct host *) host);
#ifdef WITH_AUTHENTICATION
			  mapi_reauthenticate((struct host *) host);
#endif
's avatar
committed
422
423
424
425
426
427
			  dbuf_.cmd = IGNORE_NOTIFY;
			  dbuf_.length = BASIC_SIZE;
			  
			  if(mapiipc_remote_write(&dbuf_, (struct host *) host) < 0)	// send an IPC message to mapicommd
				  break;

428
429
430
431
432
433
434
435
436
437
438
439
			  check_mapi_functions((struct host *) host);
			  mapi_get_next_packet((struct host *) host);
			  sem_trywait(& ((struct host *) host)->connection);	// lock the semaphore only if the semaphore is currently not locked
			  sem_post(& ((struct host *) host)->connection);	// unlock the semaphore
			  continue;
		  }
#else
		  continue;
#endif
	  }
      
	  if (dbuf->length > DIMAPI_DATA_SIZE) {
440
	  	  printf("Bad IPC message from agent [%s:%d]\n", __FILE__, __LINE__);
441
442
443
444
	  	  continue;
      	  }
      
	  if (dbuf->length - BASIC_SIZE>0) {
's avatar
committed
445
446

#ifdef DIMAPISSL
447
		  recv_bytes = SSL_readn( ((struct host *) host)->con, (char *)dbuf + BASIC_SIZE, dbuf->length - BASIC_SIZE );
448
#else
449
	      	  recv_bytes = readn( ((struct host *) host)->sockfd, (char *)dbuf + BASIC_SIZE, dbuf->length - BASIC_SIZE);
's avatar
committed
450
#endif
451
452
	  	  if(recv_bytes == 0){			// the peer has gone
#ifdef RECONNECT
's avatar
committed
453
		  	  //printf("\n\t--->  Mapicommd is down. Socket closed from host: %s\n", ((struct host *)host)->hostname);
454
455
456
457
458
			  check_net = check_network_mapicommd((struct host *) host);
	
			  if(check_net == 1)			// network is up
				  continue;
			  else{					// network is down
's avatar
committed
459
				  //printf("\nNetwork down ...\n");
460
				  restore_network_mapicommd((struct host *) host);
's avatar
committed
461
462
463
464
465
466
467

				  dbuf_.cmd = IGNORE_SLEEP;
				  dbuf_.length = BASIC_SIZE;
				  
				  if(mapiipc_remote_write(&dbuf_, (struct host *) host) < 0)	// send an IPC message to mapicommd
					  break;

468
469
470
471
472
473
				  mapi_recreate_flow((struct host *) host);
				  mapi_reapply_function((struct host *) host);
				  mapi_reconnect((struct host *) host);
#ifdef WITH_AUTHENTICATION
				  mapi_reauthenticate((struct host *) host);
#endif
's avatar
committed
474
475
476
477
478
479
				  dbuf_.cmd = IGNORE_NOTIFY;
				  dbuf_.length = BASIC_SIZE;
				  
				  if(mapiipc_remote_write(&dbuf_, (struct host *) host) < 0)	// send an IPC message to mapicommd
				  	break;

480
481
482
483
484
485
486
				  check_mapi_functions((struct host *) host);
				  mapi_get_next_packet((struct host *) host);
				  sem_trywait(& ((struct host *) host)->connection);	// lock the semaphore only if the semaphore is currently not locked
				  sem_post(& ((struct host *) host)->connection);	// unlock the semaphore
				  continue;
			  }
#else
487
			  check_for_read_results((struct host *) host);
488
489
490
491
492
493
			  break;
#endif
		  }

	  	  else if(recv_bytes == -1){
#ifdef RECONNECT			  
's avatar
committed
494
		  	  //printf("\n\t--->  Mapicommd is down. Socket closed from host: %s\n", ((struct host *)host)->hostname);
495
496
497
498
499
			  check_net = check_network_mapicommd((struct host *) host);
	
			  if(check_net == 1)			// network is up
				  continue;
			  else{					// network is down
's avatar
committed
500
				  //printf("\nNetwork down ...\n");
501
				  restore_network_mapicommd((struct host *) host);
's avatar
committed
502
503
504
505
506
507
508

				  dbuf_.cmd = IGNORE_SLEEP;
				  dbuf_.length = BASIC_SIZE;
				  
				  if(mapiipc_remote_write(&dbuf_, (struct host *) host) < 0)	// send an IPC message to mapicommd
					  break;

509
510
511
512
513
514
				  mapi_recreate_flow((struct host *) host);
				  mapi_reapply_function((struct host *) host);
				  mapi_reconnect((struct host *) host);
#ifdef WITH_AUTHENTICATION
				  mapi_reauthenticate((struct host *) host);
#endif
's avatar
committed
515
516
517
518
519
				  dbuf_.cmd = IGNORE_NOTIFY;
				  dbuf_.length = BASIC_SIZE;
				  
				  if(mapiipc_remote_write(&dbuf_, (struct host *) host) < 0)	// send an IPC message to mapicommd
				  	break;
520

521
522
523
524
525
526
527
528
529
530
531
				  check_mapi_functions((struct host *) host);
				  mapi_get_next_packet((struct host *) host);
				  sem_trywait(& ((struct host *) host)->connection);	// lock the semaphore only if the semaphore is currently not locked
				  sem_post(& ((struct host *) host)->connection);	// unlock the semaphore
				  continue;
			  }
#else
			  continue;
#endif
		  }
      	  }
532
533
534
535
536

	  if (dbuf->cmd==MAPI_STATS_ACK) {

		for (fnode=flist_head(((struct host*)host)->stats); fnode!=NULL; fnode=flist_next(fnode)) {
      			stat=(struct mapi_stat*)fnode->data;
's avatar
committed
537
538
			if ( strcmp( ((struct mapi_stat*)dbuf->data)->dev, stat->dev)==0 ) {
				strncpy( ((struct mapi_stat*)dbuf->data)->hostname, stat->hostname, MAPI_STR_LENGTH );
539
540
541
542
543
544
545
546
547
548
549
550
551
552
				memcpy(stat, dbuf->data, sizeof(struct mapi_stat));
				flist_remove(((struct host*)host)->stats, fnode->id);
				break;
			}
		}

		sem_post( &stats_sem );
		continue;
	  }
	  else if (dbuf->cmd==MAPI_STATS_ERR) {
			
			sem_post( &stats_sem );
			continue;
	  }
553
554
555
556
557
558
559
560
      
	  hflow=(host_flow*)flist_get( ((struct host*)host)->flows, dbuf->fd );

      	  if (hflow!=NULL) {

	    	  rflow=flist_get(remote_flowlist, hflow->scope_fd);

	    	  if (dbuf->cmd==GET_NEXT_PKT_ACK) {
561
562
563
			  if (dbuf->length == BASIC_SIZE) {
				hflow->pkt->caplen = 0;
			  }
564
565
566
567
	  		  memcpy(hflow->pkt, dbuf->data, dbuf->length-BASIC_SIZE);
	  		  flist_append(rflow->pkt_list, 0, hflow);
	  		  sem_post(&rflow->pkt_sem);
	    	  }
568
569
570
571
#ifdef RECONNECT
		  else if(dbuf->cmd == READ_RESULT_ACK_RECONNECT)
			  rflow->daemons_down = 0;	// mapid is up and runnung ...
#endif
572
573
574
	    	  else {
		  	  memcpy( hflow->dbuf, dbuf, dbuf->length );	//place data
		  	  sem_post( &rflow->fd_sem );
575
576
577
578
579
580
581
582
583
584
585
586
587
588
#ifdef RECONNECT
			  if(dbuf->cmd == ERROR_ACK){

				  void *error_num = (void *)malloc(sizeof(int));

				  memcpy(error_num, dbuf->data, dbuf->length - BASIC_SIZE);

				  if(*((int *) error_num) == MAPI_READ_RESULT_RECONNECTION){

					  free(error_num);
					  rflow->daemons_down = 1;	// mapid is down ...
				  }
			  }
#endif
589
590
591
	    	  }
      	  }
      	  else {
592
	    	  printf("Invalid IPC message, unknown fd %d [%s:%d]\n", dbuf->fd, __FILE__, __LINE__);
593
594
	    	  continue;
      	  }
595
  }
596
597
  pthread_cleanup_pop(1);	// pthread_cleanup_pop() function shall remove the routine at the top of the
 				// calling thread's cancellation cleanup stack and invoke it
's avatar
committed
598
  return NULL;
599
600
}

's avatar
committed
601
int mapiipc_remote_init(struct host *h)
602
603
//Initializes IPC for dmapi functions
{
's avatar
committed
604
605
  struct hostent* host=gethostbyname(h->hostname);
  struct timeval tv;
606

607
#ifdef DIMAPISSL
608
609
	SSL_library_init();		// registers the available ciphers and digests
	SSL_load_error_strings();	// registers the error strings for all libcrypto functions and libssl
's avatar
committed
610
611
612

	if ((ctx=SSL_CTX_new(SSLv3_client_method())) == NULL) {
		ERR_print_errors_fp(stderr);
's avatar
committed
613
		return -1;
's avatar
committed
614
615
616
	}
	if ((h->con = SSL_new(ctx)) == NULL) {
		ERR_print_errors_fp(stderr);
's avatar
committed
617
		return -1;
's avatar
committed
618
	}
619
620

	signal(SIGPIPE, sigpipe_handle);	// catch SIGPIPE signal (SSL_write), in case of reconnection ...
's avatar
committed
621
622
#endif

623
  if ((h->sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
624
    printf("ERROR: socket (%s) [%s:%d]\n", strerror(errno), __FILE__, __LINE__);
's avatar
committed
625
    return -1;
's avatar
committed
626
627
628
629
630
631
632
  }

  tv.tv_sec=10;		//timeout 10 sec for send
  tv.tv_usec=0;

  if (setsockopt(h->sockfd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(struct timeval)) == -1) {
    close(h->sockfd);
633
    printf("ERROR: Unexpected error on setsockopt() [%s:%d]\n", __FILE__, __LINE__);
's avatar
committed
634
    return -1;
's avatar
committed
635
636
637
  }

  if (host==NULL) {
638
    printf("ERROR: Could not determine address for host %s [%s:%d]\n", h->hostname, __FILE__, __LINE__);
's avatar
committed
639
    return -1;
640
  }
's avatar
committed
641

642
643
  // Construct name of dmapid's socket
  remoteaddr.sin_family = AF_INET;
's avatar
committed
644
  remoteaddr.sin_addr = *((struct in_addr *)host->h_addr);
645
646
  remoteaddr.sin_port = htons(h->port);

647
  if (connect(h->sockfd, (struct sockaddr *)&remoteaddr, sizeof(remoteaddr)) < 0) {
648
    printf("ERROR: connect failed (%s) [%s:%d]\n", strerror(errno), __FILE__, __LINE__);
's avatar
committed
649
    return -1;
650
  }
's avatar
committed
651
652

#ifdef DIMAPISSL
653
	if (SSL_set_fd(h->con, h->sockfd) == 0) {
's avatar
committed
654
		ERR_print_errors_fp(stderr);
's avatar
committed
655
		return -1;
's avatar
committed
656
657
658
	}
	if (SSL_connect(h->con) <= 0) {
		ERR_print_errors_fp(stderr);
's avatar
committed
659
		return -1;
's avatar
committed
660
661
	}
#endif
's avatar
committed
662
  return 0;
's avatar
committed
663

664
665
666
667
668
}

void mapiipc_remote_close(struct host *h)
//Releases socket resources
{
669
670
671
	shutdown(h->sockfd, SHUT_RDWR);
	close(h->sockfd);

's avatar
committed
672
#ifdef DIMAPISSL
673
	if (SSL_shutdown(h->con) == -1)	// shut down a TLS/SSL connection
's avatar
committed
674
		ERR_print_errors_fp(stderr);
675
676
677
678
679
680
681
682
683
684

	SSL_free(h->con);		// decrements the reference count of ssl, and removes the SSL structure pointed to by ssl
       					// frees up the allocated memory if the the reference count has reached 0
	if(ctx != NULL)
		SSL_CTX_free(ctx);	// decrements the reference count of ctx, and removes the SSL_CTX object pointed to by ctx
					// frees up the allocated memory if the the reference count has reached 0
	ERR_remove_state(0);		// the current thread will have its error queue removed	
	ERR_free_strings();		// frees all previously loaded error strings
	EVP_cleanup();			// removes all ciphers and digests from the table	
	CRYPTO_cleanup_all_ex_data();	// clean up all allocated state
's avatar
committed
685
#endif
686
}
687

688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
void check_for_read_results(struct host *h){

	int fd_sem_value, errno;
	struct dmapiipcbuf *dbuf = NULL;
	flist_node_t *fnode = NULL;
	host_flow *hflow = NULL;
	remote_flowdescr_t *rflow = NULL;
	
	for(fnode = flist_head(h->flows); fnode != NULL; fnode = flist_next(fnode)){	// iterate flow list of the specified host
		
		hflow = (host_flow *)fnode->data;

		if( (rflow = flist_get(remote_flowlist, hflow->scope_fd)) != NULL){
#ifndef RECONNECT
			sleep(1);	// XXX
703
704
#else
			rflow->daemons_down = 1;
705
706
707
708
709
710
711
712
713
#endif
			if(sem_getvalue(&rflow->fd_sem, &fd_sem_value) == -1){
				printf("ERROR: sem_getvalue() failed (%s) [%s:%d]\n", strerror(errno), __FILE__, __LINE__);
				break;
			}

			if(fd_sem_value == 0 && hflow->dbuf->cmd == READ_RESULT){
	
				dbuf = (struct dmapiipcbuf *)malloc(sizeof(struct dmapiipcbuf));
714

715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
				errno = MAPI_READ_RESULT_RECONNECTION;
				dbuf->cmd = ERROR_ACK;
				memcpy(dbuf->data, &errno, sizeof(int));
				dbuf->length = BASIC_SIZE + sizeof(int);
				memcpy(hflow->dbuf, dbuf, dbuf->length);
				sem_post(&rflow->fd_sem);	// critical point ...
				free(dbuf);
				break;
			}
		}
	}

	return;
}

730
#endif /* DIMAPI */
731

Arne Øslebø's avatar
Arne Øslebø committed
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759

// Helper functions for function arguments retrieval
int getargint(mapiFunctArg **pos){
	int i;
	i = *((int *)(*pos));
	//	printf("getint: %d\n", i);
	(*pos) += sizeof(int);
	return i;
}

char getargchar(mapiFunctArg **pos){
	char c;
	c = *((char *)(*pos));
	//printf("getchar: %c\n", c);
	(*pos) += sizeof(char);
	return c;
}

unsigned long long getargulonglong(mapiFunctArg **pos){
	unsigned long long l;
	l = *((unsigned long long *)(*pos));
	//printf("getulonglong: %lld\n", l);
	(*pos) += sizeof(unsigned long long);
	return l;
}

char * getargstr(mapiFunctArg **pos){
	char *s;
760
	s = (char*)*pos;
Arne Øslebø's avatar
Arne Øslebø committed
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
	//printf("getstr: %s\n", s);
	(*pos) += strlen(s)+1;
	return s;
}

void addarg(mapiFunctArg **pos, void *arg, int type)
// Helper function for mapi_apply_function()
// pos: current position in message's argument buffer.
// arg: argument to copy into buffer
// type: argument type
{
  switch(type){
    case INT:
      memcpy(*pos, arg, sizeof(int));
      //printf("add_arg: %d\n", *((int *)(*pos)));
      (*pos) += sizeof(int);
      break;
    case CHAR:
      memcpy(*pos, arg, sizeof(char));
      //printf("add_arg: %d\n", *((char *)(*pos)));
      (*pos) += sizeof(char);
      break;
    case UNSIGNED_LONG_LONG:
      memcpy(*pos, arg, sizeof(unsigned long long));
      //printf("add_arg: %llu\n", *((unsigned long long *)(*pos)));
      (*pos) += sizeof(unsigned long long);
      break;
    case STRING:
      memcpy(*pos, arg, strlen((char *)arg)+1);
      //printf("add_arg: %s\n", (char *)(*pos));
      (*pos) += strlen((char *)arg)+1;
      break;
    default:
      break;
  }
}

int mapiipc_send_fd(int sendfd)
{
  struct msghdr	msg;
  struct iovec	iov[1];
  char ptr[2];
  int ret;

#ifdef	HAVE_MSGHDR_MSG_CONTROL
  union {
    struct cmsghdr	cm;
    char control[CMSG_SPACE(sizeof(int))];
  } control_un;
  struct cmsghdr	*cmptr;
  
  msg.msg_control = control_un.control;
  msg.msg_controllen = sizeof(control_un.control);
  
  cmptr = CMSG_FIRSTHDR(&msg);
  cmptr->cmsg_len = CMSG_LEN(sizeof(int));
  cmptr->cmsg_level = SOL_SOCKET;
  cmptr->cmsg_type = SCM_RIGHTS;
  *((int *) CMSG_DATA(cmptr)) = sendfd;
#else
  msg.msg_accrights = (caddr_t) &sendfd;
  msg.msg_accrightslen = sizeof(int);
#endif
    
  iov[0].iov_base = ptr;
  iov[0].iov_len = 2;
  msg.msg_iov = iov;
  msg.msg_iovlen = 1;
  msg.msg_name = NULL;
  msg.msg_namelen = 0;

  ret=sendmsg(sock,&msg,0);
  return(ret);
}


int mapiipc_read_fd(int sock)
{
  struct msghdr	msg;
  struct iovec	iov[1];
  ssize_t n;
  int recvfd;
  char c[2];
  
#ifdef	HAVE_MSGHDR_MSG_CONTROL
  union {
    struct cmsghdr	cm;
    char				control[CMSG_SPACE(sizeof(int))];
  } control_un;
  struct cmsghdr	*cmptr;
  
  msg.msg_control = control_un.control;
  msg.msg_controllen = sizeof(control_un.control);
#else
  msg.msg_accrights = (caddr_t) &newfd;
  msg.msg_accrightslen = sizeof(int);
#endif
  
  iov[0].iov_base = &c;
  iov[0].iov_len = 2;
  msg.msg_iov = iov;
  msg.msg_iovlen = 1;
  msg.msg_name = NULL;
  msg.msg_namelen = 0;
  
  
  if ( (n = recvmsg(sock, &msg, 0)) <= 0)
    return(n);
  
#ifdef	HAVE_MSGHDR_MSG_CONTROL
  if ( (cmptr = CMSG_FIRSTHDR(&msg)) != NULL &&
       cmptr->cmsg_len == CMSG_LEN(sizeof(int))) {
    if (cmptr->cmsg_level != SOL_SOCKET) {
874
      printf("ERROR: control level != SOL_SOCKET [%s:%d]\n", __FILE__, __LINE__);
Arne Øslebø's avatar
Arne Øslebø committed
875
876
877
      return -1;
    }
    if (cmptr->cmsg_type != SCM_RIGHTS) {
878
      printf("ERROR: control type != SCM_RIGHTS [%s:%d]\n", __FILE__, __LINE__);
Arne Øslebø's avatar
Arne Øslebø committed
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
      return -1;
    }
    recvfd = *((int *) CMSG_DATA(cmptr));
  } else
    recvfd = -1;		/* descriptor was not passed */
#else
  /* *INDENT-OFF* */
  if (msg.msg_accrightslen == sizeof(int))
    recvfd = newfd;
  else
    recvfd = -1;		/* descriptor was not passed */
  /* *INDENT-ON* */
#endif

  return recvfd;
}
's avatar
committed
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919

/* Read "n" bytes from a socket. */
ssize_t readn(int fd, void *vptr, size_t n) {
        size_t nleft;
        ssize_t nread;
        char *ptr;

        ptr = vptr;
        nleft = n;
        while (nleft > 0) {
		errno=0;
                if ( (nread = read(fd, ptr, nleft)) < 0) {
                        if (errno == EINTR)
                                nread = 0;              /* and call read() again */
                        else
                                return(-1);
                } else if (nread == 0)
                        return 0;                          /* EOF */

                nleft -= nread;
                ptr   += nread;
        }
        return(n - nleft);              /* return >= 0 */
}

's avatar
committed
920
921
#ifdef DIMAPISSL
ssize_t SSL_readn(SSL *con, void *vptr, size_t n) {
922

's avatar
committed
923
924
925
        size_t nleft;
        ssize_t nread;
        char *ptr;
's avatar
committed
926

's avatar
committed
927
928
        ptr = vptr;
        nleft = n;
929

's avatar
committed
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
        while (nleft > 0) {
		errno=0;
                if ( (nread = SSL_read(con, ptr, nleft)) < 0) {
                        if (errno == EINTR)
                                nread = 0;              /* and call read() again */
                        else
                                return(-1);
                } else if (nread == 0)
                        return 0;                          /* EOF */

                nleft -= nread;
                ptr   += nread;
        }
        return(n - nleft);              /* return >= 0 */
}
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967

void sigpipe_handle(){	// catch the signal

	printf("Broken pipe (signal handler) ...\n");
	return;
}
#endif

#ifdef RECONNECT

#ifdef DIMAPI

// this function checks if network (mapicommd) is up
// returns 1 if network is up or 0 if network is down
int check_network_mapicommd(struct host *h){

	struct hostent *host;
	struct sockaddr_in remote_address;
	int sockfd = 0;

	host = gethostbyname(h->hostname);	// information about the specified host

	if( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
968
		printf("ERROR: socket (%s) [%s:%d]\n", strerror(errno), __FILE__, __LINE__);
969
970
971
972
973
974
975
976
977
978
979
    	        return -1;
	}

	// construct name of dmapid's socket
	remote_address.sin_family = AF_INET;				// address family
 	remote_address.sin_addr = *((struct in_addr *)host->h_addr);
  	remote_address.sin_port = htons(h->port);			// port number (2233)

  	if(connect(sockfd, (struct sockaddr *)&remote_address, sizeof(remote_address)) < 0)	// remote mapid server is down ...
		return 0;

's avatar
committed
980
	shutdown(sockfd, SHUT_RDWR);
981
982
983
984
985
986
987
988
989
990
991
	close(sockfd);
	return 1;
}

// this function restores the connection to mapicommd in case of a breakdown, using back-off mechanism
void restore_network_mapicommd(struct host *h){

	int tries;		// how many times will we try to reconnect
	int time = 1;		// initial waiting time
	int check_net;

992
	for(tries = 0; ; tries++){
993

994
995
996
		if(tries == 1)		// in case of read_results return NULL to application and then continue calling reconnection functions ...
			check_for_read_results(h);

's avatar
committed
997
		//printf("\n---> Reconnection try #%d", tries);
998
999
1000
1001
1002
		check_net = check_network_mapicommd(h);
		fflush(stdout);

		if(check_net == 1){		// network is now up ...

's avatar
committed
1003
			//printf("\nMapid server is back online ...\n");
1004
1005
1006
1007
1008
1009

			mapiipc_remote_close(h);	// release previous socket resources
			mapiipc_remote_init(h);		// initializes IPC for DiMAPI functions
			return;
		}

1010
1011
1012
1013
		sleep(time);		// pause execution for the specified time

		if (tries < 8)
			time += time;	// increase waiting time
1014
1015
	}

's avatar
committed
1016
	//fprintf(stderr,"\nNetwork is down (reconnection tries expired)\n");
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
	exit(EXIT_FAILURE);
}

// this function recreates all flows, that host which broke down the connection had created
void mapi_recreate_flow(struct host *h){

	flist_node_t *fnode;
	flist_t *tmp_list = NULL;	// all created flows from this host
	host_flow *hflow;
	struct dmapiipcbuf *dbuf = NULL;
	int recv_bytes;

	dbuf = (struct dmapiipcbuf *)malloc(sizeof(struct dmapiipcbuf));	// buffer to store messages that are sent/received to/from mapicommd
	tmp_list = (flist_t *)malloc(sizeof(flist_t));
	flist_init(tmp_list);
	
	for(fnode = flist_head(h->flows); fnode != NULL; fnode = flist_next(fnode)){	// iterate flow list of the specified host

		hflow = (host_flow *)fnode->data;	// data stored in the node

		dbuf->cmd = CREATE_FLOW;
		strncpy((char *) dbuf->data, hflow->dev, DATA_SIZE);
		dbuf->length = BASIC_SIZE + strlen(hflow->dev) + 1;

		if(mapiipc_remote_write(dbuf, hflow->rhost) < 0){		// send an IPC message to mapicommd
			free(dbuf); dbuf = NULL;
			exit(EXIT_FAILURE);
		}
#ifdef DIMAPISSL
		recv_bytes = SSL_readn(h->con, dbuf, BASIC_SIZE);
#else
		recv_bytes = readn(h->sockfd, dbuf, BASIC_SIZE);		// receive an IPC message from mapicommd
#endif
		if(dbuf->length - BASIC_SIZE > 0){				// TODO check recv_bytes
#ifdef DIMAPISSL
			recv_bytes = SSL_readn(h->con, (char *)dbuf + BASIC_SIZE, dbuf->length - BASIC_SIZE);
#else
			recv_bytes = readn(h->sockfd, (char *)dbuf + BASIC_SIZE, dbuf->length - BASIC_SIZE);
#endif
		}

		if(dbuf->cmd == CREATE_FLOW_ACK){
			//printf("\n\t New fd = %d, Previous fd = %d\n", *(int *)(dbuf->data), hflow->fd);

			hflow->dbuf->fd = *(int *)(dbuf->data);		// FIXME
			hflow->fd = *((int *)dbuf->data);		// change previous fd with the new one
			flist_append(tmp_list, hflow->fd, hflow);	// append new node to the tmp list
		}
		else{
1066
			printf("\nERROR: Could not re-create flow in host %s [%s:%d]\n", hflow->rhost->hostname, __FILE__, __LINE__);
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
			free(dbuf); dbuf = NULL;
			exit(EXIT_FAILURE);
		}
	}
	free(dbuf); dbuf = NULL;
	flist_destroy(h->flows);	// destroy old flow list
	free(h->flows);
	h->flows = tmp_list;		// now flow list is the tmp list

	return;
}

// this function reapplies all functions, that host which broke down the connection had applyed
void mapi_reapply_function(struct host *h){

	flist_node_t *fnode;
	host_flow *hflow;
	function_data *fdata, *fdata_;
	remote_flowdescr_t* ref_flow;
	mapiFunctArg *pos;
	struct dmapiipcbuf *dbuf = NULL;
	struct mapiipcbuf qbuf = {-1, -1, -1, -1, -1, "", -1, -1, -1, 0, "", "", -1};
	int recv_bytes, tmp, fid_, fd_, tmp_fd, tmp_fid, len = 0;
	char *argdescr_ptr, *temp, *filename, ctmp;
	char buf[DATA_SIZE], *fids, *cfids, *s, *new_fids;
	unsigned char *args;
	unsigned long long ltmp;
	unsigned int args_size;

	dbuf = (struct dmapiipcbuf *)malloc(sizeof(struct dmapiipcbuf));	// buffer to store messages that are sent/received to/from mapicommd

	for(fnode = flist_head(h->functions); fnode != NULL; fnode = flist_next(fnode)){	// iterate function list of the specified host

		fdata = (function_data *)fnode->data;		// data stored in the node
		hflow = fdata->hflow;
		
		//printf("\nFunction name = %s\n", fdata->fdef->name);

		dbuf->cmd = APPLY_FUNCTION;
		dbuf->fd = hflow->fd;		// the new fd of the flow
		memcpy(dbuf->data, fdata->fdef->name, strlen(fdata->fdef->name) + 1);	// put function name in the buffer

		pos = qbuf.data;	// point to start of arguments buffer
		args_size = 0;		// arguments size (number of bytes)

		// parse function arguments (need again, because some functions have arguments that reference to other flows and functions)
		if(strncmp(fdata->fdef->argdescr, "", 1)){		// there are some arguments

			args = (unsigned char *)fdata->args;
			argdescr_ptr = fdata->fdef->argdescr;

			while(strlen(argdescr_ptr) > 0){
				switch(*argdescr_ptr){
					case 's':
						temp = (char *)args;
						args += strlen(temp) + 1;
						addarg(&pos, temp, STRING);
						args_size += strlen(temp) + 1;
						break;
					case 'S':		  // reference to flows and functions (e.g RES2FILE)
						fids = (char *)args;
						args += strlen(fids) + 1;

						// allocate more bytes, because we can have the following case: 7@2,8@2,9@2 translated to 12@3,13@3,14@3
						new_fids = (char *)malloc(strlen(fids) * 10 * sizeof(char));
						strncpy(buf, fids, DATA_SIZE);
						cfids = buf;
						
						while( (s = strchr(cfids, ',')) != NULL){
							
							*s = '\0';
							sscanf(cfids, "%d@%d", &fid_, &fd_);
							ref_flow = flist_get(remote_flowlist, fd_);
							tmp_fd = ((host_flow *)flist_get(ref_flow->host_flowlist, fdata->index))->fd;
							fdata_ = flist_get(hflow->rhost->functions, fid_);
							tmp_fid = fdata_->fid;
							
							if(len != 0)
								len += sprintf(new_fids + len, ",");
							len += sprintf(new_fids + len, "%d", tmp_fid);
							len += sprintf(new_fids + len, "@");
							len += sprintf(new_fids + len, "%d", tmp_fd);
							
							cfids = s + 1;
						}
						
						sscanf(cfids, "%d@%d", &fid_, &fd_);
						ref_flow = flist_get(remote_flowlist, fd_);
						tmp_fd = ((host_flow *)flist_get(ref_flow->host_flowlist, fdata->index))->fd;
						fdata_ = flist_get(hflow->rhost->functions, fid_);
						tmp_fid = fdata_->fid;
						
						if(len != 0)
							len += sprintf(new_fids + len, ",");
						len += sprintf(new_fids + len, "%d", tmp_fid);
						len += sprintf(new_fids + len, "@");
						len += sprintf(new_fids + len, "%d", tmp_fd);

						addarg(&pos, new_fids, STRING);
						args_size += strlen(new_fids) + 1;
						len = 0;
						free(new_fids);
						new_fids = NULL;
						break;
					case 'i':
						memcpy(&tmp, args, sizeof(int));
						args += sizeof(int);
						addarg(&pos, &tmp, INT);
						args_size += sizeof(int);
						break;
					case 'c':
						memcpy(&ctmp, args, sizeof(char));
						args += sizeof(char);
						addarg(&pos, &ctmp, CHAR);
						args_size += sizeof(char);
						break;
					case 'l':
						memcpy(&ltmp, args, sizeof(unsigned long long));
						args += sizeof(unsigned long long);
						addarg(&pos, &ltmp, UNSIGNED_LONG_LONG);
						args_size += sizeof(unsigned long long);
						break;
					case 'w':
						filename = (char *)args;
						args += strlen(filename) + 1;
						addarg(&pos, filename, STRING);
						args_size += strlen(filename) + 1;
						break;
					case 'r':	// reference to a flow
						memcpy(&tmp, args, sizeof(int));
						args += sizeof(int);
						ref_flow = flist_get(remote_flowlist, tmp);
						tmp = ((host_flow *)flist_get(ref_flow->host_flowlist, fdata->index))->fd;
						addarg(&pos, &tmp, INT);
						args_size += sizeof(int);
						break;
					case 'f':	// reference to a fuction
						memcpy(&tmp, args, sizeof(int));
						args += sizeof(int);
						fdata_ = flist_get(hflow->rhost->functions, tmp);
						tmp = fdata_->fid;
						addarg(&pos, &tmp, INT);
						args_size += sizeof(int);
						break;
				}
				argdescr_ptr++;		// move to the next argument
			}
		}

		memcpy(dbuf->data + strlen(fdata->fdef->name) + 1, qbuf.data, args_size);	// put function arguments in the buffer
		dbuf->length = BASIC_SIZE + strlen(fdata->fdef->name) + 1 + args_size;

		if(mapiipc_remote_write(dbuf, hflow->rhost) < 0){	// send an IPC message to mapicommd
			free(dbuf); dbuf = NULL;
			exit(EXIT_FAILURE);
		}
#ifdef DIMAPISSL
		recv_bytes = SSL_readn(h->con, dbuf, BASIC_SIZE);
#else
		recv_bytes = readn(h->sockfd, dbuf, BASIC_SIZE);	// receive an IPC message from mapicommd
#endif
		if(dbuf->length - BASIC_SIZE > 0){			// TODO check recv_bytes
#ifdef DIMAPISSL
			recv_bytes = SSL_readn(h->con, (char *)dbuf + BASIC_SIZE, dbuf->length - BASIC_SIZE);
#else
			recv_bytes = readn(h->sockfd, (char *)dbuf + BASIC_SIZE, dbuf->length - BASIC_SIZE);
#endif
		}

		if(dbuf->cmd == APPLY_FUNCTION_ACK){
			//printf("\n\t APPLY OK !! New fid = %d, Previous fid = %d", dbuf->fid, fdata->fid);

			if(hflow->dbuf->fid == fdata->fid)
				hflow->dbuf->fid = dbuf->fid;	// FIXME

			fdata->fid = dbuf->fid;		// change previous fid with the new one	(IMPORTANT)
		}
		else{
1245
1246
			printf("\nERROR: Could not re-apply function %s in host %s [%s:%d]\n", fdata->fdef->name, hflow->rhost->hostname, 
												__FILE__, __LINE__);
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
			free(dbuf); dbuf = NULL;
			exit(EXIT_FAILURE);
		}
	}
	free(dbuf); dbuf = NULL;
	return;
}

// this function checks which flows of the specified host, had called mapi_connect() function
void mapi_reconnect(struct host *h){

	flist_node_t *fnode;
	remote_flowdescr_t* rflow;
	host_flow *hflow;
	struct dmapiipcbuf *dbuf = NULL;
	int recv_bytes;

	dbuf = (struct dmapiipcbuf *)malloc(sizeof(struct dmapiipcbuf));	// buffer to store messages that are sent/received to/from mapicommd

	for(fnode = flist_head(h->flows); fnode != NULL; fnode = flist_next(fnode)){	// iterate flow list of the specified host

		hflow = (host_flow *)fnode->data;	// data stored in the node
		
		if( (rflow = flist_get(remote_flowlist, hflow->scope_fd)) != NULL){
			
			if(rflow->is_connected){	// flow is already connected, via mapi_connect() function

				//printf("\n flow %d is connected\n", hflow->scope_fd);

				dbuf->cmd = CONNECT;
				dbuf->fd = hflow->fd;
				dbuf->length = BASIC_SIZE;

				if(mapiipc_remote_write(dbuf, hflow->rhost) < 0){	// send an IPC message to mapicommd
					free(dbuf); dbuf = NULL;
					exit(EXIT_FAILURE);
				}
#ifdef DIMAPISSL
				recv_bytes = SSL_readn(h->con, dbuf, BASIC_SIZE);
#else
				recv_bytes = readn(h->sockfd, dbuf, BASIC_SIZE);	// receive an IPC message from mapicommd
#endif
				if(dbuf->length - BASIC_SIZE > 0){			// TODO check recv_bytes
#ifdef DIMAPISSL
					recv_bytes = SSL_readn(h->con, (char *)dbuf + BASIC_SIZE, dbuf->length - BASIC_SIZE);
#else
					recv_bytes = readn(h->sockfd, (char *)dbuf + BASIC_SIZE, dbuf->length - BASIC_SIZE);
#endif
				}

				if(dbuf->cmd == CONNECT_ACK){

					//printf("\n Flow %d is now connected !!\n", hflow->fd);
					rflow->is_connected = 1;	// FIXME
1301
					rflow->daemons_down = 0;
1302
1303
				}
				else{
1304
					printf("ERROR: Could not re-connect to flow %d [%s:%d]\n", hflow->scope_fd, __FILE__, __LINE__);
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
					rflow->is_connected = 0;	// FIXME
					free(dbuf); dbuf = NULL;
					exit(EXIT_FAILURE);
				}
			}
			/*else{						// flow is not connected
				printf("\n flow %d is not connected\n", hflow->scope_fd);	// delete
			}*/
		}
		else	// FIXME
			return;
	}
	free(dbuf); dbuf = NULL;
	return;
}

#ifdef WITH_AUTHENTICATION
// this function checks which flows of the specified host, had called mapi_authenticate() function
void mapi_reauthenticate(struct host *h){

	flist_node_t *fnode;
	remote_flowdescr_t* rflow;
	host_flow *hflow;
	struct dmapiipcbuf *dbuf = NULL;
	int recv_bytes;
	int length;

	dbuf = (struct dmapiipcbuf *)malloc(sizeof(struct dmapiipcbuf));	// buffer to store messages that are sent/received to/from mapicommd

	for(fnode = flist_head(h->flows); fnode != NULL; fnode = flist_next(fnode)){	// iterate flow list of the specified host

		hflow = (host_flow *)fnode->data;	// data stored in the node
		
		if( (rflow = flist_get(remote_flowlist, hflow->scope_fd)) != NULL){

			if(rflow->is_authenticated == 1){

				//printf("\n flow %d is authenticated\n", hflow->scope_fd);
				length = 0;

				dbuf->cmd = AUTHENTICATE;
				dbuf->fd  = hflow->fd;
				length += sprintf(dbuf->data + length, "%s", rflow->username) + 1;
				length += sprintf(dbuf->data + length, "%s", rflow->password) + 1;
				length += sprintf(dbuf->data + length, "%s", rflow->vo) + 1;
				dbuf->length = BASIC_SIZE + length;

				if(mapiipc_remote_write(dbuf, hflow->rhost) < 0){	// send an IPC message to mapicommd
					free(dbuf); dbuf = NULL;
					exit(EXIT_FAILURE);
				}
#ifdef DIMAPISSL
				recv_bytes = SSL_readn(h->con, dbuf, BASIC_SIZE);
#else
				recv_bytes = readn(h->sockfd, dbuf, BASIC_SIZE);	// receive an IPC message from mapicommd
#endif
				if(dbuf->length - BASIC_SIZE > 0){			// TODO check recv_bytes
#ifdef DIMAPISSL
					recv_bytes = SSL_readn(h->con, (char *)dbuf + BASIC_SIZE, dbuf->length - BASIC_SIZE);
#else
					recv_bytes = readn(h->sockfd, (char *)dbuf + BASIC_SIZE, dbuf->length - BASIC_SIZE);
#endif
				}

				if(dbuf->cmd == AUTHENTICATE_ACK){

					//printf("\n Flow %d is now authenticated !!\n", hflow->fd);
					rflow->is_authenticated = 1;	// FIXME
				}
				else{
1375
					printf("ERROR: Could not re-authenticate flow %d [%s:%d]\n", hflow->scope_fd, __FILE__, __LINE__);
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
					rflow->is_authenticated = 0;	// FIXME
					free(dbuf); dbuf = NULL;
					exit(EXIT_FAILURE);
				}
			}
			/*else{						// flow is not authenticated
				printf("\n flow %d is not authenticated\n", hflow->scope_fd);	// delete
			}*/
		}
		else	// FIXME
			return;
	}
	free(dbuf); dbuf = NULL;
	return;
}
#endif

// this function checks all functions that can be called, when a break down happens
void check_mapi_functions(struct host *h){

	flist_node_t *fnode;
	host_flow *hflow;
	struct dmapiipcbuf *dbuf = NULL;

	dbuf = (struct dmapiipcbuf *)malloc(sizeof(struct dmapiipcbuf));	// buffer to store messages that are sent to mapicommd

	for(fnode = flist_head(h->flows); fnode != NULL; fnode = flist_next(fnode)){	// iterate flow list of the specified host
		
		hflow = (host_flow *)fnode->data;	// data stored in the node
	
		if(hflow->dbuf->cmd == READ_RESULT ||
				hflow->dbuf->cmd == GET_FLOW_INFO || hflow->dbuf->cmd == GET_NEXT_FLOW_INFO ||
				hflow->dbuf->cmd == GET_FUNCTION_INFO || hflow->dbuf->cmd == GET_NEXT_FUNCTION_INFO ||
1409
				hflow->dbuf->cmd == GET_DEVICE_INFO || hflow->dbuf->cmd == GET_NEXT_DEVICE_INFO ||
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
				hflow->dbuf->cmd == CREATE_FLOW || hflow->dbuf->cmd == CLOSE_FLOW || hflow->dbuf->cmd == CONNECT ||
				hflow->dbuf->cmd == APPLY_FUNCTION || hflow->dbuf->cmd == AUTHENTICATE){

			memcpy(dbuf, hflow->dbuf, hflow->dbuf->length);

			if(mapiipc_remote_write(dbuf, hflow->rhost) < 0){	// send an IPC message to mapicommd
				free(dbuf); dbuf = NULL;
				exit(EXIT_FAILURE);
			}
		}
	}

	free(dbuf); dbuf = NULL;
	return;
}

// this function checks which flows of the specified host, had called mapi_get_next_pkt() function
void mapi_get_next_packet(struct host *h){

	flist_node_t *fnode;
	remote_flowdescr_t* rflow;
	host_flow *hflow;
	function_data* fdata;
	struct dmapiipcbuf *dbuf = NULL;

	dbuf = (struct dmapiipcbuf *)malloc(sizeof(struct dmapiipcbuf));	// buffer to store messages that are sent to mapicommd

	for(fnode = flist_head(h->flows); fnode != NULL; fnode = flist_next(fnode)){	// iterate flow list of the specified host

		hflow = (host_flow *)fnode->data;	// data stored in the node

		if( (rflow = flist_get(remote_flowlist, hflow->scope_fd)) != NULL){

			if(rflow->pkt_list != NULL){		// mapi_get_next_pkt() was called for this flow

				dbuf->cmd = GET_NEXT_PKT;
				dbuf->fd = hflow->fd;

				if( (fdata = (function_data *)flist_get(hflow->functions, rflow->to_buffer_fid)) == NULL){	// to_buffer() function ...
1449
					printf("ERROR: Probably invalid fid in mapi_get_next_packet() [%s:%d]\n", __FILE__, __LINE__);
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
					free(dbuf); dbuf = NULL;
					exit(EXIT_FAILURE);
				}

				dbuf->fid = fdata->fid;
				dbuf->length = BASIC_SIZE;

				if(mapiipc_remote_write(dbuf, hflow->rhost) < 0){	// send an IPC message to mapicommd
					free(dbuf); dbuf = NULL;
					exit(EXIT_FAILURE);
				}
			}
		}
		else	// FIXME
			return;
	}

	free(dbuf); dbuf = NULL;
	return;
}

#endif
					/* *** MAPID *** */

// this function checks if network (mapid) is up
// returns 1 if network is up or 0 if network is down
int check_network_mapid(void){

	int sockfd, mapidaddr_len_;
	char *mapidsocket_;
	struct sockaddr_un mapidaddr_;
	
	if((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) == -1){		// local communication
1483
		printf("ERROR: socket (%s) [%s:%d]\n", strerror(errno), __FILE__, __LINE__);
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
		return -1;
	}
	
	mapidsocket_ = strdup(MAPIDSOCKGLOBAL);
	
	// Construct name of mapid's socket
	mapidaddr_.sun_family = AF_LOCAL;		// address family: Unix socket
	strcpy(mapidaddr_.sun_path, mapidsocket_);	// file name to use
	mapidaddr_len_ = sizeof mapidaddr_.sun_family + strlen(mapidaddr_.sun_path);
	
	if(connect(sockfd, (struct sockaddr *)&mapidaddr_, mapidaddr_len_) < 0){		// mapid is down
		free(mapidsocket_);
		return 0;
	}

	free(mapidsocket_);
	close(sockfd);
	return 1;
}

// this function restores the connection to mapid in case of a breakdown, using back-off mechanism
void restore_network_mapid(void){

	int tries;		// how many times will we try to reconnect
	int time = 1;		// initial waiting time
	int check_net;

1511
	for(tries = 0; ; tries++){
1512