mapiipc.c 56.5 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"
Arne Øslebø's avatar
Arne Øslebø committed
20
21
22

#define HAVE_MSGHDR_MSG_CONTROL 1

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

30
31
32
33
34
#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
35

's avatar
   
committed
36
37
38
static int sock;
static int mapidaddr_len;
static struct sockaddr_un mapidaddr;
's avatar
committed
39
static char* mapidsocket;
Arne Øslebø's avatar
Arne Øslebø committed
40

41
42
flist_t *flowlist = NULL;

's avatar
committed
43
44
#ifdef DIMAPISSL
static SSL_CTX *ctx;
45
void sigpipe_handle();
's avatar
committed
46
47
#endif

48
49
50
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
93
94
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
#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

int check_network_mapid(void);			// checks if network (mapid) is up. Returns 1 if network is up, 0 otherwise
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;
	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

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

    WARNING_CMD(printf("send: %s [%s:%d]\n", strerror(errno), __FILE__, __LINE__));

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

    printf("\n ---> Mapid is down\n");
    check_net = check_network_mapid();
    
    if(check_net == 1)			// network is up		FIXME XXX
	    printf("Network up ...\n");
    else{				// network is down
	    //printf("\nNetwork down ...\n");
	    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){

		    // 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;
			    }
		    }
	    }
	    else if(qbuf->cmd == GET_FLOW_INFO || qbuf->cmd == GET_NEXT_FLOW_INFO ||		// FIXME (CLOSE_FLOW ...)
				    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;
	    }

	    send(sock, qbuf, sizeof(struct mapiipcbuf), MSG_NOSIGNAL);
    }
#else
's avatar
committed
185
    return -1;
186
#endif
Arne Øslebø's avatar
Arne Øslebø committed
187
  }
's avatar
committed
188
  return 0;
Arne Øslebø's avatar
Arne Øslebø committed
189
190
}

's avatar
committed
191
int mapiipc_read(struct mapiipcbuf *qbuf)
Arne Øslebø's avatar
Arne Øslebø committed
192
193
194
195
//Reads an IPC message. Blocking call
{
  if(recv(sock, qbuf, MAX_SEND_SIZE, 0) == -1){
    ERROR_CMD(printf("recv: %s [%s:%d]\n",strerror(errno),__FILE__,__LINE__));
's avatar
committed
196
    return -1;
Arne Øslebø's avatar
Arne Øslebø committed
197
  }
's avatar
committed
198
  return 0;
Arne Øslebø's avatar
Arne Øslebø committed
199
200
}

's avatar
committed
201
int mapiipc_client_init()
Arne Øslebø's avatar
Arne Øslebø committed
202
203
204
205
//Initializes IPC for mapi functions
{
  if ((sock = socket(AF_LOCAL, SOCK_STREAM, 0)) == -1) {
    ERROR_CMD(printf("socket: %s [%s:%d]\n",strerror(errno),__FILE__,__LINE__));
's avatar
committed
206
    return -1;
Arne Øslebø's avatar
Arne Øslebø committed
207
  }
's avatar
committed
208
209
210

  mapidsocket=malloc(sizeof(MAPIDSOCKHOME)-2+strlen(getenv("HOME")));
  sprintf(mapidsocket,MAPIDSOCKHOME,getenv("HOME")); 
Arne Øslebø's avatar
Arne Øslebø committed
211
212
213

  // Construct name of mapid's socket
  mapidaddr.sun_family = AF_LOCAL;
's avatar
committed
214
  strcpy(mapidaddr.sun_path, mapidsocket);
Arne Øslebø's avatar
Arne Øslebø committed
215
216
  mapidaddr_len = sizeof mapidaddr.sun_family + strlen(mapidaddr.sun_path);

's avatar
committed
217
  if (connect(sock, (struct sockaddr *)&mapidaddr, mapidaddr_len) < 0) 
's avatar
   
committed
218
  {
's avatar
committed
219
220
221
222
      free(mapidsocket);
      mapidsocket=strdup(MAPIDSOCKGLOBAL);
      strcpy(mapidaddr.sun_path, mapidsocket);
      mapidaddr_len = sizeof mapidaddr.sun_family + strlen(mapidaddr.sun_path);
223
224
225
      if (connect(sock, (struct sockaddr *)&mapidaddr, mapidaddr_len) < 0) {
    		ERROR_CMD(printf("connect: %s [%s:%d]\n",strerror(errno),__FILE__,__LINE__));
	}
's avatar
committed
226
      else {
227
228
		free(mapidsocket);
      	return 0;
's avatar
committed
229
      }
's avatar
   
committed
230
  }
's avatar
committed
231
  free(mapidsocket);
232
  return -1;
Arne Øslebø's avatar
Arne Øslebø committed
233
234
235
236
237
238
239
240
}

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

