2 Copyright (c) 2009 Frank Lahm <franklahm@gmail.com>
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.
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.
17 * Netatalk utility functions
22 #endif /* HAVE_CONFIG_H */
25 # define _XOPEN_SOURCE 600
27 #ifndef __EXTENSIONS__
28 # define __EXTENSIONS__
35 #include <sys/types.h>
36 #include <sys/socket.h>
37 #include <arpa/inet.h>
38 #include <netinet/in.h>
44 #include <sys/ioctl.h>
46 #include <atalk/logger.h>
47 #include <atalk/util.h>
49 static char ipv4mapprefix[] = {0,0,0,0,0,0,0,0,0,0,0xff,0xff};
52 * @brief set or unset non-blocking IO on a fd
54 * @param fd (r) File descriptor
55 * @param cmd (r) 0: disable non-blocking IO, ie block\n
56 * <>0: enable non-blocking IO
58 * @returns 0 on success, -1 on failure
60 int setnonblock(int fd, int cmd)
65 if ((fdflags = ofdflags = fcntl(fd, F_GETFL, 0)) == -1)
69 fdflags |= O_NONBLOCK;
71 fdflags &= ~O_NONBLOCK;
73 if (fdflags != ofdflags)
74 if (fcntl(fd, F_SETFL, fdflags) == -1)
81 * non-blocking drop-in replacement for read with timeout using select
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
90 * @returns number of bytes actually read or -1 on timeout or error
92 ssize_t readt(int socket, void *data, const size_t length, int setnonblocking, int timeout)
96 struct timeval now, end, tv;
102 if (setnonblocking) {
103 if (setnonblock(socket, 1) != 0)
107 /* Calculate end time */
108 (void)gettimeofday(&now, NULL);
110 end.tv_sec += timeout;
112 while (stored < length) {
113 len = read(socket, (char *) data + stored, length - stored);
119 FD_SET(socket, &rfds);
123 while ((ret = select(socket + 1, &rfds, NULL, NULL, &tv)) < 1) {
126 LOG(log_debug, logtype_afpd, "select timeout %d s", timeout);
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);
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;
141 tv.tv_usec = end.tv_usec - now.tv_usec;
142 tv.tv_sec = end.tv_sec - now.tv_sec;
144 FD_SET(socket, &rfds);
147 LOG(log_error, logtype_afpd, "select: %s", strerror(errno));
151 } /* while (select) */
153 } /* switch (errno) */
154 LOG(log_error, logtype_afpd, "read: %s", strerror(errno));
162 } /* while (stored < length) */
165 if (setnonblocking) {
166 if (setnonblock(socket, 0) != 0)
170 if (len == -1 && stored == 0)
171 /* last read or select got an error and we haven't got yet anything => return -1*/
177 * non-blocking drop-in replacement for read with timeout using select
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
186 * @returns number of bytes actually read or -1 on fatal error
188 ssize_t writet(int socket, void *data, const size_t length, int setnonblocking, int timeout)
192 struct timeval now, end, tv;
196 if (setnonblocking) {
197 if (setnonblock(socket, 1) != 0)
201 /* Calculate end time */
202 (void)gettimeofday(&now, NULL);
204 end.tv_sec += timeout;
206 while (stored < length) {
207 len = write(socket, (char *) data + stored, length - stored);
214 FD_SET(socket, &rfds);
218 while ((ret = select(socket + 1, &rfds, NULL, NULL, &tv)) < 1) {
221 LOG(log_warning, logtype_afpd, "select timeout %d s", timeout);
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);
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;
235 tv.tv_usec = end.tv_usec - now.tv_usec;
236 tv.tv_sec = end.tv_sec - now.tv_sec;
239 FD_SET(socket, &rfds);
242 LOG(log_error, logtype_afpd, "select: %s", strerror(errno));
246 } /* while (select) */
248 } /* switch (errno) */
249 LOG(log_error, logtype_afpd, "read: %s", strerror(errno));
257 } /* while (stored < length) */
260 if (setnonblocking) {
261 if (setnonblock(socket, 0) != 0)
265 if (len == -1 && stored == 0)
266 /* last read or select got an error and we haven't got yet anything => return -1*/
272 * @brief convert an IPv4 or IPv6 address to a static string using inet_ntop
274 * IPv6 mapped IPv4 addresses are returned as IPv4 addreses eg
275 * ::ffff:10.0.0.0 is returned as "10.0.0.0".
277 * @param sa (r) pointer to an struct sockaddr
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.
282 const char *getip_string(const struct sockaddr *sa)
284 static char ip4[INET_ADDRSTRLEN];
285 static char ip6[INET6_ADDRSTRLEN];
287 switch (sa->sa_family) {
290 const struct sockaddr_in *sai4 = (const struct sockaddr_in *)sa;
291 if ((inet_ntop(AF_INET, &(sai4->sin_addr), ip4, INET_ADDRSTRLEN)) == NULL)
296 const struct sockaddr_in6 *sai6 = (const struct sockaddr_in6 *)sa;
297 if ((inet_ntop(AF_INET6, &(sai6->sin6_addr), ip6, INET6_ADDRSTRLEN)) == NULL)
300 /* Deal with IPv6 mapped IPv4 addresses*/
301 if ((memcmp(sai6->sin6_addr.s6_addr, ipv4mapprefix, sizeof(ipv4mapprefix))) == 0)
302 return (strrchr(ip6, ':') + 1);
306 return "getip_string ERROR";
309 /* We never get here */
313 * @brief return port number from struct sockaddr
315 * @param sa (r) pointer to an struct sockaddr
317 * @returns port as unsigned int
319 unsigned int getip_port(const struct sockaddr *sa)
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);
325 const struct sockaddr_in6 *sai6 = (const struct sockaddr_in6 *)sa;
326 return ntohs(sai6->sin6_port);
329 /* We never get here */
333 * @brief apply netmask to IP (v4 or v6)
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.
340 * @param ai (rw) pointer to an struct sockaddr
341 * @parma mask (r) number of maskbits
343 void apply_ip_mask(struct sockaddr *sa, int mask)
346 switch (sa->sa_family) {
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);
360 int i, maskbytes, maskbits;
361 struct sockaddr_in6 *si6 = (struct sockaddr_in6 *)sa;
363 /* Deal with IPv6 mapped IPv4 addresses*/
364 if ((memcmp(si6->sin6_addr.s6_addr, ipv4mapprefix, sizeof(ipv4mapprefix))) == 0) {
370 maskbytes = (128 - mask) / 8; /* maskbytes really are those that will be 0'ed */
373 for (i = maskbytes - 1; i >= 0; i--)
374 si6->sin6_addr.s6_addr[15 - i] = 0;
376 si6->sin6_addr.s6_addr[15 - maskbytes] &= ~((1 << (8 - maskbits)) - 1);
385 * @brief compare IP addresses for equality
387 * @param sa1 (r) pointer to an struct sockaddr
388 * @param sa2 (r) pointer to an struct sockaddr
390 * @returns Addresses are converted to strings and compared with strcmp and
391 * the result of strcmp is returned.
393 * @note IPv6 mapped IPv4 addresses are treated as IPv4 addresses.
395 int compare_ip(const struct sockaddr *sa1, const struct sockaddr *sa2)
401 ip1 = strdup(getip_string(sa1));
402 ip2 = getip_string(sa2);
404 ret = strcmp(ip1, ip2);
411 #define POLL_FD_SET_STARTSIZE 512
412 #define POLL_FD_SET_INCREASE 128
414 * Add a fd to a dynamic pollfd array that is allocated and grown as needed
416 * This uses an additional array of struct polldata which stores type information
417 * (enum fdtype) and a pointer to anciliary user data.
419 * 1. Allocate the arrays with an intial size of [POLL_FD_SET_STARTSIZE] if
421 * 2. Grow array as needed
422 * 3. Fill in both array elements and increase count of used elements
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
432 void fdset_add_fd(struct pollfd **fdsetp,
433 struct polldata **polldatap,
440 struct pollfd *fdset = *fdsetp;
441 struct polldata *polldata = *polldatap;
442 int fdset_size = *fdset_sizep;
444 LOG(log_debug, logtype_default, "fdset_add_fd: adding fd %i in slot %i", fd, *fdset_usedp);
446 if (fdset == NULL) { /* 1 */
447 /* Initialize with space for 512 fds */
448 fdset = calloc(POLL_FD_SET_STARTSIZE, sizeof(struct pollfd));
452 polldata = calloc(POLL_FD_SET_STARTSIZE, sizeof(struct polldata));
457 *fdset_sizep = fdset_size;
459 *polldatap = polldata;
462 if (*fdset_usedp >= fdset_size) { /* 2 */
463 fdset = realloc(fdset, sizeof(struct pollfd) * (fdset_size + POLL_FD_SET_INCREASE));
467 polldata = realloc(polldata, sizeof(struct polldata) * (fdset_size + POLL_FD_SET_INCREASE));
468 if (polldata == NULL)
471 fdset_size += POLL_FD_SET_INCREASE;
472 *fdset_sizep = fdset_size;
474 *polldatap = polldata;
478 fdset[*fdset_usedp].fd = fd;
479 fdset[*fdset_usedp].events = POLLIN;
480 polldata[*fdset_usedp].fdtype = fdtype;
481 polldata[*fdset_usedp].data = data;
486 * Remove a fd from our pollfd array
490 * 2b If we remove the last array elemnt, just decrease count
491 * 3. If found move all following elements down by one
492 * 4. Decrease count of used elements in array
494 * This currently doesn't shrink the allocated storage of the array.
496 * @param fdsetp (rw) pointer to callers pointer to the pollfd array
497 * @param polldatap (rw) pointer to callers pointer to the polldata array
498 * @param fdset_usedp (rw) pointer to an int with the number of used elements
499 * @param fdset_sizep (rw) pointer to an int which stores the array sizes
500 * @param fd (r) file descriptor to remove from the arrays
502 void fdset_del_fd(struct pollfd **fdsetp,
503 struct polldata **polldatap,
505 int *fdset_sizep _U_,
508 struct pollfd *fdset = *fdsetp;
509 struct polldata *polldata = *polldatap;
511 if (*fdset_usedp < 1)
514 for (int i = 0; i < *fdset_usedp; i++) {
515 if (fdset[i].fd == fd) { /* 1 */
516 if (i == 0 && *fdset_usedp == 1) { /* 2a */
518 memset(&polldata[i], 0, sizeof(struct polldata));
519 } else if (i < (*fdset_usedp - 1)) { /* 2b */
520 memmove(&fdset[i], &fdset[i+1], (*fdset_usedp - 1) * sizeof(struct pollfd)); /* 3 */
521 memmove(&polldata[i], &polldata[i+1], (*fdset_usedp - 1) * sizeof(struct polldata)); /* 3 */
529 /* Length of the space taken up by a padded control message of length len */
531 #define CMSG_SPACE(len) (__CMSG_ALIGN(sizeof(struct cmsghdr)) + __CMSG_ALIGN(len))
535 * Receive a fd on a suitable socket
536 * @args fd (r) PF_UNIX socket to receive on
537 * @args nonblocking (r) 0: fd is in blocking mode - 1: fd is nonblocking, poll for 1 sec
538 * @returns fd on success, -1 on error
540 int recv_fd(int fd, int nonblocking)
545 struct cmsghdr *cmsgp = NULL;
546 char buf[CMSG_SPACE(sizeof(int))];
548 struct pollfd pollfds[1];
551 pollfds[0].events = POLLIN;
553 memset(&msgh,0,sizeof(msgh));
554 memset(buf,0,sizeof(buf));
556 msgh.msg_name = NULL;
557 msgh.msg_namelen = 0;
562 iov[0].iov_base = dbuf;
563 iov[0].iov_len = sizeof(dbuf);
565 msgh.msg_control = buf;
566 msgh.msg_controllen = sizeof(buf);
570 ret = poll(pollfds, 1, 2000); /* poll 2 seconds, evtl. multipe times (EINTR) */
571 } while ( ret == -1 && errno == EINTR );
574 ret = recvmsg(fd, &msgh, 0);
577 ret = recvmsg(fd, &msgh, 0);
578 } while ( ret == -1 && errno == EINTR );
585 for ( cmsgp = CMSG_FIRSTHDR(&msgh); cmsgp != NULL; cmsgp = CMSG_NXTHDR(&msgh,cmsgp) ) {
586 if ( cmsgp->cmsg_level == SOL_SOCKET && cmsgp->cmsg_type == SCM_RIGHTS ) {
587 return *(int *) CMSG_DATA(cmsgp);
591 if ( ret == sizeof (int) )
592 errno = *(int *)dbuf; /* Rcvd errno */
594 errno = ENOENT; /* Default errno */
600 * Send a fd across a suitable socket
602 int send_fd(int socket, int fd)
607 struct cmsghdr *cmsgp = NULL;
612 size = CMSG_SPACE(sizeof fd);
615 LOG(log_error, logtype_cnid, "error in sendmsg: %s", strerror(errno));
619 memset(&msgh,0,sizeof (msgh));
622 msgh.msg_name = NULL;
623 msgh.msg_namelen = 0;
628 iov[0].iov_base = &er;
629 iov[0].iov_len = sizeof(er);
631 msgh.msg_control = buf;
632 msgh.msg_controllen = size;
634 cmsgp = CMSG_FIRSTHDR(&msgh);
635 cmsgp->cmsg_level = SOL_SOCKET;
636 cmsgp->cmsg_type = SCM_RIGHTS;
637 cmsgp->cmsg_len = CMSG_LEN(sizeof(fd));
639 *((int *)CMSG_DATA(cmsgp)) = fd;
640 msgh.msg_controllen = cmsgp->cmsg_len;
643 ret = sendmsg(socket,&msgh, 0);
644 } while ( ret == -1 && errno == EINTR );
646 LOG(log_error, logtype_cnid, "error in sendmsg: %s", strerror(errno));