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