241
242
243
244
#ifdef DIMAPI
struct sockaddr_in remoteaddr;
flist_t *remote_flowlist=NULL;

245
int mapiipc_remote_write(struct dmapiipcbuf *dbuf, struct host *h){	// sends an IPC message to mapid
's avatar
committed
246
247

#ifdef DIMAPISSL
248
249
250
251
252
253
254
255
256

#ifdef RECONNECT
	if(SSL_write(h->con, dbuf, dbuf->length) <= 0){
		WARNING_CMD(printf("SSL_write: %s [%s:%d]\n", strerror(errno), __FILE__, __LINE__));
		sem_wait(&h->connection);	// lock the semaphore
	}
#else
	if(SSL_write(h->con, dbuf, dbuf->length) <= 0){
		WARNING_CMD(printf("SSL_write: %s [%s:%d]\n", strerror(errno), __FILE__, __LINE__));
's avatar
committed
257
258
		return -1;
	}
259
260
261
262
263
264
265
266
267
268
269
#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){
		WARNING_CMD( printf("send: %s [%s:%d]\n", strerror(errno), __FILE__, __LINE__) );
		sem_wait(&h->connection);	// lock the semaphore
	}
270
271
272
273
274
#else
	if(send(h->sockfd, dbuf, dbuf->length, 0) == -1) {
		WARNING_CMD(printf("send: %s [%s:%d]\n",strerror(errno),__FILE__,__LINE__));
		return -1;
	}
275
276
#endif

's avatar
committed
277
#endif
278
	return 0;
279
280
}

's avatar
committed
281
int mapiipc_remote_write_to_all(remote_flowdescr_t* rflow)
282
283
284
{
  host_flow* hflow;
  flist_node_t* fnode;
's avatar
committed
285

286
287
288
  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
289
    if (mapiipc_remote_write(hflow->dbuf, hflow->rhost)<0) return -1;
's avatar
committed
290
  }
291

's avatar
committed
292
  for (fnode=flist_head(rflow->host_flowlist); fnode!=NULL; fnode=flist_next(fnode)) {
293
     sem_wait(&rflow->fd_sem);
294
  }
295

's avatar
committed
296
  return 0;
297
}
298
299
300
301
302
303
 
void cleanup_handler(void *arg){	//the cleanup handler

        free(arg);
	return;
}
304

305
306
void *mapiipc_comm_thread(void *host){		// reads an IPC message - blocking call

307
308
309
310
  struct dmapiipcbuf* dbuf;
  remote_flowdescr_t* rflow;
  host_flow* hflow;
  int recv_bytes;
's avatar
committed
311

312
313
#ifdef RECONNECT
  int check_net;
's avatar
committed
314
#endif
315
  
's avatar
committed
316
  /* Guarantees that thread resources are deallocated upon return */
317
318
319
320
  pthread_detach(pthread_self());
  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)
321
  dbuf = (struct dmapiipcbuf *)malloc(sizeof(struct dmapiipcbuf));
322

323
324
325
326
327
328
  // 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);

