Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
f687aa5f21748406f20b3129c23548cd5c9d863c
[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   
207   struct sockaddr_in peer_in;
208   socklen_t peer_in_len = sizeof(peer_in);
209
210   int sd;
211   int tmp_errno;
212   int size;
213                         
214   gras_trp_socket_new(1,&res);
215
216   sd = accept(sock->sd, (struct sockaddr *)&peer_in, &peer_in_len);
217   tmp_errno = errno;
218
219   if(sd == -1) {
220     gras_socket_close(sock);
221     RAISE1(system_error,
222            "Accept failed (%s). Droping server socket.", strerror(tmp_errno));
223   } else {
224     int i = 1;
225     socklen_t s = sizeof(int);
226   
227     if (setsockopt(sd, SOL_SOCKET, SO_KEEPALIVE, (char *)&i, s) 
228         || setsockopt(sd, TcpProtoNumber(), TCP_NODELAY, (char *)&i, s)) {
229        RAISE1(system_error,"setsockopt failed, cannot condition the socket: %s",
230               strerror(errno));
231     }
232  
233     (*dst)->bufSize = sock->bufSize;
234     size = sock->bufSize * 1024;
235     if (setsockopt(sd, SOL_SOCKET, SO_RCVBUF, (char *)&size, sizeof(size))
236        || setsockopt(sd, SOL_SOCKET, SO_SNDBUF, (char *)&size, sizeof(size))) {
237        WARN1("setsockopt failed, cannot set buffer size: %s",
238              strerror(errno));
239     }
240      
241     res->plugin    = sock->plugin;
242     res->incoming  = sock->incoming;
243     res->outgoing  = sock->outgoing;
244     res->accepting = 0;
245     res->sd        = sd;
246     res->port      = -1;
247     res->peer_port = peer_in.sin_port;
248
249     /* FIXME: Lock to protect inet_ntoa */
250     if (((struct sockaddr *)&peer_in)->sa_family != AF_INET) {
251       res->peer_name = (char*)strdup("unknown");
252     } else {
253       struct in_addr addrAsInAddr;
254       char *tmp;
255  
256       addrAsInAddr.s_addr = peer_in.sin_addr.s_addr;
257       
258       tmp = inet_ntoa(addrAsInAddr);
259       if (tmp != NULL) {
260         res->peer_name = (char*)strdup(tmp);
261       } else {
262         res->peer_name = (char*)strdup("unknown");
263       }
264     }
265
266     VERB3("accepted socket %d to %s:%d", sd, res->peer_name,res->peer_port);
267     
268     *dst = res;
269
270     return no_error;
271   }
272 }
273
274 void gras_trp_tcp_socket_close(gras_socket_t sock){
275   gras_trp_tcp_plug_data_t *tcp;
276   
277   if (!sock) return; /* close only once */
278   tcp=sock->plugin->data;
279
280   DEBUG1("close tcp connection %d", sock->sd);
281
282   /* FIXME: no pipe in GRAS so far  
283   if(!FD_ISSET(sd, &connectedPipes)) {
284     if(shutdown(sd, 2) < 0) {
285       GetNWSLock(&lock);
286       tmp_errno = errno;
287       ReleaseNWSLock(&lock);
288       
289       / * The other side may have beaten us to the reset. * /
290       if ((tmp_errno!=ENOTCONN) && (tmp_errno!=ECONNRESET)) {
291         WARN1("CloseSocket: shutdown error %d\n", tmp_errno);
292       }
293     }
294   } */
295
296   /* forget about the socket */
297   if (sock->raw)
298     FD_CLR(sock->sd, &(tcp->raw_socks));
299   else
300     FD_CLR(sock->sd, &(tcp->msg_socks));
301
302   /* close the socket */
303   if(close(sock->sd) < 0) {
304     WARN3("error while closing tcp socket %d: %d (%s)\n", 
305              sock->sd, errno, strerror(errno));
306   }
307 }
308
309 /**
310  * gras_trp_tcp_chunk_send:
311  *
312  * Send data on a TCP socket
313  */
314 xbt_error_t 
315 gras_trp_tcp_chunk_send(gras_socket_t sock,
316                         const char *data,
317                         long int size) {
318   
319   /* TCP sockets are in duplex mode, don't check direction */
320   xbt_assert0(size >= 0, "Cannot send a negative amount of data");
321
322   while (size) {
323     int status = 0;
324     
325     status = write(sock->sd, data, (size_t)size);
326     DEBUG3("write(%d, %p, %ld);", sock->sd, data, size);
327     
328     if (status == -1) {
329       RAISE4(system_error,"write(%d,%p,%ld) failed: %s",
330              sock->sd, data, size,
331              strerror(errno));
332     }
333     
334     if (status) {
335       size  -= status;
336       data  += status;
337     } else {
338       RAISE0(system_error,"file descriptor closed");
339     }
340   }
341
342   return no_error;
343 }
344 /**
345  * gras_trp_tcp_chunk_recv:
346  *
347  * Receive data on a TCP socket.
348  */
349 xbt_error_t 
350 gras_trp_tcp_chunk_recv(gras_socket_t sock,
351                         char *data,
352                         long int size) {
353
354   /* TCP sockets are in duplex mode, don't check direction */
355   xbt_assert0(sock, "Cannot recv on an NULL socket");
356   xbt_assert0(size >= 0, "Cannot receive a negative amount of data");
357   
358   while (size) {
359     int status = 0;
360     
361     status = read(sock->sd, data, (size_t)size);
362     DEBUG3("read(%d, %p, %ld);", sock->sd, data, size);
363     
364     if (status == -1) {
365       RAISE4(system_error,"read(%d,%p,%d) failed: %s",
366              sock->sd, data, (int)size,
367              strerror(errno));
368     }
369     
370     if (status) {
371       size  -= status;
372       data  += status;
373     } else {
374       RAISE0(system_error,"file descriptor closed");
375     }
376   }
377   
378   return no_error;
379 }
380
381
382 /*
383  * Returns the tcp protocol number from the network protocol data base.
384  *
385  * getprotobyname() is not thread safe. We need to lock it.
386  */
387 static int TcpProtoNumber(void) {
388   struct protoent *fetchedEntry;
389   static int returnValue = 0;
390   
391   if(returnValue == 0) {
392     fetchedEntry = getprotobyname("tcp");
393     xbt_assert0(fetchedEntry, "getprotobyname(tcp) gave NULL");
394     returnValue = fetchedEntry->p_proto;
395   }
396   
397   return returnValue;
398 }
399
400 /* Data exchange over raw sockets. Placing this in there is a kind of crude hack.
401    It means that the only possible raw are TCP where we may want to do UDP for them. 
402    But I fail to find a good internal organization for now. We may want to split 
403    raw and regular sockets more efficiently.
404 */
405 xbt_error_t gras_socket_raw_exchange(gras_socket_t peer,
406                                       int sender,
407                                       unsigned int timeout,
408                                       unsigned long int exp_size,
409                                       unsigned long int msg_size) {
410    char *chunk;
411    int res_last, msg_sofar, exp_sofar;
412    
413    fd_set rd_set;
414 /*    int rv; */
415    
416    struct timeval timeOut;
417    
418    chunk = xbt_malloc(msg_size);
419
420    for   (exp_sofar=0; exp_sofar < exp_size; exp_sofar += msg_size) {
421       for(msg_sofar=0; msg_sofar < msg_size; msg_sofar += res_last) {
422          
423          if(sender) {
424             res_last = send(peer->sd, chunk, msg_size - msg_sofar, 0);
425          } else {
426             res_last = 0;
427             FD_ZERO(&rd_set);
428             FD_SET(peer->sd,&rd_set);
429             timeOut.tv_sec = timeout;
430             timeOut.tv_usec = 0;
431                 
432             if (0 < select(peer->sd+1,&rd_set,NULL,NULL,&timeOut))
433               res_last = recv(peer->sd, chunk, msg_size-msg_sofar, 0);
434             
435          }
436          if (res_last == 0) {
437            /* No progress done, bail out */
438            xbt_free(chunk);
439            RAISE0(unknown_error,"Not exchanged a single byte, bailing out");
440          }
441       }
442    }
443    
444    xbt_free(chunk);
445    return no_error;
446 }