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_maxdebug, logtype_afpd, "select timeout %d s", timeout);
133 if (errno == EINTR) {
134 (void)gettimeofday(&now, NULL);
135 if (now.tv_sec >= end.tv_sec && now.tv_usec >= end.tv_usec) {
136 LOG(log_warning, logtype_afpd, "select timeout %d s", timeout);
139 if (now.tv_usec > end.tv_usec) {
140 tv.tv_usec = 1000000 + end.tv_usec - now.tv_usec;
141 tv.tv_sec = end.tv_sec - now.tv_sec - 1;
143 tv.tv_usec = end.tv_usec - now.tv_usec;
144 tv.tv_sec = end.tv_sec - now.tv_sec;
146 FD_SET(socket, &rfds);
149 LOG(log_error, logtype_afpd, "select: %s", strerror(errno));
153 } /* while (select) */
155 } /* switch (errno) */
156 LOG(log_error, logtype_afpd, "read: %s", strerror(errno));
164 } /* while (stored < length) */
167 if (setnonblocking) {
168 if (setnonblock(socket, 0) != 0)
172 if (len == -1 && stored == 0)
173 /* last read or select got an error and we haven't got yet anything => return -1*/
179 * non-blocking drop-in replacement for read with timeout using select
181 * @param socket (r) socket, if in blocking mode, pass "setnonblocking" arg as 1
182 * @param data (rw) buffer for the read data
183 * @param lenght (r) how many bytes to read
184 * @param setnonblocking (r) when non-zero this func will enable and disable non blocking
185 * io mode for the socket
186 * @param timeout (r) number of seconds to try reading
188 * @returns number of bytes actually read or -1 on fatal error
190 ssize_t writet(int socket, void *data, const size_t length, int setnonblocking, int timeout)
194 struct timeval now, end, tv;
198 if (setnonblocking) {
199 if (setnonblock(socket, 1) != 0)
203 /* Calculate end time */
204 (void)gettimeofday(&now, NULL);
206 end.tv_sec += timeout;
208 while (stored < length) {
209 len = write(socket, (char *) data + stored, length - stored);
216 FD_SET(socket, &rfds);
220 while ((ret = select(socket + 1, &rfds, NULL, NULL, &tv)) < 1) {
223 LOG(log_warning, logtype_afpd, "select timeout %d s", timeout);
227 if (errno == EINTR) {
228 (void)gettimeofday(&now, NULL);
229 if (now.tv_sec >= end.tv_sec && now.tv_usec >= end.tv_usec) {
230 LOG(log_warning, logtype_afpd, "select timeout %d s", timeout);
233 if (now.tv_usec > end.tv_usec) {
234 tv.tv_usec = 1000000 + end.tv_usec - now.tv_usec;
235 tv.tv_sec = end.tv_sec - now.tv_sec - 1;
237 tv.tv_usec = end.tv_usec - now.tv_usec;
238 tv.tv_sec = end.tv_sec - now.tv_sec;
241 FD_SET(socket, &rfds);
244 LOG(log_error, logtype_afpd, "select: %s", strerror(errno));
248 } /* while (select) */
250 } /* switch (errno) */
251 LOG(log_error, logtype_afpd, "read: %s", strerror(errno));
259 } /* while (stored < length) */
262 if (setnonblocking) {
263 if (setnonblock(socket, 0) != 0)
267 if (len == -1 && stored == 0)
268 /* last read or select got an error and we haven't got yet anything => return -1*/
274 * @brief convert an IPv4 or IPv6 address to a static string using inet_ntop
276 * IPv6 mapped IPv4 addresses are returned as IPv4 addreses eg
277 * ::ffff:10.0.0.0 is returned as "10.0.0.0".
279 * @param sa (r) pointer to an struct sockaddr
281 * @returns pointer to a static string cotaining the converted address as string.\n
282 * On error pointers to "0.0.0.0" or "::0" are returned.
284 const char *getip_string(const struct sockaddr *sa)
286 static char ip4[INET_ADDRSTRLEN];
287 static char ip6[INET6_ADDRSTRLEN];
289 switch (sa->sa_family) {
292 const struct sockaddr_in *sai4 = (const struct sockaddr_in *)sa;
293 if ((inet_ntop(AF_INET, &(sai4->sin_addr), ip4, INET_ADDRSTRLEN)) == NULL)
298 const struct sockaddr_in6 *sai6 = (const struct sockaddr_in6 *)sa;
299 if ((inet_ntop(AF_INET6, &(sai6->sin6_addr), ip6, INET6_ADDRSTRLEN)) == NULL)
302 /* Deal with IPv6 mapped IPv4 addresses*/
303 if ((memcmp(sai6->sin6_addr.s6_addr, ipv4mapprefix, sizeof(ipv4mapprefix))) == 0)
304 return (strrchr(ip6, ':') + 1);
308 return "getip_string ERROR";
311 /* We never get here */
315 * @brief return port number from struct sockaddr
317 * @param sa (r) pointer to an struct sockaddr
319 * @returns port as unsigned int
321 unsigned int getip_port(const struct sockaddr *sa)
323 if (sa->sa_family == AF_INET) { /* IPv4 */
324 const struct sockaddr_in *sai4 = (const struct sockaddr_in *)sa;
325 return ntohs(sai4->sin_port);
327 const struct sockaddr_in6 *sai6 = (const struct sockaddr_in6 *)sa;
328 return ntohs(sai6->sin6_port);
331 /* We never get here */
335 * @brief apply netmask to IP (v4 or v6)
337 * Modifies IP address in sa->sin[6]_addr-s[6]_addr. The caller is responsible
338 * for passing a value for mask that is sensible to the passed address,
339 * eg 0 <= mask <= 32 for IPv4 or 0<= mask <= 128 for IPv6. mask > 32 for
340 * IPv4 is treated as mask = 32, mask > 128 is set to 128 for IPv6.
342 * @param ai (rw) pointer to an struct sockaddr
343 * @parma mask (r) number of maskbits
345 void apply_ip_mask(struct sockaddr *sa, int mask)
348 switch (sa->sa_family) {
353 struct sockaddr_in *si = (struct sockaddr_in *)sa;
354 uint32_t nmask = mask ? ~((1 << (32 - mask)) - 1) : 0;
355 si->sin_addr.s_addr &= htonl(nmask);
362 int i, maskbytes, maskbits;
363 struct sockaddr_in6 *si6 = (struct sockaddr_in6 *)sa;
365 /* Deal with IPv6 mapped IPv4 addresses*/
366 if ((memcmp(si6->sin6_addr.s6_addr, ipv4mapprefix, sizeof(ipv4mapprefix))) == 0) {
372 maskbytes = (128 - mask) / 8; /* maskbytes really are those that will be 0'ed */
375 for (i = maskbytes - 1; i >= 0; i--)
376 si6->sin6_addr.s6_addr[15 - i] = 0;
378 si6->sin6_addr.s6_addr[15 - maskbytes] &= ~((1 << (8 - maskbits)) - 1);
387 * @brief compare IP addresses for equality
389 * @param sa1 (r) pointer to an struct sockaddr
390 * @param sa2 (r) pointer to an struct sockaddr
392 * @returns Addresses are converted to strings and compared with strcmp and
393 * the result of strcmp is returned.
395 * @note IPv6 mapped IPv4 addresses are treated as IPv4 addresses.
397 int compare_ip(const struct sockaddr *sa1, const struct sockaddr *sa2)
403 ip1 = strdup(getip_string(sa1));
404 ip2 = getip_string(sa2);
406 ret = strcmp(ip1, ip2);
413 #define POLL_FD_SET_STARTSIZE 512
414 #define POLL_FD_SET_INCREASE 128
416 * Add a fd to a dynamic pollfd array that is allocated and grown as needed
418 * This uses an additional array of struct polldata which stores type information
419 * (enum fdtype) and a pointer to anciliary user data.
421 * 1. Allocate the arrays with an intial size of [POLL_FD_SET_STARTSIZE] if
423 * 2. Grow array as needed
424 * 3. Fill in both array elements and increase count of used elements
426 * @param fdsetp (rw) pointer to callers pointer to the pollfd array
427 * @param polldatap (rw) pointer to callers pointer to the polldata array
428 * @param fdset_usedp (rw) pointer to an int with the number of used elements
429 * @param fdset_sizep (rw) pointer to an int which stores the array sizes
430 * @param fd (r) file descriptor to add to the arrays
431 * @param fdtype (r) type of fd, currently IPC_FD or LISTEN_FD
432 * @param data (rw) pointer to data the caller want to associate with an fd
434 void fdset_add_fd(struct pollfd **fdsetp,
435 struct polldata **polldatap,
442 struct pollfd *fdset = *fdsetp;
443 struct polldata *polldata = *polldatap;
444 int fdset_size = *fdset_sizep;
446 LOG(log_debug, logtype_default, "fdset_add_fd: adding fd %i in slot %i", fd, *fdset_usedp);
448 if (fdset == NULL) { /* 1 */
449 /* Initialize with space for 512 fds */
450 fdset = calloc(POLL_FD_SET_STARTSIZE, sizeof(struct pollfd));
454 polldata = calloc(POLL_FD_SET_STARTSIZE, sizeof(struct polldata));
459 *fdset_sizep = fdset_size;
461 *polldatap = polldata;
464 if (*fdset_usedp >= fdset_size) { /* 2 */
465 fdset = realloc(fdset, sizeof(struct pollfd) * (fdset_size + POLL_FD_SET_INCREASE));
469 polldata = realloc(polldata, sizeof(struct polldata) * (fdset_size + POLL_FD_SET_INCREASE));
470 if (polldata == NULL)
473 fdset_size += POLL_FD_SET_INCREASE;
474 *fdset_sizep = fdset_size;
476 *polldatap = polldata;
480 fdset[*fdset_usedp].fd = fd;
481 fdset[*fdset_usedp].events = POLLIN;
482 polldata[*fdset_usedp].fdtype = fdtype;
483 polldata[*fdset_usedp].data = data;
488 * Remove a fd from our pollfd array
492 * 2b If we remove the last array elemnt, just decrease count
493 * 3. If found move all following elements down by one
494 * 4. Decrease count of used elements in array
496 * This currently doesn't shrink the allocated storage of the array.
498 * @param fdsetp (rw) pointer to callers pointer to the pollfd array
499 * @param polldatap (rw) pointer to callers pointer to the polldata array
500 * @param fdset_usedp (rw) pointer to an int with the number of used elements
501 * @param fdset_sizep (rw) pointer to an int which stores the array sizes
502 * @param fd (r) file descriptor to remove from the arrays
504 void fdset_del_fd(struct pollfd **fdsetp,
505 struct polldata **polldatap,
507 int *fdset_sizep _U_,
510 struct pollfd *fdset = *fdsetp;
511 struct polldata *polldata = *polldatap;
513 if (*fdset_usedp < 1)
516 for (int i = 0; i < *fdset_usedp; i++) {
517 if (fdset[i].fd == fd) { /* 1 */
518 if (i == 0 && *fdset_usedp == 1) { /* 2a */
520 memset(&polldata[i], 0, sizeof(struct polldata));
521 } else if (i < (*fdset_usedp - 1)) { /* 2b */
522 memmove(&fdset[i], &fdset[i+1], (*fdset_usedp - 1) * sizeof(struct pollfd)); /* 3 */
523 memmove(&polldata[i], &polldata[i+1], (*fdset_usedp - 1) * sizeof(struct polldata)); /* 3 */
531 /* Length of the space taken up by a padded control message of length len */
533 #define CMSG_SPACE(len) (__CMSG_ALIGN(sizeof(struct cmsghdr)) + __CMSG_ALIGN(len))
537 * Receive a fd on a suitable socket
538 * @args fd (r) PF_UNIX socket to receive on
539 * @args nonblocking (r) 0: fd is in blocking mode - 1: fd is nonblocking, poll for 1 sec
540 * @returns fd on success, -1 on error
542 int recv_fd(int fd, int nonblocking)
547 struct cmsghdr *cmsgp = NULL;
548 char buf[CMSG_SPACE(sizeof(int))];
550 struct pollfd pollfds[1];
553 pollfds[0].events = POLLIN;
555 memset(&msgh,0,sizeof(msgh));
556 memset(buf,0,sizeof(buf));
558 msgh.msg_name = NULL;
559 msgh.msg_namelen = 0;
564 iov[0].iov_base = dbuf;
565 iov[0].iov_len = sizeof(dbuf);
567 msgh.msg_control = buf;
568 msgh.msg_controllen = sizeof(buf);
572 ret = poll(pollfds, 1, 2000); /* poll 2 seconds, evtl. multipe times (EINTR) */
573 } while ( ret == -1 && errno == EINTR );
576 ret = recvmsg(fd, &msgh, 0);
579 ret = recvmsg(fd, &msgh, 0);
580 } while ( ret == -1 && errno == EINTR );
587 for ( cmsgp = CMSG_FIRSTHDR(&msgh); cmsgp != NULL; cmsgp = CMSG_NXTHDR(&msgh,cmsgp) ) {
588 if ( cmsgp->cmsg_level == SOL_SOCKET && cmsgp->cmsg_type == SCM_RIGHTS ) {
589 return *(int *) CMSG_DATA(cmsgp);
593 if ( ret == sizeof (int) )
594 errno = *(int *)dbuf; /* Rcvd errno */
596 errno = ENOENT; /* Default errno */
602 * Send a fd across a suitable socket
604 int send_fd(int socket, int fd)
609 struct cmsghdr *cmsgp = NULL;
614 size = CMSG_SPACE(sizeof fd);
617 LOG(log_error, logtype_cnid, "error in sendmsg: %s", strerror(errno));
621 memset(&msgh,0,sizeof (msgh));
624 msgh.msg_name = NULL;
625 msgh.msg_namelen = 0;
630 iov[0].iov_base = &er;
631 iov[0].iov_len = sizeof(er);
633 msgh.msg_control = buf;
634 msgh.msg_controllen = size;
636 cmsgp = CMSG_FIRSTHDR(&msgh);
637 cmsgp->cmsg_level = SOL_SOCKET;
638 cmsgp->cmsg_type = SCM_RIGHTS;
639 cmsgp->cmsg_len = CMSG_LEN(sizeof(fd));
641 *((int *)CMSG_DATA(cmsgp)) = fd;
642 msgh.msg_controllen = cmsgp->cmsg_len;
645 ret = sendmsg(socket,&msgh, 0);
646 } while ( ret == -1 && errno == EINTR );
648 LOG(log_error, logtype_cnid, "error in sendmsg: %s", strerror(errno));