329
  while(1){
330

331
	  if(host == NULL) break;
's avatar
committed
332

's avatar
committed
333
#ifdef DIMAPISSL
334
      	  recv_bytes = SSL_readn( ((struct host *) host)->con, dbuf, BASIC_SIZE);
335
#else
336
      	  recv_bytes = readn( ((struct host *) host)->sockfd, dbuf, BASIC_SIZE);
's avatar
committed
337
338
#endif

339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
	  if(recv_bytes == 0){				// the peer has gone
#ifdef RECONNECT
	  	  printf("\n\t--->  Mapicommd is down. Socket closed from host: %s\n", ((struct host *)host)->hostname);
		  check_net = check_network_mapicommd((struct host *) host);

		  if(check_net == 1)			// network is up
			  continue;
		  else{					// network is down
			  printf("\nNetwork down ...\n");
			  restore_network_mapicommd((struct host *) host);
			  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
			  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
		  break;
#endif
      	  }

      	  else if(recv_bytes == -1){
#ifdef RECONNECT
	  	  printf("\n\t--->  Mapicommd is down. Socket closed from host: %s\n", ((struct host *)host)->hostname);
		  check_net = check_network_mapicommd((struct host *) host);

  		  if(check_net == 1)			// network is up
			  continue;
		  else{					// network is down
			  printf("\nNetwork down ...\n");
			  restore_network_mapicommd((struct host *) host);
			  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
			  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) {
	  	  fprintf(stderr,"Bad IPC message from agent\n");
	  	  continue;
      	  }
      
	  if (dbuf->length - BASIC_SIZE>0) {
's avatar
committed
399
400

#ifdef DIMAPISSL
401
		  recv_bytes = SSL_readn( ((struct host *) host)->con, (char *)dbuf + BASIC_SIZE, dbuf->length - BASIC_SIZE );
402
#else
403
	      	  recv_bytes = readn( ((struct host *) host)->sockfd, (char *)dbuf + BASIC_SIZE, dbuf->length - BASIC_SIZE);
's avatar
committed
404
#endif
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
	  	  if(recv_bytes == 0){			// the peer has gone
#ifdef RECONNECT
		  	  printf("\n\t--->  Mapicommd is down. Socket closed from host: %s\n", ((struct host *)host)->hostname);
			  check_net = check_network_mapicommd((struct host *) host);
	
			  if(check_net == 1)			// network is up
				  continue;
			  else{					// network is down
				  printf("\nNetwork down ...\n");
				  restore_network_mapicommd((struct host *) host);
				  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
				  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
			  break;
#endif
		  }

	  	  else if(recv_bytes == -1){
#ifdef RECONNECT			  
		  	  printf("\n\t--->  Mapicommd is down. Socket closed from host: %s\n", ((struct host *)host)->hostname);
			  check_net = check_network_mapicommd((struct host *) host);
	
			  if(check_net == 1)			// network is up
				  continue;
			  else{					// network is down
				  printf("\nNetwork down ...\n");
				  restore_network_mapicommd((struct host *) host);
				  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
				  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
		  }
      	  }
      
	  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) {
	  		  memcpy(hflow->pkt, dbuf->data, dbuf->length-BASIC_SIZE);
	  		  flist_append(rflow->pkt_list, 0, hflow);
	  		  sem_post(&rflow->pkt_sem);
	    	  }
	    	  else {
		  	  memcpy( hflow->dbuf, dbuf, dbuf->length );	//place data
		  	  sem_post( &rflow->fd_sem );
	    	  }
      	  }
      	  else {
	    	  fprintf(stderr,"Invalid IPC message, unknown fd %d\n",dbuf->fd);
	    	  continue;
      	  }
480
  }
481
482
  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
483
  return NULL;
484
485
}

's avatar
committed
486
int mapiipc_remote_init(struct host *h)
487
488
//Initializes IPC for dmapi functions
{
's avatar
committed
489
490
  struct hostent* host=gethostbyname(h->hostname);
  struct timeval tv;
491

492
#ifdef DIMAPISSL
493
494
	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
495
496
497

	if ((ctx=SSL_CTX_new(SSLv3_client_method())) == NULL) {
		ERR_print_errors_fp(stderr);
's avatar
committed
498
		return -1;
's avatar
committed
499
500
501
	}
	if ((h->con = SSL_new(ctx)) == NULL) {
		ERR_print_errors_fp(stderr);
's avatar
committed
502
		return -1;
's avatar
committed
503
	}
504
505

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

508
509
  if ((h->sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
    ERROR_CMD(printf("socket: %s [%s:%d]\n",strerror(errno),__FILE__,__LINE__));
's avatar
committed
510
    return -1;
's avatar
committed
511
512
  }

's avatar
fix    
committed
513
  /*
514
  tv.tv_sec=20;		//timeout 20 sec for recv
's avatar
committed
515
516
517
518
519
  tv.tv_usec=0;

  if (setsockopt(h->sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(struct timeval)) == -1) {
    close(h->sockfd);
    printf("Unexpected error on setsockopt()");
's avatar
committed
520
521
    //exit(-1);
    return -1;
's avatar
committed
522
  }
's avatar
fix    
committed
523
  */
524

's avatar
committed
525
526
527
528
529
530
  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);
    printf("Unexpected error on setsockopt()");
's avatar
committed
531
    return -1;
's avatar
committed
532
533
534
535
  }

  if (host==NULL) {
    printf("Could not determine address for %s\n",h->hostname);
's avatar
committed
536
    return -1;
537
  }
's avatar
committed
538

539
540
  // Construct name of dmapid's socket
  remoteaddr.sin_family = AF_INET;
's avatar
committed
541
  remoteaddr.sin_addr = *((struct in_addr *)host->h_addr);
542
543
  remoteaddr.sin_port = htons(h->port);

544
  if (connect(h->sockfd, (struct sockaddr *)&remoteaddr, sizeof(remoteaddr)) < 0) {
's avatar
committed
545
    ERROR_CMD(printf("connect failed: %s [%s:%d]\n",strerror(errno),__FILE__,__LINE__));
's avatar
committed
546
    return -1;
547
  }
's avatar
committed
548
549

#ifdef DIMAPISSL
550
	if (SSL_set_fd(h->con, h->sockfd) == 0) {
's avatar
committed
551
		ERR_print_errors_fp(stderr);
's avatar
committed
552
		return -1;
's avatar
committed
553
554
555
	}
	if (SSL_connect(h->con) <= 0) {
		ERR_print_errors_fp(stderr);
's avatar
committed
556
		return -1;
's avatar
committed
557
558
	}
#endif
's avatar
committed
559
  return 0;
's avatar
committed
560

561
562
563
564
565
}

