2 * HTTP address list routines for CUPS.
4 * Copyright 2007-2018 by Apple Inc.
5 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
7 * These coded instructions, statements, and computer programs are the
8 * property of Apple Inc. and are protected by Federal copyright
9 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
10 * which should have been included with this file. If this file is
11 * missing or damaged, see the license at "http://www.cups.org/".
13 * This file is subject to the Apple OS-Developed Software exception.
17 * Include necessary headers...
20 #include "cups-private.h"
23 #endif /* HAVE_RESOLV_H */
26 #endif /* HAVE_POLL */
33 * 'httpAddrConnect()' - Connect to any of the addresses in the list.
35 * @since CUPS 1.2/macOS 10.5@ @exclude all@
38 http_addrlist_t
* /* O - Connected address or NULL on failure */
40 http_addrlist_t
*addrlist
, /* I - List of potential addresses */
41 int *sock
) /* O - Socket */
43 DEBUG_printf(("httpAddrConnect(addrlist=%p, sock=%p)", (void *)addrlist
, (void *)sock
));
45 return (httpAddrConnect2(addrlist
, sock
, 30000, NULL
));
50 * 'httpAddrConnect2()' - Connect to any of the addresses in the list with a
51 * timeout and optional cancel.
53 * @since CUPS 1.7/macOS 10.9@
56 http_addrlist_t
* /* O - Connected address or NULL on failure */
58 http_addrlist_t
*addrlist
, /* I - List of potential addresses */
59 int *sock
, /* O - Socket */
60 int msec
, /* I - Timeout in milliseconds */
61 int *cancel
) /* I - Pointer to "cancel" variable */
63 int val
; /* Socket option value */
65 int flags
; /* Socket flags */
67 int remaining
; /* Remaining timeout */
68 int i
, j
, /* Looping vars */
69 nfds
, /* Number of file descriptors */
70 fds
[100], /* Socket file descriptors */
71 result
; /* Result from select() or poll() */
72 http_addrlist_t
*addrs
[100]; /* Addresses */
74 int max_fd
= -1; /* Highest file descriptor */
75 #endif /* !HAVE_POLL */
78 struct pollfd pfds
[100]; /* Polled file descriptors */
80 fd_set input_set
, /* select() input set */
81 output_set
, /* select() output set */
82 error_set
; /* select() error set */
83 struct timeval timeout
; /* Timeout */
84 # endif /* HAVE_POLL */
85 #endif /* O_NONBLOCK */
87 socklen_t len
; /* Length of value */
88 http_addr_t peer
; /* Peer address */
89 char temp
[256]; /* Temporary address string */
93 DEBUG_printf(("httpAddrConnect2(addrlist=%p, sock=%p, msec=%d, cancel=%p)", (void *)addrlist
, (void *)sock
, msec
, (void *)cancel
));
98 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
102 if (cancel
&& *cancel
)
109 * Loop through each address until we connect or run out of addresses...
115 while (remaining
> 0)
117 if (cancel
&& *cancel
)
122 httpAddrClose(NULL
, fds
[nfds
]);
128 if (addrlist
&& nfds
< (int)(sizeof(fds
) / sizeof(fds
[0])))
131 * Create the socket...
134 DEBUG_printf(("2httpAddrConnect2: Trying %s:%d...", httpAddrString(&(addrlist
->addr
), temp
, sizeof(temp
)), httpAddrPort(&(addrlist
->addr
))));
136 if ((fds
[nfds
] = (int)socket(httpAddrFamily(&(addrlist
->addr
)), SOCK_STREAM
, 0)) < 0)
139 * Don't abort yet, as this could just be an issue with the local
140 * system not being configured with IPv4/IPv6/domain socket enabled.
142 * Just skip this address...
145 addrlist
= addrlist
->next
;
154 setsockopt(fds
[nfds
], SOL_SOCKET
, SO_REUSEADDR
, CUPS_SOCAST
&val
, sizeof(val
));
158 setsockopt(fds
[nfds
], SOL_SOCKET
, SO_REUSEPORT
, CUPS_SOCAST
&val
, sizeof(val
));
159 #endif /* SO_REUSEPORT */
163 setsockopt(fds
[nfds
], SOL_SOCKET
, SO_NOSIGPIPE
, CUPS_SOCAST
&val
, sizeof(val
));
164 #endif /* SO_NOSIGPIPE */
167 * Using TCP_NODELAY improves responsiveness, especially on systems
168 * with a slow loopback interface...
172 setsockopt(fds
[nfds
], IPPROTO_TCP
, TCP_NODELAY
, CUPS_SOCAST
&val
, sizeof(val
));
176 * Close this socket when starting another process...
179 fcntl(fds
[nfds
], F_SETFD
, FD_CLOEXEC
);
180 #endif /* FD_CLOEXEC */
184 * Do an asynchronous connect by setting the socket non-blocking...
187 DEBUG_printf(("httpAddrConnect2: Setting non-blocking connect()"));
189 flags
= fcntl(fds
[nfds
], F_GETFL
, 0);
190 fcntl(fds
[nfds
], F_SETFL
, flags
| O_NONBLOCK
);
191 #endif /* O_NONBLOCK */
197 if (!connect(fds
[nfds
], &(addrlist
->addr
.addr
), (socklen_t
)httpAddrLength(&(addrlist
->addr
))))
199 DEBUG_printf(("1httpAddrConnect2: Connected to %s:%d...", httpAddrString(&(addrlist
->addr
), temp
, sizeof(temp
)), httpAddrPort(&(addrlist
->addr
))));
202 fcntl(fds
[nfds
], F_SETFL
, flags
);
203 #endif /* O_NONBLOCK */
210 httpAddrClose(NULL
, fds
[nfds
]);
217 if (WSAGetLastError() != WSAEINPROGRESS
&& WSAGetLastError() != WSAEWOULDBLOCK
)
219 if (errno
!= EINPROGRESS
&& errno
!= EWOULDBLOCK
)
222 DEBUG_printf(("1httpAddrConnect2: Unable to connect to %s:%d: %s", httpAddrString(&(addrlist
->addr
), temp
, sizeof(temp
)), httpAddrPort(&(addrlist
->addr
)), strerror(errno
)));
223 httpAddrClose(NULL
, fds
[nfds
]);
224 addrlist
= addrlist
->next
;
229 fcntl(fds
[nfds
], F_SETFL
, flags
);
233 if (fds
[nfds
] > max_fd
)
235 #endif /* !HAVE_POLL */
237 addrs
[nfds
] = addrlist
;
239 addrlist
= addrlist
->next
;
242 if (!addrlist
&& nfds
== 0)
246 * See if we can connect to any of the addresses so far...
250 DEBUG_puts("1httpAddrConnect2: Finishing async connect()");
254 if (cancel
&& *cancel
)
257 * Close this socket and return...
260 DEBUG_puts("1httpAddrConnect2: Canceled connect()");
265 httpAddrClose(NULL
, fds
[nfds
]);
274 for (i
= 0; i
< nfds
; i
++)
277 pfds
[i
].events
= POLLIN
| POLLOUT
;
280 result
= poll(pfds
, (nfds_t
)nfds
, addrlist
? 100 : remaining
> 250 ? 250 : remaining
);
282 DEBUG_printf(("1httpAddrConnect2: poll() returned %d (%d)", result
, errno
));
286 for (i
= 0; i
< nfds
; i
++)
287 FD_SET(fds
[i
], &input_set
);
288 output_set
= input_set
;
289 error_set
= input_set
;
292 timeout
.tv_usec
= (addrlist
? 100 : remaining
> 250 ? 250 : remaining
) * 1000;
294 result
= select(max_fd
+ 1, &input_set
, &output_set
, &error_set
, &timeout
);
296 DEBUG_printf(("1httpAddrConnect2: select() returned %d (%d)", result
, errno
));
297 # endif /* HAVE_POLL */
300 while (result
< 0 && (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
));
302 while (result
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
307 http_addrlist_t
*connaddr
= NULL
; /* Connected address, if any */
309 for (i
= 0; i
< nfds
; i
++)
312 DEBUG_printf(("pfds[%d].revents=%x\n", i
, pfds
[i
].revents
));
313 if (pfds
[i
].revents
&& !(pfds
[i
].revents
& (POLLERR
| POLLHUP
)))
315 if (FD_ISSET(fds
[i
], &input_set
) && !FD_ISSET(fds
[i
], &error_set
))
316 # endif /* HAVE_POLL */
323 if (!getpeername(fds
[i
], (struct sockaddr
*)&peer
, &len
))
324 DEBUG_printf(("1httpAddrConnect2: Connected to %s:%d...", httpAddrString(&peer
, temp
, sizeof(temp
)), httpAddrPort(&peer
)));
330 else if (pfds
[i
].revents
& (POLLERR
| POLLHUP
))
332 else if (FD_ISSET(fds
[i
], &error_set
))
333 # endif /* HAVE_POLL */
336 * Error on socket, remove from the "pool"...
339 httpAddrClose(NULL
, fds
[i
]);
343 memmove(fds
+ i
, fds
+ i
+ 1, (size_t)(nfds
- i
) * (sizeof(fds
[0])));
344 memmove(addrs
+ i
, addrs
+ i
+ 1, (size_t)(nfds
- i
) * (sizeof(addrs
[0])));
353 * Connected on one address, close all of the other sockets we have so
357 for (j
= 0; j
< i
; j
++)
358 httpAddrClose(NULL
, fds
[j
]);
360 for (j
++; j
< nfds
; j
++)
361 httpAddrClose(NULL
, fds
[j
]);
366 #endif /* O_NONBLOCK */
377 httpAddrClose(NULL
, fds
[nfds
]);
381 _cupsSetError(IPP_STATUS_ERROR_SERVICE_UNAVAILABLE
, "Connection failed", 0);
383 _cupsSetError(IPP_STATUS_ERROR_SERVICE_UNAVAILABLE
, strerror(errno
), 0);
391 * 'httpAddrCopyList()' - Copy an address list.
393 * @since CUPS 1.7/macOS 10.9@
396 http_addrlist_t
* /* O - New address list or @code NULL@ on error */
398 http_addrlist_t
*src
) /* I - Source address list */
400 http_addrlist_t
*dst
= NULL
, /* First list entry */
401 *prev
= NULL
, /* Previous list entry */
402 *current
= NULL
;/* Current list entry */
407 if ((current
= malloc(sizeof(http_addrlist_t
))) == NULL
)
414 current
= current
->next
;
422 memcpy(current
, src
, sizeof(http_addrlist_t
));
424 current
->next
= NULL
;
427 prev
->next
= current
;
440 * 'httpAddrFreeList()' - Free an address list.
442 * @since CUPS 1.2/macOS 10.5@
447 http_addrlist_t
*addrlist
) /* I - Address list to free */
449 http_addrlist_t
*next
; /* Next address in list */
453 * Free each address in the list...
458 next
= addrlist
->next
;
468 * 'httpAddrGetList()' - Get a list of addresses for a hostname.
470 * @since CUPS 1.2/macOS 10.5@
473 http_addrlist_t
* /* O - List of addresses or NULL */
474 httpAddrGetList(const char *hostname
, /* I - Hostname, IP address, or NULL for passive listen address */
475 int family
, /* I - Address family or AF_UNSPEC */
476 const char *service
) /* I - Service name or port number */
478 http_addrlist_t
*first
, /* First address in list */
479 *addr
, /* Current address in list */
480 *temp
; /* New address */
481 _cups_globals_t
*cg
= _cupsGlobals();
486 _cups_debug_printf("httpAddrGetList(hostname=\"%s\", family=AF_%s, "
488 hostname
? hostname
: "(nil)",
489 family
== AF_UNSPEC
? "UNSPEC" :
491 family
== AF_LOCAL
? "LOCAL" :
492 # endif /* AF_LOCAL */
494 family
== AF_INET6
? "INET6" :
495 # endif /* AF_INET6 */
496 family
== AF_INET
? "INET" : "???", service
);
501 * STR #2920: Initialize resolver after failure in cups-polld
503 * If the previous lookup failed, re-initialize the resolver to prevent
504 * temporary network errors from persisting. This *should* be handled by
505 * the resolver libraries, but apparently the glibc folks do not agree.
507 * We set a flag at the end of this function if we encounter an error that
508 * requires reinitialization of the resolver functions. We then call
509 * res_init() if the flag is set on the next call here or in httpAddrLookup().
512 if (cg
->need_res_init
)
516 cg
->need_res_init
= 0;
518 #endif /* HAVE_RES_INIT */
521 * Lookup the address the best way we can...
527 if (hostname
&& hostname
[0] == '/')
530 * Domain socket address...
533 if ((first
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
))) != NULL
)
536 first
->addr
.un
.sun_family
= AF_LOCAL
;
537 strlcpy(first
->addr
.un
.sun_path
, hostname
, sizeof(first
->addr
.un
.sun_path
));
541 #endif /* AF_LOCAL */
542 if (!hostname
|| _cups_strcasecmp(hostname
, "localhost"))
544 #ifdef HAVE_GETADDRINFO
545 struct addrinfo hints
, /* Address lookup hints */
546 *results
, /* Address lookup results */
547 *current
; /* Current result */
548 char ipv6
[64], /* IPv6 address */
549 *ipv6zone
; /* Pointer to zone separator */
550 int ipv6len
; /* Length of IPv6 address */
551 int error
; /* getaddrinfo() error */
555 * Lookup the address as needed...
558 memset(&hints
, 0, sizeof(hints
));
559 hints
.ai_family
= family
;
560 hints
.ai_flags
= hostname
? 0 : AI_PASSIVE
;
561 hints
.ai_socktype
= SOCK_STREAM
;
563 if (hostname
&& *hostname
== '[')
566 * Remove brackets from numeric IPv6 address...
569 if (!strncmp(hostname
, "[v1.", 4))
572 * Copy the newer address format which supports link-local addresses...
575 strlcpy(ipv6
, hostname
+ 4, sizeof(ipv6
));
576 if ((ipv6len
= (int)strlen(ipv6
) - 1) >= 0 && ipv6
[ipv6len
] == ']')
578 ipv6
[ipv6len
] = '\0';
582 * Convert "+zone" in address to "%zone"...
585 if ((ipv6zone
= strrchr(ipv6
, '+')) != NULL
)
592 * Copy the regular non-link-local IPv6 address...
595 strlcpy(ipv6
, hostname
+ 1, sizeof(ipv6
));
596 if ((ipv6len
= (int)strlen(ipv6
) - 1) >= 0 && ipv6
[ipv6len
] == ']')
598 ipv6
[ipv6len
] = '\0';
604 if ((error
= getaddrinfo(hostname
, service
, &hints
, &results
)) == 0)
607 * Copy the results to our own address list structure...
610 for (current
= results
; current
; current
= current
->ai_next
)
611 if (current
->ai_family
== AF_INET
|| current
->ai_family
== AF_INET6
)
614 * Copy the address over...
617 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
620 httpAddrFreeList(first
);
621 freeaddrinfo(results
);
622 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
626 if (current
->ai_family
== AF_INET6
)
627 memcpy(&(temp
->addr
.ipv6
), current
->ai_addr
,
628 sizeof(temp
->addr
.ipv6
));
630 memcpy(&(temp
->addr
.ipv4
), current
->ai_addr
,
631 sizeof(temp
->addr
.ipv4
));
634 * Append the address to the list...
647 * Free the results from getaddrinfo()...
650 freeaddrinfo(results
);
654 if (error
== EAI_FAIL
)
655 cg
->need_res_init
= 1;
657 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, gai_strerror(error
), 0);
663 int i
; /* Looping vars */
664 unsigned ip
[4]; /* IPv4 address components */
665 const char *ptr
; /* Pointer into hostname */
666 struct hostent
*host
; /* Result of lookup */
667 struct servent
*port
; /* Port number for service */
668 int portnum
; /* Port number */
672 * Lookup the service...
677 else if (isdigit(*service
& 255))
678 portnum
= atoi(service
);
679 else if ((port
= getservbyname(service
, NULL
)) != NULL
)
680 portnum
= ntohs(port
->s_port
);
681 else if (!strcmp(service
, "http"))
683 else if (!strcmp(service
, "https"))
685 else if (!strcmp(service
, "ipp") || !strcmp(service
, "ipps"))
687 else if (!strcmp(service
, "lpd"))
689 else if (!strcmp(service
, "socket"))
695 * This code is needed because some operating systems have a
696 * buggy implementation of gethostbyname() that does not support
697 * IPv4 addresses. If the hostname string is an IPv4 address, then
698 * sscanf() is used to extract the IPv4 components. We then pack
699 * the components into an IPv4 address manually, since the
700 * inet_aton() function is deprecated. We use the htonl() macro
701 * to get the right byte order for the address.
704 for (ptr
= hostname
; isdigit(*ptr
& 255) || *ptr
== '.'; ptr
++);
709 * We have an IPv4 address; break it up and create an IPv4 address...
712 if (sscanf(hostname
, "%u.%u.%u.%u", ip
, ip
+ 1, ip
+ 2, ip
+ 3) == 4 &&
713 ip
[0] <= 255 && ip
[1] <= 255 && ip
[2] <= 255 && ip
[3] <= 255)
715 first
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
719 first
->addr
.ipv4
.sin_family
= AF_INET
;
720 first
->addr
.ipv4
.sin_addr
.s_addr
= htonl((((((((unsigned)ip
[0] << 8) |
721 (unsigned)ip
[1]) << 8) |
722 (unsigned)ip
[2]) << 8) |
724 first
->addr
.ipv4
.sin_port
= htons(portnum
);
727 else if ((host
= gethostbyname(hostname
)) != NULL
&&
729 (host
->h_addrtype
== AF_INET
|| host
->h_addrtype
== AF_INET6
))
731 host
->h_addrtype
== AF_INET
)
732 # endif /* AF_INET6 */
734 for (i
= 0; host
->h_addr_list
[i
]; i
++)
737 * Copy the address over...
740 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
743 httpAddrFreeList(first
);
748 if (host
->h_addrtype
== AF_INET6
)
750 temp
->addr
.ipv6
.sin6_family
= AF_INET6
;
751 memcpy(&(temp
->addr
.ipv6
.sin6_addr
), host
->h_addr_list
[i
],
752 sizeof(temp
->addr
.ipv6
));
753 temp
->addr
.ipv6
.sin6_port
= htons(portnum
);
756 # endif /* AF_INET6 */
758 temp
->addr
.ipv4
.sin_family
= AF_INET
;
759 memcpy(&(temp
->addr
.ipv4
.sin_addr
), host
->h_addr_list
[i
],
760 sizeof(temp
->addr
.ipv4
));
761 temp
->addr
.ipv4
.sin_port
= htons(portnum
);
765 * Append the address to the list...
779 if (h_errno
== NO_RECOVERY
)
780 cg
->need_res_init
= 1;
782 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, hstrerror(h_errno
), 0);
785 #endif /* HAVE_GETADDRINFO */
789 * Detect some common errors and handle them sanely...
792 if (!addr
&& (!hostname
|| !_cups_strcasecmp(hostname
, "localhost")))
794 struct servent
*port
; /* Port number for service */
795 int portnum
; /* Port number */
799 * Lookup the service...
804 else if (isdigit(*service
& 255))
805 portnum
= atoi(service
);
806 else if ((port
= getservbyname(service
, NULL
)) != NULL
)
807 portnum
= ntohs(port
->s_port
);
808 else if (!strcmp(service
, "http"))
810 else if (!strcmp(service
, "https"))
812 else if (!strcmp(service
, "ipp") || !strcmp(service
, "ipps"))
814 else if (!strcmp(service
, "lpd"))
816 else if (!strcmp(service
, "socket"))
820 httpAddrFreeList(first
);
822 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unknown service name."), 1);
826 if (hostname
&& !_cups_strcasecmp(hostname
, "localhost"))
829 * Unfortunately, some users ignore all of the warnings in the
830 * /etc/hosts file and delete "localhost" from it. If we get here
831 * then we were unable to resolve the name, so use the IPv6 and/or
832 * IPv4 loopback interface addresses...
836 if (family
!= AF_INET
)
839 * Add [::1] to the address list...
842 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
845 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
846 httpAddrFreeList(first
);
850 temp
->addr
.ipv6
.sin6_family
= AF_INET6
;
851 temp
->addr
.ipv6
.sin6_port
= htons(portnum
);
853 temp
->addr
.ipv6
.sin6_addr
.u
.Byte
[15] = 1;
855 temp
->addr
.ipv6
.sin6_addr
.s6_addr32
[3] = htonl(1);
864 if (family
!= AF_INET6
)
865 #endif /* AF_INET6 */
868 * Add 127.0.0.1 to the address list...
871 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
874 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
875 httpAddrFreeList(first
);
879 temp
->addr
.ipv4
.sin_family
= AF_INET
;
880 temp
->addr
.ipv4
.sin_port
= htons(portnum
);
881 temp
->addr
.ipv4
.sin_addr
.s_addr
= htonl(0x7f000001);
893 * Provide one or more passive listening addresses...
897 if (family
!= AF_INET
)
900 * Add [::] to the address list...
903 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
906 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
907 httpAddrFreeList(first
);
911 temp
->addr
.ipv6
.sin6_family
= AF_INET6
;
912 temp
->addr
.ipv6
.sin6_port
= htons(portnum
);
920 if (family
!= AF_INET6
)
921 #endif /* AF_INET6 */
924 * Add 0.0.0.0 to the address list...
927 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
930 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
931 httpAddrFreeList(first
);
935 temp
->addr
.ipv4
.sin_family
= AF_INET
;
936 temp
->addr
.ipv4
.sin_port
= htons(portnum
);
948 * Return the address list...