]> arthur.barton.de Git - netatalk.git/blob - libatalk/dsi/dsi_tcp.c
795b80b98c48672cfb834f4cac394a4c8dd12ef3
[netatalk.git] / libatalk / dsi / dsi_tcp.c
1 /*
2  * $Id: dsi_tcp.c,v 1.24 2009-11-08 09:44:22 franklahm 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, &len);
124
125 #ifdef TCPWRAP
126     {
127         struct request_info req;
128         request_init(&req, RQ_DAEMON, dsi->program, RQ_FILE, dsi->socket, NULL);
129         fromhost(&req);
130         if (!hosts_access(&req)) {
131             LOG(deny_severity, logtype_default, "refused connect from %s", eval_client(&req));
132             close(dsi->socket);
133             errno = ECONNREFUSED;
134             dsi->socket = -1;
135         }
136     }
137 #endif /* TCPWRAP */
138
139     if (dsi->socket < 0)
140         return -1;
141
142     getitimer(ITIMER_PROF, &itimer);
143     if (0 == (pid = fork()) ) { /* child */
144         static struct itimerval timer = {{0, 0}, {DSI_TCPTIMEOUT, 0}};
145         struct sigaction newact, oldact;
146         u_int8_t block[DSI_BLOCKSIZ];
147         size_t stored;
148
149         /* reset signals */
150         server_reset_signal();
151
152 #ifndef DEBUGGING
153         /* install an alarm to deal with non-responsive connections */
154         newact.sa_handler = timeout_handler;
155         sigemptyset(&newact.sa_mask);
156         newact.sa_flags = 0;
157         sigemptyset(&oldact.sa_mask);
158         oldact.sa_flags = 0;
159         setitimer(ITIMER_PROF, &itimer, NULL);
160
161         if ((sigaction(SIGALRM, &newact, &oldact) < 0) ||
162             (setitimer(ITIMER_REAL, &timer, NULL) < 0)) {
163             LOG(log_error, logtype_default, "dsi_tcp_open: %s", strerror(errno));
164             exit(EXITERR_SYS);
165         }
166 #endif
167
168         /* read in commands. this is similar to dsi_receive except
169          * for the fact that we do some sanity checking to prevent
170          * delinquent connections from causing mischief. */
171
172         /* read in the first two bytes */
173         len = dsi_stream_read(dsi, block, 2);
174         if (!len ) {
175             /* connection already closed, don't log it (normal OSX 10.3 behaviour) */
176             exit(EXITERR_CLNT);
177         }
178         if (len < 2 || (block[0] > DSIFL_MAX) || (block[1] > DSIFUNC_MAX)) {
179             LOG(log_error, logtype_default, "dsi_tcp_open: invalid header");
180             exit(EXITERR_CLNT);
181         }
182
183         /* read in the rest of the header */
184         stored = 2;
185         while (stored < DSI_BLOCKSIZ) {
186             len = dsi_stream_read(dsi, block + stored, sizeof(block) - stored);
187             if (len > 0)
188                 stored += len;
189             else {
190                 LOG(log_error, logtype_default, "dsi_tcp_open: stream_read: %s", strerror(errno));
191                 exit(EXITERR_CLNT);
192             }
193         }
194
195         dsi->header.dsi_flags = block[0];
196         dsi->header.dsi_command = block[1];
197         memcpy(&dsi->header.dsi_requestID, block + 2,
198                sizeof(dsi->header.dsi_requestID));
199         memcpy(&dsi->header.dsi_code, block + 4, sizeof(dsi->header.dsi_code));
200         memcpy(&dsi->header.dsi_len, block + 8, sizeof(dsi->header.dsi_len));
201         memcpy(&dsi->header.dsi_reserved, block + 12,
202                sizeof(dsi->header.dsi_reserved));
203         dsi->clientID = ntohs(dsi->header.dsi_requestID);
204
205         /* make sure we don't over-write our buffers. */
206         dsi->cmdlen = min(ntohl(dsi->header.dsi_len), DSI_CMDSIZ);
207
208         stored = 0;
209         while (stored < dsi->cmdlen) {
210             len = dsi_stream_read(dsi, dsi->commands + stored, dsi->cmdlen - stored);
211             if (len > 0)
212                 stored += len;
213             else {
214                 LOG(log_error, logtype_default, "dsi_tcp_open: stream_read: %s", strerror(errno));
215                 exit(EXITERR_CLNT);
216             }
217         }
218
219         /* stop timer and restore signal handler */
220 #ifndef DEBUGGING
221         memset(&timer, 0, sizeof(timer));
222         setitimer(ITIMER_REAL, &timer, NULL);
223         sigaction(SIGALRM, &oldact, NULL);
224 #endif
225
226         dsi_tcp_timeout(dsi);
227
228         LOG(log_info, logtype_default, "AFP/TCP session from %s:%u",
229             getip_string((struct sockaddr *)&dsi->client),
230             getip_port((struct sockaddr *)&dsi->client));
231     }
232
233     /* send back our pid */
234     return pid;
235 }
236
237 /* get it from the interface list */
238 #ifndef IFF_SLAVE
239 #define IFF_SLAVE 0
240 #endif
241
242 static void guess_interface(DSI *dsi, const char *hostname)
243 {
244     int fd;
245     char **start, **list;
246     struct ifreq ifr;
247     struct sockaddr_in *sa = (struct sockaddr_in *)&dsi->server;
248
249     start = list = getifacelist();
250     if (!start)
251         return;
252         
253     fd = socket(PF_INET, SOCK_STREAM, 0);
254
255     while (list && *list) {
256         strlcpy(ifr.ifr_name, *list, sizeof(ifr.ifr_name));
257         list++;
258
259
260         if (ioctl(dsi->serversock, SIOCGIFFLAGS, &ifr) < 0)
261             continue;
262
263         if (ifr.ifr_flags & (IFF_LOOPBACK | IFF_POINTOPOINT | IFF_SLAVE))
264             continue;
265
266         if (!(ifr.ifr_flags & (IFF_UP | IFF_RUNNING)) )
267             continue;
268
269         if (ioctl(fd, SIOCGIFADDR, &ifr) < 0)
270             continue;
271
272         memset(&dsi->server, 0, sizeof(struct sockaddr_storage));
273         sa->sin_family = AF_INET;
274         sa->sin_port = htons(548);
275         sa->sin_addr = ((struct sockaddr_in *) &ifr.ifr_addr)->sin_addr;
276
277         LOG(log_info, logtype_default, "dsi_tcp: '%s' on interface '%s' will be used instead.",
278                   getip_string((struct sockaddr *)&dsi->server), ifr.ifr_name);
279         goto iflist_done;
280     }
281     LOG(log_info, logtype_default, "dsi_tcp (Chooser will not select afp/tcp) "
282         "Check to make sure %s is in /etc/hosts and the correct domain is in "
283         "/etc/resolv.conf: %s", hostname, strerror(errno));
284
285 iflist_done:
286     close(fd);
287     freeifacelist(start);
288 }
289
290 /* this needs to accept passed in addresses */
291 int dsi_tcp_init(DSI *dsi, const char *hostname, const char *address,
292                  const char *port, const int proxy)
293 {
294     int                ret;
295     int                flag;
296     struct addrinfo    hints, *servinfo, *p;
297
298     dsi->protocol = DSI_TCPIP;
299
300     /* Prepare hint for getaddrinfo */
301     memset(&hints, 0, sizeof hints);
302     hints.ai_family = AF_UNSPEC;
303     hints.ai_socktype = SOCK_STREAM;
304     hints.ai_flags = AI_NUMERICSERV;
305     if ( ! address)
306         hints.ai_flags |= AI_PASSIVE;
307     else
308         hints.ai_flags |= AI_NUMERICHOST;
309
310     if ((ret = getaddrinfo(address ? address : NULL, port ? port : "548", &hints, &servinfo)) != 0) {
311         LOG(log_error, logtype_default, "dsi_tcp_init: getaddrinfo: %s\n", gai_strerror(ret));
312         return 0;
313     }
314
315     /* create a socket */
316     if (proxy)
317         dsi->serversock = -1;
318     else {
319         /* loop through all the results and bind to the first we can */
320         for (p = servinfo; p != NULL; p = p->ai_next) {
321             if ((dsi->serversock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
322                 LOG(log_info, logtype_default, "dsi_tcp_init: socket: %s", strerror(errno));
323                 continue;
324             }
325
326             /*
327              * Set some socket options:
328              * SO_REUSEADDR deals w/ quick close/opens
329              * TCP_NODELAY diables Nagle
330              */
331 #ifdef SO_REUSEADDR
332             flag = 1;
333             setsockopt(dsi->serversock, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));
334 #endif
335
336 #ifdef USE_TCP_NODELAY
337 #ifndef SOL_TCP
338 #define SOL_TCP IPPROTO_TCP
339 #endif
340             flag = 1;
341             setsockopt(dsi->serversock, SOL_TCP, TCP_NODELAY, &flag, sizeof(flag));
342 #endif /* USE_TCP_NODELAY */
343             
344             if (bind(dsi->serversock, p->ai_addr, p->ai_addrlen) == -1) {
345                 close(dsi->serversock);
346                 LOG(log_info, logtype_default, "dsi_tcp_init: bind: %s\n", strerror(errno));
347                 continue;
348             }
349
350             if (listen(dsi->serversock, DSI_TCPMAXPEND) < 0) {
351                 close(dsi->serversock);
352                 LOG(log_info, logtype_default, "dsi_tcp_init: listen: %s\n", strerror(errno));
353                 continue;
354             }
355             
356             break;
357         }
358
359         if (p == NULL)  {
360             LOG(log_error, logtype_default, "dsi_tcp_init: no suitable network config for TCP socket");
361             freeaddrinfo(servinfo);
362             return 0;
363         }
364
365         /* Copy struct sockaddr to struct sockaddr_storage */
366         memcpy(&dsi->server, p->ai_addr, p->ai_addrlen);
367         freeaddrinfo(servinfo);
368     } /* if (proxy) */
369
370     /* Point protocol specific functions to tcp versions */
371     dsi->proto_open = dsi_tcp_open;
372     dsi->proto_close = dsi_tcp_close;
373
374     /* get real address for GetStatus. */
375
376     if (address) {
377         /* address is a parameter, use it 'as is' */
378         return 1;
379     }
380
381     /* Prepare hint for getaddrinfo */
382     memset(&hints, 0, sizeof hints);
383     hints.ai_family = AF_UNSPEC;
384     hints.ai_socktype = SOCK_STREAM;
385
386     if ((ret = getaddrinfo(hostname, port ? port : "548", &hints, &servinfo)) != 0) {
387         LOG(log_info, logtype_default, "dsi_tcp_init: getaddrinfo '%s': %s\n", hostname, gai_strerror(ret));
388         goto interfaces;
389     }
390
391     for (p = servinfo; p != NULL; p = p->ai_next) {
392         if (p->ai_family == AF_INET) { // IPv4
393             struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
394             if ( (ipv4->sin_addr.s_addr & htonl(0x7f000000)) != htonl(0x7f000000) )
395                 break;
396         } else { // IPv6
397             struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
398             unsigned char ipv6loopb[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
399             if ((memcmp(ipv6->sin6_addr.s6_addr, ipv6loopb, 16)) != 0)
400                 break;
401         }
402     }
403
404     if (p) {
405         /* Store found address in dsi->server */
406         memcpy(&dsi->server, p->ai_addr, p->ai_addrlen);
407         freeaddrinfo(servinfo);
408         return 1;
409     }
410     LOG(log_info, logtype_default, "dsi_tcp: hostname '%s' resolves to loopback address", hostname);
411     freeaddrinfo(servinfo);
412
413 interfaces:
414     guess_interface(dsi, hostname);
415     return 1;
416 }
417