Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Make sure that we won't try to reuse a socket closed by the user, even if we have...
[simgrid.git] / src / gras / Transport / transport.c
1 /* $Id$ */
2
3 /* transport - low level communication                                      */
4
5 /* Copyright (c) 2004 Martin Quinson. All rights reserved.                  */
6
7 /* This program is free software; you can redistribute it and/or modify it
8  * under the terms of the license (GNU LGPL) which comes with this package. */
9
10 #include "xbt/ex.h"
11 #include "xbt/peer.h"
12 #include "portable.h"
13 #include "gras/Transport/transport_private.h"
14
15 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(gras_trp,gras,"Conveying bytes over the network");
16 XBT_LOG_NEW_SUBCATEGORY(gras_trp_meas,gras_trp,"Conveying bytes over the network without formating for perf measurements");
17 static short int _gras_trp_started = 0;
18
19 static xbt_dict_t _gras_trp_plugins;      /* All registered plugins */
20 static void gras_trp_plugin_free(void *p); /* free one of the plugins */
21
22 static void
23 gras_trp_plugin_new(const char *name, gras_trp_setup_t setup) {
24   xbt_ex_t e;
25
26   gras_trp_plugin_t plug = xbt_new0(s_gras_trp_plugin_t, 1);
27   
28   DEBUG1("Create plugin %s",name);
29
30   plug->name=xbt_strdup(name);
31
32   TRY {
33     setup(plug);
34   } CATCH(e) {
35     if (e.category == mismatch_error) {
36       /* SG plugin raise mismatch when in RL mode (and vice versa) */
37       free(plug->name);
38       free(plug);
39       plug=NULL;
40       xbt_ex_free(e);
41     } else {
42       RETHROW;
43     }
44   }
45
46   if (plug)
47     xbt_dict_set(_gras_trp_plugins, name, plug, gras_trp_plugin_free);
48 }
49
50 void gras_trp_init(void){
51   if (!_gras_trp_started) {
52      /* make room for all plugins */
53      _gras_trp_plugins=xbt_dict_new();
54
55 #ifdef HAVE_WINSOCK2_H
56      /* initialize the windows mechanism */
57      {  
58         WORD wVersionRequested;
59         WSADATA wsaData;
60         
61         wVersionRequested = MAKEWORD( 2, 0 );
62         xbt_assert0(WSAStartup( wVersionRequested, &wsaData ) == 0,
63                     "Cannot find a usable WinSock DLL");
64         
65         /* Confirm that the WinSock DLL supports 2.0.*/
66         /* Note that if the DLL supports versions greater    */
67         /* than 2.0 in addition to 2.0, it will still return */
68         /* 2.0 in wVersion since that is the version we      */
69         /* requested.                                        */
70         
71         xbt_assert0(LOBYTE( wsaData.wVersion ) == 2 &&
72                     HIBYTE( wsaData.wVersion ) == 0,
73                     "Cannot find a usable WinSock DLL");
74         INFO0("Found and initialized winsock2");
75      }       /* The WinSock DLL is acceptable. Proceed. */
76 #elif HAVE_WINSOCK_H
77      {       WSADATA wsaData;
78         xbt_assert0(WSAStartup( 0x0101, &wsaData ) == 0,
79                     "Cannot find a usable WinSock DLL");
80         INFO0("Found and initialized winsock");
81      }
82 #endif
83    
84      /* Add plugins */
85      gras_trp_plugin_new("file",gras_trp_file_setup);
86      gras_trp_plugin_new("sg",gras_trp_sg_setup);
87      gras_trp_plugin_new("tcp", gras_trp_tcp_setup);
88   }
89    
90   _gras_trp_started++;
91 }
92
93 void
94 gras_trp_exit(void){
95   xbt_dynar_t sockets = ((gras_trp_procdata_t) gras_libdata_by_id(gras_trp_libdata_id))->sockets;
96   gras_socket_t sock_iter;
97   int cursor;
98
99    if (_gras_trp_started == 0) {
100       return;
101    }
102    
103    if ( --_gras_trp_started == 0 ) {
104 #ifdef HAVE_WINSOCK_H
105       if ( WSACleanup() == SOCKET_ERROR ) {
106          if ( WSAGetLastError() == WSAEINPROGRESS ) {
107             WSACancelBlockingCall();
108             WSACleanup();
109          }
110         }
111 #endif
112
113       /* Close all the sockets */
114       xbt_dynar_foreach(sockets,cursor,sock_iter) {
115         VERB1("Closing the socket %p left open on exit. Maybe a socket leak?",
116               sock_iter);
117         gras_socket_close(sock_iter);
118       }
119       
120       /* Delete the plugins */
121       xbt_dict_free(&_gras_trp_plugins);
122    }
123 }
124
125
126 void gras_trp_plugin_free(void *p) {
127   gras_trp_plugin_t plug = p;
128
129   if (plug) {
130     if (plug->exit) {
131       plug->exit(plug);
132     } else if (plug->data) {
133       DEBUG1("Plugin %s lacks exit(). Free data anyway.",plug->name);
134       free(plug->data);
135     }
136
137     free(plug->name);
138     free(plug);
139   }
140 }
141
142
143 /**
144  * gras_trp_socket_new:
145  *
146  * Malloc a new socket, and initialize it with defaults
147  */
148 void gras_trp_socket_new(int incoming,
149                          gras_socket_t *dst) {
150
151   gras_socket_t sock=xbt_new0(s_gras_socket_t,1);
152
153   VERB1("Create a new socket (%p)", (void*)sock);
154
155   sock->plugin = NULL;
156
157   sock->incoming  = incoming ? 1:0;
158   sock->outgoing  = incoming ? 0:1;
159   sock->accepting = incoming ? 1:0;
160   sock->meas = 0;
161   sock->recv_ok = 1;
162   sock->valid = 1;
163   sock->moredata = 0;
164
165   sock->sd     = -1;
166   sock->port      = -1;
167   sock->peer_port = -1;
168   sock->peer_name = NULL;
169   sock->peer_proc = NULL;
170
171   sock->data   = NULL;
172   sock->bufdata = NULL;
173   
174   *dst = sock;
175
176   xbt_dynar_push(((gras_trp_procdata_t) 
177                   gras_libdata_by_id(gras_trp_libdata_id))->sockets,dst);
178   XBT_OUT;
179 }
180  
181 /**
182  * @brief Opens a server socket and makes it ready to be listened to.
183  * @param port: port on which you want to listen
184  * @param buf_size: size of the buffer (in byte) on the socket (for TCP sockets only). If 0, a sain default is used (32k, but may change)
185  * @param measurement: whether this socket is meant to convey measurement (if you don't know, use 0 to exchange regular messages)
186  * 
187  * In real life, you'll get a TCP socket. 
188  */
189 gras_socket_t
190 gras_socket_server_ext(unsigned short port,
191                        
192                        unsigned long int buf_size,
193                        int measurement) {
194  
195   xbt_ex_t e;
196   gras_trp_plugin_t trp;
197   gras_socket_t sock;
198
199   DEBUG2("Create a server socket from plugin %s on port %d",
200          gras_if_RL() ? "tcp" : "sg",
201          port);
202   trp = gras_trp_plugin_get_by_name(gras_if_SG() ? "sg":"tcp");
203
204   /* defaults settings */
205   gras_trp_socket_new(1,&sock);
206   sock->plugin= trp;
207   sock->port=port;
208   sock->buf_size = buf_size>0 ? buf_size : 32*1024;
209   sock->meas = measurement;
210
211   /* Call plugin socket creation function */
212   DEBUG1("Prepare socket with plugin (fct=%p)",trp->socket_server);
213   TRY {
214     trp->socket_server(trp, sock);
215     DEBUG3("in=%c out=%c accept=%c",
216            sock->incoming?'y':'n', 
217            sock->outgoing?'y':'n',
218            sock->accepting?'y':'n');
219   } CATCH(e) {
220     int cursor;
221     gras_socket_t sock_iter;
222     xbt_dynar_t socks = ((gras_trp_procdata_t) gras_libdata_by_id(gras_trp_libdata_id))->sockets;
223     xbt_dynar_foreach(socks, cursor, sock_iter) {
224        if (sock_iter==sock) 
225          xbt_dynar_cursor_rm(socks,&cursor);
226     }     
227     free(sock);
228     RETHROW;
229   }
230
231   if (!measurement)
232      ((gras_trp_procdata_t) gras_libdata_by_id(gras_trp_libdata_id))->myport = port;
233   return sock;
234 }
235 /**
236  * @brief Opens a server socket on any port in the given range
237  * 
238  * @param minport: first port we will try
239  * @param maxport: last port we will try
240  * @param buf_size: size of the buffer (in byte) on the socket (for TCP sockets only). If 0, a sain default is used (32k, but may change)
241  * @param measurement: whether this socket is meant to convey measurement (if you don't know, use 0 to exchange regular messages)
242  * 
243  * If none of the provided ports works, raises the exception got when trying the last possibility
244  */ 
245 gras_socket_t
246 gras_socket_server_range(unsigned short minport, unsigned short maxport,
247                          unsigned long int buf_size, int measurement) {
248    
249   int port;
250   gras_socket_t res=NULL;
251   xbt_ex_t e;
252   
253   for (port=minport; port<maxport;port ++) {
254     TRY {
255       res=gras_socket_server_ext(port,buf_size,measurement);
256     } CATCH(e) {
257       if (port==maxport)
258         RETHROW;
259       xbt_ex_free(e);
260     }
261     if (res)
262       return res;
263   }
264   THROW_IMPOSSIBLE;
265 }
266    
267 /**
268  * @brief Opens a client socket to a remote host.
269  * @param host: who you want to connect to
270  * @param port: where you want to connect to on this host
271  * @param buf_size: size of the buffer (in bytes) on the socket (for TCP sockets only). If 0, a sain default is used (32k, but may change)
272  * @param measurement: whether this socket is meant to convey measurement (if you don't know, use 0 to exchange regular messages)
273  * 
274  * In real life, you'll get a TCP socket. 
275  */
276 gras_socket_t
277 gras_socket_client_ext(const char *host,
278                        unsigned short port,
279                        
280                        unsigned long int buf_size,
281                        int measurement) {
282  
283   xbt_ex_t e;
284   gras_trp_plugin_t trp;
285   gras_socket_t sock;
286
287   trp = gras_trp_plugin_get_by_name(gras_if_SG() ? "sg":"tcp");
288
289   DEBUG1("Create a client socket from plugin %s",gras_if_RL() ? "tcp" : "sg");
290   /* defaults settings */
291   gras_trp_socket_new(0,&sock);
292   sock->plugin= trp;
293   sock->peer_port = port;
294   sock->peer_name = (char*)strdup(host?host:"localhost");
295   sock->buf_size = buf_size>0 ? buf_size: 32*1024;
296   sock->meas = measurement;
297
298   /* plugin-specific */
299   TRY {
300     (*trp->socket_client)(trp, sock);
301     DEBUG3("in=%c out=%c accept=%c",
302            sock->incoming?'y':'n', 
303            sock->outgoing?'y':'n',
304            sock->accepting?'y':'n');
305   } CATCH(e) {
306     free(sock);
307     RETHROW;
308   }
309
310   return sock;
311 }
312
313 /**
314  * gras_socket_server:
315  *
316  * Opens a server socket and make it ready to be listened to.
317  * In real life, you'll get a TCP socket.
318  */
319 gras_socket_t
320 gras_socket_server(unsigned short port) {
321    return gras_socket_server_ext(port,32*1024,0);
322 }
323
324 /** @brief Opens a client socket to a remote host */
325 gras_socket_t
326 gras_socket_client(const char *host,
327                    unsigned short port) {
328    return gras_socket_client_ext(host,port,0,0);
329 }
330
331 /** @brief Opens a client socket to a remote host specified as '\a host:\a port' */
332 gras_socket_t
333 gras_socket_client_from_string(const char *host) {
334    xbt_peer_t p = xbt_peer_from_string(host);
335    gras_socket_t res = gras_socket_client_ext(p->name,p->port,0,0);
336    xbt_peer_free(p);
337    return res;
338 }
339
340 /** \brief Close socket */
341 void gras_socket_close(gras_socket_t sock) {
342   xbt_dynar_t sockets = ((gras_trp_procdata_t) gras_libdata_by_id(gras_trp_libdata_id))->sockets;
343   gras_socket_t sock_iter;
344   int cursor;
345
346   XBT_IN;
347   VERB1("Close %p",sock);
348   if (sock == _gras_lastly_selected_socket) {
349      if (sock->moredata) 
350        CRITICAL0("Closing a socket which had another message buffered after the one being handled now. Go fix your code.");
351      _gras_lastly_selected_socket=NULL;
352   }
353    
354   /* FIXME: Issue an event when the socket is closed */
355   if (sock) {
356     xbt_dynar_foreach(sockets,cursor,sock_iter) {
357       if (sock == sock_iter) {
358         xbt_dynar_cursor_rm(sockets,&cursor);
359         if (sock->plugin->socket_close) 
360           (* sock->plugin->socket_close)(sock);
361
362         /* free the memory */
363         if (sock->peer_name)
364           free(sock->peer_name);
365         free(sock);
366         XBT_OUT;
367         return;
368       }
369     }
370     WARN1("Ignoring request to free an unknown socket (%p). Execution stack:",sock);
371     xbt_backtrace_display();
372   }
373   XBT_OUT;
374 }
375
376 /**
377  * gras_trp_send:
378  *
379  * Send a bunch of bytes from on socket
380  * (stable if we know the storage will keep as is until the next trp_flush)
381  */
382 void
383 gras_trp_send(gras_socket_t sd, char *data, long int size, int stable) {
384   xbt_assert0(sd->outgoing,"Socket not suited for data send");
385   (*sd->plugin->send)(sd,data,size,stable);
386 }
387 /**
388  * gras_trp_chunk_recv:
389  *
390  * Receive a bunch of bytes from a socket
391  */
392 void
393 gras_trp_recv(gras_socket_t sd, char *data, long int size) {
394   xbt_assert0(sd->incoming,"Socket not suited for data receive");
395   (sd->plugin->recv)(sd,data,size);
396 }
397
398 /**
399  * gras_trp_flush:
400  *
401  * Make sure all pending communications are done
402  */
403 void
404 gras_trp_flush(gras_socket_t sd) {
405   if (sd->plugin->flush)
406     (sd->plugin->flush)(sd);
407 }
408
409 gras_trp_plugin_t
410 gras_trp_plugin_get_by_name(const char *name){
411   return xbt_dict_get(_gras_trp_plugins,name);
412 }
413
414 int gras_socket_my_port  (gras_socket_t sock) {
415   return sock->port;
416 }
417 int   gras_socket_peer_port(gras_socket_t sock) {
418   return sock->peer_port;
419 }
420 char *gras_socket_peer_name(gras_socket_t sock) {
421   return sock->peer_name;
422 }
423 char *gras_socket_peer_proc(gras_socket_t sock) {
424   return sock->peer_proc;
425 }
426
427 void gras_socket_peer_proc_set(gras_socket_t sock,char*peer_proc) {
428   sock->peer_proc = peer_proc;
429 }
430
431 /** \brief Check if the provided socket is a measurement one (or a regular one) */
432 int gras_socket_is_meas(gras_socket_t sock) {
433   return sock->meas;
434 }
435
436 /** \brief Send a chunk of (random) data over a measurement socket 
437  *
438  * @param peer measurement socket to use for the experiment
439  * @param timeout timeout (in seconds)
440  * @param exp_size total amount of data to send (in bytes).
441  * @param msg_size size of each chunk sent over the socket (in bytes).
442  *
443  * Calls to gras_socket_meas_send() and gras_socket_meas_recv() on 
444  * each side of the socket should be paired. 
445  * 
446  * The exchanged data is zeroed to make sure it's initialized, but
447  * there is no way to control what is sent (ie, you cannot use these 
448  * functions to exchange data out of band).
449  */
450 void gras_socket_meas_send(gras_socket_t peer, 
451                            unsigned int timeout,
452                            unsigned long int exp_size, 
453                            unsigned long int msg_size) {
454   char *chunk=NULL;
455   unsigned long int exp_sofar;
456    
457   XBT_IN;
458
459   if (gras_if_RL()) 
460     chunk=xbt_malloc0(msg_size);
461
462   xbt_assert0(peer->meas,"Asked to send measurement data on a regular socket");
463   xbt_assert0(peer->outgoing,"Socket not suited for data send (was created with gras_socket_server(), not gras_socket_client())");
464
465   for (exp_sofar=0; exp_sofar < exp_size; exp_sofar += msg_size) {
466      CDEBUG5(gras_trp_meas,"Sent %lu of %lu (msg_size=%ld) to %s:%d",
467              exp_sofar,exp_size,msg_size,
468              gras_socket_peer_name(peer), gras_socket_peer_port(peer));
469      (*peer->plugin->raw_send)(peer,chunk,msg_size);
470   }
471   CDEBUG5(gras_trp_meas,"Sent %lu of %lu (msg_size=%ld) to %s:%d",
472           exp_sofar,exp_size,msg_size,
473           gras_socket_peer_name(peer), gras_socket_peer_port(peer));
474              
475   if (gras_if_RL()) 
476     free(chunk);
477
478   XBT_OUT;
479 }
480
481 /** \brief Receive a chunk of data over a measurement socket 
482  *
483  * Calls to gras_socket_meas_send() and gras_socket_meas_recv() on 
484  * each side of the socket should be paired. 
485  */
486 void gras_socket_meas_recv(gras_socket_t peer, 
487                            unsigned int timeout,
488                            unsigned long int exp_size, 
489                            unsigned long int msg_size){
490   
491   char *chunk=NULL;
492   unsigned long int exp_sofar;
493
494   XBT_IN;
495
496   if (gras_if_RL()) 
497     chunk = xbt_malloc(msg_size);
498
499   xbt_assert0(peer->meas,
500               "Asked to receive measurement data on a regular socket");
501   xbt_assert0(peer->incoming,"Socket not suited for data receive");
502
503   for (exp_sofar=0; exp_sofar < exp_size; exp_sofar += msg_size) {
504      CDEBUG5(gras_trp_meas,"Recvd %ld of %lu (msg_size=%ld) from %s:%d",
505              exp_sofar,exp_size,msg_size,
506              gras_socket_peer_name(peer), gras_socket_peer_port(peer));
507      (peer->plugin->raw_recv)(peer,chunk,msg_size);
508   }
509   CDEBUG5(gras_trp_meas,"Recvd %ld of %lu (msg_size=%ld) from %s:%d",
510           exp_sofar,exp_size,msg_size,
511           gras_socket_peer_name(peer), gras_socket_peer_port(peer));
512
513   if (gras_if_RL()) 
514     free(chunk);
515   XBT_OUT;
516 }
517
518 /**
519  * \brief Something similar to the good old accept system call. 
520  *
521  * Make sure that there is someone speaking to the provided server socket.
522  * In RL, it does an accept(2) and return the result as last argument. 
523  * In SG, as accepts are useless, it returns the provided argument as result.
524  * You should thus test whether (peer != accepted) before closing both of them.
525  *
526  * You should only call this on measurement sockets. It is automatically 
527  * done for regular sockets, but you usually want more control about 
528  * what's going on with measurement sockets.
529  */
530 gras_socket_t gras_socket_meas_accept(gras_socket_t peer){
531   gras_socket_t res;
532
533   xbt_assert0(peer->meas,
534               "No need to accept on non-measurement sockets (it's automatic)");
535
536   if (!peer->accepting) {
537     /* nothing to accept here (must be in SG) */
538     /* BUG: FIXME: this is BAD! it makes tricky to free the accepted socket*/
539     return peer;
540   }
541
542   res = (peer->plugin->socket_accept)(peer);
543   res->meas = peer->meas;
544   CDEBUG1(gras_trp_meas,"meas_accepted onto %d",res->sd);
545
546   return res;
547
548
549
550 /*
551  * Creating procdata for this module
552  */
553 static void *gras_trp_procdata_new() {
554    gras_trp_procdata_t res = xbt_new(s_gras_trp_procdata_t,1);
555    
556    res->name = xbt_strdup("gras_trp");
557    res->name_len = 0;
558    res->sockets   = xbt_dynar_new(sizeof(gras_socket_t*), NULL);
559    res->myport = 0;
560    
561    return (void*)res;
562 }
563
564 /*
565  * Freeing procdata for this module
566  */
567 static void gras_trp_procdata_free(void *data) {
568   gras_trp_procdata_t res = (gras_trp_procdata_t)data;
569   
570   xbt_dynar_free(&( res->sockets ));
571   free(res->name);
572   free(res);
573 }
574
575 void gras_trp_socketset_dump(const char *name) {
576   gras_trp_procdata_t procdata = 
577     (gras_trp_procdata_t)gras_libdata_by_id(gras_trp_libdata_id);
578
579   int it;
580   gras_socket_t s;
581
582   INFO1("** Dump the socket set %s",name);
583   xbt_dynar_foreach(procdata->sockets, it, s) {
584     INFO4("  %p -> %s:%d %s",
585           s,gras_socket_peer_name(s),gras_socket_peer_port(s),
586           s->valid?"(valid)":"(peer dead)");
587   }
588   INFO1("** End of socket set %s",name);
589 }
590
591 /*
592  * Module registration
593  */
594 int gras_trp_libdata_id;
595 void gras_trp_register() {
596    gras_trp_libdata_id = gras_procdata_add("gras_trp",gras_trp_procdata_new, gras_trp_procdata_free);
597 }
598
599 int gras_os_myport(void)  {
600    return ((gras_trp_procdata_t) gras_libdata_by_id(gras_trp_libdata_id))->myport;
601 }
602