]> arthur.barton.de Git - netatalk.git/blob - libatalk/util/socket.c
Hangs in Netatalk which causes it to stop responding to connections
[netatalk.git] / libatalk / util / socket.c
1 /*
2    Copyright (c) 2009 Frank Lahm <franklahm@gmail.com>
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2 of the License, or
7    (at your option) any later version.
8  
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13 */
14
15 /*!
16  * @file
17  * Netatalk utility functions
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #include "config.h"
22 #endif /* HAVE_CONFIG_H */
23
24 #include <atalk/standards.h>
25
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include <sys/types.h>
29 #include <sys/socket.h>
30 #include <sys/uio.h>
31 #include <netinet/in.h>
32 #include <arpa/inet.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <errno.h>
36 #include <sys/time.h>
37 #include <time.h>
38 #include <sys/ioctl.h>
39
40 #include <atalk/logger.h>
41 #include <atalk/util.h>
42 #include <atalk/errchk.h>
43
44 static char ipv4mapprefix[] = {0,0,0,0,0,0,0,0,0,0,0xff,0xff};
45
46 /*!
47  * @brief set or unset non-blocking IO on a fd
48  *
49  * @param     fd         (r) File descriptor
50  * @param     cmd        (r) 0: disable non-blocking IO, ie block\n
51  *                           <>0: enable non-blocking IO
52  *
53  * @returns   0 on success, -1 on failure
54  */
55 int setnonblock(int fd, int cmd)
56 {
57     int ofdflags;
58     int fdflags;
59
60     if ((fdflags = ofdflags = fcntl(fd, F_GETFL, 0)) == -1)
61         return -1;
62
63     if (cmd)
64         fdflags |= O_NONBLOCK;
65     else
66         fdflags &= ~O_NONBLOCK;
67
68     if (fdflags != ofdflags)
69         if (fcntl(fd, F_SETFL, fdflags) == -1)
70             return -1;
71
72     return 0;
73 }
74
75 /*!
76  * non-blocking drop-in replacement for read with timeout using select
77  *
78  * @param socket          (r)  socket, if in blocking mode, pass "setnonblocking" arg as 1
79  * @param data            (rw) buffer for the read data
80  * @param lenght          (r)  how many bytes to read
81  * @param setnonblocking  (r)  when non-zero this func will enable and disable non blocking
82  *                             io mode for the socket
83  * @param timeout         (r)  number of seconds to try reading, 0 means no timeout
84  *
85  * @returns number of bytes actually read or -1 on timeout or error
86  */
87 ssize_t readt(int socket, void *data, const size_t length, int setnonblocking, int timeout)
88 {
89     size_t stored = 0;
90     ssize_t len = 0;
91     struct timeval now, end, tv;
92     fd_set rfds;
93     int ret;
94
95     FD_ZERO(&rfds);
96
97     if (setnonblocking) {
98         if (setnonblock(socket, 1) != 0)
99             return -1;
100     }
101
102     /* Calculate end time */
103     if (timeout) {
104         (void)gettimeofday(&now, NULL);
105         end = now;
106         end.tv_sec += timeout;
107     }
108
109     while (stored < length) {
110         len = recv(socket, (char *) data + stored, length - stored, 0);
111         if (len == -1) {
112             switch (errno) {
113             case EINTR:
114                 continue;
115             case EAGAIN:
116                 FD_SET(socket, &rfds);
117                 if (timeout) {
118                     tv.tv_usec = 0;
119                     tv.tv_sec  = timeout;
120                 }
121
122                 while ((ret = select(socket + 1, &rfds, NULL, NULL, timeout ? &tv : NULL)) < 1) {
123                     switch (ret) {
124                     case 0:
125                         LOG(log_debug, logtype_dsi, "select timeout %d s", timeout);
126                         errno = EAGAIN;
127                         goto exit;
128
129                     default: /* -1 */
130                         switch (errno) {
131                         case EINTR:
132                             if (timeout) {
133                                 (void)gettimeofday(&now, NULL);
134                                 if (now.tv_sec > end.tv_sec
135                                     ||
136                                     (now.tv_sec == end.tv_sec && now.tv_usec >= end.tv_usec)) {
137                                     LOG(log_debug, logtype_afpd, "select timeout %d s", timeout);
138                                     goto exit;
139                                 }
140                                 if (now.tv_usec > end.tv_usec) {
141                                     tv.tv_usec = 1000000 + end.tv_usec - now.tv_usec;
142                                     tv.tv_sec  = end.tv_sec - now.tv_sec - 1;
143                                 } else {
144                                     tv.tv_usec = end.tv_usec - now.tv_usec;
145                                     tv.tv_sec  = end.tv_sec - now.tv_sec;
146                                 }
147                             }
148                             FD_SET(socket, &rfds);
149                             continue;
150                         case EBADF:
151                             /* possibly entered disconnected state, don't spam log here */
152                             LOG(log_debug, logtype_afpd, "select: %s", strerror(errno));
153                             stored = -1;
154                             goto exit;
155                         default:
156                             LOG(log_error, logtype_afpd, "select: %s", strerror(errno));
157                             stored = -1;
158                             goto exit;
159                         }
160                     }
161                 } /* while (select) */
162                 continue;
163             } /* switch (errno) */
164             LOG(log_error, logtype_afpd, "read: %s", strerror(errno));
165             stored = -1;
166             goto exit;
167         } /* (len == -1) */
168         else if (len > 0)
169             stored += len;
170         else
171             break;
172     } /* while (stored < length) */
173
174 exit:
175     if (setnonblocking) {
176         if (setnonblock(socket, 0) != 0)
177             return -1;
178     }
179
180     if (len == -1 && stored == 0)
181         /* last read or select got an error and we haven't got yet anything => return -1*/
182         return -1;
183     return stored;
184 }
185
186 /*!
187  * non-blocking drop-in replacement for read with timeout using select
188  *
189  * @param socket          (r)  socket, if in blocking mode, pass "setnonblocking" arg as 1
190  * @param data            (rw) buffer for the read data
191  * @param lenght          (r)  how many bytes to read
192  * @param setnonblocking  (r)  when non-zero this func will enable and disable non blocking
193  *                             io mode for the socket
194  * @param timeout         (r)  number of seconds to try reading
195  *
196  * @returns number of bytes actually read or -1 on fatal error
197  */
198 ssize_t writet(int socket, void *data, const size_t length, int setnonblocking, int timeout)
199 {
200     size_t stored = 0;
201     ssize_t len = 0;
202     struct timeval now, end, tv;
203     fd_set rfds;
204     int ret;
205
206     if (setnonblocking) {
207         if (setnonblock(socket, 1) != 0)
208             return -1;
209     }
210
211     /* Calculate end time */
212     (void)gettimeofday(&now, NULL);
213     end = now;
214     end.tv_sec += timeout;
215
216     while (stored < length) {
217         len = write(socket, (char *) data + stored, length - stored);
218         if (len == -1) {
219             switch (errno) {
220             case EINTR:
221                 continue;
222             case EAGAIN:
223                 FD_ZERO(&rfds);
224                 FD_SET(socket, &rfds);
225                 tv.tv_usec = 0;
226                 tv.tv_sec  = timeout;
227                         
228                 while ((ret = select(socket + 1, &rfds, NULL, NULL, &tv)) < 1) {
229                     switch (ret) {
230                     case 0:
231                         LOG(log_warning, logtype_afpd, "select timeout %d s", timeout);
232                         goto exit;
233
234                     default: /* -1 */
235                         if (errno == EINTR) {
236                             (void)gettimeofday(&now, NULL);
237                             if (now.tv_sec >= end.tv_sec && now.tv_usec >= end.tv_usec) {
238                                 LOG(log_warning, logtype_afpd, "select timeout %d s", timeout);
239                                 goto exit;
240                             }
241                             if (now.tv_usec > end.tv_usec) {
242                                 tv.tv_usec = 1000000 + end.tv_usec - now.tv_usec;
243                                 tv.tv_sec  = end.tv_sec - now.tv_sec - 1;
244                             } else {
245                                 tv.tv_usec = end.tv_usec - now.tv_usec;
246                                 tv.tv_sec  = end.tv_sec - now.tv_sec;
247                             }
248                             FD_ZERO(&rfds);
249                             FD_SET(socket, &rfds);
250                             continue;
251                         }
252                         LOG(log_error, logtype_afpd, "select: %s", strerror(errno));
253                         stored = -1;
254                         goto exit;
255                     }
256                 } /* while (select) */
257                 continue;
258             } /* switch (errno) */
259             LOG(log_error, logtype_afpd, "read: %s", strerror(errno));
260             stored = -1;
261             goto exit;
262         } /* (len == -1) */
263         else if (len > 0)
264             stored += len;
265         else
266             break;
267     } /* while (stored < length) */
268
269 exit:
270     if (setnonblocking) {
271         if (setnonblock(socket, 0) != 0)
272             return -1;
273     }
274
275     if (len == -1 && stored == 0)
276         /* last read or select got an error and we haven't got yet anything => return -1*/
277         return -1;
278     return stored;
279 }
280
281 /*!
282  * @brief convert an IPv4 or IPv6 address to a static string using inet_ntop
283  *
284  * IPv6 mapped IPv4 addresses are returned as IPv4 addreses eg
285  * ::ffff:10.0.0.0 is returned as "10.0.0.0".
286  *
287  * @param  sa        (r) pointer to an struct sockaddr
288  *
289  * @returns pointer to a static string cotaining the converted address as string.\n
290  *          On error pointers to "0.0.0.0" or "::0" are returned.
291  */
292 const char *getip_string(const struct sockaddr *sa)
293 {
294     static char ip4[INET_ADDRSTRLEN];
295     static char ip6[INET6_ADDRSTRLEN];
296
297     switch (sa->sa_family) {
298
299     case AF_INET: {
300         const struct sockaddr_in *sai4 = (const struct sockaddr_in *)sa;
301         if ((inet_ntop(AF_INET, &(sai4->sin_addr), ip4, INET_ADDRSTRLEN)) == NULL)
302             return "0.0.0.0";
303         return ip4;
304     }
305     case AF_INET6: {
306         const struct sockaddr_in6 *sai6 = (const struct sockaddr_in6 *)sa;
307         if ((inet_ntop(AF_INET6, &(sai6->sin6_addr), ip6, INET6_ADDRSTRLEN)) == NULL)
308             return "::0";
309
310         /* Deal with IPv6 mapped IPv4 addresses*/
311         if ((memcmp(sai6->sin6_addr.s6_addr, ipv4mapprefix, sizeof(ipv4mapprefix))) == 0)
312             return (strrchr(ip6, ':') + 1);
313         return ip6;
314     }
315     default:
316         return "getip_string ERROR";
317     }
318
319     /* We never get here */
320 }
321
322 /*!
323  * @brief return port number from struct sockaddr
324  *
325  * @param  sa        (r) pointer to an struct sockaddr
326  *
327  * @returns port as unsigned int
328  */
329 unsigned int getip_port(const struct sockaddr  *sa)
330 {
331     if (sa->sa_family == AF_INET) { /* IPv4 */
332         const struct sockaddr_in *sai4 = (const struct sockaddr_in *)sa;
333         return ntohs(sai4->sin_port);
334     } else {                       /* IPv6 */
335         const struct sockaddr_in6 *sai6 = (const struct sockaddr_in6 *)sa;
336         return ntohs(sai6->sin6_port);
337     }
338
339     /* We never get here */
340 }
341
342 /*!
343  * @brief apply netmask to IP (v4 or v6)
344  *
345  * Modifies IP address in sa->sin[6]_addr-s[6]_addr. The caller is responsible
346  * for passing a value for mask that is sensible to the passed address,
347  * eg 0 <= mask <= 32 for IPv4 or 0<= mask <= 128 for IPv6. mask > 32 for
348  * IPv4 is treated as mask = 32, mask > 128 is set to 128 for IPv6.
349  *
350  * @param  ai        (rw) pointer to an struct sockaddr
351  * @parma  mask      (r) number of maskbits
352  */
353 void apply_ip_mask(struct sockaddr *sa, int mask)
354 {
355
356     switch (sa->sa_family) {
357     case AF_INET: {
358         if (mask >= 32)
359             return;
360
361         struct sockaddr_in *si = (struct sockaddr_in *)sa;
362         uint32_t nmask = mask ? ~((1 << (32 - mask)) - 1) : 0;
363         si->sin_addr.s_addr &= htonl(nmask);
364         break;
365     }
366     case AF_INET6: {
367         if (mask >= 128)
368             return;
369
370         int i, maskbytes, maskbits;
371         struct sockaddr_in6 *si6 = (struct sockaddr_in6 *)sa;
372
373         /* Deal with IPv6 mapped IPv4 addresses*/
374         if ((memcmp(si6->sin6_addr.s6_addr, ipv4mapprefix, sizeof(ipv4mapprefix))) == 0) {
375             mask += 96;
376             if (mask >= 128)
377                 return;
378         }
379
380         maskbytes = (128 - mask) / 8; /* maskbytes really are those that will be 0'ed */
381         maskbits = mask % 8;
382
383         for (i = maskbytes - 1; i >= 0; i--)
384             si6->sin6_addr.s6_addr[15 - i] = 0;
385         if (maskbits)
386             si6->sin6_addr.s6_addr[15 - maskbytes] &= ~((1 << (8 - maskbits)) - 1);
387         break;
388     }
389     default:
390         break;
391     }
392 }
393
394 /*!
395  * @brief compare IP addresses for equality
396  *
397  * @param  sa1       (r) pointer to an struct sockaddr
398  * @param  sa2       (r) pointer to an struct sockaddr
399  *
400  * @returns Addresses are converted to strings and compared with strcmp and
401  *          the result of strcmp is returned.
402  *
403  * @note IPv6 mapped IPv4 addresses are treated as IPv4 addresses.
404  */
405 int compare_ip(const struct sockaddr *sa1, const struct sockaddr *sa2)
406 {
407     int ret;
408     char *ip1;
409     const char *ip2;
410
411     ip1 = strdup(getip_string(sa1));
412     ip2 = getip_string(sa2);
413
414     ret = strcmp(ip1, ip2);
415
416     free(ip1);
417
418     return ret;
419 }
420
421 /*!
422  * Tokenize IP(4/6) addresses with an optional port into address and port
423  *
424  * @param ipurl    (r) IP URL string
425  * @param address  (w) IP address
426  * @param port     (w) IP port
427  *
428  * @returns 0 on success, -1 on failure
429  *
430  * Tokenize IPv4, IPv4:port, IPv6, [IPv6] or [IPv6:port] URL into address and
431  * port and return two allocated strings with the address and the port.
432  *
433  * If the function returns 0, then address point to a newly allocated
434  * valid address string, port may either be NULL or point to a newly
435  * allocated port number.
436  *
437  * If the function returns -1, then the contents of address and port are
438  * undefined.
439  */
440 int tokenize_ip_port(const char *ipurl, char **address, char **port)
441 {
442     EC_INIT;
443     char *p = NULL;
444     char *s;
445
446     AFP_ASSERT(ipurl && address && port);
447     EC_NULL( p = strdup(ipurl));
448
449     /* Either ipv4, ipv4:port, ipv6, [ipv6] or [ipv6]:port */
450
451     if (!strchr(p, ':')) {
452         /* IPv4 address without port */
453         *address = p;
454         p = NULL;  /* prevent free() */
455         *port = NULL;
456         EC_EXIT_STATUS(0);
457     }
458
459     /* Either ipv4:port, ipv6, [ipv6] or [ipv6]:port */
460
461     if (strchr(p, '.')) {
462         /* ipv4:port */
463         *address = p;
464         p = strchr(p, ':');
465         *p = '\0';
466         EC_NULL( *port = strdup(p + 1));
467         p = NULL; /* prevent free() */
468         EC_EXIT_STATUS(0);
469     }
470
471     /* Either ipv6, [ipv6] or [ipv6]:port */
472
473     if (p[0] != '[') {
474         /* ipv6 */
475         *address = p;
476         p = NULL;  /* prevent free() */
477         *port = NULL;
478         EC_EXIT_STATUS(0);
479     }
480
481     /* [ipv6] or [ipv6]:port */
482
483     EC_NULL( *address = strdup(p + 1) );
484
485     if ((s = strchr(*address, ']')) == NULL) {
486         LOG(log_error, logtype_dsi, "tokenize_ip_port: malformed ipv6 address %s\n", ipurl);
487         EC_FAIL;
488     }
489     *s = '\0';
490     /* address now points to the ipv6 address without [] */
491
492     if (s[1] == ':') {
493         /* [ipv6]:port */
494         EC_NULL( *port = strdup(s + 2) );
495     } else {
496         /* [ipv6] */
497         *port = NULL;
498     }
499
500 EC_CLEANUP:
501     if (p)
502         free(p);
503     EC_EXIT;
504 }
505
506 /**
507  * Allocate and initialize atalk socket event struct
508  **/
509 struct asev *asev_init(int max)
510 {
511     struct asev *asev = calloc(1, sizeof(struct asev));
512
513     if (asev == NULL) {
514         return NULL;
515     }
516
517     /* Initialize with space for all possibly active fds */
518     asev->fdset = calloc(max, sizeof(struct pollfd));
519     asev->data = calloc(max, sizeof(struct asev_data));
520
521     if (asev->fdset == NULL || asev->data == NULL) {
522         free(asev->fdset);
523         free(asev->data);
524         free(asev);
525         return NULL;
526     }
527
528     asev->max = max;
529     asev->used = 0;
530
531     return asev;
532 }
533
534 /**
535  * Add a fd to a dynamic pollfd array and associated data array
536  *
537  * This uses an additional array of struct polldata which stores type
538  * information (enum fdtype) and a pointer to anciliary user data.
539  **/
540 bool asev_add_fd(struct asev *asev,
541                  int fd,
542                  enum asev_fdtype fdtype,
543                  void *private)
544 {
545     if (asev == NULL) {
546         return false;
547     }
548
549     if (!(asev->used < asev->max)) {
550         return false;
551     }
552
553     asev->fdset[asev->used].fd = fd;
554     asev->fdset[asev->used].events = POLLIN;
555     asev->data[asev->used].fdtype = fdtype;
556     asev->data[asev->used].private = private;
557     asev->used++;
558
559     return true;
560 }
561
562 /**
563  * Remove fd from asev
564  *
565  * @returns true if the fd was deleted, otherwise false
566  **/
567 bool asev_del_fd(struct asev *asev, int fd)
568 {
569     int i;
570     int numafter;
571
572     if (asev == NULL) {
573         return false;
574     }
575
576     if (asev->used == 0) {
577         LOG(log_error, logtype_cnid, "asev_del_fd: empty");
578         return false;
579     }
580
581     for (i = 0; i < asev->used; i++) {
582         /*
583          * Scan the array for a matching fd
584          */
585         if (asev->fdset[i].fd == fd) {
586             /*
587              * found fd
588              */
589             if ((i + 1) == asev->used) {
590                 /*
591                  * it's the last (or only) array element, simply null it
592                  */
593                 asev->fdset[i].fd = -1;
594                 asev->data[i].fdtype = 0;
595                 asev->data[i].private = NULL;
596             } else {
597                 /*
598                  * Move down by one all subsequent elements
599                  */
600                 numafter = asev->used - (i + 1);
601                 memmove(&asev->fdset[i], &asev->fdset[i+1],
602                         numafter * sizeof(struct pollfd));
603                 memmove(&asev->data[i], &asev->data[i+1],
604                         numafter * sizeof(struct asev_data));
605             }
606             asev->used--;
607             return true;
608         }
609     }
610
611     return false;
612 }
613
614 /* Length of the space taken up by a padded control message of length len */
615 #ifndef CMSG_SPACE
616 #define CMSG_SPACE(len) (__CMSG_ALIGN(sizeof(struct cmsghdr)) + __CMSG_ALIGN(len))
617 #endif
618
619 /*
620  * Receive a fd on a suitable socket
621  * @args fd          (r) PF_UNIX socket to receive on
622  * @args nonblocking (r) 0: fd is in blocking mode - 1: fd is nonblocking, poll for 1 sec
623  * @returns fd on success, -1 on error
624  */
625 int recv_fd(int fd, int nonblocking)
626 {
627     int ret;
628     struct msghdr msgh;
629     struct iovec iov[1];
630     struct cmsghdr *cmsgp = NULL;
631     char buf[CMSG_SPACE(sizeof(int))];
632     char dbuf[80];
633     struct pollfd pollfds[1];
634
635     pollfds[0].fd = fd;
636     pollfds[0].events = POLLIN;
637
638     memset(&msgh,0,sizeof(msgh));
639     memset(buf,0,sizeof(buf));
640
641     msgh.msg_name = NULL;
642     msgh.msg_namelen = 0;
643
644     msgh.msg_iov = iov;
645     msgh.msg_iovlen = 1;
646
647     iov[0].iov_base = dbuf;
648     iov[0].iov_len = sizeof(dbuf);
649
650     msgh.msg_control = buf;
651     msgh.msg_controllen = sizeof(buf);
652
653     if (nonblocking) {
654         do {
655             ret = poll(pollfds, 1, 2000); /* poll 2 seconds, evtl. multipe times (EINTR) */
656         } while ( ret == -1 && errno == EINTR );
657         if (ret != 1)
658             return -1;
659         ret = recvmsg(fd, &msgh, 0);
660     } else {
661         do  {
662             ret = recvmsg(fd, &msgh, 0);
663         } while ( ret == -1 && errno == EINTR );
664     }
665
666     if ( ret == -1 ) {
667         return -1;
668     }
669
670     for ( cmsgp = CMSG_FIRSTHDR(&msgh); cmsgp != NULL; cmsgp = CMSG_NXTHDR(&msgh,cmsgp) ) {
671         if ( cmsgp->cmsg_level == SOL_SOCKET && cmsgp->cmsg_type == SCM_RIGHTS ) {
672             return *(int *) CMSG_DATA(cmsgp);
673         }
674     }
675
676     if ( ret == sizeof (int) )
677         errno = *(int *)dbuf; /* Rcvd errno */
678     else
679         errno = ENOENT;    /* Default errno */
680
681     return -1;
682 }
683
684 /*
685  * Send a fd across a suitable socket
686  */
687 int send_fd(int socket, int fd)
688 {
689     int ret;
690     struct msghdr msgh;
691     struct iovec iov[1];
692     struct cmsghdr *cmsgp = NULL;
693     char *buf;
694     size_t size;
695     int er=0;
696
697     size = CMSG_SPACE(sizeof fd);
698     buf = malloc(size);
699     if (!buf) {
700         LOG(log_error, logtype_cnid, "error in sendmsg: %s", strerror(errno));
701         return -1;
702     }
703
704     memset(&msgh,0,sizeof (msgh));
705     memset(buf,0, size);
706
707     msgh.msg_name = NULL;
708     msgh.msg_namelen = 0;
709
710     msgh.msg_iov = iov;
711     msgh.msg_iovlen = 1;
712
713     iov[0].iov_base = &er;
714     iov[0].iov_len = sizeof(er);
715
716     msgh.msg_control = buf;
717     msgh.msg_controllen = size;
718
719     cmsgp = CMSG_FIRSTHDR(&msgh);
720     cmsgp->cmsg_level = SOL_SOCKET;
721     cmsgp->cmsg_type = SCM_RIGHTS;
722     cmsgp->cmsg_len = CMSG_LEN(sizeof(fd));
723
724     *((int *)CMSG_DATA(cmsgp)) = fd;
725     msgh.msg_controllen = cmsgp->cmsg_len;
726
727     do  {
728         ret = sendmsg(socket,&msgh, 0);
729     } while ( ret == -1 && errno == EINTR );
730     if (ret == -1) {
731         LOG(log_error, logtype_cnid, "error in sendmsg: %s", strerror(errno));
732         free(buf);
733         return -1;
734     }
735     free(buf);
736     return 0;
737 }