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 #include <atalk/standards.h>
28 #include <sys/types.h>
29 #include <sys/socket.h>
31 #include <netinet/in.h>
32 #include <arpa/inet.h>
38 #include <sys/ioctl.h>
40 #include <atalk/logger.h>
41 #include <atalk/util.h>
42 #include <atalk/errchk.h>
44 static char ipv4mapprefix[] = {0,0,0,0,0,0,0,0,0,0,0xff,0xff};
47 * @brief set or unset non-blocking IO on a fd
49 * @param fd (r) File descriptor
50 * @param cmd (r) 0: disable non-blocking IO, ie block\n
51 * <>0: enable non-blocking IO
53 * @returns 0 on success, -1 on failure
55 int setnonblock(int fd, int cmd)
60 if ((fdflags = ofdflags = fcntl(fd, F_GETFL, 0)) == -1)
64 fdflags |= O_NONBLOCK;
66 fdflags &= ~O_NONBLOCK;
68 if (fdflags != ofdflags)
69 if (fcntl(fd, F_SETFL, fdflags) == -1)
76 * non-blocking drop-in replacement for read with timeout using select
78 * @param socket (r) socket, if in blocking mode, pass "setnonblocking" arg as 1
79 * @param data (rw) buffer for the read data
80 * @param lenght (r) how many bytes to read
81 * @param setnonblocking (r) when non-zero this func will enable and disable non blocking
82 * io mode for the socket
83 * @param timeout (r) number of seconds to try reading, 0 means no timeout
85 * @returns number of bytes actually read or -1 on timeout or error
87 ssize_t readt(int socket, void *data, const size_t length, int setnonblocking, int timeout)
91 struct timeval now, end, tv;
98 if (setnonblock(socket, 1) != 0)
102 /* Calculate end time */
104 (void)gettimeofday(&now, NULL);
106 end.tv_sec += timeout;
109 while (stored < length) {
110 len = recv(socket, (char *) data + stored, length - stored, 0);
116 FD_SET(socket, &rfds);
122 while ((ret = select(socket + 1, &rfds, NULL, NULL, timeout ? &tv : NULL)) < 1) {
125 LOG(log_debug, logtype_dsi, "select timeout %d s", timeout);
133 (void)gettimeofday(&now, NULL);
134 if (now.tv_sec > end.tv_sec
136 (now.tv_sec == end.tv_sec && now.tv_usec >= end.tv_usec)) {
137 LOG(log_debug, logtype_afpd, "select timeout %d s", timeout);
140 if (now.tv_usec > end.tv_usec) {
141 tv.tv_usec = 1000000 + end.tv_usec - now.tv_usec;
142 tv.tv_sec = end.tv_sec - now.tv_sec - 1;
144 tv.tv_usec = end.tv_usec - now.tv_usec;
145 tv.tv_sec = end.tv_sec - now.tv_sec;
148 FD_SET(socket, &rfds);
151 /* possibly entered disconnected state, don't spam log here */
152 LOG(log_debug, logtype_afpd, "select: %s", strerror(errno));
156 LOG(log_error, logtype_afpd, "select: %s", strerror(errno));
161 } /* while (select) */
163 } /* switch (errno) */
164 LOG(log_error, logtype_afpd, "read: %s", strerror(errno));
172 } /* while (stored < length) */
175 if (setnonblocking) {
176 if (setnonblock(socket, 0) != 0)
180 if (len == -1 && stored == 0)
181 /* last read or select got an error and we haven't got yet anything => return -1*/
187 * non-blocking drop-in replacement for read with timeout using select
189 * @param socket (r) socket, if in blocking mode, pass "setnonblocking" arg as 1
190 * @param data (rw) buffer for the read data
191 * @param lenght (r) how many bytes to read
192 * @param setnonblocking (r) when non-zero this func will enable and disable non blocking
193 * io mode for the socket
194 * @param timeout (r) number of seconds to try reading
196 * @returns number of bytes actually read or -1 on fatal error
198 ssize_t writet(int socket, void *data, const size_t length, int setnonblocking, int timeout)
202 struct timeval now, end, tv;
206 if (setnonblocking) {
207 if (setnonblock(socket, 1) != 0)
211 /* Calculate end time */
212 (void)gettimeofday(&now, NULL);
214 end.tv_sec += timeout;
216 while (stored < length) {
217 len = write(socket, (char *) data + stored, length - stored);
224 FD_SET(socket, &rfds);
228 while ((ret = select(socket + 1, &rfds, NULL, NULL, &tv)) < 1) {
231 LOG(log_warning, logtype_afpd, "select timeout %d s", timeout);
235 if (errno == EINTR) {
236 (void)gettimeofday(&now, NULL);
237 if (now.tv_sec >= end.tv_sec && now.tv_usec >= end.tv_usec) {
238 LOG(log_warning, logtype_afpd, "select timeout %d s", timeout);
241 if (now.tv_usec > end.tv_usec) {
242 tv.tv_usec = 1000000 + end.tv_usec - now.tv_usec;
243 tv.tv_sec = end.tv_sec - now.tv_sec - 1;
245 tv.tv_usec = end.tv_usec - now.tv_usec;
246 tv.tv_sec = end.tv_sec - now.tv_sec;
249 FD_SET(socket, &rfds);
252 LOG(log_error, logtype_afpd, "select: %s", strerror(errno));
256 } /* while (select) */
258 } /* switch (errno) */
259 LOG(log_error, logtype_afpd, "read: %s", strerror(errno));
267 } /* while (stored < length) */
270 if (setnonblocking) {
271 if (setnonblock(socket, 0) != 0)
275 if (len == -1 && stored == 0)
276 /* last read or select got an error and we haven't got yet anything => return -1*/
282 * @brief convert an IPv4 or IPv6 address to a static string using inet_ntop
284 * IPv6 mapped IPv4 addresses are returned as IPv4 addreses eg
285 * ::ffff:10.0.0.0 is returned as "10.0.0.0".
287 * @param sa (r) pointer to an struct sockaddr
289 * @returns pointer to a static string cotaining the converted address as string.\n
290 * On error pointers to "0.0.0.0" or "::0" are returned.
292 const char *getip_string(const struct sockaddr *sa)
294 static char ip4[INET_ADDRSTRLEN];
295 static char ip6[INET6_ADDRSTRLEN];
297 switch (sa->sa_family) {
300 const struct sockaddr_in *sai4 = (const struct sockaddr_in *)sa;
301 if ((inet_ntop(AF_INET, &(sai4->sin_addr), ip4, INET_ADDRSTRLEN)) == NULL)
306 const struct sockaddr_in6 *sai6 = (const struct sockaddr_in6 *)sa;
307 if ((inet_ntop(AF_INET6, &(sai6->sin6_addr), ip6, INET6_ADDRSTRLEN)) == NULL)
310 /* Deal with IPv6 mapped IPv4 addresses*/
311 if ((memcmp(sai6->sin6_addr.s6_addr, ipv4mapprefix, sizeof(ipv4mapprefix))) == 0)
312 return (strrchr(ip6, ':') + 1);
316 return "getip_string ERROR";
319 /* We never get here */
323 * @brief return port number from struct sockaddr
325 * @param sa (r) pointer to an struct sockaddr
327 * @returns port as unsigned int
329 unsigned int getip_port(const struct sockaddr *sa)
331 if (sa->sa_family == AF_INET) { /* IPv4 */
332 const struct sockaddr_in *sai4 = (const struct sockaddr_in *)sa;
333 return ntohs(sai4->sin_port);
335 const struct sockaddr_in6 *sai6 = (const struct sockaddr_in6 *)sa;
336 return ntohs(sai6->sin6_port);
339 /* We never get here */
343 * @brief apply netmask to IP (v4 or v6)
345 * Modifies IP address in sa->sin[6]_addr-s[6]_addr. The caller is responsible
346 * for passing a value for mask that is sensible to the passed address,
347 * eg 0 <= mask <= 32 for IPv4 or 0<= mask <= 128 for IPv6. mask > 32 for
348 * IPv4 is treated as mask = 32, mask > 128 is set to 128 for IPv6.
350 * @param ai (rw) pointer to an struct sockaddr
351 * @parma mask (r) number of maskbits
353 void apply_ip_mask(struct sockaddr *sa, int mask)
356 switch (sa->sa_family) {
361 struct sockaddr_in *si = (struct sockaddr_in *)sa;
362 uint32_t nmask = mask ? ~((1 << (32 - mask)) - 1) : 0;
363 si->sin_addr.s_addr &= htonl(nmask);
370 int i, maskbytes, maskbits;
371 struct sockaddr_in6 *si6 = (struct sockaddr_in6 *)sa;
373 /* Deal with IPv6 mapped IPv4 addresses*/
374 if ((memcmp(si6->sin6_addr.s6_addr, ipv4mapprefix, sizeof(ipv4mapprefix))) == 0) {
380 maskbytes = (128 - mask) / 8; /* maskbytes really are those that will be 0'ed */
383 for (i = maskbytes - 1; i >= 0; i--)
384 si6->sin6_addr.s6_addr[15 - i] = 0;
386 si6->sin6_addr.s6_addr[15 - maskbytes] &= ~((1 << (8 - maskbits)) - 1);
395 * @brief compare IP addresses for equality
397 * @param sa1 (r) pointer to an struct sockaddr
398 * @param sa2 (r) pointer to an struct sockaddr
400 * @returns Addresses are converted to strings and compared with strcmp and
401 * the result of strcmp is returned.
403 * @note IPv6 mapped IPv4 addresses are treated as IPv4 addresses.
405 int compare_ip(const struct sockaddr *sa1, const struct sockaddr *sa2)
411 ip1 = strdup(getip_string(sa1));
412 ip2 = getip_string(sa2);
414 ret = strcmp(ip1, ip2);
422 * Tokenize IP(4/6) addresses with an optional port into address and port
424 * @param ipurl (r) IP URL string
425 * @param address (w) IP address
426 * @param port (w) IP port
428 * @returns 0 on success, -1 on failure
430 * Tokenize IPv4, IPv4:port, IPv6, [IPv6] or [IPv6:port] URL into address and
431 * port and return two allocated strings with the address and the port.
433 * If the function returns 0, then address point to a newly allocated
434 * valid address string, port may either be NULL or point to a newly
435 * allocated port number.
437 * If the function returns -1, then the contents of address and port are
440 int tokenize_ip_port(const char *ipurl, char **address, char **port)
446 AFP_ASSERT(ipurl && address && port);
447 EC_NULL( p = strdup(ipurl));
449 /* Either ipv4, ipv4:port, ipv6, [ipv6] or [ipv6]:port */
451 if (!strchr(p, ':')) {
452 /* IPv4 address without port */
454 p = NULL; /* prevent free() */
459 /* Either ipv4:port, ipv6, [ipv6] or [ipv6]:port */
461 if (strchr(p, '.')) {
466 EC_NULL( *port = strdup(p + 1));
467 p = NULL; /* prevent free() */
471 /* Either ipv6, [ipv6] or [ipv6]:port */
476 p = NULL; /* prevent free() */
481 /* [ipv6] or [ipv6]:port */
483 EC_NULL( *address = strdup(p + 1) );
485 if ((s = strchr(*address, ']')) == NULL) {
486 LOG(log_error, logtype_dsi, "tokenize_ip_port: malformed ipv6 address %s\n", ipurl);
490 /* address now points to the ipv6 address without [] */
494 EC_NULL( *port = strdup(s + 2) );
507 * Allocate and initialize atalk socket event struct
509 struct asev *asev_init(int max)
511 struct asev *asev = calloc(1, sizeof(struct asev));
517 /* Initialize with space for all possibly active fds */
518 asev->fdset = calloc(max, sizeof(struct pollfd));
519 asev->data = calloc(max, sizeof(struct asev_data));
521 if (asev->fdset == NULL || asev->data == NULL) {
535 * Add a fd to a dynamic pollfd array and associated data array
537 * This uses an additional array of struct polldata which stores type
538 * information (enum fdtype) and a pointer to anciliary user data.
540 bool asev_add_fd(struct asev *asev,
542 enum asev_fdtype fdtype,
549 if (!(asev->used < asev->max)) {
553 asev->fdset[asev->used].fd = fd;
554 asev->fdset[asev->used].events = POLLIN;
555 asev->data[asev->used].fdtype = fdtype;
556 asev->data[asev->used].private = private;
563 * Remove fd from asev
565 * @returns true if the fd was deleted, otherwise false
567 bool asev_del_fd(struct asev *asev, int fd)
576 if (asev->used == 0) {
577 LOG(log_error, logtype_cnid, "asev_del_fd: empty");
581 for (i = 0; i < asev->used; i++) {
583 * Scan the array for a matching fd
585 if (asev->fdset[i].fd == fd) {
589 if ((i + 1) == asev->used) {
591 * it's the last (or only) array element, simply null it
593 asev->fdset[i].fd = -1;
594 asev->data[i].fdtype = 0;
595 asev->data[i].private = NULL;
598 * Move down by one all subsequent elements
600 numafter = asev->used - (i + 1);
601 memmove(&asev->fdset[i], &asev->fdset[i+1],
602 numafter * sizeof(struct pollfd));
603 memmove(&asev->data[i], &asev->data[i+1],
604 numafter * sizeof(struct asev_data));
614 /* Length of the space taken up by a padded control message of length len */
616 #define CMSG_SPACE(len) (__CMSG_ALIGN(sizeof(struct cmsghdr)) + __CMSG_ALIGN(len))
620 * Receive a fd on a suitable socket
621 * @args fd (r) PF_UNIX socket to receive on
622 * @args nonblocking (r) 0: fd is in blocking mode - 1: fd is nonblocking, poll for 1 sec
623 * @returns fd on success, -1 on error
625 int recv_fd(int fd, int nonblocking)
630 struct cmsghdr *cmsgp = NULL;
631 char buf[CMSG_SPACE(sizeof(int))];
633 struct pollfd pollfds[1];
636 pollfds[0].events = POLLIN;
638 memset(&msgh,0,sizeof(msgh));
639 memset(buf,0,sizeof(buf));
641 msgh.msg_name = NULL;
642 msgh.msg_namelen = 0;
647 iov[0].iov_base = dbuf;
648 iov[0].iov_len = sizeof(dbuf);
650 msgh.msg_control = buf;
651 msgh.msg_controllen = sizeof(buf);
655 ret = poll(pollfds, 1, 2000); /* poll 2 seconds, evtl. multipe times (EINTR) */
656 } while ( ret == -1 && errno == EINTR );
659 ret = recvmsg(fd, &msgh, 0);
662 ret = recvmsg(fd, &msgh, 0);
663 } while ( ret == -1 && errno == EINTR );
670 for ( cmsgp = CMSG_FIRSTHDR(&msgh); cmsgp != NULL; cmsgp = CMSG_NXTHDR(&msgh,cmsgp) ) {
671 if ( cmsgp->cmsg_level == SOL_SOCKET && cmsgp->cmsg_type == SCM_RIGHTS ) {
672 return *(int *) CMSG_DATA(cmsgp);
676 if ( ret == sizeof (int) )
677 errno = *(int *)dbuf; /* Rcvd errno */
679 errno = ENOENT; /* Default errno */
685 * Send a fd across a suitable socket
687 int send_fd(int socket, int fd)
692 struct cmsghdr *cmsgp = NULL;
697 size = CMSG_SPACE(sizeof fd);
700 LOG(log_error, logtype_cnid, "error in sendmsg: %s", strerror(errno));
704 memset(&msgh,0,sizeof (msgh));
707 msgh.msg_name = NULL;
708 msgh.msg_namelen = 0;
713 iov[0].iov_base = &er;
714 iov[0].iov_len = sizeof(er);
716 msgh.msg_control = buf;
717 msgh.msg_controllen = size;
719 cmsgp = CMSG_FIRSTHDR(&msgh);
720 cmsgp->cmsg_level = SOL_SOCKET;
721 cmsgp->cmsg_type = SCM_RIGHTS;
722 cmsgp->cmsg_len = CMSG_LEN(sizeof(fd));
724 *((int *)CMSG_DATA(cmsgp)) = fd;
725 msgh.msg_controllen = cmsgp->cmsg_len;
728 ret = sendmsg(socket,&msgh, 0);
729 } while ( ret == -1 && errno == EINTR );
731 LOG(log_error, logtype_cnid, "error in sendmsg: %s", strerror(errno));