Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
c5cb39730590b0851e9f07489a0919c5030bcd9f
[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 /* Authors: Martin Quinson                                                  */
6 /* Copyright (C) 2004 Martin Quinson.                                       */
7
8 /* This program is free software; you can redistribute it and/or modify it
9    under the terms of the license (GNU LGPL) which comes with this package. */
10
11 #include <unistd.h>       /* close() pipe() read() write() */
12 #include <signal.h>       /* close() pipe() read() write() */
13 #include <netinet/in.h>   /* sometimes required for #include <arpa/inet.h> */
14 #include <netinet/tcp.h>  /* TCP_NODELAY */
15 #include <arpa/inet.h>    /* inet_ntoa() */
16 #include <netdb.h>        /* getprotobyname() */
17 #include <sys/time.h>     /* struct timeval */
18 #include <errno.h>        /* errno */
19 #include <sys/wait.h>     /* waitpid() */
20 #include <sys/socket.h>   /* getpeername() socket() */
21 #include <stdlib.h>
22 #include <string.h>       /* memset */
23
24 #include "transport_private.h"
25
26 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(trp_tcp,transport,"TCP transport");
27
28 /***
29  *** Prototypes 
30  ***/
31 xbt_error_t gras_trp_tcp_socket_client(gras_trp_plugin_t *self,
32                                         gras_socket_t sock);
33 xbt_error_t gras_trp_tcp_socket_server(gras_trp_plugin_t *self,
34                                         gras_socket_t sock);
35 xbt_error_t gras_trp_tcp_socket_accept(gras_socket_t  sock,
36                                         gras_socket_t *dst);
37
38 void         gras_trp_tcp_socket_close(gras_socket_t sd);
39   
40 xbt_error_t gras_trp_tcp_chunk_send(gras_socket_t sd,
41                                      const char *data,
42                                      long int size);
43
44 xbt_error_t gras_trp_tcp_chunk_recv(gras_socket_t sd,
45                                      char *data,
46                                      long int size);
47
48 void gras_trp_tcp_exit(gras_trp_plugin_t *plug);
49
50
51 static int TcpProtoNumber(void);
52 /***
53  *** Specific plugin part
54  ***/
55
56 typedef struct {
57   fd_set msg_socks;
58   fd_set raw_socks;
59 } gras_trp_tcp_plug_data_t;
60
61 /***
62  *** Specific socket part
63  ***/
64
65 typedef struct {
66   int buffsize;
67 } gras_trp_tcp_sock_data_t;
68
69
70 /***
71  *** Code
72  ***/
73 xbt_error_t gras_trp_tcp_setup(gras_trp_plugin_t *plug) {
74
75   gras_trp_tcp_plug_data_t *data = xbt_new(gras_trp_tcp_plug_data_t,1);
76
77   FD_ZERO(&(data->msg_socks));
78   FD_ZERO(&(data->raw_socks));
79
80   plug->socket_client = gras_trp_tcp_socket_client;
81   plug->socket_server = gras_trp_tcp_socket_server;
82   plug->socket_accept = gras_trp_tcp_socket_accept;
83   plug->socket_close  = gras_trp_tcp_socket_close;
84
85   plug->chunk_send    = gras_trp_tcp_chunk_send;
86   plug->chunk_recv    = gras_trp_tcp_chunk_recv;
87
88   plug->flush = NULL; /* nothing's cached */
89
90   plug->data = (void*)data;
91   plug->exit = gras_trp_tcp_exit;
92
93   return no_error;
94 }
95
96 void gras_trp_tcp_exit(gras_trp_plugin_t *plug) {
97   DEBUG1("Exit plugin TCP (free %p)", plug->data);
98   xbt_free(plug->data);
99 }
100
101 xbt_error_t gras_trp_tcp_socket_client(gras_trp_plugin_t *self,
102                                         gras_socket_t sock){
103   
104   struct sockaddr_in addr;
105   struct hostent *he;
106   struct in_addr *haddr;
107   int size = sock->bufSize * 1024; 
108
109   sock->incoming = 1; /* TCP sockets are duplex'ed */
110
111   sock->sd = socket (AF_INET, SOCK_STREAM, 0);
112   
113   if (sock->sd < 0) {
114     RAISE1(system_error,
115            "Failed to create socket: %s",
116            strerror (errno));
117   }
118
119   if (setsockopt(sock->sd, SOL_SOCKET, SO_RCVBUF, (char *)&size, sizeof(size)) ||
120       setsockopt(sock->sd, SOL_SOCKET, SO_SNDBUF, (char *)&size, sizeof(size))) {
121      WARN1("setsockopt failed, cannot set buffer size: %s",
122            strerror(errno));
123   }
124   
125   he = gethostbyname (sock->peer_name);
126   if (he == NULL) {
127     RAISE2(system_error,
128            "Failed to lookup hostname %s: %s",
129            sock->peer_name, strerror (errno));
130   }
131   
132   haddr = ((struct in_addr *) (he->h_addr_list)[0]);
133   
134   memset(&addr, 0, sizeof(struct sockaddr_in));
135   memcpy (&addr.sin_addr, haddr, sizeof(struct in_addr));
136   addr.sin_family = AF_INET;
137   addr.sin_port = htons (sock->peer_port);
138
139   if (connect (sock->sd, (struct sockaddr*) &addr, sizeof (addr)) < 0) {
140     close(sock->sd);
141     RAISE3(system_error,
142            "Failed to connect socket to %s:%d (%s)",
143            sock->peer_name, sock->peer_port, strerror (errno));
144   }
145   
146   return no_error;
147 }
148
149 /**
150  * gras_trp_tcp_socket_server:
151  *
152  * Open a socket used to receive messages.
153  */
154 xbt_error_t gras_trp_tcp_socket_server(gras_trp_plugin_t *self,
155                                         /* OUT */ gras_socket_t sock){
156   int size = sock->bufSize * 1024; 
157   int on = 1;
158   struct sockaddr_in server;
159
160   gras_trp_tcp_plug_data_t *tcp=(gras_trp_tcp_plug_data_t*)self->data;
161  
162   sock->outgoing  = 1; /* TCP => duplex mode */
163
164   server.sin_port = htons((u_short)sock->port);
165   server.sin_addr.s_addr = INADDR_ANY;
166   server.sin_family = AF_INET;
167   if((sock->sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
168     RAISE1(system_error,"Socket allocation failed: %s", strerror(errno));
169   }
170
171   if (setsockopt(sock->sd, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on))) {
172      RAISE1(system_error,"setsockopt failed, cannot condition the socket: %s",
173             strerror(errno));
174   }
175    
176   if (setsockopt(sock->sd, SOL_SOCKET, SO_RCVBUF, (char *)&size, sizeof(size)) ||
177       setsockopt(sock->sd, SOL_SOCKET, SO_SNDBUF, (char *)&size, sizeof(size))) {
178      WARN1("setsockopt failed, cannot set buffer size: %s",
179            strerror(errno));
180   }
181         
182   if (bind(sock->sd, (struct sockaddr *)&server, sizeof(server)) == -1) {
183     close(sock->sd);
184     RAISE2(system_error,"Cannot bind to port %d: %s",sock->port, strerror(errno));
185   }
186
187   if (listen(sock->sd, 5) < 0) {
188     close(sock->sd);
189     RAISE2(system_error,"Cannot listen to port %d: %s",sock->port,strerror(errno));
190   }
191
192   if (sock->raw)
193     FD_SET(sock->sd, &(tcp->raw_socks));
194   else
195     FD_SET(sock->sd, &(tcp->msg_socks));
196
197   DEBUG2("Openned a server socket on port %d (sock %d)",sock->port,sock->sd);
198   
199   return no_error;
200 }
201
202 xbt_error_t
203 gras_trp_tcp_socket_accept(gras_socket_t  sock,
204                            gras_socket_t *dst) {
205   gras_socket_t res;
206   xbt_error_t errcode;
207   
208   struct sockaddr_in peer_in;
209   socklen_t peer_in_len = sizeof(peer_in);
210
211   int sd;
212   int tmp_errno;
213   int size;
214                         
215   gras_trp_socket_new(1,&res);
216
217   sd = accept(sock->sd, (struct sockaddr *)&peer_in, &peer_in_len);
218   tmp_errno = errno;
219
220   if(sd == -1) {
221     gras_socket_close(sock);
222     RAISE1(system_error,
223            "Accept failed (%s). Droping server socket.", strerror(tmp_errno));
224   } else {
225     int i = 1;
226     socklen_t s = sizeof(int);
227   
228     if (setsockopt(sd, SOL_SOCKET, SO_KEEPALIVE, (char *)&i, s) 
229         || setsockopt(sd, TcpProtoNumber(), TCP_NODELAY, (char *)&i, s)) {
230        RAISE1(system_error,"setsockopt failed, cannot condition the socket: %s",
231               strerror(errno));
232     }
233  
234     (*dst)->bufSize = sock->bufSize;
235     size = sock->bufSize * 1024;
236     if (setsockopt(sd, SOL_SOCKET, SO_RCVBUF, (char *)&size, sizeof(size))
237        || setsockopt(sd, SOL_SOCKET, SO_SNDBUF, (char *)&size, sizeof(size))) {
238        WARN1("setsockopt failed, cannot set buffer size: %s",
239              strerror(errno));
240     }
241      
242     res->plugin    = sock->plugin;
243     res->incoming  = sock->incoming;
244     res->outgoing  = sock->outgoing;
245     res->accepting = 0;
246     res->sd        = sd;
247     res->port      = -1;
248     res->peer_port = peer_in.sin_port;
249
250     /* FIXME: Lock to protect inet_ntoa */
251     if (((struct sockaddr *)&peer_in)->sa_family != AF_INET) {
252       res->peer_name = (char*)strdup("unknown");
253     } else {
254       struct in_addr addrAsInAddr;
255       char *tmp;
256  
257       addrAsInAddr.s_addr = peer_in.sin_addr.s_addr;
258       
259       tmp = inet_ntoa(addrAsInAddr);
260       if (tmp != NULL) {
261         res->peer_name = (char*)strdup(tmp);
262       } else {
263         res->peer_name = (char*)strdup("unknown");
264       }
265     }
266
267     VERB3("accepted socket %d to %s:%d", sd, res->peer_name,res->peer_port);
268     
269     *dst = res;
270
271     return no_error;
272   }
273 }
274
275 void gras_trp_tcp_socket_close(gras_socket_t sock){
276   gras_trp_tcp_plug_data_t *tcp;
277   
278   if (!sock) return; /* close only once */
279   tcp=sock->plugin->data;
280
281   DEBUG1("close tcp connection %d", sock->sd);
282
283   /* FIXME: no pipe in GRAS so far  
284   if(!FD_ISSET(sd, &connectedPipes)) {
285     if(shutdown(sd, 2) < 0) {
286       GetNWSLock(&lock);
287       tmp_errno = errno;
288       ReleaseNWSLock(&lock);
289       
290       / * The other side may have beaten us to the reset. * /
291       if ((tmp_errno!=ENOTCONN) && (tmp_errno!=ECONNRESET)) {
292         WARN1("CloseSocket: shutdown error %d\n", tmp_errno);
293       }
294     }
295   } */
296
297   /* forget about the socket */
298   if (sock->raw)
299     FD_CLR(sock->sd, &(tcp->raw_socks));
300   else
301     FD_CLR(sock->sd, &(tcp->msg_socks));
302
303   /* close the socket */
304   if(close(sock->sd) < 0) {
305     WARN3("error while closing tcp socket %d: %d (%s)\n", 
306              sock->sd, errno, strerror(errno));
307   }
308 }
309
310 /**
311  * gras_trp_tcp_chunk_send:
312  *
313  * Send data on a TCP socket
314  */
315 xbt_error_t 
316 gras_trp_tcp_chunk_send(gras_socket_t sock,
317                         const char *data,
318                         long int size) {
319   
320   /* TCP sockets are in duplex mode, don't check direction */
321   xbt_assert0(size >= 0, "Cannot send a negative amount of data");
322
323   while (size) {
324     int status = 0;
325     
326     status = write(sock->sd, data, (size_t)size);
327     DEBUG3("write(%d, %p, %ld);", sock->sd, data, size);
328     
329     if (status == -1) {
330       RAISE4(system_error,"write(%d,%p,%ld) failed: %s",
331              sock->sd, data, size,
332              strerror(errno));
333     }
334     
335     if (status) {
336       size  -= status;
337       data  += status;
338     } else {
339       RAISE0(system_error,"file descriptor closed");
340     }
341   }
342
343   return no_error;
344 }
345 /**
346  * gras_trp_tcp_chunk_recv:
347  *
348  * Receive data on a TCP socket.
349  */
350 xbt_error_t 
351 gras_trp_tcp_chunk_recv(gras_socket_t sock,
352                         char *data,
353                         long int size) {
354
355   /* TCP sockets are in duplex mode, don't check direction */
356   xbt_assert0(sock, "Cannot recv on an NULL socket");
357   xbt_assert0(size >= 0, "Cannot receive a negative amount of data");
358   
359   while (size) {
360     int status = 0;
361     
362     status = read(sock->sd, data, (size_t)size);
363     DEBUG3("read(%d, %p, %ld);", sock->sd, data, size);
364     
365     if (status == -1) {
366       RAISE4(system_error,"read(%d,%p,%d) failed: %s",
367              sock->sd, data, (int)size,
368              strerror(errno));
369     }
370     
371     if (status) {
372       size  -= status;
373       data  += status;
374     } else {
375       RAISE0(system_error,"file descriptor closed");
376     }
377   }
378   
379   return no_error;
380 }
381
382
383 /*
384  * Returns the tcp protocol number from the network protocol data base.
385  *
386  * getprotobyname() is not thread safe. We need to lock it.
387  */
388 static int TcpProtoNumber(void) {
389   struct protoent *fetchedEntry;
390   static int returnValue = 0;
391   
392   if(returnValue == 0) {
393     fetchedEntry = getprotobyname("tcp");
394     xbt_assert0(fetchedEntry, "getprotobyname(tcp) gave NULL");
395     returnValue = fetchedEntry->p_proto;
396   }
397   
398   return returnValue;
399 }
400
401 /* Data exchange over raw sockets. Placing this in there is a kind of crude hack.
402    It means that the only possible raw are TCP where we may want to do UDP for them. 
403    But I fail to find a good internal organization for now. We may want to split 
404    raw and regular sockets more efficiently.
405 */
406 xbt_error_t gras_socket_raw_exchange(gras_socket_t peer,
407                                       int sender,
408                                       unsigned int timeout,
409                                       unsigned long int exp_size,
410                                       unsigned long int msg_size) {
411    char *chunk;
412    int res_last, msg_sofar, exp_sofar;
413    
414    fd_set rd_set;
415    int rv;
416    
417    struct timeval timeOut;
418    
419    chunk = xbt_malloc(msg_size);
420
421    for   (exp_sofar=0; exp_sofar < exp_size; exp_sofar += msg_size) {
422       for(msg_sofar=0; msg_sofar < msg_size; msg_sofar += res_last) {
423          
424          if(sender) {
425             res_last = send(peer->sd, chunk, msg_size - msg_sofar, 0);
426          } else {
427             res_last = 0;
428             FD_ZERO(&rd_set);
429             FD_SET(peer->sd,&rd_set);
430             timeOut.tv_sec = timeout;
431             timeOut.tv_usec = 0;
432                 
433             if (0 < select(peer->sd+1,&rd_set,NULL,NULL,&timeOut))
434               res_last = recv(peer->sd, chunk, msg_size-msg_sofar, 0);
435             
436          }
437          if (res_last == 0) {
438            /* No progress done, bail out */
439            xbt_free(chunk);
440            RAISE0(unknown_error,"Not exchanged a single byte, bailing out");
441          }
442       }
443    }
444    
445    xbt_free(chunk);
446    return no_error;
447 }