void mapiipc_remote_close(struct host *h)
//Releases socket resources
{
566
567
568
	shutdown(h->sockfd, SHUT_RDWR);
	close(h->sockfd);

's avatar
committed
569
#ifdef DIMAPISSL
570
	if (SSL_shutdown(h->con) == -1)	// shut down a TLS/SSL connection
's avatar
committed
571
		ERR_print_errors_fp(stderr);
572
573
574
575
576
577
578
579
580
581

	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
582
#endif
583
}
584
585

#endif /* DIMAPI */
586

Arne Øslebø's avatar
Arne Øslebø committed
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614

// 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;
615
	s = (char*)*pos;
Arne Øslebø's avatar
Arne Øslebø committed
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
	//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) {
      // err_quit("control level != SOL_SOCKET");
      fprintf(stderr, "control level != SOL_SOCKET");
      return -1;
    }
    if (cmptr->cmsg_type != SCM_RIGHTS) {
      // err_quit("control type != SCM_RIGHTS");
      fprintf(stderr, "control type != SCM_RIGHTS");
      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
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776

/* 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
777
778
#ifdef DIMAPISSL
ssize_t SSL_readn(SSL *con, void *vptr, size_t n) {
779

's avatar
committed
780
781
782
        size_t nleft;
        ssize_t nread;
        char *ptr;
's avatar
committed
783

's avatar
committed
784
785
        ptr = vptr;
        nleft = n;
786

's avatar
committed
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
        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 */
}
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
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
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
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
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
1066
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
1245
1246
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
1301
1302
1303
1304
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
1375
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
1409
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
1449
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
1483
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
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811

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){
		ERROR_CMD(printf("socket: %s [%s:%d]\n", strerror(errno), __FILE__, __LINE__));
    	        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;

	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;

	for(tries = 0; tries < 10; tries++){

		printf("\n---> Reconnection try #%d", tries);
		check_net = check_network_mapicommd(h);
		fflush(stdout);

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

			printf("\nMapid server is back online ...\n");

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

		sleep(time);	// pause execution for the specified time
		time += time;	// increase waiting time
	}

	fprintf(stderr,"\nNetwork is down (reconnection tries expired)\n");
	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{
			fprintf(stderr, "\nError: Could not re-create flow in host %s [%s : %d]\n", hflow->rhost->hostname, __FILE__, __LINE__);
			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{
			fprintf(stderr, "\nError: Could not re-apply function %s in host %s [%s : %d]\n", fdata->fdef->name, hflow->rhost->hostname,
														__FILE__, __LINE__);
			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
				}
				else{
					fprintf(stderr, "Error: Could not re-connect to flow %d [%s : %d]\n", hflow->scope_fd, __FILE__, __LINE__);
					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{
					fprintf(stderr, "Error: Could not re-authenticate flow %d [%s : %d]\n", hflow->scope_fd, __FILE__, __LINE__);
					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 ||
				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 ...
					fprintf(stderr, "Error: Probably invalid fid in mapi_get_next_packet() [%s : %d]\n", __FILE__, __LINE__);
					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
		ERROR_CMD(printf("socket: %s [%s:%d]\n", strerror(errno), __FILE__, __LINE__));
		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;

	for(tries = 0; tries < 10; tries++){

		printf("\n---> Reconnection try #%d", tries);
		check_net = check_network_mapid();
		fflush(stdout);

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

			printf("\nMapid is back online ...\n\n");
			mapiipc_client_close();		// release previous socket resources
			mapiipc_client_init();		// initializes IPC for mapi functions
			return;
		}
		sleep(time);	// pause execution for the specified time
		time += time;	// increase waiting time
	}
	fprintf(stderr,"\nNetwork is down (reconnection tries expired)\n");
	exit(EXIT_FAILURE);
}

// this function recreates all offline devices, that have been created and not deleted
void mapi_create_offline_device_mapid(void){

	flist_node_t *fnode, *fnode_;
	offline_device *device = NULL;
	flowdescr_t *flow;
	struct mapiipcbuf qbuf;
	int file;
	
	for(fnode = flist_head(offline_device_list); fnode != NULL; fnode = flist_next(fnode)){
		
		device = (offline_device *)fnode->data;		// data stored in the node
		
		if( (file = open(device->path, O_LARGEFILE)) == -1)
			exit(EXIT_FAILURE);
		
		qbuf.mtype = 1;
		qbuf.cmd = CREATE_OFFLINE_DEVICE;
		qbuf.fd = getpid();
		qbuf.pid = getpid();
		qbuf.fid = device->format;
		strncpy((char *) qbuf.data, device->path, DATA_SIZE);
		
		if(mapiipc_write((struct mapiipcbuf *) &qbuf) < 0)	// sends an IPC message to mapid
			exit(EXIT_FAILURE);
		
		if(mapiipc_read((struct mapiipcbuf *) &qbuf) < 0)	// reads an IPC message (blocking call)
			exit(EXIT_FAILURE);
		
		if(qbuf.cmd == SEND_FD){
			if(mapiipc_send_fd(file) == -1)
				exit(EXIT_FAILURE);
		}
		else
			exit(EXIT_FAILURE);
		
		if(mapiipc_read((struct mapiipcbuf *) &qbuf) < 0)	// reads an IPC message (blocking call)
			exit(EXIT_FAILURE);
		
		if(qbuf.cmd == CREATE_OFFLINE_DEVICE_ACK){
			
			//printf("\n\t New device = %s, Previous device = %s\n", (char *)qbuf.data, device->previous_device);
			
			for(fnode_ = flist_head(flowlist); fnode_ != NULL; fnode_ = flist_next(fnode_)){	// iterate list with all active flows
				
				flow = (flowdescr_t *)fnode_->data;	// data stored in the node

				if(!strcmp(flow->device, device->previous_device))	// change previous device name with the new one (mapi_create_flow())
					strcpy(flow->device, (char *) qbuf.data);	// XXX

			}
			strcpy(device->new_device, (char *) qbuf.data);	// XXX
		}
		else{
			fprintf(stderr, "\nError: Could not re-create offline device %s [%s : %d]\n", device->path, __FILE__, __LINE__);
			exit(EXIT_FAILURE);
		}
	}
	return;
}

// this function recreates all flows, on-line and off-line, that have been created and not closed
void mapi_recreate_flow_mapid(void){
	
	flist_node_t *fnode;
	flowdescr_t *flow;
	struct mapiipcbuf qbuf;
	int file;	// need for offline flows

	for(fnode = flist_head(flowlist); fnode != NULL; fnode = flist_next(fnode)){	// iterate list with all active flows

		flow = (flowdescr_t *)fnode->data;	// data stored in the node

		if(flow->file == -1){			// ON-LINE flow ...
		
			qbuf.mtype = 1;
			qbuf.cmd = CREATE_FLOW;
			qbuf.fd = getpid();		// get process identification
			qbuf.pid = getpid();
			strncpy((char *) qbuf.data, flow->device, DATA_SIZE);
			
			if(mapiipc_write((struct mapiipcbuf *) &qbuf) < 0)	// sends an IPC message to mapid
				exit(EXIT_FAILURE);
		
			if(mapiipc_read((struct mapiipcbuf *) &qbuf) < 0)	// reads an IPC message (blocking call)
				exit(EXIT_FAILURE);
			
			if(qbuf.cmd == CREATE_FLOW_ACK){

				//printf("\n\t New fd = %d, Previous fd = %d", qbuf.fd, flow->fd);
				flow->fd = qbuf.fd;				// the new fd of the flow
				strcpy(flow->devtype, (char *) qbuf.data);	// XXX
			}
			else{
				fprintf(stderr, "\nError: Could not re-create flow with device %s [%s : %d]\n", flow->device, __FILE__, __LINE__);
				exit(EXIT_FAILURE);
			}
		}
		else{					// OFF-LINE flow ...
			if( (file = open(flow->device, O_LARGEFILE)) == -1)
				exit(EXIT_FAILURE);
			
			qbuf.mtype = 1;
			qbuf.cmd = CREATE_OFFLINE_FLOW;
			qbuf.fd = getpid();
			qbuf.pid = getpid();
			qbuf.fid = flow->format;
			strncpy((char *) qbuf.data, flow->device, DATA_SIZE);
			
			if(mapiipc_write((struct mapiipcbuf *) &qbuf) < 0)	// sends an IPC message to mapid
				exit(EXIT_FAILURE);

			if(mapiipc_read((struct mapiipcbuf *) &qbuf) < 0)	// reads an IPC message (blocking call)
				exit(EXIT_FAILURE);
			
			if(qbuf.cmd == SEND_FD){
				
				if(mapiipc_send_fd(file) == -1)
					exit(EXIT_FAILURE);
			}
			else
				exit(EXIT_FAILURE);
			
			if(mapiipc_read((struct mapiipcbuf *) &qbuf) < 0)	// reads an IPC message (blocking call)
				exit(EXIT_FAILURE);

			if(qbuf.cmd == CREATE_OFFLINE_FLOW_ACK){

				//printf("\n\t New fd = %d, Previous fd = %d \t off-line", qbuf.fd, flow->fd);
				flow->fd = qbuf.fd;				// the new fd of the flow
				strcpy(flow->devtype, (char *) qbuf.data);	// XXX
				flow->file = file;        			// new file descriptor of offline flow
			}
			else{
				fprintf(stderr, "\nError: Could not re-create offline flow with device %s [%s : %d]\n", flow->device, __FILE__, __LINE__);
				exit(EXIT_FAILURE);
			}
		}
	}
	return;
}

// this function reapplies all functions, that have been applyed to flows that have not been closed
void mapi_reapply_function_mapid(void){

	flist_node_t *fnode;
	functdescr_t *fun, *fun_;
	mapiFunctArg *pos;
	flowdescr_t *flow;
	struct mapiipcbuf qbuf = {-1, -1, -1, -1, -1, "", -1, -1, -1, 0, "", "", -1};
	unsigned char *args;
	char *argdescr_ptr, *temp, *fids, *new_fids, *cfids, *s, ctmp, buf[DATA_SIZE];
	unsigned long long ltmp;
	int c, tmp, fid_, fd_, len = 0;
	
	for(fnode = flist_head(function_list); fnode != NULL; fnode = flist_next(fnode)){	// iterate function list

		fun = (functdescr_t *)fnode->data;	// data stored in the node
		
		pos = qbuf.data;	// point to start of arguments buffer
		
		if(strncmp(fun->def->argdescr, "", 1)){		// there are some arguments
			
			args = (unsigned char *)fun->funct->instance->args;
			argdescr_ptr = fun->def->argdescr;
			
			while(strlen(argdescr_ptr) > 0){
				switch(*argdescr_ptr){
					case 's':
						temp = (char *)args;
						args += strlen(temp) + 1;
						addarg(&pos, temp, STRING);
						break;
					case 'S':		  // reference to flows and functions (e.g RES2FILE)
						fids = (char *)args;
						args += strlen(fids) + 1;

						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_);

							if((flow = flist_get(flowlist, fd_)) == NULL){		// search list using previous fd
								fprintf(stderr, "Error: Probably invalid flow in re-apply function [%s : %d]\n",
											__FILE__, __LINE__);
								free(new_fids); new_fids = NULL;
								exit(EXIT_FAILURE);
							}
							fd_ = flow->fd;		// new fd

							if((fun_ = flist_get(function_list, fid_)) == NULL){	// search list using previous fid
								fprintf(stderr, "Error: Probably invalid fid in re-apply function [%s : %d]\n",
											__FILE__, __LINE__);
								free(new_fids); new_fids = NULL;
								exit(EXIT_FAILURE);
							}
							fid_ = fun_->fid;	// new fid
							
							if(len != 0)
								len += sprintf(new_fids + len, ",");
							len += sprintf(new_fids + len, "%d", fid_);
							len += sprintf(new_fids + len, "@");
							len += sprintf(new_fids + len, "%d", fd_);
							
							cfids = s + 1;
						}
						
						sscanf(cfids, "%d@%d", &fid_, &fd_);
						
						if((flow = flist_get(flowlist, fd_)) == NULL){		// search list using previous fd
							fprintf(stderr, "Error: Probably invalid flow in re-apply function [%s : %d]\n", __FILE__, __LINE__);
							free(new_fids); new_fids = NULL;
							exit(EXIT_FAILURE);
						}
						fd_ = flow->fd;		// new fd
						
						if((fun_ = flist_get(function_list, fid_)) == NULL){	// search list using previous fid
							fprintf(stderr, "Error: Probably invalid fid in re-apply function [%s : %d]\n", __FILE__, __LINE__);
							free(new_fids); new_fids = NULL;
							exit(EXIT_FAILURE);
						}
						fid_ = fun_->fid;	// new fid
						
						if(len != 0)
							len += sprintf(new_fids + len, ",");
						len += sprintf(new_fids + len, "%d", fid_);
						len += sprintf(new_fids + len, "@");
						len += sprintf(new_fids + len, "%d", fd_);

						addarg(&pos, new_fids, STRING);
						len = 0;
						free(new_fids); new_fids = NULL;
						break;
					case 'i':
						memcpy(&tmp, args, sizeof(int));
						args += sizeof(int);
						addarg(&pos, &tmp, INT);
						break;
					case 'c':
						memcpy(&ctmp, args, sizeof(char));
						args += sizeof(char);
						addarg(&pos, &ctmp, CHAR);
						break;
					case 'l':
						memcpy(&ltmp, args, sizeof(unsigned long long));
						args += sizeof(unsigned long long);
						addarg(&pos, &ltmp, UNSIGNED_LONG_LONG);
						break;
					case 'r':	// reference to a flow
						memcpy(&tmp, args, sizeof(int));
						args += sizeof(int);

						if((flow = flist_get(flowlist, tmp)) == NULL){		// search list using previous fd
							fprintf(stderr, "Error: Probably invalid flow in re-apply function [%s : %d]\n", __FILE__, __LINE__);
							exit(EXIT_FAILURE);
						}
						tmp = flow->fd;			// new fd
						addarg(&pos, &tmp, INT);
						break;
					case 'f':	// reference to a fuction
						memcpy(&tmp, args, sizeof(int));
						args += sizeof(int);

						if((fun_ = flist_get(function_list, tmp)) == NULL){	// search list using previous fid
							fprintf(stderr, "Error: Probably invalid fid in re-apply function [%s : %d]\n",	__FILE__, __LINE__);
							exit(EXIT_FAILURE);
						}
						tmp = fun_->fid;		// new fid
						addarg(&pos, &tmp, INT);
						break;
					case 'w':				// XXX
						memcpy(&tmp, args, sizeof(int));
						args += sizeof(int);
						addarg(&pos, &tmp, INT);
						break;
				}
				argdescr_ptr++;		// move to the next argument
			}
		}

		qbuf.mtype = 1;
		qbuf.cmd = APPLY_FUNCTION;
		qbuf.fd = fun->flow->fd;
		qbuf.pid = getpid();
		strncpy(qbuf.function, fun->def->name, FUNCT_NAME_LENGTH);		// function's name
		strncpy((char *) qbuf.argdescr, fun->def->argdescr, ARG_LENGTH);	// arguments descriptor
		
		if(mapiipc_write((struct mapiipcbuf *) &qbuf) < 0)		// sends an IPC message to mapid
			exit(EXIT_FAILURE);
		
		for(c = 0; c < fun->numfd; c++){

			if(mapiipc_read((struct mapiipcbuf *) &qbuf) < 0)	// reads an IPC message (blocking call)
				exit(EXIT_FAILURE);

			if(qbuf.cmd != SEND_FD)
				exit(EXIT_FAILURE);

			if(mapiipc_send_fd(fun->flow->fds[c]) == -1)
				exit(EXIT_FAILURE);
		}
		
		if(mapiipc_read((struct mapiipcbuf *) &qbuf) < 0)		// reads an IPC message (blocking call)
			exit(EXIT_FAILURE);
		
		if(qbuf.cmd == APPLY_FUNCTION_ACK){

			//printf("\n+++\t APPLY OK (%s)!! New fid = %d, Previous fid = %d\n", fun->def->name, qbuf.fid, fun->fid);
			
			fun->fid = qbuf.fid;		// change previous fid with the new one
			fun->funct->fid = qbuf.fid;
			memcpy(fun->funct->instance->args, qbuf.data, FUNCTARGS_BUF_SIZE);	// copy arguments
		}
		else{
			fprintf(stderr, "\nError: Could not re-apply function %s [%s : %d]\n", fun->def->name, __FILE__, __LINE__);
			exit(EXIT_FAILURE);
		}
	}
	//flist_destroy(function_list);		// destroy list (remove all nodes)	XXX
	return;
}

