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