]> arthur.barton.de Git - netatalk.git/blob - libatalk/dsi/dsi_tcp.c
2c16323e2d607884e60ceff2dc6371b3f0a92a7b
[netatalk.git] / libatalk / dsi / dsi_tcp.c
1 /*
2  * Copyright (c) 1997, 1998 Adrian Sun (asun@zoology.washington.edu)
3  * All rights reserved. See COPYRIGHT.
4  *
5  * this provides both proto_open() and proto_close() to account for
6  * protocol specific initialization and shutdown procedures. all the
7  * read/write stuff is done in dsi_stream.c.  */
8
9 #ifdef HAVE_CONFIG_H
10 #include "config.h"
11 #endif /* HAVE_CONFIG_H */
12
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <unistd.h>
17 #include <errno.h>
18 #ifdef HAVE_NETDB_H
19 #include <netdb.h>
20 #endif /* HAVE_NETDB_H */
21 #include <sys/types.h>
22 #include <sys/time.h>
23 #include <sys/socket.h>
24 #include <stdint.h>
25
26 #include <sys/ioctl.h>
27 #ifdef TRU64
28 #include <sys/mbuf.h>
29 #include <net/route.h>
30 #endif /* TRU64 */
31 #include <net/if.h>
32 #include <netinet/tcp.h>
33 #include <netinet/in.h>
34 #include <arpa/inet.h>
35
36 #include <signal.h>
37 #include <atalk/logger.h>
38
39 #ifdef __svr4__
40 #include <sys/sockio.h>
41 #endif /* __svr4__ */
42
43 #ifdef TCPWRAP
44 #include <tcpd.h>
45 int allow_severity = log_info;
46 int deny_severity = log_warning;
47 #endif /* TCPWRAP */
48
49 #include <atalk/dsi.h>
50 #include <atalk/compat.h>
51 #include <atalk/util.h>
52 #include <atalk/errchk.h>
53
54 #define min(a,b)  ((a) < (b) ? (a) : (b))
55
56 #ifndef DSI_TCPMAXPEND
57 #define DSI_TCPMAXPEND      20       /* max # of pending connections */
58 #endif /* DSI_TCPMAXPEND */
59
60 #ifndef DSI_TCPTIMEOUT
61 #define DSI_TCPTIMEOUT      120     /* timeout in seconds for connections */
62 #endif /* ! DSI_TCPTIMEOUT */
63
64
65 /* FIXME/SOCKLEN_T: socklen_t is a unix98 feature. */
66 #ifndef SOCKLEN_T
67 #define SOCKLEN_T unsigned int
68 #endif /* ! SOCKLEN_T */
69
70 static void dsi_tcp_close(DSI *dsi)
71 {
72     if (dsi->socket == -1)
73         return;
74
75     close(dsi->socket);
76     dsi->socket = -1;
77 }
78
79 /* alarm handler for tcp_open */
80 static void timeout_handler(int sig _U_)
81 {
82     LOG(log_error, logtype_dsi, "dsi_tcp_open: connection timed out");
83     exit(EXITERR_CLNT);
84 }
85
86 static struct itimerval itimer;
87 /* accept the socket and do a little sanity checking */
88 static int dsi_tcp_open(DSI *dsi)
89 {
90     pid_t pid;
91     SOCKLEN_T len;
92
93     len = sizeof(dsi->client);
94     dsi->socket = accept(dsi->serversock, (struct sockaddr *) &dsi->client, &len);
95
96 #ifdef TCPWRAP
97     {
98         struct request_info req;
99         request_init(&req, RQ_DAEMON, "afpd", RQ_FILE, dsi->socket, NULL);
100         fromhost(&req);
101         if (!hosts_access(&req)) {
102             LOG(deny_severity, logtype_dsi, "refused connect from %s", eval_client(&req));
103             close(dsi->socket);
104             errno = ECONNREFUSED;
105             dsi->socket = -1;
106         }
107     }
108 #endif /* TCPWRAP */
109
110     if (dsi->socket < 0)
111         return -1;
112
113     getitimer(ITIMER_PROF, &itimer);
114     if (0 == (pid = fork()) ) { /* child */
115         static struct itimerval timer = {{0, 0}, {DSI_TCPTIMEOUT, 0}};
116         struct sigaction newact, oldact;
117         uint8_t block[DSI_BLOCKSIZ];
118         size_t stored;
119
120         /* reset signals */
121         server_reset_signal();
122
123 #ifndef DEBUGGING
124         /* install an alarm to deal with non-responsive connections */
125         newact.sa_handler = timeout_handler;
126         sigemptyset(&newact.sa_mask);
127         newact.sa_flags = 0;
128         sigemptyset(&oldact.sa_mask);
129         oldact.sa_flags = 0;
130         setitimer(ITIMER_PROF, &itimer, NULL);
131
132         if ((sigaction(SIGALRM, &newact, &oldact) < 0) ||
133             (setitimer(ITIMER_REAL, &timer, NULL) < 0)) {
134             LOG(log_error, logtype_dsi, "dsi_tcp_open: %s", strerror(errno));
135             exit(EXITERR_SYS);
136         }
137 #endif
138
139         /* read in commands. this is similar to dsi_receive except
140          * for the fact that we do some sanity checking to prevent
141          * delinquent connections from causing mischief. */
142
143         /* read in the first two bytes */
144         len = dsi_stream_read(dsi, block, 2);
145         if (!len ) {
146             /* connection already closed, don't log it (normal OSX 10.3 behaviour) */
147             exit(EXITERR_CLNT);
148         }
149         if (len < 2 || (block[0] > DSIFL_MAX) || (block[1] > DSIFUNC_MAX)) {
150             LOG(log_error, logtype_dsi, "dsi_tcp_open: invalid header");
151             exit(EXITERR_CLNT);
152         }
153
154         /* read in the rest of the header */
155         stored = 2;
156         while (stored < DSI_BLOCKSIZ) {
157             len = dsi_stream_read(dsi, block + stored, sizeof(block) - stored);
158             if (len > 0)
159                 stored += len;
160             else {
161                 LOG(log_error, logtype_dsi, "dsi_tcp_open: stream_read: %s", strerror(errno));
162                 exit(EXITERR_CLNT);
163             }
164         }
165
166         dsi->header.dsi_flags = block[0];
167         dsi->header.dsi_command = block[1];
168         memcpy(&dsi->header.dsi_requestID, block + 2,
169                sizeof(dsi->header.dsi_requestID));
170         memcpy(&dsi->header.dsi_code, block + 4, sizeof(dsi->header.dsi_code));
171         memcpy(&dsi->header.dsi_len, block + 8, sizeof(dsi->header.dsi_len));
172         memcpy(&dsi->header.dsi_reserved, block + 12,
173                sizeof(dsi->header.dsi_reserved));
174         dsi->clientID = ntohs(dsi->header.dsi_requestID);
175
176         /* make sure we don't over-write our buffers. */
177         dsi->cmdlen = min(ntohl(dsi->header.dsi_len), DSI_CMDSIZ);
178
179         stored = 0;
180         while (stored < dsi->cmdlen) {
181             len = dsi_stream_read(dsi, dsi->commands + stored, dsi->cmdlen - stored);
182             if (len > 0)
183                 stored += len;
184             else {
185                 LOG(log_error, logtype_dsi, "dsi_tcp_open: stream_read: %s", strerror(errno));
186                 exit(EXITERR_CLNT);
187             }
188         }
189
190         /* stop timer and restore signal handler */
191 #ifndef DEBUGGING
192         memset(&timer, 0, sizeof(timer));
193         setitimer(ITIMER_REAL, &timer, NULL);
194         sigaction(SIGALRM, &oldact, NULL);
195 #endif
196
197         LOG(log_info, logtype_dsi, "AFP/TCP session from %s:%u",
198             getip_string((struct sockaddr *)&dsi->client),
199             getip_port((struct sockaddr *)&dsi->client));
200     }
201
202     /* send back our pid */
203     return pid;
204 }
205
206 /* get it from the interface list */
207 #ifndef IFF_SLAVE
208 #define IFF_SLAVE 0
209 #endif
210
211 static void guess_interface(DSI *dsi, const char *hostname, const char *port)
212 {
213     int fd;
214     char **start, **list;
215     struct ifreq ifr;
216     struct sockaddr_in *sa = (struct sockaddr_in *)&dsi->server;
217
218     start = list = getifacelist();
219     if (!start)
220         return;
221         
222     fd = socket(PF_INET, SOCK_STREAM, 0);
223
224     while (list && *list) {
225         strlcpy(ifr.ifr_name, *list, sizeof(ifr.ifr_name));
226         list++;
227
228
229         if (ioctl(dsi->serversock, SIOCGIFFLAGS, &ifr) < 0)
230             continue;
231
232         if (ifr.ifr_flags & (IFF_LOOPBACK | IFF_POINTOPOINT | IFF_SLAVE))
233             continue;
234
235         if (!(ifr.ifr_flags & (IFF_UP | IFF_RUNNING)) )
236             continue;
237
238         if (ioctl(fd, SIOCGIFADDR, &ifr) < 0)
239             continue;
240
241         memset(&dsi->server, 0, sizeof(struct sockaddr_storage));
242         sa->sin_family = AF_INET;
243         sa->sin_port = htons(atoi(port));
244         sa->sin_addr = ((struct sockaddr_in *) &ifr.ifr_addr)->sin_addr;
245
246         LOG(log_info, logtype_dsi, "dsi_tcp: '%s:%s' on interface '%s' will be used instead.",
247             getip_string((struct sockaddr *)&dsi->server), port, ifr.ifr_name);
248         goto iflist_done;
249     }
250
251     LOG(log_note, logtype_dsi, "dsi_tcp: couldn't find network interface with IP address to advertice, "
252         "check to make sure \"%s\" is in /etc/hosts or can be resolved with DNS, or "
253         "add a netinterface that is not a loopback or point-2-point type", hostname);
254
255 iflist_done:
256     close(fd);
257     freeifacelist(start);
258 }
259
260
261 #ifndef AI_NUMERICSERV
262 #define AI_NUMERICSERV 0
263 #endif
264
265 /* this needs to accept passed in addresses */
266 int dsi_tcp_init(DSI *dsi, const char *hostname, const char *inaddress, const char *inport)
267 {
268     EC_INIT;
269     int                flag, err;
270     char               *a = NULL, *b;
271     const char         *address;
272     const char         *port;
273     struct addrinfo    hints, *servinfo, *p;
274
275     /* Check whether address is of the from IP:PORT and split */
276     address = inaddress;
277     port = inport;
278     if (address && strchr(address, ':')) {
279         EC_NULL_LOG( address = a = strdup(address) );
280         b = strchr(a, ':');
281         *b = 0;
282         port = b + 1;
283     }
284
285     /* Prepare hint for getaddrinfo */
286     memset(&hints, 0, sizeof hints);
287 #if !defined(FREEBSD)
288     hints.ai_family = AF_UNSPEC;
289 #endif
290     hints.ai_socktype = SOCK_STREAM;
291     hints.ai_flags = AI_NUMERICSERV;
292
293     if ( ! address) {
294         hints.ai_flags |= AI_PASSIVE;
295 #if defined(FREEBSD)
296         hints.ai_family = AF_INET6;
297 #endif
298     } else {
299         hints.ai_flags |= AI_NUMERICHOST;
300 #if defined(FREEBSD)
301         hints.ai_family = AF_UNSPEC;
302 #endif
303     }
304     if ((ret = getaddrinfo(address ? address : NULL, port, &hints, &servinfo)) != 0) {
305         LOG(log_error, logtype_dsi, "dsi_tcp_init: getaddrinfo: %s\n", gai_strerror(ret));
306         EC_FAIL;
307     }
308
309     /* loop through all the results and bind to the first we can */
310     for (p = servinfo; p != NULL; p = p->ai_next) {
311         if ((dsi->serversock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
312             LOG(log_info, logtype_dsi, "dsi_tcp_init: socket: %s", strerror(errno));
313             continue;
314         }
315
316         /*
317          * Set some socket options:
318          * SO_REUSEADDR deals w/ quick close/opens
319          * TCP_NODELAY diables Nagle
320          */
321 #ifdef SO_REUSEADDR
322         flag = 1;
323         setsockopt(dsi->serversock, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));
324 #endif
325 #if defined(FREEBSD) && defined(IPV6_BINDV6ONLY)
326         int on = 0;
327         setsockopt(dsi->serversock, IPPROTO_IPV6, IPV6_BINDV6ONLY, (char *)&on, sizeof (on));
328 #endif
329
330 #ifndef SOL_TCP
331 #define SOL_TCP IPPROTO_TCP
332 #endif
333         flag = 1;
334         setsockopt(dsi->serversock, SOL_TCP, TCP_NODELAY, &flag, sizeof(flag));
335             
336         if (bind(dsi->serversock, p->ai_addr, p->ai_addrlen) == -1) {
337             close(dsi->serversock);
338             LOG(log_info, logtype_dsi, "dsi_tcp_init: bind: %s\n", strerror(errno));
339             continue;
340         }
341
342         if (listen(dsi->serversock, DSI_TCPMAXPEND) < 0) {
343             close(dsi->serversock);
344             LOG(log_info, logtype_dsi, "dsi_tcp_init: listen: %s\n", strerror(errno));
345             continue;
346         }
347             
348         break;
349     }
350
351     if (p == NULL)  {
352         LOG(log_error, logtype_dsi, "dsi_tcp_init: no suitable network config for TCP socket");
353         freeaddrinfo(servinfo);
354         EC_FAIL;
355     }
356
357     /* Copy struct sockaddr to struct sockaddr_storage */
358     memcpy(&dsi->server, p->ai_addr, p->ai_addrlen);
359     freeaddrinfo(servinfo);
360
361     /* Point protocol specific functions to tcp versions */
362     dsi->proto_open = dsi_tcp_open;
363     dsi->proto_close = dsi_tcp_close;
364
365     /* get real address for GetStatus. */
366
367     if (address) {
368         /* address is a parameter, use it 'as is' */
369         goto EC_CLEANUP;
370     }
371
372     /* Prepare hint for getaddrinfo */
373     memset(&hints, 0, sizeof hints);
374     hints.ai_family = AF_UNSPEC;
375     hints.ai_socktype = SOCK_STREAM;
376
377     if ((err = getaddrinfo(hostname, port, &hints, &servinfo)) != 0) {
378         LOG(log_info, logtype_dsi, "dsi_tcp_init: getaddrinfo '%s': %s\n", hostname, gai_strerror(err));
379         goto interfaces;
380     }
381
382     for (p = servinfo; p != NULL; p = p->ai_next) {
383         if (p->ai_family == AF_INET) { // IPv4
384             struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
385             if ( (ipv4->sin_addr.s_addr & htonl(0x7f000000)) != htonl(0x7f000000) )
386                 break;
387         } else { // IPv6
388             struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
389             unsigned char ipv6loopb[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
390             if ((memcmp(ipv6->sin6_addr.s6_addr, ipv6loopb, 16)) != 0)
391                 break;
392         }
393     }
394
395     if (p) {
396         /* Store found address in dsi->server */
397         memcpy(&dsi->server, p->ai_addr, p->ai_addrlen);
398         freeaddrinfo(servinfo);
399         goto EC_CLEANUP;
400     }
401     LOG(log_info, logtype_dsi, "dsi_tcp: hostname '%s' resolves to loopback address", hostname);
402     freeaddrinfo(servinfo);
403
404 interfaces:
405     guess_interface(dsi, hostname, port ? port : "548");
406
407 EC_CLEANUP:
408     if (a)
409         free(a);
410     EC_EXIT;
411 }
412