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