Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
180e2846624f73b5b2e6e21ba33b20ae7ef8665d
[simgrid.git] / src / gras / Transport / transport_plugin_tcp.c
1 /* $Id$ */
2
3 /* tcp trp (transport) - send/receive a bunch of bytes from a tcp socket    */
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 "portable.h"
11
12 #if 0
13 #  include <unistd.h>       /* close() pipe() read() write() */
14 #  include <signal.h>       /* close() pipe() read() write() */
15 #  include <netinet/in.h>   /* sometimes required for #include <arpa/inet.h> */
16 #  include <netinet/tcp.h>  /* TCP_NODELAY */
17 #  include <arpa/inet.h>    /* inet_ntoa() */
18 #  include <netdb.h>        /* getprotobyname() */
19 #  include <sys/time.h>     /* struct timeval */
20 #  include <errno.h>        /* errno */
21 #  include <sys/wait.h>     /* waitpid() */
22 #  include <sys/socket.h>   /* getpeername() socket() */
23 #  include <stdlib.h>
24 #  include <string.h>       /* memset */
25 #endif
26
27
28 #include "transport_private.h"
29
30 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(trp_tcp,transport,"TCP transport");
31
32 /***
33  *** Prototypes 
34  ***/
35 xbt_error_t gras_trp_tcp_socket_client(gras_trp_plugin_t *self,
36                                         gras_socket_t sock);
37 xbt_error_t gras_trp_tcp_socket_server(gras_trp_plugin_t *self,
38                                         gras_socket_t sock);
39 xbt_error_t gras_trp_tcp_socket_accept(gras_socket_t  sock,
40                                         gras_socket_t *dst);
41
42 void         gras_trp_tcp_socket_close(gras_socket_t sd);
43   
44 xbt_error_t gras_trp_tcp_chunk_send(gras_socket_t sd,
45                                      const char *data,
46                                      long int size);
47
48 xbt_error_t gras_trp_tcp_chunk_recv(gras_socket_t sd,
49                                      char *data,
50                                      long int size);
51
52 void gras_trp_tcp_exit(gras_trp_plugin_t *plug);
53
54
55 static int TcpProtoNumber(void);
56 /***
57  *** Specific plugin part
58  ***/
59
60 typedef struct {
61   fd_set msg_socks;
62   fd_set raw_socks;
63 } gras_trp_tcp_plug_data_t;
64
65 /***
66  *** Specific socket part
67  ***/
68
69 typedef struct {
70   int buffsize;
71 } gras_trp_tcp_sock_data_t;
72
73
74 /***
75  *** Code
76  ***/
77 xbt_error_t gras_trp_tcp_setup(gras_trp_plugin_t *plug) {
78
79   gras_trp_tcp_plug_data_t *data = xbt_new(gras_trp_tcp_plug_data_t,1);
80
81   FD_ZERO(&(data->msg_socks));
82   FD_ZERO(&(data->raw_socks));
83
84   plug->socket_client = gras_trp_tcp_socket_client;
85   plug->socket_server = gras_trp_tcp_socket_server;
86   plug->socket_accept = gras_trp_tcp_socket_accept;
87   plug->socket_close  = gras_trp_tcp_socket_close;
88
89   plug->chunk_send    = gras_trp_tcp_chunk_send;
90   plug->chunk_recv    = gras_trp_tcp_chunk_recv;
91
92   plug->flush = NULL; /* nothing's cached */
93
94   plug->data = (void*)data;
95   plug->exit = gras_trp_tcp_exit;
96    
97   return no_error;
98 }
99
100 void gras_trp_tcp_exit(gras_trp_plugin_t *plug) {
101   DEBUG1("Exit plugin TCP (free %p)", plug->data);
102   xbt_free(plug->data);
103 }
104
105 xbt_error_t gras_trp_tcp_socket_client(gras_trp_plugin_t *self,
106                                         gras_socket_t sock){
107   
108   struct sockaddr_in addr;
109   struct hostent *he;
110   struct in_addr *haddr;
111   int size = sock->bufSize * 1024; 
112
113   sock->incoming = 1; /* TCP sockets are duplex'ed */
114
115   sock->sd = socket (AF_INET, SOCK_STREAM, 0);
116   
117   if (sock->sd < 0) {
118     RAISE1(system_error,
119            "Failed to create socket: %s",
120            sock_errstr);
121   }
122
123   if (setsockopt(sock->sd, SOL_SOCKET, SO_RCVBUF, (char *)&size, sizeof(size)) ||
124       setsockopt(sock->sd, SOL_SOCKET, SO_SNDBUF, (char *)&size, sizeof(size))) {
125      WARN1("setsockopt failed, cannot set buffer size: %s",sock_errstr);
126   }
127   
128   he = gethostbyname (sock->peer_name);
129   if (he == NULL) {
130     RAISE2(system_error,
131            "Failed to lookup hostname %s: %s",
132            sock->peer_name, sock_errstr);
133   }
134   
135   haddr = ((struct in_addr *) (he->h_addr_list)[0]);
136   
137   memset(&addr, 0, sizeof(struct sockaddr_in));
138   memcpy (&addr.sin_addr, haddr, sizeof(struct in_addr));
139   addr.sin_family = AF_INET;
140   addr.sin_port = htons (sock->peer_port);
141
142   if (connect (sock->sd, (struct sockaddr*) &addr, sizeof (addr)) < 0) {
143     tcp_close(sock->sd);
144     RAISE3(system_error,
145            "Failed to connect socket to %s:%d (%s)",
146            sock->peer_name, sock->peer_port, sock_errstr);
147   }
148   
149   return no_error;
150 }
151
152 /**
153  * gras_trp_tcp_socket_server:
154  *
155  * Open a socket used to receive messages.
156  */
157 xbt_error_t gras_trp_tcp_socket_server(gras_trp_plugin_t *self,
158                                         /* OUT */ gras_socket_t sock){
159   int size = sock->bufSize * 1024; 
160   int on = 1;
161   struct sockaddr_in server;
162
163   gras_trp_tcp_plug_data_t *tcp=(gras_trp_tcp_plug_data_t*)self->data;
164  
165   sock->outgoing  = 1; /* TCP => duplex mode */
166
167   server.sin_port = htons((u_short)sock->port);
168   server.sin_addr.s_addr = INADDR_ANY;
169   server.sin_family = AF_INET;
170   if((sock->sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
171     RAISE1(system_error,"Socket allocation failed: %s", sock_errstr);
172   }
173
174   if (setsockopt(sock->sd, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on))) {
175      RAISE1(system_error,"setsockopt failed, cannot condition the socket: %s",
176             sock_errstr);
177   }
178    
179   if (setsockopt(sock->sd, SOL_SOCKET, SO_RCVBUF, (char *)&size, sizeof(size)) ||
180       setsockopt(sock->sd, SOL_SOCKET, SO_SNDBUF, (char *)&size, sizeof(size))) {
181      WARN1("setsockopt failed, cannot set buffer size: %s",
182            sock_errstr);
183   }
184         
185   if (bind(sock->sd, (struct sockaddr *)&server, sizeof(server)) == -1) {
186     tcp_close(sock->sd);
187     RAISE2(system_error,"Cannot bind to port %d: %s",sock->port, sock_errstr);
188   }
189
190   if (listen(sock->sd, 5) < 0) {
191     tcp_close(sock->sd);
192     RAISE2(system_error,"Cannot listen to port %d: %s",sock->port,sock_errstr);
193   }
194
195   if (sock->raw)
196     FD_SET(sock->sd, &(tcp->raw_socks));
197   else
198     FD_SET(sock->sd, &(tcp->msg_socks));
199
200   DEBUG2("Openned a server socket on port %d (sock %d)",sock->port,sock->sd);
201   
202   return no_error;
203 }
204
205 xbt_error_t
206 gras_trp_tcp_socket_accept(gras_socket_t  sock,
207                            gras_socket_t *dst) {
208   gras_socket_t res;
209   
210   struct sockaddr_in peer_in;
211   socklen_t peer_in_len = sizeof(peer_in);
212
213   int sd;
214   int tmp_errno;
215   int size;
216                 
217   XBT_IN;
218   gras_trp_socket_new(1,&res);
219
220   sd = accept(sock->sd, (struct sockaddr *)&peer_in, &peer_in_len);
221   tmp_errno = errno;
222
223   if(sd == -1) {
224     gras_socket_close(sock);
225     RAISE1(system_error,
226            "Accept failed (%s). Droping server socket.", sock_errstr);
227   } else {
228     int i = 1;
229     socklen_t s = sizeof(int);
230   
231     if (setsockopt(sd, SOL_SOCKET, SO_KEEPALIVE, (char *)&i, s) 
232         || setsockopt(sd, TcpProtoNumber(), TCP_NODELAY, (char *)&i, s)) {
233        RAISE1(system_error,"setsockopt failed, cannot condition the socket: %s",
234               sock_errstr);
235     }
236
237     res->bufSize = sock->bufSize;
238     size = sock->bufSize * 1024;
239     if (setsockopt(sd, SOL_SOCKET, SO_RCVBUF, (char *)&size, sizeof(size))
240        || setsockopt(sd, SOL_SOCKET, SO_SNDBUF, (char *)&size, sizeof(size))) {
241        WARN1("setsockopt failed, cannot set buffer size: %s",
242              sock_errstr);
243     }
244      
245     res->plugin    = sock->plugin;
246     res->incoming  = sock->incoming;
247     res->outgoing  = sock->outgoing;
248     res->accepting = 0;
249     res->sd        = sd;
250     res->port      = -1;
251     res->peer_port = peer_in.sin_port;
252
253     /* FIXME: Lock to protect inet_ntoa */
254     if (((struct sockaddr *)&peer_in)->sa_family != AF_INET) {
255       res->peer_name = (char*)strdup("unknown");
256     } else {
257       struct in_addr addrAsInAddr;
258       char *tmp;
259  
260       addrAsInAddr.s_addr = peer_in.sin_addr.s_addr;
261       
262       tmp = inet_ntoa(addrAsInAddr);
263       if (tmp != NULL) {
264         res->peer_name = (char*)strdup(tmp);
265       } else {
266         res->peer_name = (char*)strdup("unknown");
267       }
268     }
269
270     VERB3("accepted socket %d to %s:%d", sd, res->peer_name,res->peer_port);
271     
272     *dst = res;
273
274     XBT_OUT;
275     return no_error;
276   }
277 }
278
279 void gras_trp_tcp_socket_close(gras_socket_t sock){
280   gras_trp_tcp_plug_data_t *tcp;
281   
282   if (!sock) return; /* close only once */
283   tcp=sock->plugin->data;
284
285   DEBUG1("close tcp connection %d", sock->sd);
286
287   /* FIXME: no pipe in GRAS so far  
288   if(!FD_ISSET(sd, &connectedPipes)) {
289     if(shutdown(sd, 2) < 0) {
290       GetNWSLock(&lock);
291       tmp_errno = errno;
292       ReleaseNWSLock(&lock);
293       
294       / * The other side may have beaten us to the reset. * /
295       if ((tmp_errno!=ENOTCONN) && (tmp_errno!=ECONNRESET)) {
296         WARN1("CloseSocket: shutdown error %d\n", tmp_errno);
297       }
298     }
299   } */
300
301 #ifndef HAVE_WINSOCK_H
302   /* forget about the socket 
303      ... but not when using winsock since accept'ed socket can not fit 
304      into the fd_set*/
305   if (sock->raw){
306     FD_CLR(sock->sd, &(tcp->raw_socks));
307   } else {
308     FD_CLR(sock->sd, &(tcp->msg_socks));
309   }
310 #endif
311    
312   /* close the socket */
313   if(tcp_close(sock->sd) < 0) {
314     WARN3("error while closing tcp socket %d: %d (%s)\n", 
315              sock->sd, sock_errno, sock_errstr);
316   }
317
318 }
319
320 /**
321  * gras_trp_tcp_chunk_send:
322  *
323  * Send data on a TCP socket
324  */
325 xbt_error_t 
326 gras_trp_tcp_chunk_send(gras_socket_t sock,
327                         const char *data,
328                         long int size) {
329   
330   /* TCP sockets are in duplex mode, don't check direction */
331   xbt_assert0(size >= 0, "Cannot send a negative amount of data");
332
333   while (size) {
334     int status = 0;
335     
336     status = tcp_write(sock->sd, data, (size_t)size);
337     DEBUG3("write(%d, %p, %ld);", sock->sd, data, size);
338     
339     if (status <= 0) {
340       RAISE4(system_error,"write(%d,%p,%ld) failed: %s",
341              sock->sd, data, size,
342              sock_errstr);
343     }
344     
345     if (status) {
346       size  -= status;
347       data  += status;
348     } else {
349       RAISE0(system_error,"file descriptor closed");
350     }
351   }
352
353   return no_error;
354 }
355 /**
356  * gras_trp_tcp_chunk_recv:
357  *
358  * Receive data on a TCP socket.
359  */
360 xbt_error_t 
361 gras_trp_tcp_chunk_recv(gras_socket_t sock,
362                         char *data,
363                         long int size) {
364
365   /* TCP sockets are in duplex mode, don't check direction */
366   xbt_assert0(sock, "Cannot recv on an NULL socket");
367   xbt_assert0(size >= 0, "Cannot receive a negative amount of data");
368   
369   while (size) {
370     int status = 0;
371     
372     status = tcp_read(sock->sd, data, (size_t)size);
373     DEBUG3("read(%d, %p, %ld);", sock->sd, data, size);
374     
375     if (status <= 0) {
376       RAISE4(system_error,"read(%d,%p,%d) failed: %s",
377              sock->sd, data, (int)size,
378              sock_errstr);
379     }
380     
381     if (status) {
382       size  -= status;
383       data  += status;
384     } else {
385       RAISE0(system_error,"file descriptor closed");
386     }
387   }
388   
389   return no_error;
390 }
391
392
393 /*
394  * Returns the tcp protocol number from the network protocol data base.
395  *
396  * getprotobyname() is not thread safe. We need to lock it.
397  */
398 static int TcpProtoNumber(void) {
399   struct protoent *fetchedEntry;
400   static int returnValue = 0;
401   
402   if(returnValue == 0) {
403     fetchedEntry = getprotobyname("tcp");
404     xbt_assert0(fetchedEntry, "getprotobyname(tcp) gave NULL");
405     returnValue = fetchedEntry->p_proto;
406   }
407   
408   return returnValue;
409 }
410
411 /* Data exchange over raw sockets. Placing this in there is a kind of crude hack.
412    It means that the only possible raw are TCP where we may want to do UDP for them. 
413    But I fail to find a good internal organization for now. We may want to split 
414    raw and regular sockets more efficiently.
415 */
416 xbt_error_t gras_socket_raw_exchange(gras_socket_t peer,
417                                       int sender,
418                                       unsigned int timeout,
419                                       unsigned long int exp_size,
420                                       unsigned long int msg_size) {
421    char *chunk;
422    int res_last, msg_sofar, exp_sofar;
423    
424    fd_set rd_set;
425 /*    int rv; */
426    
427    struct timeval timeOut;
428    
429    chunk = xbt_malloc(msg_size);
430
431    for   (exp_sofar=0; exp_sofar < exp_size; exp_sofar += msg_size) {
432       for(msg_sofar=0; msg_sofar < msg_size; msg_sofar += res_last) {
433          
434          if(sender) {
435             res_last = send(peer->sd, chunk, msg_size - msg_sofar, 0);
436          } else {
437             res_last = 0;
438             FD_ZERO(&rd_set);
439             FD_SET(peer->sd,&rd_set);
440             timeOut.tv_sec = timeout;
441             timeOut.tv_usec = 0;
442                 
443             if (0 < select(peer->sd+1,&rd_set,NULL,NULL,&timeOut))
444               res_last = recv(peer->sd, chunk, msg_size-msg_sofar, 0);
445             
446          }
447          if (res_last == 0) {
448            /* No progress done, bail out */
449            xbt_free(chunk);
450            RAISE0(unknown_error,"Not exchanged a single byte, bailing out");
451          }
452       }
453    }
454    
455    xbt_free(chunk);
456    return no_error;
457 }
458
459
460 #ifdef HAVE_WINSOCK_H
461 #define RETSTR( x ) case x: return #x
462
463 const char *gras_wsa_err2string( int err ) {
464    switch( err ) {
465       RETSTR( WSAEINTR );
466       RETSTR( WSAEBADF );
467       RETSTR( WSAEACCES );
468       RETSTR( WSAEFAULT );
469       RETSTR( WSAEINVAL );
470       RETSTR( WSAEMFILE );
471       RETSTR( WSAEWOULDBLOCK );
472       RETSTR( WSAEINPROGRESS );
473       RETSTR( WSAEALREADY );
474       RETSTR( WSAENOTSOCK );
475       RETSTR( WSAEDESTADDRREQ );
476       RETSTR( WSAEMSGSIZE );
477       RETSTR( WSAEPROTOTYPE );
478       RETSTR( WSAENOPROTOOPT );
479       RETSTR( WSAEPROTONOSUPPORT );
480       RETSTR( WSAESOCKTNOSUPPORT );
481       RETSTR( WSAEOPNOTSUPP );
482       RETSTR( WSAEPFNOSUPPORT );
483       RETSTR( WSAEAFNOSUPPORT );
484       RETSTR( WSAEADDRINUSE );
485       RETSTR( WSAEADDRNOTAVAIL );
486       RETSTR( WSAENETDOWN );
487       RETSTR( WSAENETUNREACH );
488       RETSTR( WSAENETRESET );
489       RETSTR( WSAECONNABORTED );
490       RETSTR( WSAECONNRESET );
491       RETSTR( WSAENOBUFS );
492       RETSTR( WSAEISCONN );
493       RETSTR( WSAENOTCONN );
494       RETSTR( WSAESHUTDOWN );
495       RETSTR( WSAETOOMANYREFS );
496       RETSTR( WSAETIMEDOUT );
497       RETSTR( WSAECONNREFUSED );
498       RETSTR( WSAELOOP );
499       RETSTR( WSAENAMETOOLONG );
500       RETSTR( WSAEHOSTDOWN );
501       RETSTR( WSAEHOSTUNREACH );
502       RETSTR( WSAENOTEMPTY );
503       RETSTR( WSAEPROCLIM );
504       RETSTR( WSAEUSERS );
505       RETSTR( WSAEDQUOT );
506       RETSTR( WSAESTALE );
507       RETSTR( WSAEREMOTE );
508       RETSTR( WSASYSNOTREADY );
509       RETSTR( WSAVERNOTSUPPORTED );
510       RETSTR( WSANOTINITIALISED );
511       RETSTR( WSAEDISCON );
512       
513 #ifdef HAVE_WINSOCK2
514       RETSTR( WSAENOMORE );
515       RETSTR( WSAECANCELLED );
516       RETSTR( WSAEINVALIDPROCTABLE );
517       RETSTR( WSAEINVALIDPROVIDER );
518       RETSTR( WSASYSCALLFAILURE );
519       RETSTR( WSASERVICE_NOT_FOUND );
520       RETSTR( WSATYPE_NOT_FOUND );
521       RETSTR( WSA_E_NO_MORE );
522       RETSTR( WSA_E_CANCELLED );
523       RETSTR( WSAEREFUSED );
524 #endif /* HAVE_WINSOCK2 */
525
526       RETSTR( WSAHOST_NOT_FOUND );
527       RETSTR( WSATRY_AGAIN );
528       RETSTR( WSANO_RECOVERY );
529       RETSTR( WSANO_DATA );
530    }
531    return "unknown WSA error";
532 }
533 #endif /* HAVE_WINSOCK_H */