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>
43 static char ipv4mapprefix[] = {0,0,0,0,0,0,0,0,0,0,0xff,0xff};
46 * @brief set or unset non-blocking IO on a fd
48 * @param fd (r) File descriptor
49 * @param cmd (r) 0: disable non-blocking IO, ie block\n
50 * <>0: enable non-blocking IO
52 * @returns 0 on success, -1 on failure
54 int setnonblock(int fd, int cmd)
59 if ((fdflags = ofdflags = fcntl(fd, F_GETFL, 0)) == -1)
63 fdflags |= O_NONBLOCK;
65 fdflags &= ~O_NONBLOCK;
67 if (fdflags != ofdflags)
68 if (fcntl(fd, F_SETFL, fdflags) == -1)
75 * non-blocking drop-in replacement for read with timeout using select
77 * @param socket (r) socket, if in blocking mode, pass "setnonblocking" arg as 1
78 * @param data (rw) buffer for the read data
79 * @param lenght (r) how many bytes to read
80 * @param setnonblocking (r) when non-zero this func will enable and disable non blocking
81 * io mode for the socket
82 * @param timeout (r) number of seconds to try reading
84 * @returns number of bytes actually read or -1 on timeout or error
86 ssize_t readt(int socket, void *data, const size_t length, int setnonblocking, int timeout)
90 struct timeval now, end, tv;
97 if (setnonblock(socket, 1) != 0)
101 /* Calculate end time */
102 (void)gettimeofday(&now, NULL);
104 end.tv_sec += timeout;
106 while (stored < length) {
107 len = read(socket, (char *) data + stored, length - stored);
113 FD_SET(socket, &rfds);
117 while ((ret = select(socket + 1, &rfds, NULL, NULL, &tv)) < 1) {
120 LOG(log_debug, logtype_afpd, "select timeout %d s", timeout);
127 (void)gettimeofday(&now, NULL);
128 if (now.tv_sec > end.tv_sec
130 (now.tv_sec == end.tv_sec && now.tv_usec >= end.tv_usec)) {
131 LOG(log_debug, logtype_afpd, "select timeout %d s", timeout);
134 if (now.tv_usec > end.tv_usec) {
135 tv.tv_usec = 1000000 + end.tv_usec - now.tv_usec;
136 tv.tv_sec = end.tv_sec - now.tv_sec - 1;
138 tv.tv_usec = end.tv_usec - now.tv_usec;
139 tv.tv_sec = end.tv_sec - now.tv_sec;
141 FD_SET(socket, &rfds);
144 /* possibly entered disconnected state, don't spam log here */
145 LOG(log_debug, logtype_afpd, "select: %s", strerror(errno));
149 LOG(log_error, logtype_afpd, "select: %s", strerror(errno));
154 } /* while (select) */
156 } /* switch (errno) */
157 LOG(log_error, logtype_afpd, "read: %s", strerror(errno));
165 } /* while (stored < length) */
168 if (setnonblocking) {
169 if (setnonblock(socket, 0) != 0)
173 if (len == -1 && stored == 0)
174 /* last read or select got an error and we haven't got yet anything => return -1*/
180 * non-blocking drop-in replacement for read with timeout using select
182 * @param socket (r) socket, if in blocking mode, pass "setnonblocking" arg as 1
183 * @param data (rw) buffer for the read data
184 * @param lenght (r) how many bytes to read
185 * @param setnonblocking (r) when non-zero this func will enable and disable non blocking
186 * io mode for the socket
187 * @param timeout (r) number of seconds to try reading
189 * @returns number of bytes actually read or -1 on fatal error
191 ssize_t writet(int socket, void *data, const size_t length, int setnonblocking, int timeout)
195 struct timeval now, end, tv;
199 if (setnonblocking) {
200 if (setnonblock(socket, 1) != 0)
204 /* Calculate end time */
205 (void)gettimeofday(&now, NULL);
207 end.tv_sec += timeout;
209 while (stored < length) {
210 len = write(socket, (char *) data + stored, length - stored);
217 FD_SET(socket, &rfds);
221 while ((ret = select(socket + 1, &rfds, NULL, NULL, &tv)) < 1) {
224 LOG(log_warning, logtype_afpd, "select timeout %d s", timeout);
228 if (errno == EINTR) {
229 (void)gettimeofday(&now, NULL);
230 if (now.tv_sec >= end.tv_sec && now.tv_usec >= end.tv_usec) {
231 LOG(log_warning, logtype_afpd, "select timeout %d s", timeout);
234 if (now.tv_usec > end.tv_usec) {
235 tv.tv_usec = 1000000 + end.tv_usec - now.tv_usec;
236 tv.tv_sec = end.tv_sec - now.tv_sec - 1;
238 tv.tv_usec = end.tv_usec - now.tv_usec;
239 tv.tv_sec = end.tv_sec - now.tv_sec;
242 FD_SET(socket, &rfds);
245 LOG(log_error, logtype_afpd, "select: %s", strerror(errno));
249 } /* while (select) */
251 } /* switch (errno) */
252 LOG(log_error, logtype_afpd, "read: %s", strerror(errno));
260 } /* while (stored < length) */
263 if (setnonblocking) {
264 if (setnonblock(socket, 0) != 0)
268 if (len == -1 && stored == 0)
269 /* last read or select got an error and we haven't got yet anything => return -1*/
275 * @brief convert an IPv4 or IPv6 address to a static string using inet_ntop
277 * IPv6 mapped IPv4 addresses are returned as IPv4 addreses eg
278 * ::ffff:10.0.0.0 is returned as "10.0.0.0".
280 * @param sa (r) pointer to an struct sockaddr
282 * @returns pointer to a static string cotaining the converted address as string.\n
283 * On error pointers to "0.0.0.0" or "::0" are returned.
285 const char *getip_string(const struct sockaddr *sa)
287 static char ip4[INET_ADDRSTRLEN];
288 static char ip6[INET6_ADDRSTRLEN];
290 switch (sa->sa_family) {
293 const struct sockaddr_in *sai4 = (const struct sockaddr_in *)sa;
294 if ((inet_ntop(AF_INET, &(sai4->sin_addr), ip4, INET_ADDRSTRLEN)) == NULL)
299 const struct sockaddr_in6 *sai6 = (const struct sockaddr_in6 *)sa;
300 if ((inet_ntop(AF_INET6, &(sai6->sin6_addr), ip6, INET6_ADDRSTRLEN)) == NULL)
303 /* Deal with IPv6 mapped IPv4 addresses*/
304 if ((memcmp(sai6->sin6_addr.s6_addr, ipv4mapprefix, sizeof(ipv4mapprefix))) == 0)
305 return (strrchr(ip6, ':') + 1);
309 return "getip_string ERROR";
312 /* We never get here */
316 * @brief return port number from struct sockaddr
318 * @param sa (r) pointer to an struct sockaddr
320 * @returns port as unsigned int
322 unsigned int getip_port(const struct sockaddr *sa)
324 if (sa->sa_family == AF_INET) { /* IPv4 */
325 const struct sockaddr_in *sai4 = (const struct sockaddr_in *)sa;
326 return ntohs(sai4->sin_port);
328 const struct sockaddr_in6 *sai6 = (const struct sockaddr_in6 *)sa;
329 return ntohs(sai6->sin6_port);
332 /* We never get here */
336 * @brief apply netmask to IP (v4 or v6)
338 * Modifies IP address in sa->sin[6]_addr-s[6]_addr. The caller is responsible
339 * for passing a value for mask that is sensible to the passed address,
340 * eg 0 <= mask <= 32 for IPv4 or 0<= mask <= 128 for IPv6. mask > 32 for
341 * IPv4 is treated as mask = 32, mask > 128 is set to 128 for IPv6.
343 * @param ai (rw) pointer to an struct sockaddr
344 * @parma mask (r) number of maskbits
346 void apply_ip_mask(struct sockaddr *sa, int mask)
349 switch (sa->sa_family) {
354 struct sockaddr_in *si = (struct sockaddr_in *)sa;
355 uint32_t nmask = mask ? ~((1 << (32 - mask)) - 1) : 0;
356 si->sin_addr.s_addr &= htonl(nmask);
363 int i, maskbytes, maskbits;
364 struct sockaddr_in6 *si6 = (struct sockaddr_in6 *)sa;
366 /* Deal with IPv6 mapped IPv4 addresses*/
367 if ((memcmp(si6->sin6_addr.s6_addr, ipv4mapprefix, sizeof(ipv4mapprefix))) == 0) {
373 maskbytes = (128 - mask) / 8; /* maskbytes really are those that will be 0'ed */
376 for (i = maskbytes - 1; i >= 0; i--)
377 si6->sin6_addr.s6_addr[15 - i] = 0;
379 si6->sin6_addr.s6_addr[15 - maskbytes] &= ~((1 << (8 - maskbits)) - 1);
388 * @brief compare IP addresses for equality
390 * @param sa1 (r) pointer to an struct sockaddr
391 * @param sa2 (r) pointer to an struct sockaddr
393 * @returns Addresses are converted to strings and compared with strcmp and
394 * the result of strcmp is returned.
396 * @note IPv6 mapped IPv4 addresses are treated as IPv4 addresses.
398 int compare_ip(const struct sockaddr *sa1, const struct sockaddr *sa2)
404 ip1 = strdup(getip_string(sa1));
405 ip2 = getip_string(sa2);
407 ret = strcmp(ip1, ip2);
415 * Add a fd to a dynamic pollfd array that is allocated and grown as needed
417 * This uses an additional array of struct polldata which stores type information
418 * (enum fdtype) and a pointer to anciliary user data.
420 * 1. Allocate the arrays with the size of "maxconns" if *fdsetp is NULL.
421 * 2. Fill in both array elements and increase count of used elements
423 * @param maxconns (r) maximum number of connections, determines array size
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(int maxconns,
433 struct pollfd **fdsetp,
434 struct polldata **polldatap,
441 struct pollfd *fdset = *fdsetp;
442 struct polldata *polldata = *polldatap;
443 int fdset_size = *fdset_sizep;
445 LOG(log_debug, logtype_default, "fdset_add_fd: adding fd %i in slot %i", fd, *fdset_usedp);
447 if (fdset == NULL) { /* 1 */
448 /* Initialize with space for all possibly active fds */
449 fdset = calloc(maxconns, sizeof(struct pollfd));
453 polldata = calloc(maxconns, sizeof(struct polldata));
457 fdset_size = maxconns;
459 *fdset_sizep = fdset_size;
461 *polldatap = polldata;
463 LOG(log_debug, logtype_default, "fdset_add_fd: initialized with space for %i conncections",
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 * 2a Matched last (or only) in the set ? null it and return
480 * 2b If we remove the last array elemnt, just decrease count
481 * 3. If found move all following elements down by one
482 * 4. Decrease count of used elements in array
484 * This currently doesn't shrink the allocated storage of the array.
486 * @param fdsetp (rw) pointer to callers pointer to the pollfd array
487 * @param polldatap (rw) pointer to callers pointer to the polldata array
488 * @param fdset_usedp (rw) pointer to an int with the number of used elements
489 * @param fdset_sizep (rw) pointer to an int which stores the array sizes
490 * @param fd (r) file descriptor to remove from the arrays
492 void fdset_del_fd(struct pollfd **fdsetp,
493 struct polldata **polldatap,
495 int *fdset_sizep _U_,
498 struct pollfd *fdset = *fdsetp;
499 struct polldata *polldata = *polldatap;
501 if (*fdset_usedp < 1)
504 for (int i = 0; i < *fdset_usedp; i++) {
505 if (fdset[i].fd == fd) { /* 1 */
506 if ((i + 1) == *fdset_usedp) { /* 2a */
508 memset(&polldata[i], 0, sizeof(struct polldata));
509 } else if (i < (*fdset_usedp - 1)) { /* 2b */
512 (*fdset_usedp - i - 1) * sizeof(struct pollfd)); /* 3 */
513 memmove(&polldata[i],
515 (*fdset_usedp - i - 1) * sizeof(struct polldata)); /* 3 */
523 /* Length of the space taken up by a padded control message of length len */
525 #define CMSG_SPACE(len) (__CMSG_ALIGN(sizeof(struct cmsghdr)) + __CMSG_ALIGN(len))
529 * Receive a fd on a suitable socket
530 * @args fd (r) PF_UNIX socket to receive on
531 * @args nonblocking (r) 0: fd is in blocking mode - 1: fd is nonblocking, poll for 1 sec
532 * @returns fd on success, -1 on error
534 int recv_fd(int fd, int nonblocking)
539 struct cmsghdr *cmsgp = NULL;
540 char buf[CMSG_SPACE(sizeof(int))];
542 struct pollfd pollfds[1];
545 pollfds[0].events = POLLIN;
547 memset(&msgh,0,sizeof(msgh));
548 memset(buf,0,sizeof(buf));
550 msgh.msg_name = NULL;
551 msgh.msg_namelen = 0;
556 iov[0].iov_base = dbuf;
557 iov[0].iov_len = sizeof(dbuf);
559 msgh.msg_control = buf;
560 msgh.msg_controllen = sizeof(buf);
564 ret = poll(pollfds, 1, 2000); /* poll 2 seconds, evtl. multipe times (EINTR) */
565 } while ( ret == -1 && errno == EINTR );
568 ret = recvmsg(fd, &msgh, 0);
571 ret = recvmsg(fd, &msgh, 0);
572 } while ( ret == -1 && errno == EINTR );
579 for ( cmsgp = CMSG_FIRSTHDR(&msgh); cmsgp != NULL; cmsgp = CMSG_NXTHDR(&msgh,cmsgp) ) {
580 if ( cmsgp->cmsg_level == SOL_SOCKET && cmsgp->cmsg_type == SCM_RIGHTS ) {
581 return *(int *) CMSG_DATA(cmsgp);
585 if ( ret == sizeof (int) )
586 errno = *(int *)dbuf; /* Rcvd errno */
588 errno = ENOENT; /* Default errno */
594 * Send a fd across a suitable socket
596 int send_fd(int socket, int fd)
601 struct cmsghdr *cmsgp = NULL;
606 size = CMSG_SPACE(sizeof fd);
609 LOG(log_error, logtype_cnid, "error in sendmsg: %s", strerror(errno));
613 memset(&msgh,0,sizeof (msgh));
616 msgh.msg_name = NULL;
617 msgh.msg_namelen = 0;
622 iov[0].iov_base = &er;
623 iov[0].iov_len = sizeof(er);
625 msgh.msg_control = buf;
626 msgh.msg_controllen = size;
628 cmsgp = CMSG_FIRSTHDR(&msgh);
629 cmsgp->cmsg_level = SOL_SOCKET;
630 cmsgp->cmsg_type = SCM_RIGHTS;
631 cmsgp->cmsg_len = CMSG_LEN(sizeof(fd));
633 *((int *)CMSG_DATA(cmsgp)) = fd;
634 msgh.msg_controllen = cmsgp->cmsg_len;
637 ret = sendmsg(socket,&msgh, 0);
638 } while ( ret == -1 && errno == EINTR );
640 LOG(log_error, logtype_cnid, "error in sendmsg: %s", strerror(errno));