]> arthur.barton.de Git - netatalk.git/blob - libatalk/dsi/dsi_tcp.c
Fix unnamed union inside struct
[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 /*!
87  * Allocate DSI read buffer and read-ahead buffer
88  */
89 static void dsi_init_buffer(DSI *dsi)
90 {
91     if ((dsi->commands = malloc(dsi->server_quantum)) == NULL) {
92         LOG(log_error, logtype_dsi, "dsi_init_buffer: OOM");
93         AFP_PANIC("OOM in dsi_init_buffer");
94     }
95
96     /* dsi_peek() read ahead buffer, default is 12 * 300k = 3,6 MB (Apr 2011) */
97     if ((dsi->buffer = malloc(dsi->dsireadbuf * dsi->server_quantum)) == NULL) {
98         LOG(log_error, logtype_dsi, "dsi_init_buffer: OOM");
99         AFP_PANIC("OOM in dsi_init_buffer");
100     }
101     dsi->start = dsi->buffer;
102     dsi->eof = dsi->buffer;
103     dsi->end = dsi->buffer + (dsi->dsireadbuf * dsi->server_quantum);
104 }
105
106 /*!
107  * Free any allocated ressources of the master afpd DSI objects and close server socket
108  */
109 void dsi_free(DSI *dsi)
110 {
111     close(dsi->serversock);
112     dsi->serversock = -1;
113
114     free(dsi->commands);
115     dsi->commands = NULL;
116
117     free(dsi->buffer);
118     dsi->buffer = NULL;
119
120 #ifdef USE_ZEROCONF
121     free(dsi->bonjourname);
122     dsi->bonjourname = NULL;
123 #endif
124 }
125
126 static struct itimerval itimer;
127 /* accept the socket and do a little sanity checking */
128 static pid_t dsi_tcp_open(DSI *dsi)
129 {
130     pid_t pid;
131     SOCKLEN_T len;
132
133     len = sizeof(dsi->client);
134     dsi->socket = accept(dsi->serversock, (struct sockaddr *) &dsi->client, &len);
135
136 #ifdef TCPWRAP
137     {
138         struct request_info req;
139         request_init(&req, RQ_DAEMON, "afpd", RQ_FILE, dsi->socket, NULL);
140         fromhost(&req);
141         if (!hosts_access(&req)) {
142             LOG(deny_severity, logtype_dsi, "refused connect from %s", eval_client(&req));
143             close(dsi->socket);
144             errno = ECONNREFUSED;
145             dsi->socket = -1;
146         }
147     }
148 #endif /* TCPWRAP */
149
150     if (dsi->socket < 0)
151         return -1;
152
153     getitimer(ITIMER_PROF, &itimer);
154     if (0 == (pid = fork()) ) { /* child */
155         static struct itimerval timer = {{0, 0}, {DSI_TCPTIMEOUT, 0}};
156         struct sigaction newact, oldact;
157         uint8_t block[DSI_BLOCKSIZ];
158         size_t stored;
159
160         /* reset signals */
161         server_reset_signal();
162
163 #ifndef DEBUGGING
164         /* install an alarm to deal with non-responsive connections */
165         newact.sa_handler = timeout_handler;
166         sigemptyset(&newact.sa_mask);
167         newact.sa_flags = 0;
168         sigemptyset(&oldact.sa_mask);
169         oldact.sa_flags = 0;
170         setitimer(ITIMER_PROF, &itimer, NULL);
171
172         if ((sigaction(SIGALRM, &newact, &oldact) < 0) ||
173             (setitimer(ITIMER_REAL, &timer, NULL) < 0)) {
174             LOG(log_error, logtype_dsi, "dsi_tcp_open: %s", strerror(errno));
175             exit(EXITERR_SYS);
176         }
177 #endif
178
179         dsi_init_buffer(dsi);
180
181         /* read in commands. this is similar to dsi_receive except
182          * for the fact that we do some sanity checking to prevent
183          * delinquent connections from causing mischief. */
184
185         /* read in the first two bytes */
186         len = dsi_stream_read(dsi, block, 2);
187         if (!len ) {
188             /* connection already closed, don't log it (normal OSX 10.3 behaviour) */
189             exit(EXITERR_CLNT);
190         }
191         if (len < 2 || (block[0] > DSIFL_MAX) || (block[1] > DSIFUNC_MAX)) {
192             LOG(log_error, logtype_dsi, "dsi_tcp_open: invalid header");
193             exit(EXITERR_CLNT);
194         }
195
196         /* read in the rest of the header */
197         stored = 2;
198         while (stored < DSI_BLOCKSIZ) {
199             len = dsi_stream_read(dsi, block + stored, sizeof(block) - stored);
200             if (len > 0)
201                 stored += len;
202             else {
203                 LOG(log_error, logtype_dsi, "dsi_tcp_open: stream_read: %s", strerror(errno));
204                 exit(EXITERR_CLNT);
205             }
206         }
207
208         dsi->header.dsi_flags = block[0];
209         dsi->header.dsi_command = block[1];
210         memcpy(&dsi->header.dsi_requestID, block + 2,
211                sizeof(dsi->header.dsi_requestID));
212         memcpy(&dsi->header.dsi_data.dsi_code, block + 4, sizeof(dsi->header.dsi_data.dsi_code));
213         memcpy(&dsi->header.dsi_len, block + 8, sizeof(dsi->header.dsi_len));
214         memcpy(&dsi->header.dsi_reserved, block + 12,
215                sizeof(dsi->header.dsi_reserved));
216         dsi->clientID = ntohs(dsi->header.dsi_requestID);
217
218         /* make sure we don't over-write our buffers. */
219         dsi->cmdlen = min(ntohl(dsi->header.dsi_len), dsi->server_quantum);
220
221         stored = 0;
222         while (stored < dsi->cmdlen) {
223             len = dsi_stream_read(dsi, dsi->commands + stored, dsi->cmdlen - stored);
224             if (len > 0)
225                 stored += len;
226             else {
227                 LOG(log_error, logtype_dsi, "dsi_tcp_open: stream_read: %s", strerror(errno));
228                 exit(EXITERR_CLNT);
229             }
230         }
231
232         /* stop timer and restore signal handler */
233 #ifndef DEBUGGING
234         memset(&timer, 0, sizeof(timer));
235         setitimer(ITIMER_REAL, &timer, NULL);
236         sigaction(SIGALRM, &oldact, NULL);
237 #endif
238
239         LOG(log_info, logtype_dsi, "AFP/TCP session from %s:%u",
240             getip_string((struct sockaddr *)&dsi->client),
241             getip_port((struct sockaddr *)&dsi->client));
242     }
243
244     /* send back our pid */
245     return pid;
246 }
247
248 /* get it from the interface list */
249 #ifndef IFF_SLAVE
250 #define IFF_SLAVE 0
251 #endif
252
253 static void guess_interface(DSI *dsi, const char *hostname, const char *port)
254 {
255     int fd;
256     char **start, **list;
257     struct ifreq ifr;
258     struct sockaddr_in *sa = (struct sockaddr_in *)&dsi->server;
259
260     start = list = getifacelist();
261     if (!start)
262         return;
263         
264     fd = socket(PF_INET, SOCK_STREAM, 0);
265
266     while (list && *list) {
267         strlcpy(ifr.ifr_name, *list, sizeof(ifr.ifr_name));
268         list++;
269
270
271         if (ioctl(dsi->serversock, SIOCGIFFLAGS, &ifr) < 0)
272             continue;
273
274         if (ifr.ifr_flags & (IFF_LOOPBACK | IFF_POINTOPOINT | IFF_SLAVE))
275             continue;
276
277         if (!(ifr.ifr_flags & (IFF_UP | IFF_RUNNING)) )
278             continue;
279
280         if (ioctl(fd, SIOCGIFADDR, &ifr) < 0)
281             continue;
282
283         memset(&dsi->server, 0, sizeof(struct sockaddr_storage));
284         sa->sin_family = AF_INET;
285         sa->sin_port = htons(atoi(port));
286         sa->sin_addr = ((struct sockaddr_in *) &ifr.ifr_addr)->sin_addr;
287
288         LOG(log_info, logtype_dsi, "dsi_tcp: '%s:%s' on interface '%s' will be used instead.",
289             getip_string((struct sockaddr *)&dsi->server), port, ifr.ifr_name);
290         goto iflist_done;
291     }
292
293     LOG(log_note, logtype_dsi, "dsi_tcp: couldn't find network interface with IP address to advertice, "
294         "check to make sure \"%s\" is in /etc/hosts or can be resolved with DNS, or "
295         "add a netinterface that is not a loopback or point-2-point type", hostname);
296
297 iflist_done:
298     close(fd);
299     freeifacelist(start);
300 }
301
302
303 #ifndef AI_NUMERICSERV
304 #define AI_NUMERICSERV 0
305 #endif
306
307 /* this needs to accept passed in addresses */
308 int dsi_tcp_init(DSI *dsi, const char *hostname, const char *inaddress, const char *inport)
309 {
310     EC_INIT;
311     int                flag, err;
312     char               *a = NULL, *b;
313     const char         *address;
314     const char         *port;
315     struct addrinfo    hints, *servinfo, *p;
316
317     /* Check whether address is of the from IP:PORT and split */
318     address = inaddress;
319     port = inport;
320     if (address && strchr(address, ':')) {
321         EC_NULL_LOG( address = a = strdup(address) );
322         b = strchr(a, ':');
323         *b = 0;
324         port = b + 1;
325     }
326
327     /* Prepare hint for getaddrinfo */
328     memset(&hints, 0, sizeof hints);
329 #if !defined(FREEBSD)
330     hints.ai_family = AF_UNSPEC;
331 #endif
332     hints.ai_socktype = SOCK_STREAM;
333     hints.ai_flags = AI_NUMERICSERV;
334
335     if ( ! address) {
336         hints.ai_flags |= AI_PASSIVE;
337 #if defined(FREEBSD)
338         hints.ai_family = AF_INET6;
339 #endif
340     } else {
341         hints.ai_flags |= AI_NUMERICHOST;
342 #if defined(FREEBSD)
343         hints.ai_family = AF_UNSPEC;
344 #endif
345     }
346     if ((ret = getaddrinfo(address ? address : NULL, port, &hints, &servinfo)) != 0) {
347         LOG(log_error, logtype_dsi, "dsi_tcp_init: getaddrinfo: %s\n", gai_strerror(ret));
348         EC_FAIL;
349     }
350
351     /* loop through all the results and bind to the first we can */
352     for (p = servinfo; p != NULL; p = p->ai_next) {
353         if ((dsi->serversock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
354             LOG(log_info, logtype_dsi, "dsi_tcp_init: socket: %s", strerror(errno));
355             continue;
356         }
357
358         /*
359          * Set some socket options:
360          * SO_REUSEADDR deals w/ quick close/opens
361          * TCP_NODELAY diables Nagle
362          */
363 #ifdef SO_REUSEADDR
364         flag = 1;
365         setsockopt(dsi->serversock, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));
366 #endif
367 #if defined(FREEBSD) && defined(IPV6_BINDV6ONLY)
368         int on = 0;
369         setsockopt(dsi->serversock, IPPROTO_IPV6, IPV6_BINDV6ONLY, (char *)&on, sizeof (on));
370 #endif
371
372 #ifndef SOL_TCP
373 #define SOL_TCP IPPROTO_TCP
374 #endif
375         flag = 1;
376         setsockopt(dsi->serversock, SOL_TCP, TCP_NODELAY, &flag, sizeof(flag));
377             
378         if (bind(dsi->serversock, p->ai_addr, p->ai_addrlen) == -1) {
379             close(dsi->serversock);
380             LOG(log_info, logtype_dsi, "dsi_tcp_init: bind: %s\n", strerror(errno));
381             continue;
382         }
383
384         if (listen(dsi->serversock, DSI_TCPMAXPEND) < 0) {
385             close(dsi->serversock);
386             LOG(log_info, logtype_dsi, "dsi_tcp_init: listen: %s\n", strerror(errno));
387             continue;
388         }
389             
390         break;
391     }
392
393     if (p == NULL)  {
394         LOG(log_error, logtype_dsi, "dsi_tcp_init: no suitable network config for TCP socket");
395         freeaddrinfo(servinfo);
396         EC_FAIL;
397     }
398
399     /* Copy struct sockaddr to struct sockaddr_storage */
400     memcpy(&dsi->server, p->ai_addr, p->ai_addrlen);
401     freeaddrinfo(servinfo);
402
403     /* Point protocol specific functions to tcp versions */
404     dsi->proto_open = dsi_tcp_open;
405     dsi->proto_close = dsi_tcp_close;
406
407     /* get real address for GetStatus. */
408
409     if (address) {
410         /* address is a parameter, use it 'as is' */
411         goto EC_CLEANUP;
412     }
413
414     /* Prepare hint for getaddrinfo */
415     memset(&hints, 0, sizeof hints);
416     hints.ai_family = AF_UNSPEC;
417     hints.ai_socktype = SOCK_STREAM;
418
419     if ((err = getaddrinfo(hostname, port, &hints, &servinfo)) != 0) {
420         LOG(log_info, logtype_dsi, "dsi_tcp_init: getaddrinfo '%s': %s\n", hostname, gai_strerror(err));
421         goto interfaces;
422     }
423
424     for (p = servinfo; p != NULL; p = p->ai_next) {
425         if (p->ai_family == AF_INET) { // IPv4
426             struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
427             if ( (ipv4->sin_addr.s_addr & htonl(0x7f000000)) != htonl(0x7f000000) )
428                 break;
429         } else { // IPv6
430             struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
431             unsigned char ipv6loopb[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
432             if ((memcmp(ipv6->sin6_addr.s6_addr, ipv6loopb, 16)) != 0)
433                 break;
434         }
435     }
436
437     if (p) {
438         /* Store found address in dsi->server */
439         memcpy(&dsi->server, p->ai_addr, p->ai_addrlen);
440         freeaddrinfo(servinfo);
441         goto EC_CLEANUP;
442     }
443     LOG(log_info, logtype_dsi, "dsi_tcp: hostname '%s' resolves to loopback address", hostname);
444     freeaddrinfo(servinfo);
445
446 interfaces:
447     guess_interface(dsi, hostname, port ? port : "548");
448
449 EC_CLEANUP:
450     if (a)
451         free(a);
452     EC_EXIT;
453 }
454