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