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 */
26 #include <sys/types.h>
27 #include <sys/socket.h>
28 #include <arpa/inet.h>
29 #include <netinet/in.h>
35 #include <sys/ioctl.h>
37 #include <atalk/logger.h>
38 #include <atalk/util.h>
40 static char ipv4mapprefix[] = {0,0,0,0,0,0,0,0,0,0,0xff,0xff};
43 * @brief set or unset non-blocking IO on a fd
45 * @param fd (r) File descriptor
46 * @param cmd (r) 0: disable non-blocking IO, ie block\n
47 * <>0: enable non-blocking IO
49 * @returns 0 on success, -1 on failure
51 int setnonblock(int fd, int cmd)
56 if ((fdflags = ofdflags = fcntl(fd, F_GETFL, 0)) == -1)
60 fdflags |= O_NONBLOCK;
62 fdflags &= ~O_NONBLOCK;
64 if (fdflags != ofdflags)
65 if (fcntl(fd, F_SETFL, fdflags) == -1)
72 * non-blocking drop-in replacement for read with timeout using select
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
81 * @returns number of bytes actually read or -1 on fatal error
83 ssize_t readt(int socket, void *data, const size_t length, int setnonblocking, int timeout)
87 struct timeval now, end, tv;
92 if (setnonblock(socket, 1) != 0)
96 /* Calculate end time */
97 (void)gettimeofday(&now, NULL);
99 end.tv_sec += timeout;
101 while (stored < length) {
102 len = read(socket, (char *) data + stored, length - stored);
109 FD_SET(socket, &rfds);
113 while ((ret = select(socket + 1, &rfds, NULL, NULL, &tv)) < 1) {
116 LOG(log_warning, logtype_afpd, "select timeout %d s", timeout);
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);
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;
130 tv.tv_usec = end.tv_usec - now.tv_usec;
131 tv.tv_sec = end.tv_sec - now.tv_sec;
134 FD_SET(socket, &rfds);
137 LOG(log_error, logtype_afpd, "select: %s", strerror(errno));
141 } /* while (select) */
143 } /* switch (errno) */
144 LOG(log_error, logtype_afpd, "read: %s", strerror(errno));
152 } /* while (stored < length) */
155 if (setnonblocking) {
156 if (setnonblock(socket, 0) != 0)
160 if (len == -1 && stored == 0)
161 /* last read or select got an error and we haven't got yet anything => return -1*/
167 * non-blocking drop-in replacement for read with timeout using select
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
176 * @returns number of bytes actually read or -1 on fatal error
178 ssize_t writet(int socket, void *data, const size_t length, int setnonblocking, int timeout)
182 struct timeval now, end, tv;
186 if (setnonblocking) {
187 if (setnonblock(socket, 1) != 0)
191 /* Calculate end time */
192 (void)gettimeofday(&now, NULL);
194 end.tv_sec += timeout;
196 while (stored < length) {
197 len = write(socket, (char *) data + stored, length - stored);
204 FD_SET(socket, &rfds);
208 while ((ret = select(socket + 1, &rfds, NULL, NULL, &tv)) < 1) {
211 LOG(log_warning, logtype_afpd, "select timeout %d s", timeout);
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);
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;
225 tv.tv_usec = end.tv_usec - now.tv_usec;
226 tv.tv_sec = end.tv_sec - now.tv_sec;
229 FD_SET(socket, &rfds);
232 LOG(log_error, logtype_afpd, "select: %s", strerror(errno));
236 } /* while (select) */
238 } /* switch (errno) */
239 LOG(log_error, logtype_afpd, "read: %s", strerror(errno));
247 } /* while (stored < length) */
250 if (setnonblocking) {
251 if (setnonblock(socket, 0) != 0)
255 if (len == -1 && stored == 0)
256 /* last read or select got an error and we haven't got yet anything => return -1*/
262 * @brief convert an IPv4 or IPv6 address to a static string using inet_ntop
264 * IPv6 mapped IPv4 addresses are returned as IPv4 addreses eg
265 * ::ffff:10.0.0.0 is returned as "10.0.0.0".
267 * @param sa (r) pointer to an struct sockaddr
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.
272 const char *getip_string(const struct sockaddr *sa)
274 static char ip4[INET_ADDRSTRLEN];
275 static char ip6[INET6_ADDRSTRLEN];
277 switch (sa->sa_family) {
280 const struct sockaddr_in *sai4 = (const struct sockaddr_in *)sa;
281 if ((inet_ntop(AF_INET, &(sai4->sin_addr), ip4, INET_ADDRSTRLEN)) == NULL)
286 const struct sockaddr_in6 *sai6 = (const struct sockaddr_in6 *)sa;
287 if ((inet_ntop(AF_INET6, &(sai6->sin6_addr), ip6, INET6_ADDRSTRLEN)) == NULL)
290 /* Deal with IPv6 mapped IPv4 addresses*/
291 if ((memcmp(sai6->sin6_addr.s6_addr, ipv4mapprefix, sizeof(ipv4mapprefix))) == 0)
292 return (strrchr(ip6, ':') + 1);
296 return "getip_string ERROR";
299 /* We never get here */
303 * @brief return port number from struct sockaddr
305 * @param sa (r) pointer to an struct sockaddr
307 * @returns port as unsigned int
309 unsigned int getip_port(const struct sockaddr *sa)
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);
315 const struct sockaddr_in6 *sai6 = (const struct sockaddr_in6 *)sa;
316 return ntohs(sai6->sin6_port);
319 /* We never get here */
323 * @brief apply netmask to IP (v4 or v6)
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.
330 * @param ai (rw) pointer to an struct sockaddr
331 * @parma mask (r) number of maskbits
333 void apply_ip_mask(struct sockaddr *sa, int mask)
336 switch (sa->sa_family) {
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);
350 int i, maskbytes, maskbits;
351 struct sockaddr_in6 *si6 = (struct sockaddr_in6 *)sa;
353 /* Deal with IPv6 mapped IPv4 addresses*/
354 if ((memcmp(si6->sin6_addr.s6_addr, ipv4mapprefix, sizeof(ipv4mapprefix))) == 0) {
360 maskbytes = (128 - mask) / 8; /* maskbytes really are those that will be 0'ed */
363 for (i = maskbytes - 1; i >= 0; i--)
364 si6->sin6_addr.s6_addr[15 - i] = 0;
366 si6->sin6_addr.s6_addr[15 - maskbytes] &= ~((1 << (8 - maskbits)) - 1);
375 * @brief compare IP addresses for equality
377 * @param sa1 (r) pointer to an struct sockaddr
378 * @param sa2 (r) pointer to an struct sockaddr
380 * @returns Addresses are converted to strings and compared with strcmp and
381 * the result of strcmp is returned.
383 * @note IPv6 mapped IPv4 addresses are treated as IPv4 addresses.
385 int compare_ip(const struct sockaddr *sa1, const struct sockaddr *sa2)
391 ip1 = strdup(getip_string(sa1));
392 ip2 = getip_string(sa2);
394 ret = strcmp(ip1, ip2);
401 #define POLL_FD_SET_STARTSIZE 512
402 #define POLL_FD_SET_INCREASE 128
404 * Add a fd to a dynamic pollfd array that is allocated and grown as needed
406 * This uses an additional array of struct polldata which stores type information
407 * (enum fdtype) and a pointer to anciliary user data.
409 * 1. Allocate the arrays with an intial size of [POLL_FD_SET_STARTSIZE] if
411 * 2. Grow array as needed
412 * 3. Fill in both array elements and increase count of used elements
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
422 void fdset_add_fd(struct pollfd **fdsetp,
423 struct polldata **polldatap,
430 struct pollfd *fdset = *fdsetp;
431 struct polldata *polldata = *polldatap;
432 int fdset_size = *fdset_sizep;
434 LOG(log_debug, logtype_default, "fdset_add_fd: adding fd %i in slot %i", fd, *fdset_usedp);
436 if (fdset == NULL) { /* 1 */
437 /* Initialize with space for 512 fds */
438 fdset = calloc(POLL_FD_SET_STARTSIZE, sizeof(struct pollfd));
442 polldata = calloc(POLL_FD_SET_STARTSIZE, sizeof(struct polldata));
447 *fdset_sizep = fdset_size;
449 *polldatap = polldata;
452 if (*fdset_usedp >= fdset_size) { /* 2 */
453 fdset = realloc(fdset, sizeof(struct pollfd) * (fdset_size + POLL_FD_SET_INCREASE));
457 polldata = realloc(polldata, sizeof(struct polldata) * (fdset_size + POLL_FD_SET_INCREASE));
458 if (polldata == NULL)
461 fdset_size += POLL_FD_SET_INCREASE;
462 *fdset_sizep = fdset_size;
464 *polldatap = polldata;
468 fdset[*fdset_usedp].fd = fd;
469 fdset[*fdset_usedp].events = POLLIN;
470 polldata[*fdset_usedp].fdtype = fdtype;
471 polldata[*fdset_usedp].data = data;
476 * Remove a fd from our pollfd array
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
483 * This currently doesn't shrink the allocated storage of the array.
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
491 void fdset_del_fd(struct pollfd **fdsetp,
492 struct polldata **polldatap,
494 int *fdset_sizep _U_,
497 struct pollfd *fdset = *fdsetp;
498 struct polldata *polldata = *polldatap;
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 */
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
518 int recv_fd(int fd, int nonblocking)
523 struct cmsghdr *cmsgp = NULL;
524 char buf[CMSG_SPACE(sizeof(int))];
526 struct pollfd pollfds[1];
529 pollfds[0].events = POLLIN;
531 memset(&msgh,0,sizeof(msgh));
532 memset(buf,0,sizeof(buf));
534 msgh.msg_name = NULL;
535 msgh.msg_namelen = 0;
540 iov[0].iov_base = dbuf;
541 iov[0].iov_len = sizeof(dbuf);
543 msgh.msg_control = buf;
544 msgh.msg_controllen = sizeof(buf);
548 ret = poll(pollfds, 1, 2000); /* poll 2 seconds, evtl. multipe times (EINTR) */
549 } while ( ret == -1 && errno == EINTR );
552 ret = recvmsg(fd, &msgh, 0);
555 ret = recvmsg(fd, &msgh, 0);
556 } while ( ret == -1 && errno == EINTR );
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);
569 if ( ret == sizeof (int) )
570 errno = *(int *)dbuf; /* Rcvd errno */
572 errno = ENOENT; /* Default errno */
578 * Send a fd across a suitable socket
580 int send_fd(int socket, int fd)
585 struct cmsghdr *cmsgp = NULL;
590 size = CMSG_SPACE(sizeof fd);
593 LOG(log_error, logtype_cnid, "error in sendmsg: %s", strerror(errno));
597 memset(&msgh,0,sizeof (msgh));
600 msgh.msg_name = NULL;
601 msgh.msg_namelen = 0;
606 iov[0].iov_base = &er;
607 iov[0].iov_len = sizeof(er);
609 msgh.msg_control = buf;
610 msgh.msg_controllen = size;
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));
617 *((int *)CMSG_DATA(cmsgp)) = fd;
618 msgh.msg_controllen = cmsgp->cmsg_len;
621 ret = sendmsg(socket,&msgh, 0);
622 } while ( ret == -1 && errno == EINTR );
624 LOG(log_error, logtype_cnid, "error in sendmsg: %s", strerror(errno));