Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Do not use recv() but read() to check whether a socket returned by select() is valid...
[simgrid.git] / src / gras / Transport / transport_plugin_tcp.c
1 /* $Id$ */
2
3 /* buf trp (transport) - buffered transport using the TCP one               */
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 <stdlib.h>
11 #include <string.h>       /* memset */
12
13 #include "portable.h"
14 #include "xbt/misc.h"
15 #include "xbt/sysdep.h"
16 #include "xbt/ex.h"
17 #include "gras/Transport/transport_private.h"
18
19 /* FIXME maybe READV is sometime a good thing? */
20 #undef HAVE_READV
21
22 #ifdef HAVE_READV
23 #include <sys/uio.h>
24 #endif       
25
26 #ifndef MIN
27 #define MIN(a,b) ((a)<(b)?(a):(b))
28 #endif
29
30 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(gras_trp_tcp,gras_trp,
31       "TCP buffered transport");
32
33 /***
34  *** Specific socket part
35  ***/
36
37 typedef enum { buffering_buf, buffering_iov } buffering_kind;
38
39 typedef struct {
40   int size;
41   char *data;
42   int pos; /* for receive; not exchanged over the net */
43 } gras_trp_buf_t;
44
45
46 struct gras_trp_bufdata_{
47   int buffsize;
48   gras_trp_buf_t in_buf;
49   gras_trp_buf_t out_buf;
50
51 #ifdef HAVE_READV
52   xbt_dynar_t in_buf_v;
53   xbt_dynar_t out_buf_v;
54 #endif
55
56   buffering_kind in;
57   buffering_kind out;
58 };
59
60
61 /*****************************/
62 /****[ SOCKET MANAGEMENT ]****/
63 /*****************************/
64 /* we exchange port number on client side on socket creation,
65    so we need to be able to talk right now. */
66 static XBT_INLINE void gras_trp_tcp_send(gras_socket_t sock, const char *data,
67                                      unsigned long int size);
68 static int gras_trp_tcp_recv(gras_socket_t sock, char *data,
69                              unsigned long int size);
70
71
72 static int _gras_tcp_proto_number(void);
73
74 static XBT_INLINE void gras_trp_sock_socket_client(gras_trp_plugin_t ignored,
75                                                gras_socket_t sock){
76   
77   struct sockaddr_in addr;
78   struct hostent *he;
79   struct in_addr *haddr;
80   int size = sock->buf_size; 
81   uint32_t myport = htonl(((gras_trp_procdata_t) gras_libdata_by_id(gras_trp_libdata_id))->myport);
82
83   sock->incoming = 1; /* TCP sockets are duplex'ed */
84
85   sock->sd = socket (AF_INET, SOCK_STREAM, 0);
86   
87   if (sock->sd < 0) {
88     THROW1(system_error,0, "Failed to create socket: %s", sock_errstr(sock_errno));
89   }
90
91   if (setsockopt(sock->sd, SOL_SOCKET, SO_RCVBUF, (char *)&size, sizeof(size)) ||
92       setsockopt(sock->sd, SOL_SOCKET, SO_SNDBUF, (char *)&size, sizeof(size))) {
93      WARN1("setsockopt failed, cannot set buffer size: %s",sock_errstr(sock_errno));
94   }
95   
96   he = gethostbyname (sock->peer_name);
97   if (he == NULL) {
98     THROW2(system_error,0, "Failed to lookup hostname %s: %s",
99            sock->peer_name, sock_errstr(sock_errno));
100   }
101   
102   haddr = ((struct in_addr *) (he->h_addr_list)[0]);
103   
104   memset(&addr, 0, sizeof(struct sockaddr_in));
105   memcpy (&addr.sin_addr, haddr, sizeof(struct in_addr));
106   addr.sin_family = AF_INET;
107   addr.sin_port = htons (sock->peer_port);
108
109   if (connect (sock->sd, (struct sockaddr*) &addr, sizeof (addr)) < 0) {
110     tcp_close(sock->sd);
111     THROW3(system_error,0,
112            "Failed to connect socket to %s:%d (%s)",
113            sock->peer_name, sock->peer_port, sock_errstr(sock_errno));
114   }
115
116   gras_trp_tcp_send(sock,(char*)&myport,sizeof(uint32_t));
117   DEBUG1("peerport sent to %d", sock->peer_port);
118
119   VERB4("Connect to %s:%d (sd=%d, port %d here)",
120         sock->peer_name, sock->peer_port, sock->sd, sock->port);
121 }
122
123 /**
124  * gras_trp_sock_socket_server:
125  *
126  * Open a socket used to receive messages.
127  */
128 static XBT_INLINE void gras_trp_sock_socket_server(gras_trp_plugin_t ignored,
129                                                gras_socket_t sock){
130   int size = sock->buf_size; 
131   int on = 1;
132   struct sockaddr_in server;
133
134   sock->outgoing  = 1; /* TCP => duplex mode */
135
136   server.sin_port = htons((u_short)sock->port);
137   server.sin_addr.s_addr = INADDR_ANY;
138   server.sin_family = AF_INET;
139   if((sock->sd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
140     THROW1(system_error,0,"Socket allocation failed: %s", sock_errstr(sock_errno));
141
142   if (setsockopt(sock->sd, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on)))
143      THROW1(system_error,0,
144             "setsockopt failed, cannot condition the socket: %s",
145             sock_errstr(sock_errno));
146    
147   if (   setsockopt(sock->sd, SOL_SOCKET, SO_RCVBUF,
148                     (char *)&size, sizeof(size)) 
149       || setsockopt(sock->sd, SOL_SOCKET, SO_SNDBUF, 
150                     (char *)&size, sizeof(size))) {
151      WARN1("setsockopt failed, cannot set buffer size: %s",
152            sock_errstr(sock_errno));
153   }
154         
155   if (bind(sock->sd, (struct sockaddr *)&server, sizeof(server)) == -1) {
156     tcp_close(sock->sd);
157     THROW2(system_error,0,
158            "Cannot bind to port %d: %s",
159            sock->port, sock_errstr(sock_errno));
160   }
161
162   DEBUG2("Listen on port %d (sd=%d)",sock->port, sock->sd);
163   if (listen(sock->sd, 5) < 0) {
164     tcp_close(sock->sd);
165     THROW2(system_error,0,
166            "Cannot listen on port %d: %s",
167            sock->port,sock_errstr(sock_errno));
168   }
169
170   VERB2("Openned a server socket on port %d (sd=%d)",sock->port,sock->sd);
171 }
172
173 static gras_socket_t gras_trp_sock_socket_accept(gras_socket_t sock) {
174   gras_socket_t res;
175   
176   struct sockaddr_in peer_in;
177   socklen_t peer_in_len = sizeof(peer_in);
178
179   int sd;
180   int tmp_errno;
181   int size;
182
183   int i = 1;
184   socklen_t s = sizeof(int);
185
186   uint32_t hisport;
187                 
188   XBT_IN;
189   gras_trp_socket_new(1,&res);
190
191   sd = accept(sock->sd, (struct sockaddr *)&peer_in, &peer_in_len);
192   tmp_errno = sock_errno;
193
194   if (sd == -1) {
195     gras_socket_close(sock);
196     THROW1(system_error,0,
197            "Accept failed (%s). Droping server socket.", sock_errstr(tmp_errno));
198   }
199   
200   if (setsockopt(sd, SOL_SOCKET, SO_KEEPALIVE, (char *)&i, s) 
201       || setsockopt(sd, _gras_tcp_proto_number(), TCP_NODELAY, (char *)&i, s))
202     THROW1(system_error,0,"setsockopt failed, cannot condition the socket: %s",
203            sock_errstr(tmp_errno));
204
205   res->buf_size = sock->buf_size;
206   size = sock->buf_size;
207   if (setsockopt(sd, SOL_SOCKET, SO_RCVBUF, (char *)&size, sizeof(size))
208       || setsockopt(sd, SOL_SOCKET, SO_SNDBUF, (char *)&size, sizeof(size)))
209     WARN1("setsockopt failed, cannot set buffer size: %s", sock_errstr(tmp_errno));
210      
211   res->plugin    = sock->plugin;
212   res->incoming  = sock->incoming;
213   res->outgoing  = sock->outgoing;
214   res->accepting = 0;
215   res->sd        = sd;
216   res->port      = -1;
217
218   gras_trp_tcp_recv(res,(char*)&hisport,sizeof(hisport));
219   res->peer_port = ntohl(hisport);
220   DEBUG1("peerport %d received",res->peer_port);
221
222   /* FIXME: Lock to protect inet_ntoa */
223   if (((struct sockaddr *)&peer_in)->sa_family != AF_INET) {
224     res->peer_name = (char*)strdup("unknown");
225   } else {
226     struct in_addr addrAsInAddr;
227     char *tmp;
228     
229     addrAsInAddr.s_addr = peer_in.sin_addr.s_addr;
230     
231     tmp = inet_ntoa(addrAsInAddr);
232     if (tmp != NULL) {
233       res->peer_name = (char*)strdup(tmp);
234     } else {
235       res->peer_name = (char*)strdup("unknown");
236     }
237   }
238   
239   VERB3("Accepted from %s:%d (sd=%d)", res->peer_name,res->peer_port,sd);
240   xbt_dynar_push(((gras_trp_procdata_t)
241                   gras_libdata_by_id(gras_trp_libdata_id))->sockets,&res);
242    
243   XBT_OUT;
244   return res;
245 }
246
247 static void gras_trp_sock_socket_close(gras_socket_t sock){
248   
249   if (!sock) return; /* close only once */
250
251   VERB1("close tcp connection %d", sock->sd);
252
253   /* FIXME: no pipe in GRAS so far  
254   if(!FD_ISSET(sd, &connectedPipes)) {
255     if(shutdown(sd, 2) < 0) {
256       GetNWSLock(&lock);
257       tmp_errno = errno;
258       ReleaseNWSLock(&lock);
259       
260       / * The other side may have beaten us to the reset. * /
261       if ((tmp_errno!=ENOTCONN) && (tmp_errno!=ECONNRESET)) {
262         WARN1("CloseSocket: shutdown error %d\n", tmp_errno);
263       }
264     }
265   } */
266
267    
268   /* close the socket */
269   if(tcp_close(sock->sd) < 0) {
270     WARN3("error while closing tcp socket %d: %d (%s)\n", 
271              sock->sd, sock_errno, sock_errstr(sock_errno));
272   }
273
274 }
275 /************************************/
276 /****[ end of SOCKET MANAGEMENT ]****/
277 /************************************/
278
279
280 /************************************/
281 /****[ UNBUFFERED DATA EXCHANGE ]****/
282 /************************************/
283 /* Temptation to merge this with file data exchange is great, 
284    but doesn't work on BillWare (see tcp_write() in portable.h) */
285 static XBT_INLINE void gras_trp_tcp_send(gras_socket_t sock,
286                                      const char *data,
287                                      unsigned long int size) {
288   
289   while (size) {
290     int status = 0;
291     
292     status = tcp_write(sock->sd, data, (size_t)size);
293     DEBUG3("write(%d, %p, %ld);", sock->sd, data, size);
294     
295     if (status < 0) {
296 #ifdef EWOULDBLOCK
297        if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)
298 #else
299        if (errno == EINTR || errno == EAGAIN)
300 #endif
301          continue;
302        
303       THROW4(system_error,0,"write(%d,%p,%ld) failed: %s",
304              sock->sd, data, size,
305              sock_errstr(sock_errno));
306     }
307     
308     if (status) {
309       size  -= status;
310       data  += status;
311     } else {
312       THROW1(system_error,0,"file descriptor closed (%s)",
313              sock_errstr(sock_errno));
314     }
315   }
316 }
317 static XBT_INLINE int 
318 gras_trp_tcp_recv_withbuffer(gras_socket_t sock,
319                                    char *data,
320                                    unsigned long int size,
321                                    unsigned long int bufsize) {
322
323   int got = 0;
324
325   if (sock->recvd) {
326      data[0] = sock->recvd_val;
327      sock->recvd = 0;
328      got++;
329      bufsize--;
330   }   
331
332   while (size>got) {
333     int status = 0;
334     
335     DEBUG5("read(%d, %p, %ld) got %d so far (%s)",
336           sock->sd, data+got, bufsize, got,
337           hexa_str((unsigned char*)data,got,0));
338     status = tcp_read(sock->sd, data+got, (size_t)bufsize);
339     
340     if (status < 0) {
341       THROW7(system_error,0,"read(%d,%p,%d) from %s:%d failed: %s; got %d so far",
342              sock->sd, data+got, (int)size,
343              gras_socket_peer_name(sock),gras_socket_peer_port(sock),
344              sock_errstr(sock_errno),
345              got);
346     }
347     DEBUG2("Got %d more bytes (%s)",status,hexa_str((unsigned char*)data+got,status,0));
348     
349     if (status) {
350       bufsize -= status;
351       got     += status;
352     } else {
353       THROW1(system_error,errno,"Socket closed by remote side (got %d bytes before this)",
354              got);
355     }
356   }
357
358   return got;
359 }
360
361 static int gras_trp_tcp_recv(gras_socket_t sock,
362                                    char *data,
363                                    unsigned long int size) {
364   return gras_trp_tcp_recv_withbuffer(sock,data,size,size);
365
366 }
367 /*******************************************/
368 /****[ end of UNBUFFERED DATA EXCHANGE ]****/
369 /*******************************************/
370
371 /**********************************/
372 /****[ BUFFERED DATA EXCHANGE ]****/
373 /**********************************/
374
375 /* Make sure the data is sent */
376 static void
377 gras_trp_bufiov_flush(gras_socket_t sock) {
378 #ifdef HAVE_READV
379   xbt_dynar_t vect;
380   int size;
381 #endif
382   gras_trp_bufdata_t *data=sock->bufdata;
383   XBT_IN;    
384   
385   DEBUG0("Flush");
386   if (data->out == buffering_buf) {
387     if (XBT_LOG_ISENABLED(gras_trp_tcp,xbt_log_priority_debug))
388       hexa_print("chunk to send ",
389                  (unsigned char *) data->out_buf.data,data->out_buf.size);
390     if ((data->out_buf.size - data->out_buf.pos) != 0) { 
391       DEBUG3("Send the chunk (size=%d) to %s:%d",data->out_buf.size,
392              gras_socket_peer_name(sock),gras_socket_peer_port(sock));
393       gras_trp_tcp_send(sock, data->out_buf.data, data->out_buf.size);
394       VERB1("Chunk sent (size=%d)",data->out_buf.size);
395       data->out_buf.size = 0;
396     }
397   }
398
399 #ifdef HAVE_READV
400   if (data->out == buffering_iov) {
401     DEBUG0("Flush out iov");
402     vect = sock->bufdata->out_buf_v;
403     if ((size = xbt_dynar_length(vect))) {
404       DEBUG1("Flush %d chunks out of this socket",size);
405       writev(sock->sd,xbt_dynar_get_ptr(vect,0),size);
406       xbt_dynar_reset(vect);
407     }
408     data->out_buf.size = 0; /* reset the buffer containing non-stable data */
409   }
410
411   if (data->in == buffering_iov) {
412     DEBUG0("Flush in iov");
413     vect = sock->bufdata->in_buf_v;
414     if ((size = xbt_dynar_length(vect))) {
415       DEBUG1("Get %d chunks from of this socket",size);
416       readv(sock->sd,xbt_dynar_get_ptr(vect,0),size);
417       xbt_dynar_reset(vect);
418     }
419   }
420 #endif
421 }
422 static void
423 gras_trp_buf_send(gras_socket_t sock,
424                   const char *chunk,
425                   unsigned long int size,
426                   int stable_ignored) {
427
428   gras_trp_bufdata_t *data=(gras_trp_bufdata_t*)sock->bufdata;
429   int chunk_pos=0;
430
431   XBT_IN;
432
433   while (chunk_pos < size) {
434     /* size of the chunk to receive in that shot */
435     long int thissize = min(size-chunk_pos,data->buffsize-data->out_buf.size);
436     DEBUG4("Set the chars %d..%ld into the buffer; size=%ld, ctn=(%s)",
437            (int)data->out_buf.size,
438            ((int)data->out_buf.size) + thissize -1,
439            size,
440            hexa_str((unsigned char*)chunk,thissize,0));
441
442     memcpy(data->out_buf.data + data->out_buf.size, chunk + chunk_pos, thissize);
443
444     data->out_buf.size += thissize;
445     chunk_pos      += thissize;
446     DEBUG4("New pos = %d; Still to send = %ld of %ld; ctn sofar=(%s)",
447            data->out_buf.size,size-chunk_pos,size,hexa_str((unsigned char*)chunk,chunk_pos,0));
448
449     if (data->out_buf.size == data->buffsize) /* out of space. Flush it */
450       gras_trp_bufiov_flush(sock);
451   }
452
453   XBT_OUT;
454 }
455
456 static int
457 gras_trp_buf_recv(gras_socket_t sock,
458                   char *chunk,
459                   unsigned long int size) {
460
461   gras_trp_bufdata_t *data=sock->bufdata;
462   long int chunk_pos = 0;
463    
464   XBT_IN;
465
466   while (chunk_pos < size) {
467     /* size of the chunk to receive in that shot */
468     long int thissize;
469
470     if (data->in_buf.size == data->in_buf.pos) { /* out of data. Get more */
471
472       DEBUG2("Get more data (size=%d,bufsize=%d)",
473              (int)MIN(size-chunk_pos,data->buffsize),
474              (int)data->buffsize);
475
476        
477       data->in_buf.size = 
478         gras_trp_tcp_recv_withbuffer(sock, data->in_buf.data, 
479                                      MIN(size-chunk_pos,data->buffsize),
480                                      data->buffsize);
481        
482       data->in_buf.pos=0;
483     }
484      
485     thissize = min(size-chunk_pos ,  data->in_buf.size - data->in_buf.pos);
486     memcpy(chunk+chunk_pos, data->in_buf.data + data->in_buf.pos, thissize);
487
488     data->in_buf.pos += thissize;
489     chunk_pos        += thissize;
490     DEBUG4("New pos = %d; Still to receive = %ld of %ld. Ctn so far=(%s)",
491            data->in_buf.pos,size - chunk_pos,size,hexa_str((unsigned char*)chunk,chunk_pos,0));
492   }
493   /* indicate on need to the gras_select function that there is more to read on this socket so that it does not actually select */
494   sock->moredata = (data->in_buf.size > data->in_buf.pos);
495   DEBUG1("There is %smore data",(sock->moredata?"":"no "));
496    
497   XBT_OUT;
498   return chunk_pos;
499 }
500
501 /*****************************************/
502 /****[ end of BUFFERED DATA EXCHANGE ]****/
503 /*****************************************/
504
505 /********************************/
506 /****[ VECTOR DATA EXCHANGE ]****/
507 /********************************/
508 #ifdef HAVE_READV
509 static void
510 gras_trp_iov_send(gras_socket_t sock,
511                   const char *chunk,
512                   unsigned long int size,
513                   int stable) {
514   struct iovec elm;
515   gras_trp_bufdata_t *data=(gras_trp_bufdata_t*)sock->bufdata;
516     
517
518   DEBUG1("Buffer one chunk to be sent later (%s)",
519         hexa_str((char*)chunk,size,0));
520
521   elm.iov_len = (size_t)size;
522
523   if (!stable) {
524     /* data storage won't last until flush. Save it in a buffer if we can */
525
526     if (size > data->buffsize-data->out_buf.size) {
527       /* buffer too small: 
528          flush the socket, using data in its actual storage */
529       elm.iov_base = (void*)chunk;
530       xbt_dynar_push(data->out_buf_v,&elm);
531
532       gras_trp_bufiov_flush(sock);      
533       return;
534     } else {
535       /* buffer big enough: 
536          copy data into it, and chain it for upcoming writev */
537       memcpy(data->out_buf.data + data->out_buf.size, chunk, size);
538       elm.iov_base = (void*)(data->out_buf.data + data->out_buf.size);
539       data->out_buf.size += size;
540
541       xbt_dynar_push(data->out_buf_v,&elm);
542     }
543
544   } else {
545     /* data storage stable. Chain it */
546     
547     elm.iov_base = (void*)chunk;
548     xbt_dynar_push(data->out_buf_v,&elm);
549   }
550 }
551 static int
552 gras_trp_iov_recv(gras_socket_t sock,
553                   char *chunk,
554                   unsigned long int size) {
555   struct iovec elm;
556
557   DEBUG0("Buffer one chunk to be received later");
558   elm.iov_base = (void*)chunk;
559   elm.iov_len = (size_t)size;
560   xbt_dynar_push(sock->bufdata->in_buf_v,&elm);
561
562   return size;
563 }
564
565 #endif
566 /***************************************/
567 /****[ end of VECTOR DATA EXCHANGE ]****/
568 /***************************************/
569
570
571 /***
572  *** Prototypes of BUFFERED
573  ***/
574    
575 void gras_trp_buf_socket_client(gras_trp_plugin_t self,
576                                 gras_socket_t sock);
577 void gras_trp_buf_socket_server(gras_trp_plugin_t self,
578                                 gras_socket_t sock);
579 gras_socket_t gras_trp_buf_socket_accept(gras_socket_t sock);
580
581 void         gras_trp_buf_socket_close(gras_socket_t sd);
582   
583
584 gras_socket_t gras_trp_buf_init_sock(gras_socket_t sock) {
585   gras_trp_bufdata_t *data=xbt_new(gras_trp_bufdata_t,1);
586   
587   data->buffsize = 100 * 1024 ; /* 100k */ 
588
589   data->in_buf.size  = 0;
590   data->in_buf.data  = xbt_malloc(data->buffsize);
591   data->in_buf.pos   = 0; /* useless, indeed, since size==pos */
592    
593   data->out_buf.size = 0;
594   data->out_buf.data = xbt_malloc(data->buffsize);
595   data->out_buf.pos  = data->out_buf.size;
596
597 #ifdef HAVE_READV
598   data->in_buf_v = data->out_buf_v = NULL;
599   data->in_buf_v=xbt_dynar_new(sizeof(struct iovec),NULL);
600   data->out_buf_v=xbt_dynar_new(sizeof(struct iovec),NULL);
601   data->out = buffering_iov;
602 #else
603   data->out = buffering_buf;
604 #endif
605    
606   data->in = buffering_buf;
607
608   sock->bufdata = data;
609   return sock;
610 }
611
612 /***
613  *** Code
614  ***/
615 void
616 gras_trp_tcp_setup(gras_trp_plugin_t plug) {
617
618   plug->socket_client = gras_trp_buf_socket_client;
619   plug->socket_server = gras_trp_buf_socket_server;
620   plug->socket_accept = gras_trp_buf_socket_accept;
621   plug->socket_close  = gras_trp_buf_socket_close;
622
623 #ifdef HAVE_READV
624   plug->send = gras_trp_iov_send;
625 #else
626   plug->send = gras_trp_buf_send;
627 #endif
628   plug->recv = gras_trp_buf_recv;
629
630   plug->raw_send    = gras_trp_tcp_send;
631   plug->raw_recv    = gras_trp_tcp_recv;
632
633   plug->flush         = gras_trp_bufiov_flush;
634
635   plug->data = NULL;
636   plug->exit = NULL;
637 }
638
639 void gras_trp_buf_socket_client(gras_trp_plugin_t self,
640                                 /* OUT */ gras_socket_t sock){
641
642   gras_trp_sock_socket_client(NULL,sock);
643   gras_trp_buf_init_sock(sock);
644 }
645
646 /**
647  * gras_trp_buf_socket_server:
648  *
649  * Open a socket used to receive messages.
650  */
651 void gras_trp_buf_socket_server(gras_trp_plugin_t self,
652                                 /* OUT */ gras_socket_t sock){
653
654   gras_trp_sock_socket_server(NULL,sock);
655   gras_trp_buf_init_sock(sock);
656 }
657
658 gras_socket_t gras_trp_buf_socket_accept(gras_socket_t sock) {
659   return gras_trp_buf_init_sock(gras_trp_sock_socket_accept(sock));
660 }
661
662 void gras_trp_buf_socket_close(gras_socket_t sock){
663   gras_trp_bufdata_t *data=sock->bufdata;
664
665   if (data->in_buf.size!=data->in_buf.pos) {
666      WARN3("Socket closed, but %d bytes were unread (size=%d,pos=%d)",
667            data->in_buf.size - data->in_buf.pos,
668            data->in_buf.size, data->in_buf.pos);
669   }
670   if (data->in_buf.data)
671     free(data->in_buf.data);
672    
673   if (data->out_buf.size!=data->out_buf.pos) {
674     DEBUG2("Flush the socket before closing (in=%d,out=%d)",
675            data->in_buf.size, data->out_buf.size);
676     gras_trp_bufiov_flush(sock);
677   }   
678   if (data->out_buf.data)
679     free(data->out_buf.data);
680
681 #ifdef HAVE_READV
682   if (data->in_buf_v) {
683     if (xbt_dynar_length(data->in_buf_v)) 
684       WARN0("Socket closed, but some bytes were unread");
685     xbt_dynar_free(&data->in_buf_v);
686   }
687   if (data->out_buf_v) {
688     if (xbt_dynar_length(data->out_buf_v)) {
689       DEBUG0("Flush the socket before closing");
690       gras_trp_bufiov_flush(sock);
691     }
692     xbt_dynar_free(&data->out_buf_v);
693   }
694 #endif
695
696   free(data);
697   gras_trp_sock_socket_close(sock);
698 }
699
700 /****************************/
701 /****[ HELPER FUNCTIONS ]****/
702 /****************************/
703
704 /*
705  * Returns the tcp protocol number from the network protocol data base.
706  *
707  * getprotobyname() is not thread safe. We need to lock it.
708  */
709 static int _gras_tcp_proto_number(void) {
710   struct protoent *fetchedEntry;
711   static int returnValue = 0;
712   
713   if(returnValue == 0) {
714     fetchedEntry = getprotobyname("tcp");
715     xbt_assert0(fetchedEntry, "getprotobyname(tcp) gave NULL");
716     returnValue = fetchedEntry->p_proto;
717   }
718   
719   return returnValue;
720 }
721
722 #ifdef HAVE_WINSOCK_H
723 #define RETSTR( x ) case x: return #x
724
725 const char *gras_wsa_err2string( int err ) {
726    switch( err ) {
727       RETSTR( WSAEINTR );
728       RETSTR( WSAEBADF );
729       RETSTR( WSAEACCES );
730       RETSTR( WSAEFAULT );
731       RETSTR( WSAEINVAL );
732       RETSTR( WSAEMFILE );
733       RETSTR( WSAEWOULDBLOCK );
734       RETSTR( WSAEINPROGRESS );
735       RETSTR( WSAEALREADY );
736       RETSTR( WSAENOTSOCK );
737       RETSTR( WSAEDESTADDRREQ );
738       RETSTR( WSAEMSGSIZE );
739       RETSTR( WSAEPROTOTYPE );
740       RETSTR( WSAENOPROTOOPT );
741       RETSTR( WSAEPROTONOSUPPORT );
742       RETSTR( WSAESOCKTNOSUPPORT );
743       RETSTR( WSAEOPNOTSUPP );
744       RETSTR( WSAEPFNOSUPPORT );
745       RETSTR( WSAEAFNOSUPPORT );
746       RETSTR( WSAEADDRINUSE );
747       RETSTR( WSAEADDRNOTAVAIL );
748       RETSTR( WSAENETDOWN );
749       RETSTR( WSAENETUNREACH );
750       RETSTR( WSAENETRESET );
751       RETSTR( WSAECONNABORTED );
752       RETSTR( WSAECONNRESET );
753       RETSTR( WSAENOBUFS );
754       RETSTR( WSAEISCONN );
755       RETSTR( WSAENOTCONN );
756       RETSTR( WSAESHUTDOWN );
757       RETSTR( WSAETOOMANYREFS );
758       RETSTR( WSAETIMEDOUT );
759       RETSTR( WSAECONNREFUSED );
760       RETSTR( WSAELOOP );
761       RETSTR( WSAENAMETOOLONG );
762       RETSTR( WSAEHOSTDOWN );
763       RETSTR( WSAEHOSTUNREACH );
764       RETSTR( WSAENOTEMPTY );
765       RETSTR( WSAEPROCLIM );
766       RETSTR( WSAEUSERS );
767       RETSTR( WSAEDQUOT );
768       RETSTR( WSAESTALE );
769       RETSTR( WSAEREMOTE );
770       RETSTR( WSASYSNOTREADY );
771       RETSTR( WSAVERNOTSUPPORTED );
772       RETSTR( WSANOTINITIALISED );
773       RETSTR( WSAEDISCON );
774       
775 #ifdef HAVE_WINSOCK2
776       RETSTR( WSAENOMORE );
777       RETSTR( WSAECANCELLED );
778       RETSTR( WSAEINVALIDPROCTABLE );
779       RETSTR( WSAEINVALIDPROVIDER );
780       RETSTR( WSASYSCALLFAILURE );
781       RETSTR( WSASERVICE_NOT_FOUND );
782       RETSTR( WSATYPE_NOT_FOUND );
783       RETSTR( WSA_E_NO_MORE );
784       RETSTR( WSA_E_CANCELLED );
785       RETSTR( WSAEREFUSED );
786 #endif /* HAVE_WINSOCK2 */
787
788       RETSTR( WSAHOST_NOT_FOUND );
789       RETSTR( WSATRY_AGAIN );
790       RETSTR( WSANO_RECOVERY );
791       RETSTR( WSANO_DATA );
792    }
793    return "unknown WSA error";
794 }
795 #endif /* HAVE_WINSOCK_H */
796
797 /***********************************/
798 /****[ end of HELPER FUNCTIONS ]****/
799 /***********************************/