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 */
24 #if !defined(__FreeBSD__)
25 # ifndef _XOPEN_SOURCE
26 # define _XOPEN_SOURCE 600
28 # ifndef __EXTENSIONS__
29 # define __EXTENSIONS__
37 #include <sys/types.h>
38 #include <sys/socket.h>
39 #include <arpa/inet.h>
40 #include <netinet/in.h>
46 #include <sys/ioctl.h>
48 #include <atalk/logger.h>
49 #include <atalk/util.h>
51 static char ipv4mapprefix[] = {0,0,0,0,0,0,0,0,0,0,0xff,0xff};
54 * @brief set or unset non-blocking IO on a fd
56 * @param fd (r) File descriptor
57 * @param cmd (r) 0: disable non-blocking IO, ie block\n
58 * <>0: enable non-blocking IO
60 * @returns 0 on success, -1 on failure
62 int setnonblock(int fd, int cmd)
67 if ((fdflags = ofdflags = fcntl(fd, F_GETFL, 0)) == -1)
71 fdflags |= O_NONBLOCK;
73 fdflags &= ~O_NONBLOCK;
75 if (fdflags != ofdflags)
76 if (fcntl(fd, F_SETFL, fdflags) == -1)
83 * non-blocking drop-in replacement for read with timeout using select
85 * @param socket (r) socket, if in blocking mode, pass "setnonblocking" arg as 1
86 * @param data (rw) buffer for the read data
87 * @param lenght (r) how many bytes to read
88 * @param setnonblocking (r) when non-zero this func will enable and disable non blocking
89 * io mode for the socket
90 * @param timeout (r) number of seconds to try reading
92 * @returns number of bytes actually read or -1 on timeout or error
94 ssize_t readt(int socket, void *data, const size_t length, int setnonblocking, int timeout)
98 struct timeval now, end, tv;
104 if (setnonblocking) {
105 if (setnonblock(socket, 1) != 0)
109 /* Calculate end time */
110 (void)gettimeofday(&now, NULL);
112 end.tv_sec += timeout;
114 while (stored < length) {
115 len = read(socket, (char *) data + stored, length - stored);
121 FD_SET(socket, &rfds);
125 while ((ret = select(socket + 1, &rfds, NULL, NULL, &tv)) < 1) {
128 LOG(log_debug, logtype_afpd, "select timeout %d s", timeout);
135 (void)gettimeofday(&now, NULL);
136 if (now.tv_sec > end.tv_sec
138 (now.tv_sec == end.tv_sec && now.tv_usec >= end.tv_usec)) {
139 LOG(log_debug, logtype_afpd, "select timeout %d s", timeout);
142 if (now.tv_usec > end.tv_usec) {
143 tv.tv_usec = 1000000 + end.tv_usec - now.tv_usec;
144 tv.tv_sec = end.tv_sec - now.tv_sec - 1;
146 tv.tv_usec = end.tv_usec - now.tv_usec;
147 tv.tv_sec = end.tv_sec - now.tv_sec;
149 FD_SET(socket, &rfds);
152 /* possibly entered disconnected state, don't spam log here */
153 LOG(log_debug, logtype_afpd, "select: %s", strerror(errno));
157 LOG(log_error, logtype_afpd, "select: %s", strerror(errno));
162 } /* while (select) */
164 } /* switch (errno) */
165 LOG(log_error, logtype_afpd, "read: %s", strerror(errno));
173 } /* while (stored < length) */
176 if (setnonblocking) {
177 if (setnonblock(socket, 0) != 0)
181 if (len == -1 && stored == 0)
182 /* last read or select got an error and we haven't got yet anything => return -1*/
188 * non-blocking drop-in replacement for read with timeout using select
190 * @param socket (r) socket, if in blocking mode, pass "setnonblocking" arg as 1
191 * @param data (rw) buffer for the read data
192 * @param lenght (r) how many bytes to read
193 * @param setnonblocking (r) when non-zero this func will enable and disable non blocking
194 * io mode for the socket
195 * @param timeout (r) number of seconds to try reading
197 * @returns number of bytes actually read or -1 on fatal error
199 ssize_t writet(int socket, void *data, const size_t length, int setnonblocking, int timeout)
203 struct timeval now, end, tv;
207 if (setnonblocking) {
208 if (setnonblock(socket, 1) != 0)
212 /* Calculate end time */
213 (void)gettimeofday(&now, NULL);
215 end.tv_sec += timeout;
217 while (stored < length) {
218 len = write(socket, (char *) data + stored, length - stored);
225 FD_SET(socket, &rfds);
229 while ((ret = select(socket + 1, &rfds, NULL, NULL, &tv)) < 1) {
232 LOG(log_warning, logtype_afpd, "select timeout %d s", timeout);
236 if (errno == EINTR) {
237 (void)gettimeofday(&now, NULL);
238 if (now.tv_sec >= end.tv_sec && now.tv_usec >= end.tv_usec) {
239 LOG(log_warning, logtype_afpd, "select timeout %d s", timeout);
242 if (now.tv_usec > end.tv_usec) {
243 tv.tv_usec = 1000000 + end.tv_usec - now.tv_usec;
244 tv.tv_sec = end.tv_sec - now.tv_sec - 1;
246 tv.tv_usec = end.tv_usec - now.tv_usec;
247 tv.tv_sec = end.tv_sec - now.tv_sec;
250 FD_SET(socket, &rfds);
253 LOG(log_error, logtype_afpd, "select: %s", strerror(errno));
257 } /* while (select) */
259 } /* switch (errno) */
260 LOG(log_error, logtype_afpd, "read: %s", strerror(errno));
268 } /* while (stored < length) */
271 if (setnonblocking) {
272 if (setnonblock(socket, 0) != 0)
276 if (len == -1 && stored == 0)
277 /* last read or select got an error and we haven't got yet anything => return -1*/
283 * @brief convert an IPv4 or IPv6 address to a static string using inet_ntop
285 * IPv6 mapped IPv4 addresses are returned as IPv4 addreses eg
286 * ::ffff:10.0.0.0 is returned as "10.0.0.0".
288 * @param sa (r) pointer to an struct sockaddr
290 * @returns pointer to a static string cotaining the converted address as string.\n
291 * On error pointers to "0.0.0.0" or "::0" are returned.
293 const char *getip_string(const struct sockaddr *sa)
295 static char ip4[INET_ADDRSTRLEN];
296 static char ip6[INET6_ADDRSTRLEN];
298 switch (sa->sa_family) {
301 const struct sockaddr_in *sai4 = (const struct sockaddr_in *)sa;
302 if ((inet_ntop(AF_INET, &(sai4->sin_addr), ip4, INET_ADDRSTRLEN)) == NULL)
307 const struct sockaddr_in6 *sai6 = (const struct sockaddr_in6 *)sa;
308 if ((inet_ntop(AF_INET6, &(sai6->sin6_addr), ip6, INET6_ADDRSTRLEN)) == NULL)
311 /* Deal with IPv6 mapped IPv4 addresses*/
312 if ((memcmp(sai6->sin6_addr.s6_addr, ipv4mapprefix, sizeof(ipv4mapprefix))) == 0)
313 return (strrchr(ip6, ':') + 1);
317 return "getip_string ERROR";
320 /* We never get here */
324 * @brief return port number from struct sockaddr
326 * @param sa (r) pointer to an struct sockaddr
328 * @returns port as unsigned int
330 unsigned int getip_port(const struct sockaddr *sa)
332 if (sa->sa_family == AF_INET) { /* IPv4 */
333 const struct sockaddr_in *sai4 = (const struct sockaddr_in *)sa;
334 return ntohs(sai4->sin_port);
336 const struct sockaddr_in6 *sai6 = (const struct sockaddr_in6 *)sa;
337 return ntohs(sai6->sin6_port);
340 /* We never get here */
344 * @brief apply netmask to IP (v4 or v6)
346 * Modifies IP address in sa->sin[6]_addr-s[6]_addr. The caller is responsible
347 * for passing a value for mask that is sensible to the passed address,
348 * eg 0 <= mask <= 32 for IPv4 or 0<= mask <= 128 for IPv6. mask > 32 for
349 * IPv4 is treated as mask = 32, mask > 128 is set to 128 for IPv6.
351 * @param ai (rw) pointer to an struct sockaddr
352 * @parma mask (r) number of maskbits
354 void apply_ip_mask(struct sockaddr *sa, int mask)
357 switch (sa->sa_family) {
362 struct sockaddr_in *si = (struct sockaddr_in *)sa;
363 uint32_t nmask = mask ? ~((1 << (32 - mask)) - 1) : 0;
364 si->sin_addr.s_addr &= htonl(nmask);
371 int i, maskbytes, maskbits;
372 struct sockaddr_in6 *si6 = (struct sockaddr_in6 *)sa;
374 /* Deal with IPv6 mapped IPv4 addresses*/
375 if ((memcmp(si6->sin6_addr.s6_addr, ipv4mapprefix, sizeof(ipv4mapprefix))) == 0) {
381 maskbytes = (128 - mask) / 8; /* maskbytes really are those that will be 0'ed */
384 for (i = maskbytes - 1; i >= 0; i--)
385 si6->sin6_addr.s6_addr[15 - i] = 0;
387 si6->sin6_addr.s6_addr[15 - maskbytes] &= ~((1 << (8 - maskbits)) - 1);
396 * @brief compare IP addresses for equality
398 * @param sa1 (r) pointer to an struct sockaddr
399 * @param sa2 (r) pointer to an struct sockaddr
401 * @returns Addresses are converted to strings and compared with strcmp and
402 * the result of strcmp is returned.
404 * @note IPv6 mapped IPv4 addresses are treated as IPv4 addresses.
406 int compare_ip(const struct sockaddr *sa1, const struct sockaddr *sa2)
412 ip1 = strdup(getip_string(sa1));
413 ip2 = getip_string(sa2);
415 ret = strcmp(ip1, ip2);
422 #define POLL_FD_SET_STARTSIZE 512
423 #define POLL_FD_SET_INCREASE 128
425 * Add a fd to a dynamic pollfd array that is allocated and grown as needed
427 * This uses an additional array of struct polldata which stores type information
428 * (enum fdtype) and a pointer to anciliary user data.
430 * 1. Allocate the arrays with an intial size of [POLL_FD_SET_STARTSIZE] if
432 * 2. Grow array as needed
433 * 3. Fill in both array elements and increase count of used elements
435 * @param fdsetp (rw) pointer to callers pointer to the pollfd array
436 * @param polldatap (rw) pointer to callers pointer to the polldata array
437 * @param fdset_usedp (rw) pointer to an int with the number of used elements
438 * @param fdset_sizep (rw) pointer to an int which stores the array sizes
439 * @param fd (r) file descriptor to add to the arrays
440 * @param fdtype (r) type of fd, currently IPC_FD or LISTEN_FD
441 * @param data (rw) pointer to data the caller want to associate with an fd
443 void fdset_add_fd(struct pollfd **fdsetp,
444 struct polldata **polldatap,
451 struct pollfd *fdset = *fdsetp;
452 struct polldata *polldata = *polldatap;
453 int fdset_size = *fdset_sizep;
455 LOG(log_debug, logtype_default, "fdset_add_fd: adding fd %i in slot %i", fd, *fdset_usedp);
457 if (fdset == NULL) { /* 1 */
458 /* Initialize with space for 512 fds */
459 fdset = calloc(POLL_FD_SET_STARTSIZE, sizeof(struct pollfd));
463 polldata = calloc(POLL_FD_SET_STARTSIZE, sizeof(struct polldata));
468 *fdset_sizep = fdset_size;
470 *polldatap = polldata;
473 if (*fdset_usedp >= fdset_size) { /* 2 */
474 fdset = realloc(fdset, sizeof(struct pollfd) * (fdset_size + POLL_FD_SET_INCREASE));
478 polldata = realloc(polldata, sizeof(struct polldata) * (fdset_size + POLL_FD_SET_INCREASE));
479 if (polldata == NULL)
482 fdset_size += POLL_FD_SET_INCREASE;
483 *fdset_sizep = fdset_size;
485 *polldatap = polldata;
489 fdset[*fdset_usedp].fd = fd;
490 fdset[*fdset_usedp].events = POLLIN;
491 polldata[*fdset_usedp].fdtype = fdtype;
492 polldata[*fdset_usedp].data = data;
497 * Remove a fd from our pollfd array
501 * 2b If we remove the last array elemnt, just decrease count
502 * 3. If found move all following elements down by one
503 * 4. Decrease count of used elements in array
505 * This currently doesn't shrink the allocated storage of the array.
507 * @param fdsetp (rw) pointer to callers pointer to the pollfd array
508 * @param polldatap (rw) pointer to callers pointer to the polldata array
509 * @param fdset_usedp (rw) pointer to an int with the number of used elements
510 * @param fdset_sizep (rw) pointer to an int which stores the array sizes
511 * @param fd (r) file descriptor to remove from the arrays
513 void fdset_del_fd(struct pollfd **fdsetp,
514 struct polldata **polldatap,
516 int *fdset_sizep _U_,
519 struct pollfd *fdset = *fdsetp;
520 struct polldata *polldata = *polldatap;
522 if (*fdset_usedp < 1)
525 for (int i = 0; i < *fdset_usedp; i++) {
526 if (fdset[i].fd == fd) { /* 1 */
527 if (i == 0 && *fdset_usedp == 1) { /* 2a */
529 memset(&polldata[i], 0, sizeof(struct polldata));
530 } else if (i < (*fdset_usedp - 1)) { /* 2b */
531 memmove(&fdset[i], &fdset[i+1], (*fdset_usedp - 1) * sizeof(struct pollfd)); /* 3 */
532 memmove(&polldata[i], &polldata[i+1], (*fdset_usedp - 1) * sizeof(struct polldata)); /* 3 */
540 /* Length of the space taken up by a padded control message of length len */
542 #define CMSG_SPACE(len) (__CMSG_ALIGN(sizeof(struct cmsghdr)) + __CMSG_ALIGN(len))
546 * Receive a fd on a suitable socket
547 * @args fd (r) PF_UNIX socket to receive on
548 * @args nonblocking (r) 0: fd is in blocking mode - 1: fd is nonblocking, poll for 1 sec
549 * @returns fd on success, -1 on error
551 int recv_fd(int fd, int nonblocking)
556 struct cmsghdr *cmsgp = NULL;
557 char buf[CMSG_SPACE(sizeof(int))];
559 struct pollfd pollfds[1];
562 pollfds[0].events = POLLIN;
564 memset(&msgh,0,sizeof(msgh));
565 memset(buf,0,sizeof(buf));
567 msgh.msg_name = NULL;
568 msgh.msg_namelen = 0;
573 iov[0].iov_base = dbuf;
574 iov[0].iov_len = sizeof(dbuf);
576 msgh.msg_control = buf;
577 msgh.msg_controllen = sizeof(buf);
581 ret = poll(pollfds, 1, 2000); /* poll 2 seconds, evtl. multipe times (EINTR) */
582 } while ( ret == -1 && errno == EINTR );
585 ret = recvmsg(fd, &msgh, 0);
588 ret = recvmsg(fd, &msgh, 0);
589 } while ( ret == -1 && errno == EINTR );
596 for ( cmsgp = CMSG_FIRSTHDR(&msgh); cmsgp != NULL; cmsgp = CMSG_NXTHDR(&msgh,cmsgp) ) {
597 if ( cmsgp->cmsg_level == SOL_SOCKET && cmsgp->cmsg_type == SCM_RIGHTS ) {
598 return *(int *) CMSG_DATA(cmsgp);
602 if ( ret == sizeof (int) )
603 errno = *(int *)dbuf; /* Rcvd errno */
605 errno = ENOENT; /* Default errno */
611 * Send a fd across a suitable socket
613 int send_fd(int socket, int fd)
618 struct cmsghdr *cmsgp = NULL;
623 size = CMSG_SPACE(sizeof fd);
626 LOG(log_error, logtype_cnid, "error in sendmsg: %s", strerror(errno));
630 memset(&msgh,0,sizeof (msgh));
633 msgh.msg_name = NULL;
634 msgh.msg_namelen = 0;
639 iov[0].iov_base = &er;
640 iov[0].iov_len = sizeof(er);
642 msgh.msg_control = buf;
643 msgh.msg_controllen = size;
645 cmsgp = CMSG_FIRSTHDR(&msgh);
646 cmsgp->cmsg_level = SOL_SOCKET;
647 cmsgp->cmsg_type = SCM_RIGHTS;
648 cmsgp->cmsg_len = CMSG_LEN(sizeof(fd));
650 *((int *)CMSG_DATA(cmsgp)) = fd;
651 msgh.msg_controllen = cmsgp->cmsg_len;
654 ret = sendmsg(socket,&msgh, 0);
655 } while ( ret == -1 && errno == EINTR );
657 LOG(log_error, logtype_cnid, "error in sendmsg: %s", strerror(errno));