]> arthur.barton.de Git - netatalk.git/blob - libatalk/dsi/dsi_tcp.c
Not all systems define AI_NUMERICSERV
[netatalk.git] / libatalk / dsi / dsi_tcp.c
1 /*
2  * $Id: dsi_tcp.c,v 1.25 2009-12-08 22:34:37 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, &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
291 #ifndef AI_NUMERICSERV
292 #define AI_NUMERICSERV 0
293 #endif
294
295 /* this needs to accept passed in addresses */
296 int dsi_tcp_init(DSI *dsi, const char *hostname, const char *address,
297                  const char *port, const int proxy)
298 {
299     int                ret;
300     int                flag;
301     struct addrinfo    hints, *servinfo, *p;
302
303     dsi->protocol = DSI_TCPIP;
304
305     /* Prepare hint for getaddrinfo */
306     memset(&hints, 0, sizeof hints);
307     hints.ai_family = AF_UNSPEC;
308     hints.ai_socktype = SOCK_STREAM;
309     hints.ai_flags = AI_NUMERICSERV;
310     if ( ! address)
311         hints.ai_flags |= AI_PASSIVE;
312     else
313         hints.ai_flags |= AI_NUMERICHOST;
314
315     if ((ret = getaddrinfo(address ? address : NULL, port ? port : "548", &hints, &servinfo)) != 0) {
316         LOG(log_error, logtype_default, "dsi_tcp_init: getaddrinfo: %s\n", gai_strerror(ret));
317         return 0;
318     }
319
320     /* create a socket */
321     if (proxy)
322         dsi->serversock = -1;
323     else {
324         /* loop through all the results and bind to the first we can */
325         for (p = servinfo; p != NULL; p = p->ai_next) {
326             if ((dsi->serversock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
327                 LOG(log_info, logtype_default, "dsi_tcp_init: socket: %s", strerror(errno));
328                 continue;
329             }
330
331             /*
332              * Set some socket options:
333              * SO_REUSEADDR deals w/ quick close/opens
334              * TCP_NODELAY diables Nagle
335              */
336 #ifdef SO_REUSEADDR
337             flag = 1;
338             setsockopt(dsi->serversock, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));
339 #endif
340
341 #ifdef USE_TCP_NODELAY
342 #ifndef SOL_TCP
343 #define SOL_TCP IPPROTO_TCP
344 #endif
345             flag = 1;
346             setsockopt(dsi->serversock, SOL_TCP, TCP_NODELAY, &flag, sizeof(flag));
347 #endif /* USE_TCP_NODELAY */
348             
349             if (bind(dsi->serversock, p->ai_addr, p->ai_addrlen) == -1) {
350                 close(dsi->serversock);
351                 LOG(log_info, logtype_default, "dsi_tcp_init: bind: %s\n", strerror(errno));
352                 continue;
353             }
354
355             if (listen(dsi->serversock, DSI_TCPMAXPEND) < 0) {
356                 close(dsi->serversock);
357                 LOG(log_info, logtype_default, "dsi_tcp_init: listen: %s\n", strerror(errno));
358                 continue;
359             }
360             
361             break;
362         }
363
364         if (p == NULL)  {
365             LOG(log_error, logtype_default, "dsi_tcp_init: no suitable network config for TCP socket");
366             freeaddrinfo(servinfo);
367             return 0;
368         }
369
370         /* Copy struct sockaddr to struct sockaddr_storage */
371         memcpy(&dsi->server, p->ai_addr, p->ai_addrlen);
372         freeaddrinfo(servinfo);
373     } /* if (proxy) */
374
375     /* Point protocol specific functions to tcp versions */
376     dsi->proto_open = dsi_tcp_open;
377     dsi->proto_close = dsi_tcp_close;
378
379     /* get real address for GetStatus. */
380
381     if (address) {
382         /* address is a parameter, use it 'as is' */
383         return 1;
384     }
385
386     /* Prepare hint for getaddrinfo */
387     memset(&hints, 0, sizeof hints);
388     hints.ai_family = AF_UNSPEC;
389     hints.ai_socktype = SOCK_STREAM;
390
391     if ((ret = getaddrinfo(hostname, port ? port : "548", &hints, &servinfo)) != 0) {
392         LOG(log_info, logtype_default, "dsi_tcp_init: getaddrinfo '%s': %s\n", hostname, gai_strerror(ret));
393         goto interfaces;
394     }
395
396     for (p = servinfo; p != NULL; p = p->ai_next) {
397         if (p->ai_family == AF_INET) { // IPv4
398             struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
399             if ( (ipv4->sin_addr.s_addr & htonl(0x7f000000)) != htonl(0x7f000000) )
400                 break;
401         } else { // IPv6
402             struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
403             unsigned char ipv6loopb[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
404             if ((memcmp(ipv6->sin6_addr.s6_addr, ipv6loopb, 16)) != 0)
405                 break;
406         }
407     }
408
409     if (p) {
410         /* Store found address in dsi->server */
411         memcpy(&dsi->server, p->ai_addr, p->ai_addrlen);
412         freeaddrinfo(servinfo);
413         return 1;
414     }
415     LOG(log_info, logtype_default, "dsi_tcp: hostname '%s' resolves to loopback address", hostname);
416     freeaddrinfo(servinfo);
417
418 interfaces:
419     guess_interface(dsi, hostname);
420     return 1;
421 }
422