]> arthur.barton.de Git - netatalk.git/blob - libatalk/dsi/dsi_tcp.c
1) try a better workaround for deadlocks when both the server and the client are...
[netatalk.git] / libatalk / dsi / dsi_tcp.c
1 /*
2  * $Id: dsi_tcp.c,v 1.16 2009-10-25 06:13:11 didg Exp $
3  *
4  * Copyright (c) 1997, 1998 Adrian Sun (asun@zoology.washington.edu)
5  * All rights reserved. See COPYRIGHT.
6  *
7  * this provides both proto_open() and proto_close() to account for
8  * protocol specific initialization and shutdown procedures. all the
9  * read/write stuff is done in dsi_stream.c.  */
10
11 #ifdef HAVE_CONFIG_H
12 #include "config.h"
13 #endif /* HAVE_CONFIG_H */
14
15 #define USE_TCP_NODELAY
16
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #ifdef HAVE_UNISTD_H
21 #include <unistd.h>
22 #endif /* HAVE_UNISTD_H */
23 #include <errno.h>
24 #ifdef HAVE_NETDB_H
25 #include <netdb.h>
26 #endif /* HAVE_NETDB_H */
27 #include <sys/types.h>
28 #include <sys/time.h>
29 #include <sys/socket.h>
30
31 #ifdef HAVE_STDINT_H
32 #include <stdint.h>
33 #endif /* HAVE_STDINT_H */
34
35 #include <sys/ioctl.h>
36 #ifdef TRU64
37 #include <sys/mbuf.h>
38 #include <net/route.h>
39 #endif /* TRU64 */
40 #include <net/if.h>
41 #include <netinet/tcp.h>
42 #include <netinet/in.h>
43 #include <arpa/inet.h>
44
45 #include <signal.h>
46 #include <atalk/logger.h>
47
48 #ifdef __svr4__
49 #include <sys/sockio.h>
50 #endif /* __svr4__ */
51
52 #ifdef TCPWRAP
53 #include <tcpd.h>
54 int allow_severity = log_info;
55 int deny_severity = log_warning;
56 #endif /* TCPWRAP */
57
58 #include <atalk/dsi.h>
59 #include <atalk/compat.h>
60 #include <atalk/util.h>
61 #include <netatalk/endian.h>
62 #include "dsi_private.h"
63
64 #define min(a,b)  ((a) < (b) ? (a) : (b))
65
66 #ifndef DSI_TCPMAXPEND
67 #define DSI_TCPMAXPEND      20       /* max # of pending connections */
68 #endif /* DSI_TCPMAXPEND */
69
70 #ifndef DSI_TCPTIMEOUT
71 #define DSI_TCPTIMEOUT      120     /* timeout in seconds for connections */
72 #endif /* ! DSI_TCPTIMEOUT */
73
74
75 /* FIXME/SOCKLEN_T: socklen_t is a unix98 feature. */
76 #ifndef SOCKLEN_T
77 #define SOCKLEN_T unsigned int
78 #endif /* ! SOCKLEN_T */
79
80 static void dsi_tcp_close(DSI *dsi)
81 {
82   if (dsi->socket == -1)
83     return;
84
85   close(dsi->socket);
86   dsi->socket = -1;
87 }
88
89 static void dsi_tcp_timeout(DSI *dsi)
90 {
91   struct timeval tv;
92   /* 2 seconds delay, most of the time it translates to 4 seconds:
93    * send/write returns first with whatever it has written and the 
94    * second time it returns EAGAIN
95   */
96   tv.tv_sec = 2;
97   tv.tv_usec = 0;
98
99   /* Note: write isn't a restartable syscall if there's a timeout on the socket 
100    * we have to test for EINTR
101   */
102   if (setsockopt(dsi->socket, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)) < 0) {
103       LOG(log_error, logtype_default, "dsi_tcp_open: unable to set timeout %s", strerror(errno));
104       exit(EXITERR_CLNT);
105   }
106 }
107                                   
108 /* alarm handler for tcp_open */
109 static void timeout_handler(int sig _U_)
110 {
111   LOG(log_error, logtype_default, "dsi_tcp_open: connection timed out");
112   exit(EXITERR_CLNT);
113 }
114
115 static struct itimerval itimer;
116 /* accept the socket and do a little sanity checking */
117 static int dsi_tcp_open(DSI *dsi)
118 {
119   pid_t pid;
120   SOCKLEN_T len;
121
122   len = sizeof(dsi->client);
123   dsi->socket = accept(dsi->serversock, (struct sockaddr *) &dsi->client,
124                        &len);
125
126 #ifdef TCPWRAP
127   {
128     struct request_info req;
129     request_init(&req, RQ_DAEMON, dsi->program, RQ_FILE, dsi->socket, NULL);
130     fromhost(&req);
131     if (!hosts_access(&req)) {
132       LOG(deny_severity, logtype_default, "refused connect from %s", eval_client(&req));
133       close(dsi->socket);
134       errno = ECONNREFUSED;
135       dsi->socket = -1;
136     }
137   }
138 #endif /* TCPWRAP */
139
140   if (dsi->socket < 0)
141     return -1;
142
143   getitimer(ITIMER_PROF, &itimer);
144   if (0 == (pid = fork()) ) { /* child */
145     static struct itimerval timer = {{0, 0}, {DSI_TCPTIMEOUT, 0}};
146     struct sigaction newact, oldact;
147     u_int8_t block[DSI_BLOCKSIZ];
148     size_t stored;
149
150     /* reset signals */
151     server_reset_signal();
152
153 #ifndef DEBUGGING
154     /* install an alarm to deal with non-responsive connections */
155     newact.sa_handler = timeout_handler;
156     sigemptyset(&newact.sa_mask);
157     newact.sa_flags = 0;
158     sigemptyset(&oldact.sa_mask);
159     oldact.sa_flags = 0;
160     setitimer(ITIMER_PROF, &itimer, NULL);
161
162     if ((sigaction(SIGALRM, &newact, &oldact) < 0) ||
163         (setitimer(ITIMER_REAL, &timer, NULL) < 0)) {
164         LOG(log_error, logtype_default, "dsi_tcp_open: %s", strerror(errno));
165         exit(EXITERR_SYS);
166     }
167 #endif
168     
169     /* read in commands. this is similar to dsi_receive except
170      * for the fact that we do some sanity checking to prevent
171      * delinquent connections from causing mischief. */
172     
173     /* read in the first two bytes */
174     len = dsi_stream_read(dsi, block, 2);
175     if (!len ) {
176       /* connection already closed, don't log it (normal OSX 10.3 behaviour) */
177       exit(EXITERR_CLNT);
178     }
179     if (len < 2 || (block[0] > DSIFL_MAX) || (block[1] > DSIFUNC_MAX)) {
180       LOG(log_error, logtype_default, "dsi_tcp_open: invalid header");
181       exit(EXITERR_CLNT);
182     }      
183     
184     /* read in the rest of the header */
185     stored = 2;
186     while (stored < DSI_BLOCKSIZ) {
187       len = dsi_stream_read(dsi, block + stored, sizeof(block) - stored);
188       if (len > 0)
189         stored += len;
190       else {
191         LOG(log_error, logtype_default, "dsi_tcp_open: stream_read: %s", strerror(errno));
192         exit(EXITERR_CLNT);
193       }
194     }
195     
196     dsi->header.dsi_flags = block[0];
197     dsi->header.dsi_command = block[1];
198     memcpy(&dsi->header.dsi_requestID, block + 2, 
199            sizeof(dsi->header.dsi_requestID));
200     memcpy(&dsi->header.dsi_code, block + 4, sizeof(dsi->header.dsi_code));
201     memcpy(&dsi->header.dsi_len, block + 8, sizeof(dsi->header.dsi_len));
202     memcpy(&dsi->header.dsi_reserved, block + 12,
203            sizeof(dsi->header.dsi_reserved));
204     dsi->clientID = ntohs(dsi->header.dsi_requestID);
205     
206     /* make sure we don't over-write our buffers. */
207     dsi->cmdlen = min(ntohl(dsi->header.dsi_len), DSI_CMDSIZ);
208     
209     stored = 0;
210     while (stored < dsi->cmdlen) {
211       len = dsi_stream_read(dsi, dsi->commands + stored, dsi->cmdlen - stored);
212       if (len > 0)
213         stored += len;
214       else {
215         LOG(log_error, logtype_default, "dsi_tcp_open: stream_read: %s", strerror(errno));
216         exit(EXITERR_CLNT);
217       }
218     }
219     
220     /* stop timer and restore signal handler */
221 #ifndef DEBUGGING
222     memset(&timer, 0, sizeof(timer));
223     setitimer(ITIMER_REAL, &timer, NULL);
224     sigaction(SIGALRM, &oldact, NULL);
225 #endif
226     
227     dsi_tcp_timeout(dsi);
228
229     LOG(log_info, logtype_default,"ASIP session:%u(%d) from %s:%u(%d)", 
230            ntohs(dsi->server.sin_port), dsi->serversock, 
231            inet_ntoa(dsi->client.sin_addr), ntohs(dsi->client.sin_port),
232            dsi->socket);
233   }
234   
235   /* send back our pid */
236   return pid;
237 }
238
239 /* this needs to accept passed in addresses */
240 int dsi_tcp_init(DSI *dsi, const char *hostname, const char *address,
241                  const u_int16_t ipport, const int proxy)
242 {
243   struct servent     *service;
244   struct hostent     *host;
245   int                port;
246
247   dsi->protocol = DSI_TCPIP;
248
249   /* create a socket */
250   if (proxy)
251     dsi->serversock = -1;
252   else if ((dsi->serversock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
253     return 0;
254       
255   /* find port */
256   if (ipport)
257     port = htons(ipport);
258   else if ((service = getservbyname("afpovertcp", "tcp")))
259     port = service->s_port;
260   else
261     port = htons(DSI_AFPOVERTCP_PORT);
262
263   /* find address */
264   if (!address) 
265     dsi->server.sin_addr.s_addr = htonl(INADDR_ANY);
266   else if (inet_aton(address, &dsi->server.sin_addr) == 0) {
267     LOG(log_info, logtype_default, "dsi_tcp: invalid address (%s)", address);
268     return 0;
269   }
270
271   dsi->server.sin_family = AF_INET;
272   dsi->server.sin_port = port;
273
274   if (!proxy) {
275     /* this deals w/ quick close/opens */    
276 #ifdef SO_REUSEADDR
277     port = 1;
278     setsockopt(dsi->serversock, SOL_SOCKET, SO_REUSEADDR, &port, sizeof(port));
279 #endif
280
281 #ifdef USE_TCP_NODELAY 
282
283 #ifndef SOL_TCP
284 #define SOL_TCP IPPROTO_TCP
285 #endif 
286
287     port = 1;
288     setsockopt(dsi->serversock, SOL_TCP, TCP_NODELAY, &port, sizeof(port));
289 #endif /* USE_TCP_NODELAY */
290
291     /* now, bind the socket and set it up for listening */
292     if ((bind(dsi->serversock, (struct sockaddr *) &dsi->server, 
293               sizeof(dsi->server)) < 0) || 
294         (listen(dsi->serversock, DSI_TCPMAXPEND) < 0)) {
295       close(dsi->serversock);
296       return 0;
297     }
298   }
299
300   /* Point protocol specific functions to tcp versions */
301   dsi->proto_open = dsi_tcp_open;
302   dsi->proto_close = dsi_tcp_close;
303
304   /* get real address for GetStatus. we'll go through the list of 
305    * interfaces if necessary. */
306
307   if (address) {
308       /* address is a parameter, use it 'as is' */
309       return 1;
310   }
311   
312   if (!(host = gethostbyname(hostname)) ) { /* we can't resolve the name */
313
314       LOG(log_info, logtype_default, "dsi_tcp: cannot resolve hostname '%s'", hostname);
315       if (proxy) {
316          /* give up we have nothing to advertise */
317          return 0;
318       }
319   }
320   else {
321       if (( ((struct in_addr *) host->h_addr)->s_addr & htonl(0x7F000000) ) !=  htonl(0x7F000000)) { /* FIXME ugly check */
322           dsi->server.sin_addr.s_addr = ((struct in_addr *) host->h_addr)->s_addr;
323           return 1;
324       }
325       LOG(log_info, logtype_default, "dsi_tcp: hostname '%s' resolves to loopback address", hostname);
326   }
327   {
328       char **start, **list;
329       struct ifreq ifr;
330
331       /* get it from the interface list */
332       start = list = getifacelist();
333       while (list && *list) {
334           strlcpy(ifr.ifr_name, *list, sizeof(ifr.ifr_name));
335           list++;
336
337 #ifndef IFF_SLAVE
338 #define IFF_SLAVE 0
339 #endif
340
341           if (ioctl(dsi->serversock, SIOCGIFFLAGS, &ifr) < 0)
342             continue;
343
344           if (ifr.ifr_flags & (IFF_LOOPBACK | IFF_POINTOPOINT | IFF_SLAVE))
345             continue;
346
347           if (!(ifr.ifr_flags & (IFF_UP | IFF_RUNNING)) )
348             continue;
349
350           if (ioctl(dsi->serversock, SIOCGIFADDR, &ifr) < 0)
351             continue;
352         
353           dsi->server.sin_addr.s_addr = 
354             ((struct sockaddr_in *) &ifr.ifr_addr)->sin_addr.s_addr;
355           LOG(log_info, logtype_default, "dsi_tcp: '%s' on interface '%s' will be used instead.",
356                inet_ntoa(dsi->server.sin_addr), ifr.ifr_name);
357           goto iflist_done;
358       }
359       LOG(log_info, logtype_default, "dsi_tcp (Chooser will not select afp/tcp) \
360 Check to make sure %s is in /etc/hosts and the correct domain is in \
361 /etc/resolv.conf: %s", hostname, strerror(errno));
362
363 iflist_done:
364       if (start)
365           freeifacelist(start);
366   }
367
368   return 1;
369
370 }
371