// this function checks which flows, had called mapi_connect() function and not mapi_close_flow()
void mapi_reconnect_mapid(void){

	flist_node_t *fnode;
	flowdescr_t *flow;
	struct mapiipcbuf qbuf;

	for(fnode = flist_head(flowlist); fnode != NULL; fnode = flist_next(fnode)){	// iterate list with all active flows

		flow = (flowdescr_t *)fnode->data;	// data stored in the node

		if(flow->is_connected){		// flow is already connected, via mapi_connect() function

			//printf("\n flow %d is connected\n", flow->fd);
			
			qbuf.mtype = 1;
			qbuf.cmd = CONNECT;
			qbuf.fd = flow->fd;		// new fd of the flow
			qbuf.pid = getpid();

			if(mapiipc_write((struct mapiipcbuf *) &qbuf) < 0)	// sends an IPC message to mapid
				exit(EXIT_FAILURE);

			if(mapiipc_read((struct mapiipcbuf *) &qbuf) < 0)	// reads an IPC message (blocking call)
				exit(EXIT_FAILURE);
			
			if(qbuf.cmd == CONNECT_ACK){
				//printf("--> Flow %d is now connected !!\n", flow->fd);
				flow->is_connected = 1;		// FIXME
			}
			else{
				fprintf(stderr, "Error: Could not re-connect to flow %d [%s : %d]\n", flow->fd, __FILE__, __LINE__);
				flow->is_connected = 0;		// FIXME
				exit(EXIT_FAILURE);
			}
		}
		/*else				// flow is not connected
			printf("\n flow %d is not connected\n", flow->fd);	// delete
		*/
	}
	return;
}

