]> arthur.barton.de Git - netatalk.git/blob - libatalk/util/socket.c
8d2300f2c908cadc4413331134f431fa51ca23ec
[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 #if !defined(__FreeBSD__)
25 # ifndef _XOPEN_SOURCE
26 #  define _XOPEN_SOURCE 600
27 # endif
28 # ifndef __EXTENSIONS__
29 #  define __EXTENSIONS__
30 # endif
31 # ifndef _GNU_SOURCE
32 #  define _GNU_SOURCE
33 # endif
34 #endif
35 #include <unistd.h>
36 #include <fcntl.h>
37 #include <sys/types.h>
38 #include <sys/socket.h>
39 #include <arpa/inet.h>
40 #include <netinet/in.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <errno.h>
44 #include <sys/time.h>
45 #include <time.h>
46 #include <sys/ioctl.h>
47
48 #include <atalk/logger.h>
49 #include <atalk/util.h>
50
51 static char ipv4mapprefix[] = {0,0,0,0,0,0,0,0,0,0,0xff,0xff};
52
53 /*!
54  * @brief set or unset non-blocking IO on a fd
55  *
56  * @param     fd         (r) File descriptor
57  * @param     cmd        (r) 0: disable non-blocking IO, ie block\n
58  *                           <>0: enable non-blocking IO
59  *
60  * @returns   0 on success, -1 on failure
61  */
62 int setnonblock(int fd, int cmd)
63 {
64     int ofdflags;
65     int fdflags;
66
67     if ((fdflags = ofdflags = fcntl(fd, F_GETFL, 0)) == -1)
68         return -1;
69
70     if (cmd)
71         fdflags |= O_NONBLOCK;
72     else
73         fdflags &= ~O_NONBLOCK;
74
75     if (fdflags != ofdflags)
76         if (fcntl(fd, F_SETFL, fdflags) == -1)
77             return -1;
78
79     return 0;
80 }
81
82 /*!
83  * non-blocking drop-in replacement for read with timeout using select
84  *
85  * @param socket          (r)  socket, if in blocking mode, pass "setnonblocking" arg as 1
86  * @param data            (rw) buffer for the read data
87  * @param lenght          (r)  how many bytes to read
88  * @param setnonblocking  (r)  when non-zero this func will enable and disable non blocking
89  *                             io mode for the socket
90  * @param timeout         (r)  number of seconds to try reading
91  *
92  * @returns number of bytes actually read or -1 on timeout or error
93  */
94 ssize_t readt(int socket, void *data, const size_t length, int setnonblocking, int timeout)
95 {
96     size_t stored = 0;
97     ssize_t len = 0;
98     struct timeval now, end, tv;
99     fd_set rfds;
100     int ret;
101
102     FD_ZERO(&rfds);
103
104     if (setnonblocking) {
105         if (setnonblock(socket, 1) != 0)
106             return -1;
107     }
108
109     /* Calculate end time */
110     (void)gettimeofday(&now, NULL);
111     end = now;
112     end.tv_sec += timeout;
113
114     while (stored < length) {
115         len = read(socket, (char *) data + stored, length - stored);
116         if (len == -1) {
117             switch (errno) {
118             case EINTR:
119                 continue;
120             case EAGAIN:
121                 FD_SET(socket, &rfds);
122                 tv.tv_usec = 0;
123                 tv.tv_sec  = timeout;
124                         
125                 while ((ret = select(socket + 1, &rfds, NULL, NULL, &tv)) < 1) {
126                     switch (ret) {
127                     case 0:
128                         LOG(log_debug, logtype_afpd, "select timeout %d s", timeout);
129                         errno = EAGAIN;
130                         goto exit;
131
132                     default: /* -1 */
133                         switch (errno) {
134                         case EINTR:
135                             (void)gettimeofday(&now, NULL);
136                             if (now.tv_sec > end.tv_sec
137                                 ||
138                                 (now.tv_sec == end.tv_sec && now.tv_usec >= end.tv_usec)) {
139                                 LOG(log_debug, logtype_afpd, "select timeout %d s", timeout);
140                                 goto exit;
141                             }
142                             if (now.tv_usec > end.tv_usec) {
143                                 tv.tv_usec = 1000000 + end.tv_usec - now.tv_usec;
144                                 tv.tv_sec  = end.tv_sec - now.tv_sec - 1;
145                             } else {
146                                 tv.tv_usec = end.tv_usec - now.tv_usec;
147                                 tv.tv_sec  = end.tv_sec - now.tv_sec;
148                             }
149                             FD_SET(socket, &rfds);
150                             continue;
151                         case EBADF:
152                             /* possibly entered disconnected state, don't spam log here */
153                             LOG(log_debug, logtype_afpd, "select: %s", strerror(errno));
154                             stored = -1;
155                             goto exit;
156                         default:
157                             LOG(log_error, logtype_afpd, "select: %s", strerror(errno));
158                             stored = -1;
159                             goto exit;
160                         }
161                     }
162                 } /* while (select) */
163                 continue;
164             } /* switch (errno) */
165             LOG(log_error, logtype_afpd, "read: %s", strerror(errno));
166             stored = -1;
167             goto exit;
168         } /* (len == -1) */
169         else if (len > 0)
170             stored += len;
171         else
172             break;
173     } /* while (stored < length) */
174
175 exit:
176     if (setnonblocking) {
177         if (setnonblock(socket, 0) != 0)
178             return -1;
179     }
180
181     if (len == -1 && stored == 0)
182         /* last read or select got an error and we haven't got yet anything => return -1*/
183         return -1;
184     return stored;
185 }
186
187 /*!
188  * non-blocking drop-in replacement for read with timeout using select
189  *
190  * @param socket          (r)  socket, if in blocking mode, pass "setnonblocking" arg as 1
191  * @param data            (rw) buffer for the read data
192  * @param lenght          (r)  how many bytes to read
193  * @param setnonblocking  (r)  when non-zero this func will enable and disable non blocking
194  *                             io mode for the socket
195  * @param timeout         (r)  number of seconds to try reading
196  *
197  * @returns number of bytes actually read or -1 on fatal error
198  */
199 ssize_t writet(int socket, void *data, const size_t length, int setnonblocking, int timeout)
200 {
201     size_t stored = 0;
202     ssize_t len = 0;
203     struct timeval now, end, tv;
204     fd_set rfds;
205     int ret;
206
207     if (setnonblocking) {
208         if (setnonblock(socket, 1) != 0)
209             return -1;
210     }
211
212     /* Calculate end time */
213     (void)gettimeofday(&now, NULL);
214     end = now;
215     end.tv_sec += timeout;
216
217     while (stored < length) {
218         len = write(socket, (char *) data + stored, length - stored);
219         if (len == -1) {
220             switch (errno) {
221             case EINTR:
222                 continue;
223             case EAGAIN:
224                 FD_ZERO(&rfds);
225                 FD_SET(socket, &rfds);
226                 tv.tv_usec = 0;
227                 tv.tv_sec  = timeout;
228                         
229                 while ((ret = select(socket + 1, &rfds, NULL, NULL, &tv)) < 1) {
230                     switch (ret) {
231                     case 0:
232                         LOG(log_warning, logtype_afpd, "select timeout %d s", timeout);
233                         goto exit;
234
235                     default: /* -1 */
236                         if (errno == EINTR) {
237                             (void)gettimeofday(&now, NULL);
238                             if (now.tv_sec >= end.tv_sec && now.tv_usec >= end.tv_usec) {
239                                 LOG(log_warning, logtype_afpd, "select timeout %d s", timeout);
240                                 goto exit;
241                             }
242                             if (now.tv_usec > end.tv_usec) {
243                                 tv.tv_usec = 1000000 + end.tv_usec - now.tv_usec;
244                                 tv.tv_sec  = end.tv_sec - now.tv_sec - 1;
245                             } else {
246                                 tv.tv_usec = end.tv_usec - now.tv_usec;
247                                 tv.tv_sec  = end.tv_sec - now.tv_sec;
248                             }
249                             FD_ZERO(&rfds);
250                             FD_SET(socket, &rfds);
251                             continue;
252                         }
253                         LOG(log_error, logtype_afpd, "select: %s", strerror(errno));
254                         stored = -1;
255                         goto exit;
256                     }
257                 } /* while (select) */
258                 continue;
259             } /* switch (errno) */
260             LOG(log_error, logtype_afpd, "read: %s", strerror(errno));
261             stored = -1;
262             goto exit;
263         } /* (len == -1) */
264         else if (len > 0)
265             stored += len;
266         else
267             break;
268     } /* while (stored < length) */
269
270 exit:
271     if (setnonblocking) {
272         if (setnonblock(socket, 0) != 0)
273             return -1;
274     }
275
276     if (len == -1 && stored == 0)
277         /* last read or select got an error and we haven't got yet anything => return -1*/
278         return -1;
279     return stored;
280 }
281
282 /*!
283  * @brief convert an IPv4 or IPv6 address to a static string using inet_ntop
284  *
285  * IPv6 mapped IPv4 addresses are returned as IPv4 addreses eg
286  * ::ffff:10.0.0.0 is returned as "10.0.0.0".
287  *
288  * @param  sa        (r) pointer to an struct sockaddr
289  *
290  * @returns pointer to a static string cotaining the converted address as string.\n
291  *          On error pointers to "0.0.0.0" or "::0" are returned.
292  */
293 const char *getip_string(const struct sockaddr *sa)
294 {
295     static char ip4[INET_ADDRSTRLEN];
296     static char ip6[INET6_ADDRSTRLEN];
297
298     switch (sa->sa_family) {
299
300     case AF_INET: {
301         const struct sockaddr_in *sai4 = (const struct sockaddr_in *)sa;
302         if ((inet_ntop(AF_INET, &(sai4->sin_addr), ip4, INET_ADDRSTRLEN)) == NULL)
303             return "0.0.0.0";
304         return ip4;
305     }
306     case AF_INET6: {
307         const struct sockaddr_in6 *sai6 = (const struct sockaddr_in6 *)sa;
308         if ((inet_ntop(AF_INET6, &(sai6->sin6_addr), ip6, INET6_ADDRSTRLEN)) == NULL)
309             return "::0";
310
311         /* Deal with IPv6 mapped IPv4 addresses*/
312         if ((memcmp(sai6->sin6_addr.s6_addr, ipv4mapprefix, sizeof(ipv4mapprefix))) == 0)
313             return (strrchr(ip6, ':') + 1);
314         return ip6;
315     }
316     default:
317         return "getip_string ERROR";
318     }
319
320     /* We never get here */
321 }
322
323 /*!
324  * @brief return port number from struct sockaddr
325  *
326  * @param  sa        (r) pointer to an struct sockaddr
327  *
328  * @returns port as unsigned int
329  */
330 unsigned int getip_port(const struct sockaddr  *sa)
331 {
332     if (sa->sa_family == AF_INET) { /* IPv4 */
333         const struct sockaddr_in *sai4 = (const struct sockaddr_in *)sa;
334         return ntohs(sai4->sin_port);
335     } else {                       /* IPv6 */
336         const struct sockaddr_in6 *sai6 = (const struct sockaddr_in6 *)sa;
337         return ntohs(sai6->sin6_port);
338     }
339
340     /* We never get here */
341 }
342
343 /*!
344  * @brief apply netmask to IP (v4 or v6)
345  *
346  * Modifies IP address in sa->sin[6]_addr-s[6]_addr. The caller is responsible
347  * for passing a value for mask that is sensible to the passed address,
348  * eg 0 <= mask <= 32 for IPv4 or 0<= mask <= 128 for IPv6. mask > 32 for
349  * IPv4 is treated as mask = 32, mask > 128 is set to 128 for IPv6.
350  *
351  * @param  ai        (rw) pointer to an struct sockaddr
352  * @parma  mask      (r) number of maskbits
353  */
354 void apply_ip_mask(struct sockaddr *sa, int mask)
355 {
356
357     switch (sa->sa_family) {
358     case AF_INET: {
359         if (mask >= 32)
360             return;
361
362         struct sockaddr_in *si = (struct sockaddr_in *)sa;
363         uint32_t nmask = mask ? ~((1 << (32 - mask)) - 1) : 0;
364         si->sin_addr.s_addr &= htonl(nmask);
365         break;
366     }
367     case AF_INET6: {
368         if (mask >= 128)
369             return;
370
371         int i, maskbytes, maskbits;
372         struct sockaddr_in6 *si6 = (struct sockaddr_in6 *)sa;
373
374         /* Deal with IPv6 mapped IPv4 addresses*/
375         if ((memcmp(si6->sin6_addr.s6_addr, ipv4mapprefix, sizeof(ipv4mapprefix))) == 0) {
376             mask += 96;
377             if (mask >= 128)
378                 return;
379         }
380
381         maskbytes = (128 - mask) / 8; /* maskbytes really are those that will be 0'ed */
382         maskbits = mask % 8;
383
384         for (i = maskbytes - 1; i >= 0; i--)
385             si6->sin6_addr.s6_addr[15 - i] = 0;
386         if (maskbits)
387             si6->sin6_addr.s6_addr[15 - maskbytes] &= ~((1 << (8 - maskbits)) - 1);
388         break;
389     }
390     default:
391         break;
392     }
393 }
394
395 /*!
396  * @brief compare IP addresses for equality
397  *
398  * @param  sa1       (r) pointer to an struct sockaddr
399  * @param  sa2       (r) pointer to an struct sockaddr
400  *
401  * @returns Addresses are converted to strings and compared with strcmp and
402  *          the result of strcmp is returned.
403  *
404  * @note IPv6 mapped IPv4 addresses are treated as IPv4 addresses.
405  */
406 int compare_ip(const struct sockaddr *sa1, const struct sockaddr *sa2)
407 {
408     int ret;
409     char *ip1;
410     const char *ip2;
411
412     ip1 = strdup(getip_string(sa1));
413     ip2 = getip_string(sa2);
414
415     ret = strcmp(ip1, ip2);
416
417     free(ip1);
418
419     return ret;
420 }
421
422 /*!
423  * Add a fd to a dynamic pollfd array that is allocated and grown as needed
424  *
425  * This uses an additional array of struct polldata which stores type information
426  * (enum fdtype) and a pointer to anciliary user data.
427  *
428  * 1. Allocate the arrays with the size of "maxconns" if *fdsetp is NULL.
429  * 2. Fill in both array elements and increase count of used elements
430  * 
431  * @param maxconns    (r)  maximum number of connections, determines array size
432  * @param fdsetp      (rw) pointer to callers pointer to the pollfd array
433  * @param polldatap   (rw) pointer to callers pointer to the polldata array
434  * @param fdset_usedp (rw) pointer to an int with the number of used elements
435  * @param fdset_sizep (rw) pointer to an int which stores the array sizes
436  * @param fd          (r)  file descriptor to add to the arrays
437  * @param fdtype      (r)  type of fd, currently IPC_FD or LISTEN_FD
438  * @param data        (rw) pointer to data the caller want to associate with an fd
439  */
440 void fdset_add_fd(int maxconns,
441                   struct pollfd **fdsetp,
442                   struct polldata **polldatap,
443                   int *fdset_usedp,
444                   int *fdset_sizep,
445                   int fd,
446                   enum fdtype fdtype,
447                   void *data)
448 {
449     struct pollfd *fdset = *fdsetp;
450     struct polldata *polldata = *polldatap;
451     int fdset_size = *fdset_sizep;
452
453     LOG(log_debug, logtype_default, "fdset_add_fd: adding fd %i in slot %i", fd, *fdset_usedp);
454
455     if (fdset == NULL) { /* 1 */
456         /* Initialize with space for all possibly active fds */
457         fdset = calloc(maxconns, sizeof(struct pollfd));
458         if (! fdset)
459             exit(EXITERR_SYS);
460
461         polldata = calloc(maxconns, sizeof(struct polldata));
462         if (! polldata)
463             exit(EXITERR_SYS);
464
465         fdset_size = maxconns;
466
467         *fdset_sizep = fdset_size;
468         *fdsetp = fdset;
469         *polldatap = polldata;
470     }
471
472     /* 2 */
473     fdset[*fdset_usedp].fd = fd;
474     fdset[*fdset_usedp].events = POLLIN;
475     polldata[*fdset_usedp].fdtype = fdtype;
476     polldata[*fdset_usedp].data = data;
477     (*fdset_usedp)++;
478 }
479
480 /*!
481  * Remove a fd from our pollfd array
482  *
483  * 1. Search fd
484  * 2a Matched last (or only) in the set ? null it and return
485  * 2b If we remove the last array elemnt, just decrease count
486  * 3. If found move all following elements down by one
487  * 4. Decrease count of used elements in array
488  *
489  * This currently doesn't shrink the allocated storage of the array.
490  *
491  * @param fdsetp      (rw) pointer to callers pointer to the pollfd array
492  * @param polldatap   (rw) pointer to callers pointer to the polldata array
493  * @param fdset_usedp (rw) pointer to an int with the number of used elements
494  * @param fdset_sizep (rw) pointer to an int which stores the array sizes
495  * @param fd          (r)  file descriptor to remove from the arrays
496  */
497 void fdset_del_fd(struct pollfd **fdsetp,
498                   struct polldata **polldatap,
499                   int *fdset_usedp,
500                   int *fdset_sizep _U_,
501                   int fd)
502 {
503     struct pollfd *fdset = *fdsetp;
504     struct polldata *polldata = *polldatap;
505
506     if (*fdset_usedp < 1)
507         return;
508
509     for (int i = 0; i < *fdset_usedp; i++) {
510         if (fdset[i].fd == fd) { /* 1 */
511             if ((i + 1) == *fdset_usedp) { /* 2a */
512                 fdset[i].fd = -1;
513                 memset(&polldata[i], 0, sizeof(struct polldata));
514             } else if (i < (*fdset_usedp - 1)) { /* 2b */
515                 memmove(&fdset[i],
516                         &fdset[i+1],
517                         (*fdset_usedp - i - 1) * sizeof(struct pollfd)); /* 3 */
518                 memmove(&polldata[i],
519                         &polldata[i+1],
520                         (*fdset_usedp - i - 1) * sizeof(struct polldata)); /* 3 */
521             }
522             (*fdset_usedp)--;
523             break;
524         }
525     }
526 }
527
528 /* Length of the space taken up by a padded control message of length len */
529 #ifndef CMSG_SPACE
530 #define CMSG_SPACE(len) (__CMSG_ALIGN(sizeof(struct cmsghdr)) + __CMSG_ALIGN(len))
531 #endif
532
533 /*
534  * Receive a fd on a suitable socket
535  * @args fd          (r) PF_UNIX socket to receive on
536  * @args nonblocking (r) 0: fd is in blocking mode - 1: fd is nonblocking, poll for 1 sec
537  * @returns fd on success, -1 on error
538  */
539 int recv_fd(int fd, int nonblocking)
540 {
541     int ret;
542     struct msghdr msgh;
543     struct iovec iov[1];
544     struct cmsghdr *cmsgp = NULL;
545     char buf[CMSG_SPACE(sizeof(int))];
546     char dbuf[80];
547     struct pollfd pollfds[1];
548
549     pollfds[0].fd = fd;
550     pollfds[0].events = POLLIN;
551
552     memset(&msgh,0,sizeof(msgh));
553     memset(buf,0,sizeof(buf));
554
555     msgh.msg_name = NULL;
556     msgh.msg_namelen = 0;
557
558     msgh.msg_iov = iov;
559     msgh.msg_iovlen = 1;
560
561     iov[0].iov_base = dbuf;
562     iov[0].iov_len = sizeof(dbuf);
563
564     msgh.msg_control = buf;
565     msgh.msg_controllen = sizeof(buf);
566
567     if (nonblocking) {
568         do {
569             ret = poll(pollfds, 1, 2000); /* poll 2 seconds, evtl. multipe times (EINTR) */
570         } while ( ret == -1 && errno == EINTR );
571         if (ret != 1)
572             return -1;
573         ret = recvmsg(fd, &msgh, 0);
574     } else {
575         do  {
576             ret = recvmsg(fd, &msgh, 0);
577         } while ( ret == -1 && errno == EINTR );
578     }
579
580     if ( ret == -1 ) {
581         return -1;
582     }
583
584     for ( cmsgp = CMSG_FIRSTHDR(&msgh); cmsgp != NULL; cmsgp = CMSG_NXTHDR(&msgh,cmsgp) ) {
585         if ( cmsgp->cmsg_level == SOL_SOCKET && cmsgp->cmsg_type == SCM_RIGHTS ) {
586             return *(int *) CMSG_DATA(cmsgp);
587         }
588     }
589
590     if ( ret == sizeof (int) )
591         errno = *(int *)dbuf; /* Rcvd errno */
592     else
593         errno = ENOENT;    /* Default errno */
594
595     return -1;
596 }
597
598 /*
599  * Send a fd across a suitable socket
600  */
601 int send_fd(int socket, int fd)
602 {
603     int ret;
604     struct msghdr msgh;
605     struct iovec iov[1];
606     struct cmsghdr *cmsgp = NULL;
607     char *buf;
608     size_t size;
609     int er=0;
610
611     size = CMSG_SPACE(sizeof fd);
612     buf = malloc(size);
613     if (!buf) {
614         LOG(log_error, logtype_cnid, "error in sendmsg: %s", strerror(errno));
615         return -1;
616     }
617
618     memset(&msgh,0,sizeof (msgh));
619     memset(buf,0, size);
620
621     msgh.msg_name = NULL;
622     msgh.msg_namelen = 0;
623
624     msgh.msg_iov = iov;
625     msgh.msg_iovlen = 1;
626
627     iov[0].iov_base = &er;
628     iov[0].iov_len = sizeof(er);
629
630     msgh.msg_control = buf;
631     msgh.msg_controllen = size;
632
633     cmsgp = CMSG_FIRSTHDR(&msgh);
634     cmsgp->cmsg_level = SOL_SOCKET;
635     cmsgp->cmsg_type = SCM_RIGHTS;
636     cmsgp->cmsg_len = CMSG_LEN(sizeof(fd));
637
638     *((int *)CMSG_DATA(cmsgp)) = fd;
639     msgh.msg_controllen = cmsgp->cmsg_len;
640
641     do  {
642         ret = sendmsg(socket,&msgh, 0);
643     } while ( ret == -1 && errno == EINTR );
644     if (ret == -1) {
645         LOG(log_error, logtype_cnid, "error in sendmsg: %s", strerror(errno));
646         free(buf);
647         return -1;
648     }
649     free(buf);
650     return 0;
651 }