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