Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Field renaming in the plugin struct to cleanup; raw is now a field of the socket...
[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);
28
29 typedef struct {
30   int buffsize;
31 } gras_trp_tcp_sock_specific_t;
32
33 /***
34  *** Prototypes 
35  ***/
36 gras_error_t gras_trp_tcp_socket_client(gras_trp_plugin_t *self,
37                                         const char *host,
38                                         unsigned short port,
39                                         int raw,
40                                         /* OUT */ gras_socket_t *sock);
41 gras_error_t gras_trp_tcp_socket_server(gras_trp_plugin_t *self,
42                                         unsigned short port,
43                                         int raw,
44                                         /* OUT */ gras_socket_t *sock);
45 gras_error_t gras_trp_tcp_socket_accept(gras_socket_t  *sock,
46                                         gras_socket_t **dst);
47
48 void         gras_trp_tcp_socket_close(gras_socket_t *sd);
49   
50 gras_error_t gras_trp_tcp_chunk_send(gras_socket_t *sd,
51                                      char *data,
52                                      size_t size);
53
54 gras_error_t gras_trp_tcp_chunk_recv(gras_socket_t *sd,
55                                      char *data,
56                                      size_t size);
57
58 void         gras_trp_tcp_free_specific(void *s);
59
60
61 static int TcpProtoNumber(void);
62 /***
63  *** Specific plugin part
64  ***/
65
66 typedef struct {
67   fd_set incoming_socks;
68 } gras_trp_tcp_specific_t;
69
70 /***
71  *** Specific socket part
72  ***/
73
74
75 /***
76  *** Code
77  ***/
78 gras_error_t
79 gras_trp_tcp_init(gras_trp_plugin_t **dst) {
80
81   gras_trp_plugin_t *res=malloc(sizeof(gras_trp_plugin_t));
82   gras_trp_tcp_specific_t *tcp = malloc(sizeof(gras_trp_tcp_specific_t));
83   if (!res || !tcp)
84     RAISE_MALLOC;
85
86   FD_ZERO(&(tcp->incoming_socks));
87
88   res->name = strdup("TCP");
89   res->socket_client = gras_trp_tcp_socket_client;
90   res->socket_server = gras_trp_tcp_socket_server;
91   res->socket_accept = gras_trp_tcp_socket_accept;
92   res->socket_close  = gras_trp_tcp_socket_close;
93
94   res->chunk_send    = gras_trp_tcp_chunk_send;
95   res->chunk_recv    = gras_trp_tcp_chunk_recv;
96
97   res->specific      = (void*)tcp;
98   res->free_specific = gras_trp_tcp_free_specific;
99
100   *dst = res;
101   return no_error;
102 }
103
104 void gras_trp_tcp_free_specific(void *s) {
105   gras_trp_tcp_specific_t *specific = s;
106   free(specific);
107 }
108
109 gras_error_t gras_trp_tcp_socket_client(gras_trp_plugin_t *self,
110                                         const char *host,
111                                         unsigned short port,
112                                         int raw,
113                                         /* OUT */ gras_socket_t *sock){
114   
115   struct sockaddr_in addr;
116   struct hostent *he;
117   struct in_addr *haddr;
118
119   gras_assert0(!raw,"Raw TCP sockets not implemented yet");
120    
121   sock->incoming = 1; /* TCP sockets are duplex'ed */
122
123   sock->sd = socket (AF_INET, SOCK_STREAM, 0);
124   
125   if (sock->sd < 0) {
126     RAISE1(system_error,
127            "Failed to create socket: %s",
128            strerror (errno));
129   }
130   
131   he = gethostbyname (host);
132   if (he == NULL) {
133     RAISE2(system_error,
134            "Failed to lookup hostname %s: %s",
135            host, strerror (errno));
136   }
137   
138   haddr = ((struct in_addr *) (he->h_addr_list)[0]);
139   
140   memset(&addr, 0, sizeof(struct sockaddr_in));
141   memcpy (&addr.sin_addr, haddr, sizeof(struct in_addr));
142   addr.sin_family = AF_INET;
143   addr.sin_port = htons (port);
144
145   if (connect (sock->sd, (struct sockaddr*) &addr, sizeof (addr)) < 0) {
146     close(sock->sd);
147     RAISE3(system_error,
148            "Failed to connect socket to %s:%d (%s)",
149            host, port, strerror (errno));
150   }
151   
152   return no_error;
153 }
154
155 /**
156  * gras_trp_tcp_socket_server:
157  *
158  * Open a socket used to receive messages.
159  */
160 gras_error_t gras_trp_tcp_socket_server(gras_trp_plugin_t *self,
161                                         unsigned short port,
162                                         int raw,
163                                         /* OUT */ gras_socket_t *sock){
164 //  int size = bufSize * 1024;
165   int on = 1;
166   struct sockaddr_in server;
167
168   gras_assert0(!raw,"Raw TCP sockets not implemented yet");
169
170    gras_trp_tcp_specific_t *data=(gras_trp_tcp_specific_t*)self -> specific;
171  
172   sock->outgoing  = 1; /* TCP => duplex mode */
173
174   server.sin_port = htons((u_short)port);
175   server.sin_addr.s_addr = INADDR_ANY;
176   server.sin_family = AF_INET;
177   if((sock->sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
178     RAISE1(system_error,"socket allocation failed: %s", strerror(errno));
179   }
180
181   (void)setsockopt(sock->sd, SOL_SOCKET, SO_REUSEADDR, 
182                    (char *)&on, sizeof(on));
183    /*
184   (void)setsockopt(sd, SOL_SOCKET, SO_RCVBUF, (char *)&size, sizeof(size));
185   (void)setsockopt(sd, SOL_SOCKET, SO_SNDBUF, (char *)&size, sizeof(size));
186     */
187   if (bind(sock->sd, (struct sockaddr *)&server, sizeof(server)) == -1) {
188     close(sock->sd);
189     RAISE2(system_error,"Cannot bind to port %d: %s",port, strerror(errno));
190   }
191
192   if (listen(sock->sd, 5) < 0) {
193     close(sock->sd);
194     RAISE2(system_error,"Cannot listen to port %d: %s",port,strerror(errno));
195   }
196
197   FD_SET(sock->sd, &(data->incoming_socks));
198
199   DEBUG2("Openned a server socket on port %d (sock %d)",port,sock->sd);
200   
201   return no_error;
202 }
203
204 gras_error_t
205 gras_trp_tcp_socket_accept(gras_socket_t  *sock,
206                            gras_socket_t **dst) {
207   gras_socket_t *res;
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                                 
215   res=malloc(sizeof(gras_socket_t));
216   if (!res)
217     RAISE_MALLOC;
218
219   sd = accept(sock->sd, (struct sockaddr *)&peer_in, &peer_in_len);
220   tmp_errno = errno;
221
222   if(sd == -1) {
223     gras_socket_close(&sock);
224     RAISE1(system_error,
225            "Accept failed (%s). Droping server socket.", strerror(tmp_errno));
226   } else {
227     int i = 1;
228     socklen_t s = sizeof(int);
229   
230     if (setsockopt(sd, SOL_SOCKET, SO_KEEPALIVE, (char *)&i, s) 
231         || setsockopt(sd, TcpProtoNumber(), TCP_NODELAY, (char *)&i, s)) {
232       WARN0("setsockopt failed, cannot condition the accepted socket");
233     }
234  
235      /* FIXME: bufSize removed until we can have optionsets 
236     i = ((gras_trp_tcp_sock_specific_t*)sock->specific)->buffsize;
237     if (setsockopt(sd, SOL_SOCKET, SO_RCVBUF, (char *)&i, s)
238         || setsockopt(sd, SOL_SOCKET, SO_SNDBUF, (char *)&i, s)) {
239       WARNING0("setsockopt failed, cannot set buffsize");       
240     }
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 = 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 = strdup(tmp);
263       } else {
264         res->peer_name = strdup("unknown");
265       }
266     }
267
268     VERB3("accepted socket %d to %s:%d\n", 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_specific_t *tcp;
278   
279   if (!sock) return; /* close only once */
280   tcp=sock->plugin->specific;
281
282   DEBUG1("close tcp connection %d\n", 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   FD_CLR(sock->sd, &(tcp->incoming_socks));
300
301   /* close the socket */
302   if(close(sock->sd) < 0) {
303     WARN3("error while closing tcp socket %d: %d (%s)\n", 
304              sock->sd, errno, strerror(errno));
305   }
306 }
307
308 /**
309  * gras_trp_tcp_chunk_send:
310  *
311  * Send data on a TCP socket
312  */
313 gras_error_t 
314 gras_trp_tcp_chunk_send(gras_socket_t *sock,
315                     char *data,
316                     size_t size) {
317   
318   /* TCP sockets are in duplex mode, don't check direction */
319   gras_assert0(size >= 0, "Cannot send a negative amount of data");
320
321   while (size) {
322     int status = 0;
323     
324     status = write(sock->sd, data, (size_t)size);
325     DEBUG3("write(%d, %p, %ld);\n", sock->sd, data, size);
326     
327     if (status == -1) {
328       RAISE4(system_error,"write(%d,%p,%d) failed: %s",
329              sock->sd, data, (int)size,
330              strerror(errno));
331     }
332     
333     if (status) {
334       size  -= status;
335       data  += status;
336     } else {
337       RAISE0(system_error,"file descriptor closed");
338     }
339   }
340
341   return no_error;
342 }
343 /**
344  * gras_trp_tcp_chunk_recv:
345  *
346  * Receive data on a TCP socket.
347  */
348 gras_error_t 
349 gras_trp_tcp_chunk_recv(gras_socket_t *sock,
350                         char *data,
351                         size_t size) {
352
353   /* TCP sockets are in duplex mode, don't check direction */
354   gras_assert0(sock, "Cannot recv on an NULL socket");
355   gras_assert0(size >= 0, "Cannot receive a negative amount of data");
356   
357   while (size) {
358     int status = 0;
359     
360     status = read(sock->sd, data, (size_t)size);
361     DEBUG3("read(%d, %p, %ld);\n", sock->sd, data, size);
362     
363     if (status == -1) {
364       RAISE4(system_error,"read(%d,%p,%d) failed: %s",
365              sock->sd, data, (int)size,
366              strerror(errno));
367     }
368     
369     if (status) {
370       size  -= status;
371       data  += status;
372     } else {
373       RAISE0(system_error,"file descriptor closed");
374     }
375   }
376   
377   return no_error;
378 }
379
380
381 /*
382  * Returns the tcp protocol number from the network protocol data base.
383  *
384  * getprotobyname() is not thread safe. We need to lock it.
385  */
386 static int TcpProtoNumber(void) {
387   struct protoent *fetchedEntry;
388   static int returnValue = 0;
389   
390   if(returnValue == 0) {
391     fetchedEntry = getprotobyname("tcp");
392     gras_assert0(fetchedEntry, "getprotobyname(tcp) gave NULL");
393     returnValue = fetchedEntry->p_proto;
394   }
395   
396   return returnValue;
397 }