Logo AND Algorithmique Numérique Distribuée

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