4 * HTTP address list routines for CUPS.
6 * Copyright 2007-2014 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * These coded instructions, statements, and computer programs are the
10 * property of Apple Inc. and are protected by Federal copyright
11 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
12 * which should have been included with this file. If this file is
13 * file is missing or damaged, see the license at "http://www.cups.org/".
15 * This file is subject to the Apple OS-Developed Software exception.
19 * Include necessary headers...
22 #include "cups-private.h"
25 #endif /* HAVE_RESOLV_H */
28 #endif /* HAVE_POLL */
35 * 'httpAddrConnect()' - Connect to any of the addresses in the list.
37 * @since CUPS 1.2/OS X 10.5@
40 http_addrlist_t
* /* O - Connected address or NULL on failure */
42 http_addrlist_t
*addrlist
, /* I - List of potential addresses */
43 int *sock
) /* O - Socket */
45 DEBUG_printf(("httpAddrConnect(addrlist=%p, sock=%p)", addrlist
, sock
));
47 return (httpAddrConnect2(addrlist
, sock
, 30000, NULL
));
52 * 'httpAddrConnect2()' - Connect to any of the addresses in the list with a
53 * timeout and optional cancel.
55 * @since CUPS 1.7/OS X 10.9@
58 http_addrlist_t
* /* O - Connected address or NULL on failure */
60 http_addrlist_t
*addrlist
, /* I - List of potential addresses */
61 int *sock
, /* O - Socket */
62 int msec
, /* I - Timeout in milliseconds */
63 int *cancel
) /* I - Pointer to "cancel" variable */
65 int val
; /* Socket option value */
67 socklen_t len
; /* Length of value */
68 http_addr_t peer
; /* Peer address */
69 int flags
, /* Socket flags */
70 remaining
; /* Remaining timeout */
72 struct pollfd pfd
; /* Polled file descriptor */
74 fd_set input_set
, /* select() input set */
75 output_set
; /* select() output set */
76 struct timeval timeout
; /* Timeout */
77 # endif /* HAVE_POLL */
78 int nfds
; /* Result from select()/poll() */
79 #endif /* O_NONBLOCK */
81 char temp
[256]; /* Temporary address string */
85 DEBUG_printf(("httpAddrConnect2(addrlist=%p, sock=%p, msec=%d, cancel=%p)",
86 addrlist
, sock
, msec
, cancel
));
91 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
95 if (cancel
&& *cancel
)
98 if (msec
<= 0 || getenv("CUPS_DISABLE_ASYNC_CONNECT"))
102 * Loop through each address until we connect or run out of addresses...
107 if (cancel
&& *cancel
)
111 * Create the socket...
114 DEBUG_printf(("2httpAddrConnect2: Trying %s:%d...",
115 httpAddrString(&(addrlist
->addr
), temp
, sizeof(temp
)),
116 httpAddrPort(&(addrlist
->addr
))));
118 if ((*sock
= (int)socket(httpAddrFamily(&(addrlist
->addr
)), SOCK_STREAM
,
122 * Don't abort yet, as this could just be an issue with the local
123 * system not being configured with IPv4/IPv6/domain socket enabled...
126 addrlist
= addrlist
->next
;
135 setsockopt(*sock
, SOL_SOCKET
, SO_REUSEADDR
, CUPS_SOCAST
&val
, sizeof(val
));
139 setsockopt(*sock
, SOL_SOCKET
, SO_REUSEPORT
, CUPS_SOCAST
&val
, sizeof(val
));
140 #endif /* SO_REUSEPORT */
144 setsockopt(*sock
, SOL_SOCKET
, SO_NOSIGPIPE
, CUPS_SOCAST
&val
, sizeof(val
));
145 #endif /* SO_NOSIGPIPE */
148 * Using TCP_NODELAY improves responsiveness, especially on systems
149 * with a slow loopback interface...
153 setsockopt(*sock
, IPPROTO_TCP
, TCP_NODELAY
, CUPS_SOCAST
&val
, sizeof(val
));
157 * Close this socket when starting another process...
160 fcntl(*sock
, F_SETFD
, FD_CLOEXEC
);
161 #endif /* FD_CLOEXEC */
165 * Do an asynchronous connect by setting the socket non-blocking...
168 DEBUG_printf(("httpAddrConnect2: Setting non-blocking connect()"));
170 flags
= fcntl(*sock
, F_GETFL
, 0);
173 DEBUG_puts("httpAddrConnect2: Setting non-blocking connect()");
175 fcntl(*sock
, F_SETFL
, flags
| O_NONBLOCK
);
177 #endif /* O_NONBLOCK */
183 if (!connect(*sock
, &(addrlist
->addr
.addr
), (socklen_t
)httpAddrLength(&(addrlist
->addr
))))
185 DEBUG_printf(("1httpAddrConnect2: Connected to %s:%d...",
186 httpAddrString(&(addrlist
->addr
), temp
, sizeof(temp
)),
187 httpAddrPort(&(addrlist
->addr
))));
190 fcntl(*sock
, F_SETFL
, flags
);
191 #endif /* O_NONBLOCK */
198 if (WSAGetLastError() == WSAEINPROGRESS
||
199 WSAGetLastError() == WSAEWOULDBLOCK
)
201 if (errno
== EINPROGRESS
|| errno
== EWOULDBLOCK
)
204 DEBUG_puts("1httpAddrConnect2: Finishing async connect()");
206 fcntl(*sock
, F_SETFL
, flags
);
208 for (remaining
= msec
; remaining
> 0; remaining
-= 250)
212 if (cancel
&& *cancel
)
215 * Close this socket and return...
218 DEBUG_puts("1httpAddrConnect2: Canceled connect()");
220 httpAddrClose(NULL
, *sock
);
229 pfd
.events
= POLLIN
| POLLOUT
;
231 nfds
= poll(&pfd
, 1, remaining
> 250 ? 250 : remaining
);
233 DEBUG_printf(("1httpAddrConnect2: poll() returned %d (%d)", nfds
,
238 FD_SET(*sock
, &input_set
);
239 output_set
= input_set
;
242 timeout
.tv_usec
= (remaining
> 250 ? 250 : remaining
) * 1000;
244 nfds
= select(*sock
+ 1, &input_set
, &output_set
, NULL
, &timeout
);
246 DEBUG_printf(("1httpAddrConnect2: select() returned %d (%d)", nfds
,
248 # endif /* HAVE_POLL */
251 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
252 WSAGetLastError() == WSAEWOULDBLOCK
));
254 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
260 if (!getpeername(*sock
, (struct sockaddr
*)&peer
, &len
))
262 DEBUG_printf(("1httpAddrConnect2: Connected to %s:%d...",
263 httpAddrString(&peer
, temp
, sizeof(temp
)),
264 httpAddrPort(&peer
)));
273 #endif /* O_NONBLOCK */
275 DEBUG_printf(("1httpAddrConnect2: Unable to connect to %s:%d: %s",
276 httpAddrString(&(addrlist
->addr
), temp
, sizeof(temp
)),
277 httpAddrPort(&(addrlist
->addr
)), strerror(errno
)));
280 if (errno
== EINPROGRESS
)
285 * Close this socket and move to the next address...
288 httpAddrClose(NULL
, *sock
);
291 addrlist
= addrlist
->next
;
296 _cupsSetError(IPP_STATUS_ERROR_SERVICE_UNAVAILABLE
, "Connection failed", 0);
298 _cupsSetError(IPP_STATUS_ERROR_SERVICE_UNAVAILABLE
, strerror(errno
), 0);
307 * 'httpAddrCopyList()' - Copy an address list.
309 * @since CUPS 1.7/OS X 10.9@
312 http_addrlist_t
* /* O - New address list or @code NULL@ on error */
314 http_addrlist_t
*src
) /* I - Source address list */
316 http_addrlist_t
*dst
= NULL
, /* First list entry */
317 *prev
= NULL
, /* Previous list entry */
318 *current
= NULL
;/* Current list entry */
323 if ((current
= malloc(sizeof(http_addrlist_t
))) == NULL
)
330 current
= current
->next
;
338 memcpy(current
, src
, sizeof(http_addrlist_t
));
340 current
->next
= NULL
;
343 prev
->next
= current
;
356 * 'httpAddrFreeList()' - Free an address list.
358 * @since CUPS 1.2/OS X 10.5@
363 http_addrlist_t
*addrlist
) /* I - Address list to free */
365 http_addrlist_t
*next
; /* Next address in list */
369 * Free each address in the list...
374 next
= addrlist
->next
;
384 * 'httpAddrGetList()' - Get a list of addresses for a hostname.
386 * @since CUPS 1.2/OS X 10.5@
389 http_addrlist_t
* /* O - List of addresses or NULL */
390 httpAddrGetList(const char *hostname
, /* I - Hostname, IP address, or NULL for passive listen address */
391 int family
, /* I - Address family or AF_UNSPEC */
392 const char *service
) /* I - Service name or port number */
394 http_addrlist_t
*first
, /* First address in list */
395 *addr
, /* Current address in list */
396 *temp
; /* New address */
397 _cups_globals_t
*cg
= _cupsGlobals();
402 _cups_debug_printf("httpAddrGetList(hostname=\"%s\", family=AF_%s, "
404 hostname
? hostname
: "(nil)",
405 family
== AF_UNSPEC
? "UNSPEC" :
407 family
== AF_LOCAL
? "LOCAL" :
408 # endif /* AF_LOCAL */
410 family
== AF_INET6
? "INET6" :
411 # endif /* AF_INET6 */
412 family
== AF_INET
? "INET" : "???", service
);
417 * STR #2920: Initialize resolver after failure in cups-polld
419 * If the previous lookup failed, re-initialize the resolver to prevent
420 * temporary network errors from persisting. This *should* be handled by
421 * the resolver libraries, but apparently the glibc folks do not agree.
423 * We set a flag at the end of this function if we encounter an error that
424 * requires reinitialization of the resolver functions. We then call
425 * res_init() if the flag is set on the next call here or in httpAddrLookup().
428 if (cg
->need_res_init
)
432 cg
->need_res_init
= 0;
434 #endif /* HAVE_RES_INIT */
437 * Lookup the address the best way we can...
443 if (hostname
&& hostname
[0] == '/')
446 * Domain socket address...
449 if ((first
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
))) != NULL
)
452 first
->addr
.un
.sun_family
= AF_LOCAL
;
453 strlcpy(first
->addr
.un
.sun_path
, hostname
, sizeof(first
->addr
.un
.sun_path
));
457 #endif /* AF_LOCAL */
458 if (!hostname
|| _cups_strcasecmp(hostname
, "localhost"))
460 #ifdef HAVE_GETADDRINFO
461 struct addrinfo hints
, /* Address lookup hints */
462 *results
, /* Address lookup results */
463 *current
; /* Current result */
464 char ipv6
[64], /* IPv6 address */
465 *ipv6zone
; /* Pointer to zone separator */
466 int ipv6len
; /* Length of IPv6 address */
467 int error
; /* getaddrinfo() error */
471 * Lookup the address as needed...
474 memset(&hints
, 0, sizeof(hints
));
475 hints
.ai_family
= family
;
476 hints
.ai_flags
= hostname
? 0 : AI_PASSIVE
;
477 hints
.ai_socktype
= SOCK_STREAM
;
479 if (hostname
&& *hostname
== '[')
482 * Remove brackets from numeric IPv6 address...
485 if (!strncmp(hostname
, "[v1.", 4))
488 * Copy the newer address format which supports link-local addresses...
491 strlcpy(ipv6
, hostname
+ 4, sizeof(ipv6
));
492 if ((ipv6len
= (int)strlen(ipv6
) - 1) >= 0 && ipv6
[ipv6len
] == ']')
494 ipv6
[ipv6len
] = '\0';
498 * Convert "+zone" in address to "%zone"...
501 if ((ipv6zone
= strrchr(ipv6
, '+')) != NULL
)
508 * Copy the regular non-link-local IPv6 address...
511 strlcpy(ipv6
, hostname
+ 1, sizeof(ipv6
));
512 if ((ipv6len
= (int)strlen(ipv6
) - 1) >= 0 && ipv6
[ipv6len
] == ']')
514 ipv6
[ipv6len
] = '\0';
520 if ((error
= getaddrinfo(hostname
, service
, &hints
, &results
)) == 0)
523 * Copy the results to our own address list structure...
526 for (current
= results
; current
; current
= current
->ai_next
)
527 if (current
->ai_family
== AF_INET
|| current
->ai_family
== AF_INET6
)
530 * Copy the address over...
533 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
536 httpAddrFreeList(first
);
537 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
541 if (current
->ai_family
== AF_INET6
)
542 memcpy(&(temp
->addr
.ipv6
), current
->ai_addr
,
543 sizeof(temp
->addr
.ipv6
));
545 memcpy(&(temp
->addr
.ipv4
), current
->ai_addr
,
546 sizeof(temp
->addr
.ipv4
));
549 * Append the address to the list...
562 * Free the results from getaddrinfo()...
565 freeaddrinfo(results
);
569 if (error
== EAI_FAIL
)
570 cg
->need_res_init
= 1;
572 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, gai_strerror(error
), 0);
578 int i
; /* Looping vars */
579 unsigned ip
[4]; /* IPv4 address components */
580 const char *ptr
; /* Pointer into hostname */
581 struct hostent
*host
; /* Result of lookup */
582 struct servent
*port
; /* Port number for service */
583 int portnum
; /* Port number */
587 * Lookup the service...
592 else if (isdigit(*service
& 255))
593 portnum
= atoi(service
);
594 else if ((port
= getservbyname(service
, NULL
)) != NULL
)
595 portnum
= ntohs(port
->s_port
);
596 else if (!strcmp(service
, "http"))
598 else if (!strcmp(service
, "https"))
600 else if (!strcmp(service
, "ipp") || !strcmp(service
, "ipps"))
602 else if (!strcmp(service
, "lpd"))
604 else if (!strcmp(service
, "socket"))
610 * This code is needed because some operating systems have a
611 * buggy implementation of gethostbyname() that does not support
612 * IPv4 addresses. If the hostname string is an IPv4 address, then
613 * sscanf() is used to extract the IPv4 components. We then pack
614 * the components into an IPv4 address manually, since the
615 * inet_aton() function is deprecated. We use the htonl() macro
616 * to get the right byte order for the address.
619 for (ptr
= hostname
; isdigit(*ptr
& 255) || *ptr
== '.'; ptr
++);
624 * We have an IPv4 address; break it up and create an IPv4 address...
627 if (sscanf(hostname
, "%u.%u.%u.%u", ip
, ip
+ 1, ip
+ 2, ip
+ 3) == 4 &&
628 ip
[0] <= 255 && ip
[1] <= 255 && ip
[2] <= 255 && ip
[3] <= 255)
630 first
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
634 first
->addr
.ipv4
.sin_family
= AF_INET
;
635 first
->addr
.ipv4
.sin_addr
.s_addr
= htonl((((((((unsigned)ip
[0] << 8) |
636 (unsigned)ip
[1]) << 8) |
637 (unsigned)ip
[2]) << 8) |
639 first
->addr
.ipv4
.sin_port
= htons(portnum
);
642 else if ((host
= gethostbyname(hostname
)) != NULL
&&
644 (host
->h_addrtype
== AF_INET
|| host
->h_addrtype
== AF_INET6
))
646 host
->h_addrtype
== AF_INET
)
647 # endif /* AF_INET6 */
649 for (i
= 0; host
->h_addr_list
[i
]; i
++)
652 * Copy the address over...
655 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
658 httpAddrFreeList(first
);
663 if (host
->h_addrtype
== AF_INET6
)
665 temp
->addr
.ipv6
.sin6_family
= AF_INET6
;
666 memcpy(&(temp
->addr
.ipv6
.sin6_addr
), host
->h_addr_list
[i
],
667 sizeof(temp
->addr
.ipv6
));
668 temp
->addr
.ipv6
.sin6_port
= htons(portnum
);
671 # endif /* AF_INET6 */
673 temp
->addr
.ipv4
.sin_family
= AF_INET
;
674 memcpy(&(temp
->addr
.ipv4
.sin_addr
), host
->h_addr_list
[i
],
675 sizeof(temp
->addr
.ipv4
));
676 temp
->addr
.ipv4
.sin_port
= htons(portnum
);
680 * Append the address to the list...
694 if (h_errno
== NO_RECOVERY
)
695 cg
->need_res_init
= 1;
697 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, hstrerror(h_errno
), 0);
700 #endif /* HAVE_GETADDRINFO */
704 * Detect some common errors and handle them sanely...
707 if (!addr
&& (!hostname
|| !_cups_strcasecmp(hostname
, "localhost")))
709 struct servent
*port
; /* Port number for service */
710 int portnum
; /* Port number */
714 * Lookup the service...
719 else if (isdigit(*service
& 255))
720 portnum
= atoi(service
);
721 else if ((port
= getservbyname(service
, NULL
)) != NULL
)
722 portnum
= ntohs(port
->s_port
);
723 else if (!strcmp(service
, "http"))
725 else if (!strcmp(service
, "https"))
727 else if (!strcmp(service
, "ipp") || !strcmp(service
, "ipps"))
729 else if (!strcmp(service
, "lpd"))
731 else if (!strcmp(service
, "socket"))
735 httpAddrFreeList(first
);
737 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unknown service name."), 1);
741 if (hostname
&& !_cups_strcasecmp(hostname
, "localhost"))
744 * Unfortunately, some users ignore all of the warnings in the
745 * /etc/hosts file and delete "localhost" from it. If we get here
746 * then we were unable to resolve the name, so use the IPv6 and/or
747 * IPv4 loopback interface addresses...
751 if (family
!= AF_INET
)
754 * Add [::1] to the address list...
757 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
760 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
761 httpAddrFreeList(first
);
765 temp
->addr
.ipv6
.sin6_family
= AF_INET6
;
766 temp
->addr
.ipv6
.sin6_port
= htons(portnum
);
768 temp
->addr
.ipv6
.sin6_addr
.u
.Byte
[15] = 1;
770 temp
->addr
.ipv6
.sin6_addr
.s6_addr32
[3] = htonl(1);
779 if (family
!= AF_INET6
)
780 #endif /* AF_INET6 */
783 * Add 127.0.0.1 to the address list...
786 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
789 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
790 httpAddrFreeList(first
);
794 temp
->addr
.ipv4
.sin_family
= AF_INET
;
795 temp
->addr
.ipv4
.sin_port
= htons(portnum
);
796 temp
->addr
.ipv4
.sin_addr
.s_addr
= htonl(0x7f000001);
808 * Provide one or more passive listening addresses...
812 if (family
!= AF_INET
)
815 * Add [::] to the address list...
818 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
821 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
822 httpAddrFreeList(first
);
826 temp
->addr
.ipv6
.sin6_family
= AF_INET6
;
827 temp
->addr
.ipv6
.sin6_port
= htons(portnum
);
835 if (family
!= AF_INET6
)
836 #endif /* AF_INET6 */
839 * Add 0.0.0.0 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
.ipv4
.sin_family
= AF_INET
;
851 temp
->addr
.ipv4
.sin_port
= htons(portnum
);
863 * Return the address list...