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