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