]> arthur.barton.de Git - netatalk.git/blob - libatalk/util/socket.c
Merge 2-1
[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 timeout or 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     FD_ZERO(&rfds);
101
102     if (setnonblocking) {
103         if (setnonblock(socket, 1) != 0)
104             return -1;
105     }
106
107     /* Calculate end time */
108     (void)gettimeofday(&now, NULL);
109     end = now;
110     end.tv_sec += timeout;
111
112     while (stored < length) {
113         len = read(socket, (char *) data + stored, length - stored);
114         if (len == -1) {
115             switch (errno) {
116             case EINTR:
117                 continue;
118             case EAGAIN:
119                 FD_SET(socket, &rfds);
120                 tv.tv_usec = 0;
121                 tv.tv_sec  = timeout;
122                         
123                 while ((ret = select(socket + 1, &rfds, NULL, NULL, &tv)) < 1) {
124                     switch (ret) {
125                     case 0:
126                         LOG(log_debug, logtype_afpd, "select timeout %d s", timeout);
127                         errno = EAGAIN;
128                         goto exit;
129
130                     default: /* -1 */
131                         if (errno == EINTR) {
132                             (void)gettimeofday(&now, NULL);
133                             if (now.tv_sec >= end.tv_sec && now.tv_usec >= end.tv_usec) {
134                                 LOG(log_warning, logtype_afpd, "select timeout %d s", timeout);
135                                 goto exit;
136                             }
137                             if (now.tv_usec > end.tv_usec) {
138                                 tv.tv_usec = 1000000 + end.tv_usec - now.tv_usec;
139                                 tv.tv_sec  = end.tv_sec - now.tv_sec - 1;
140                             } else {
141                                 tv.tv_usec = end.tv_usec - now.tv_usec;
142                                 tv.tv_sec  = end.tv_sec - now.tv_sec;
143                             }
144                             FD_SET(socket, &rfds);
145                             continue;
146                         }
147                         LOG(log_error, logtype_afpd, "select: %s", strerror(errno));
148                         stored = -1;
149                         goto exit;
150                     }
151                 } /* while (select) */
152                 continue;
153             } /* switch (errno) */
154             LOG(log_error, logtype_afpd, "read: %s", strerror(errno));
155             stored = -1;
156             goto exit;
157         } /* (len == -1) */
158         else if (len > 0)
159             stored += len;
160         else
161             break;
162     } /* while (stored < length) */
163
164 exit:
165     if (setnonblocking) {
166         if (setnonblock(socket, 0) != 0)
167             return -1;
168     }
169
170     if (len == -1 && stored == 0)
171         /* last read or select got an error and we haven't got yet anything => return -1*/
172         return -1;
173     return stored;
174 }
175
176 /*!
177  * non-blocking drop-in replacement for read with timeout using select
178  *
179  * @param socket          (r)  socket, if in blocking mode, pass "setnonblocking" arg as 1
180  * @param data            (rw) buffer for the read data
181  * @param lenght          (r)  how many bytes to read
182  * @param setnonblocking  (r)  when non-zero this func will enable and disable non blocking
183  *                             io mode for the socket
184  * @param timeout         (r)  number of seconds to try reading
185  *
186  * @returns number of bytes actually read or -1 on fatal error
187  */
188 ssize_t writet(int socket, void *data, const size_t length, int setnonblocking, int timeout)
189 {
190     size_t stored = 0;
191     ssize_t len = 0;
192     struct timeval now, end, tv;
193     fd_set rfds;
194     int ret;
195
196     if (setnonblocking) {
197         if (setnonblock(socket, 1) != 0)
198             return -1;
199     }
200
201     /* Calculate end time */
202     (void)gettimeofday(&now, NULL);
203     end = now;
204     end.tv_sec += timeout;
205
206     while (stored < length) {
207         len = write(socket, (char *) data + stored, length - stored);
208         if (len == -1) {
209             switch (errno) {
210             case EINTR:
211                 continue;
212             case EAGAIN:
213                 FD_ZERO(&rfds);
214                 FD_SET(socket, &rfds);
215                 tv.tv_usec = 0;
216                 tv.tv_sec  = timeout;
217                         
218                 while ((ret = select(socket + 1, &rfds, NULL, NULL, &tv)) < 1) {
219                     switch (ret) {
220                     case 0:
221                         LOG(log_warning, logtype_afpd, "select timeout %d s", timeout);
222                         goto exit;
223
224                     default: /* -1 */
225                         if (errno == EINTR) {
226                             (void)gettimeofday(&now, NULL);
227                             if (now.tv_sec >= end.tv_sec && now.tv_usec >= end.tv_usec) {
228                                 LOG(log_warning, logtype_afpd, "select timeout %d s", timeout);
229                                 goto exit;
230                             }
231                             if (now.tv_usec > end.tv_usec) {
232                                 tv.tv_usec = 1000000 + end.tv_usec - now.tv_usec;
233                                 tv.tv_sec  = end.tv_sec - now.tv_sec - 1;
234                             } else {
235                                 tv.tv_usec = end.tv_usec - now.tv_usec;
236                                 tv.tv_sec  = end.tv_sec - now.tv_sec;
237                             }
238                             FD_ZERO(&rfds);
239                             FD_SET(socket, &rfds);
240                             continue;
241                         }
242                         LOG(log_error, logtype_afpd, "select: %s", strerror(errno));
243                         stored = -1;
244                         goto exit;
245                     }
246                 } /* while (select) */
247                 continue;
248             } /* switch (errno) */
249             LOG(log_error, logtype_afpd, "read: %s", strerror(errno));
250             stored = -1;
251             goto exit;
252         } /* (len == -1) */
253         else if (len > 0)
254             stored += len;
255         else
256             break;
257     } /* while (stored < length) */
258
259 exit:
260     if (setnonblocking) {
261         if (setnonblock(socket, 0) != 0)
262             return -1;
263     }
264
265     if (len == -1 && stored == 0)
266         /* last read or select got an error and we haven't got yet anything => return -1*/
267         return -1;
268     return stored;
269 }
270
271 /*!
272  * @brief convert an IPv4 or IPv6 address to a static string using inet_ntop
273  *
274  * IPv6 mapped IPv4 addresses are returned as IPv4 addreses eg
275  * ::ffff:10.0.0.0 is returned as "10.0.0.0".
276  *
277  * @param  sa        (r) pointer to an struct sockaddr
278  *
279  * @returns pointer to a static string cotaining the converted address as string.\n
280  *          On error pointers to "0.0.0.0" or "::0" are returned.
281  */
282 const char *getip_string(const struct sockaddr *sa)
283 {
284     static char ip4[INET_ADDRSTRLEN];
285     static char ip6[INET6_ADDRSTRLEN];
286
287     switch (sa->sa_family) {
288
289     case AF_INET: {
290         const struct sockaddr_in *sai4 = (const struct sockaddr_in *)sa;
291         if ((inet_ntop(AF_INET, &(sai4->sin_addr), ip4, INET_ADDRSTRLEN)) == NULL)
292             return "0.0.0.0";
293         return ip4;
294     }
295     case AF_INET6: {
296         const struct sockaddr_in6 *sai6 = (const struct sockaddr_in6 *)sa;
297         if ((inet_ntop(AF_INET6, &(sai6->sin6_addr), ip6, INET6_ADDRSTRLEN)) == NULL)
298             return "::0";
299
300         /* Deal with IPv6 mapped IPv4 addresses*/
301         if ((memcmp(sai6->sin6_addr.s6_addr, ipv4mapprefix, sizeof(ipv4mapprefix))) == 0)
302             return (strrchr(ip6, ':') + 1);
303         return ip6;
304     }
305     default:
306         return "getip_string ERROR";
307     }
308
309     /* We never get here */
310 }
311
312 /*!
313  * @brief return port number from struct sockaddr
314  *
315  * @param  sa        (r) pointer to an struct sockaddr
316  *
317  * @returns port as unsigned int
318  */
319 unsigned int getip_port(const struct sockaddr  *sa)
320 {
321     if (sa->sa_family == AF_INET) { /* IPv4 */
322         const struct sockaddr_in *sai4 = (const struct sockaddr_in *)sa;
323         return ntohs(sai4->sin_port);
324     } else {                       /* IPv6 */
325         const struct sockaddr_in6 *sai6 = (const struct sockaddr_in6 *)sa;
326         return ntohs(sai6->sin6_port);
327     }
328
329     /* We never get here */
330 }
331
332 /*!
333  * @brief apply netmask to IP (v4 or v6)
334  *
335  * Modifies IP address in sa->sin[6]_addr-s[6]_addr. The caller is responsible
336  * for passing a value for mask that is sensible to the passed address,
337  * eg 0 <= mask <= 32 for IPv4 or 0<= mask <= 128 for IPv6. mask > 32 for
338  * IPv4 is treated as mask = 32, mask > 128 is set to 128 for IPv6.
339  *
340  * @param  ai        (rw) pointer to an struct sockaddr
341  * @parma  mask      (r) number of maskbits
342  */
343 void apply_ip_mask(struct sockaddr *sa, int mask)
344 {
345
346     switch (sa->sa_family) {
347     case AF_INET: {
348         if (mask >= 32)
349             return;
350
351         struct sockaddr_in *si = (struct sockaddr_in *)sa;
352         uint32_t nmask = mask ? ~((1 << (32 - mask)) - 1) : 0;
353         si->sin_addr.s_addr &= htonl(nmask);
354         break;
355     }
356     case AF_INET6: {
357         if (mask >= 128)
358             return;
359
360         int i, maskbytes, maskbits;
361         struct sockaddr_in6 *si6 = (struct sockaddr_in6 *)sa;
362
363         /* Deal with IPv6 mapped IPv4 addresses*/
364         if ((memcmp(si6->sin6_addr.s6_addr, ipv4mapprefix, sizeof(ipv4mapprefix))) == 0) {
365             mask += 96;
366             if (mask >= 128)
367                 return;
368         }
369
370         maskbytes = (128 - mask) / 8; /* maskbytes really are those that will be 0'ed */
371         maskbits = mask % 8;
372
373         for (i = maskbytes - 1; i >= 0; i--)
374             si6->sin6_addr.s6_addr[15 - i] = 0;
375         if (maskbits)
376             si6->sin6_addr.s6_addr[15 - maskbytes] &= ~((1 << (8 - maskbits)) - 1);
377         break;
378     }
379     default:
380         break;
381     }
382 }
383
384 /*!
385  * @brief compare IP addresses for equality
386  *
387  * @param  sa1       (r) pointer to an struct sockaddr
388  * @param  sa2       (r) pointer to an struct sockaddr
389  *
390  * @returns Addresses are converted to strings and compared with strcmp and
391  *          the result of strcmp is returned.
392  *
393  * @note IPv6 mapped IPv4 addresses are treated as IPv4 addresses.
394  */
395 int compare_ip(const struct sockaddr *sa1, const struct sockaddr *sa2)
396 {
397     int ret;
398     char *ip1;
399     const char *ip2;
400
401     ip1 = strdup(getip_string(sa1));
402     ip2 = getip_string(sa2);
403
404     ret = strcmp(ip1, ip2);
405
406     free(ip1);
407
408     return ret;
409 }
410
411 #define POLL_FD_SET_STARTSIZE 512
412 #define POLL_FD_SET_INCREASE  128
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 an intial size of [POLL_FD_SET_STARTSIZE] if
420  *    *fdsetp is NULL.
421  * 2. Grow array as needed
422  * 3. Fill in both array elements and increase count of used elements
423  * 
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(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 512 fds */
448         fdset = calloc(POLL_FD_SET_STARTSIZE, sizeof(struct pollfd));
449         if (! fdset)
450             exit(EXITERR_SYS);
451
452         polldata = calloc(POLL_FD_SET_STARTSIZE, sizeof(struct polldata));
453         if (! polldata)
454             exit(EXITERR_SYS);
455
456         fdset_size = 512;
457         *fdset_sizep = fdset_size;
458         *fdsetp = fdset;
459         *polldatap = polldata;
460     }
461
462     if (*fdset_usedp >= fdset_size) { /* 2 */
463         fdset = realloc(fdset, sizeof(struct pollfd) * (fdset_size + POLL_FD_SET_INCREASE));
464         if (fdset == NULL)
465             exit(EXITERR_SYS);
466
467         polldata = realloc(polldata, sizeof(struct polldata) * (fdset_size + POLL_FD_SET_INCREASE));
468         if (polldata == NULL)
469             exit(EXITERR_SYS);
470
471         fdset_size += POLL_FD_SET_INCREASE;
472         *fdset_sizep = fdset_size;
473         *fdsetp = fdset;
474         *polldatap = polldata;
475     }
476
477     /* 3 */
478     fdset[*fdset_usedp].fd = fd;
479     fdset[*fdset_usedp].events = POLLIN;
480     polldata[*fdset_usedp].fdtype = fdtype;
481     polldata[*fdset_usedp].data = data;
482     (*fdset_usedp)++;
483 }
484
485 /*!
486  * Remove a fd from our pollfd array
487  *
488  * 1. Search fd
489  * 2. If we remove the last array elemnt, just decrease count
490  * 3. If found move all following elements down by one
491  * 4. Decrease count of used elements in array
492  *
493  * This currently doesn't shrink the allocated storage of the array.
494  *
495  * @param fdsetp      (rw) pointer to callers pointer to the pollfd array
496  * @param polldatap   (rw) pointer to callers pointer to the polldata array
497  * @param fdset_usedp (rw) pointer to an int with the number of used elements
498  * @param fdset_sizep (rw) pointer to an int which stores the array sizes
499  * @param fd          (r)  file descriptor to remove from the arrays
500  */
501 void fdset_del_fd(struct pollfd **fdsetp,
502                   struct polldata **polldatap,
503                   int *fdset_usedp,
504                   int *fdset_sizep _U_,
505                   int fd)
506 {
507     struct pollfd *fdset = *fdsetp;
508     struct polldata *polldata = *polldatap;
509
510     for (int i = 0; i < *fdset_usedp; i++) {
511         if (fdset[i].fd == fd) { /* 1 */
512             if (i < (*fdset_usedp - 1)) { /* 2 */
513                 memmove(&fdset[i], &fdset[i+1], (*fdset_usedp - 1) * sizeof(struct pollfd)); /* 3 */
514                 memmove(&polldata[i], &polldata[i+1], (*fdset_usedp - 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 }