// this function checks which flows, had called mapi_start_offline_device() function and not mapi_delete_offline_device()
void mapi_start_offline_device_mapid(void){

	flist_node_t *fnode;
	offline_device *device = NULL;
	struct mapiipcbuf qbuf;

	for(fnode = flist_head(offline_device_list); fnode != NULL; fnode = flist_next(fnode)){
		
		device = (offline_device *)fnode->data;		// data stored in the node

		if(device->is_started){		// offline device is already started, via mapi_start_offline_device() function

			//printf("device %s is started\n", device->previous_device);
			
			qbuf.mtype = 1;
			qbuf.cmd = START_OFFLINE_DEVICE;
			qbuf.fd = getpid();
			qbuf.pid = getpid();
			strncpy((char *) qbuf.data, device->new_device, DATA_SIZE);
			qbuf.fid = 0;

			if(mapiipc_write((struct mapiipcbuf *) &qbuf) < 0)	// sends an IPC message to mapid
				exit(EXIT_FAILURE);

			if(mapiipc_read((struct mapiipcbuf *) &qbuf) < 0)	// reads an IPC message (blocking call)
				exit(EXIT_FAILURE);

			if(qbuf.cmd == START_OFFLINE_DEVICE_ACK)
				device->is_started = 1;
			else{
				fprintf(stderr, "Error: Could not re-start offline device %s [%s : %d]\n", device->path, __FILE__, __LINE__);
				device->is_started = 0;		// FIXME
				exit(EXIT_FAILURE);
			}
		}
		/*else
			//printf("device %s is NOT started\n", device->previous_device);
		*/
	}
	return;
}

// this function initializes shared memory segments for new results of a function, after reconnection
void mapi_read_results_mapid(void){

	flist_node_t *fnode, *fnode_;
	flowdescr_t *flow;
	functdescr_t *fun;

	for(fnode = flist_head(flowlist); fnode != NULL; fnode = flist_next(fnode)){	// iterate list with all active flows

		flow = (flowdescr_t *)fnode->data;	// data stored in the node
		flow->shm_base = NULL;			// used in default_read_result_init() function [ get pointer to shared memory ]
		
		for(fnode_ = flist_head(flow->flist); fnode_ != NULL; fnode_ = flist_next(fnode_)){	// iterate list with all functions of the flow
			
			fun = (functdescr_t *)fnode_->data;
			fun->result_init = 0;		// in order to call function get_results_info(flow, fun) again
		}
	}
	return;
}
's avatar
committed
1812
#endif