4 * HTTP address list routines for CUPS.
6 * Copyright 2007-2013 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/".
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/OS X 10.5@
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)", addrlist
, 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/OS X 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 socklen_t len
; /* Length of value */
66 http_addr_t peer
; /* Peer address */
67 int flags
, /* Socket flags */
68 remaining
; /* Remaining timeout */
70 struct pollfd pfd
; /* Polled file descriptor */
72 fd_set input_set
, /* select() input set */
73 output_set
; /* select() output set */
74 struct timeval timeout
; /* Timeout */
75 # endif /* HAVE_POLL */
76 int nfds
; /* Result from select()/poll() */
77 #endif /* O_NONBLOCK */
79 char temp
[256]; /* Temporary address string */
83 DEBUG_printf(("httpAddrConnect2(addrlist=%p, sock=%p, msec=%d, cancel=%p)",
84 addrlist
, sock
, msec
, cancel
));
89 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
93 if (cancel
&& *cancel
)
96 if (msec
<= 0 || getenv("CUPS_DISABLE_ASYNC_CONNECT"))
100 * Loop through each address until we connect or run out of addresses...
105 if (cancel
&& *cancel
)
109 * Create the socket...
112 DEBUG_printf(("2httpAddrConnect2: Trying %s:%d...",
113 httpAddrString(&(addrlist
->addr
), temp
, sizeof(temp
)),
114 httpAddrPort(&(addrlist
->addr
))));
116 if ((*sock
= (int)socket(httpAddrFamily(&(addrlist
->addr
)), SOCK_STREAM
,
120 * Don't abort yet, as this could just be an issue with the local
121 * system not being configured with IPv4/IPv6/domain socket enabled...
124 addrlist
= addrlist
->next
;
133 setsockopt(*sock
, SOL_SOCKET
, SO_REUSEADDR
, CUPS_SOCAST
&val
, sizeof(val
));
137 setsockopt(*sock
, SOL_SOCKET
, SO_REUSEPORT
, CUPS_SOCAST
&val
, sizeof(val
));
138 #endif /* SO_REUSEPORT */
142 setsockopt(*sock
, SOL_SOCKET
, SO_NOSIGPIPE
, CUPS_SOCAST
&val
, sizeof(val
));
143 #endif /* SO_NOSIGPIPE */
146 * Using TCP_NODELAY improves responsiveness, especially on systems
147 * with a slow loopback interface...
151 setsockopt(*sock
, IPPROTO_TCP
, TCP_NODELAY
, CUPS_SOCAST
&val
, sizeof(val
));
155 * Close this socket when starting another process...
158 fcntl(*sock
, F_SETFD
, FD_CLOEXEC
);
159 #endif /* FD_CLOEXEC */
163 * Do an asynchronous connect by setting the socket non-blocking...
166 DEBUG_printf(("httpAddrConnect2: Setting non-blocking connect()"));
168 flags
= fcntl(*sock
, F_GETFL
, 0);
171 DEBUG_puts("httpAddrConnect2: Setting non-blocking connect()");
173 fcntl(*sock
, F_SETFL
, flags
| O_NONBLOCK
);
175 #endif /* O_NONBLOCK */
181 if (!connect(*sock
, &(addrlist
->addr
.addr
),
182 httpAddrLength(&(addrlist
->addr
))))
184 DEBUG_printf(("1httpAddrConnect2: Connected to %s:%d...",
185 httpAddrString(&(addrlist
->addr
), temp
, sizeof(temp
)),
186 httpAddrPort(&(addrlist
->addr
))));
189 fcntl(*sock
, F_SETFL
, flags
);
190 #endif /* O_NONBLOCK */
197 if (WSAGetLastError() == WSAEINPROGRESS
||
198 WSAGetLastError() == WSAEWOULDBLOCK
)
200 if (errno
== EINPROGRESS
|| errno
== EWOULDBLOCK
)
203 DEBUG_puts("1httpAddrConnect2: Finishing async connect()");
205 fcntl(*sock
, F_SETFL
, flags
);
207 for (remaining
= msec
; remaining
> 0; remaining
-= 250)
211 if (cancel
&& *cancel
)
214 * Close this socket and return...
217 DEBUG_puts("1httpAddrConnect2: Canceled connect()");
219 httpAddrClose(NULL
, *sock
);
228 pfd
.events
= POLLIN
| POLLOUT
;
230 nfds
= poll(&pfd
, 1, remaining
> 250 ? 250 : remaining
);
232 DEBUG_printf(("1httpAddrConnect2: poll() returned %d (%d)", nfds
,
237 FD_SET(*sock
, &input_set
);
238 output_set
= input_set
;
241 timeout
.tv_usec
= (remaining
> 250 ? 250 : remaining
) * 1000;
243 nfds
= select(*sock
+ 1, &input_set
, &output_set
, NULL
, &timeout
);
245 DEBUG_printf(("1httpAddrConnect2: select() returned %d (%d)", nfds
,
247 # endif /* HAVE_POLL */
250 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
251 WSAGetLastError() == WSAEWOULDBLOCK
));
253 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
259 if (!getpeername(*sock
, (struct sockaddr
*)&peer
, &len
))
261 DEBUG_printf(("1httpAddrConnect2: Connected to %s:%d...",
262 httpAddrString(&peer
, temp
, sizeof(temp
)),
263 httpAddrPort(&peer
)));
272 #endif /* O_NONBLOCK */
274 DEBUG_printf(("1httpAddrConnect2: Unable to connect to %s:%d: %s",
275 httpAddrString(&(addrlist
->addr
), temp
, sizeof(temp
)),
276 httpAddrPort(&(addrlist
->addr
)), strerror(errno
)));
279 if (errno
== EINPROGRESS
)
284 * Close this socket and move to the next address...
287 httpAddrClose(NULL
, *sock
);
290 addrlist
= addrlist
->next
;
295 _cupsSetError(IPP_STATUS_ERROR_SERVICE_UNAVAILABLE
, "Connection failed", 0);
297 _cupsSetError(IPP_STATUS_ERROR_SERVICE_UNAVAILABLE
, strerror(errno
), 0);
306 * 'httpAddrCopyList()' - Copy an address list.
308 * @since CUPS 1.7/OS X 10.9@
311 http_addrlist_t
* /* O - New address list or @code NULL@ on error */
313 http_addrlist_t
*src
) /* I - Source address list */
315 http_addrlist_t
*dst
= NULL
, /* First list entry */
316 *prev
= NULL
, /* Previous list entry */
317 *current
= NULL
;/* Current list entry */
322 if ((current
= malloc(sizeof(http_addrlist_t
))) == NULL
)
329 current
= current
->next
;
337 memcpy(current
, src
, sizeof(http_addrlist_t
));
339 current
->next
= NULL
;
342 prev
->next
= current
;
355 * 'httpAddrFreeList()' - Free an address list.
357 * @since CUPS 1.2/OS X 10.5@
362 http_addrlist_t
*addrlist
) /* I - Address list to free */
364 http_addrlist_t
*next
; /* Next address in list */
368 * Free each address in the list...
373 next
= addrlist
->next
;
383 * 'httpAddrGetList()' - Get a list of addresses for a hostname.
385 * @since CUPS 1.2/OS X 10.5@
388 http_addrlist_t
* /* O - List of addresses or NULL */
389 httpAddrGetList(const char *hostname
, /* I - Hostname, IP address, or NULL for passive listen address */
390 int family
, /* I - Address family or AF_UNSPEC */
391 const char *service
) /* I - Service name or port number */
393 http_addrlist_t
*first
, /* First address in list */
394 *addr
, /* Current address in list */
395 *temp
; /* New address */
396 _cups_globals_t
*cg
= _cupsGlobals();
401 _cups_debug_printf("httpAddrGetList(hostname=\"%s\", family=AF_%s, "
403 hostname
? hostname
: "(nil)",
404 family
== AF_UNSPEC
? "UNSPEC" :
406 family
== AF_LOCAL
? "LOCAL" :
407 # endif /* AF_LOCAL */
409 family
== AF_INET6
? "INET6" :
410 # endif /* AF_INET6 */
411 family
== AF_INET
? "INET" : "???", service
);
416 * STR #2920: Initialize resolver after failure in cups-polld
418 * If the previous lookup failed, re-initialize the resolver to prevent
419 * temporary network errors from persisting. This *should* be handled by
420 * the resolver libraries, but apparently the glibc folks do not agree.
422 * We set a flag at the end of this function if we encounter an error that
423 * requires reinitialization of the resolver functions. We then call
424 * res_init() if the flag is set on the next call here or in httpAddrLookup().
427 if (cg
->need_res_init
)
431 cg
->need_res_init
= 0;
433 #endif /* HAVE_RES_INIT */
436 * Lookup the address the best way we can...
442 if (hostname
&& hostname
[0] == '/')
445 * Domain socket address...
448 if ((first
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
))) != NULL
)
450 first
->addr
.un
.sun_family
= AF_LOCAL
;
451 strlcpy(first
->addr
.un
.sun_path
, hostname
, sizeof(first
->addr
.un
.sun_path
));
455 #endif /* AF_LOCAL */
456 if (!hostname
|| _cups_strcasecmp(hostname
, "localhost"))
458 #ifdef HAVE_GETADDRINFO
459 struct addrinfo hints
, /* Address lookup hints */
460 *results
, /* Address lookup results */
461 *current
; /* Current result */
462 char ipv6
[64], /* IPv6 address */
463 *ipv6zone
; /* Pointer to zone separator */
464 int ipv6len
; /* Length of IPv6 address */
465 int error
; /* getaddrinfo() error */
469 * Lookup the address as needed...
472 memset(&hints
, 0, sizeof(hints
));
473 hints
.ai_family
= family
;
474 hints
.ai_flags
= hostname
? 0 : AI_PASSIVE
;
475 hints
.ai_socktype
= SOCK_STREAM
;
477 if (hostname
&& *hostname
== '[')
480 * Remove brackets from numeric IPv6 address...
483 if (!strncmp(hostname
, "[v1.", 4))
486 * Copy the newer address format which supports link-local addresses...
489 strlcpy(ipv6
, hostname
+ 4, sizeof(ipv6
));
490 if ((ipv6len
= (int)strlen(ipv6
) - 1) >= 0 && ipv6
[ipv6len
] == ']')
492 ipv6
[ipv6len
] = '\0';
496 * Convert "+zone" in address to "%zone"...
499 if ((ipv6zone
= strrchr(ipv6
, '+')) != NULL
)
506 * Copy the regular non-link-local IPv6 address...
509 strlcpy(ipv6
, hostname
+ 1, sizeof(ipv6
));
510 if ((ipv6len
= (int)strlen(ipv6
) - 1) >= 0 && ipv6
[ipv6len
] == ']')
512 ipv6
[ipv6len
] = '\0';
518 if ((error
= getaddrinfo(hostname
, service
, &hints
, &results
)) == 0)
521 * Copy the results to our own address list structure...
524 for (current
= results
; current
; current
= current
->ai_next
)
525 if (current
->ai_family
== AF_INET
|| current
->ai_family
== AF_INET6
)
528 * Copy the address over...
531 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
534 httpAddrFreeList(first
);
535 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
539 if (current
->ai_family
== AF_INET6
)
540 memcpy(&(temp
->addr
.ipv6
), current
->ai_addr
,
541 sizeof(temp
->addr
.ipv6
));
543 memcpy(&(temp
->addr
.ipv4
), current
->ai_addr
,
544 sizeof(temp
->addr
.ipv4
));
547 * Append the address to the list...
560 * Free the results from getaddrinfo()...
563 freeaddrinfo(results
);
567 if (error
== EAI_FAIL
)
568 cg
->need_res_init
= 1;
570 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, gai_strerror(error
), 0);
576 int i
; /* Looping vars */
577 unsigned ip
[4]; /* IPv4 address components */
578 const char *ptr
; /* Pointer into hostname */
579 struct hostent
*host
; /* Result of lookup */
580 struct servent
*port
; /* Port number for service */
581 int portnum
; /* Port number */
585 * Lookup the service...
590 else if (isdigit(*service
& 255))
591 portnum
= atoi(service
);
592 else if ((port
= getservbyname(service
, NULL
)) != NULL
)
593 portnum
= ntohs(port
->s_port
);
594 else if (!strcmp(service
, "http"))
596 else if (!strcmp(service
, "https"))
598 else if (!strcmp(service
, "ipp") || !strcmp(service
, "ipps"))
600 else if (!strcmp(service
, "lpd"))
602 else if (!strcmp(service
, "socket"))
608 * This code is needed because some operating systems have a
609 * buggy implementation of gethostbyname() that does not support
610 * IPv4 addresses. If the hostname string is an IPv4 address, then
611 * sscanf() is used to extract the IPv4 components. We then pack
612 * the components into an IPv4 address manually, since the
613 * inet_aton() function is deprecated. We use the htonl() macro
614 * to get the right byte order for the address.
617 for (ptr
= hostname
; isdigit(*ptr
& 255) || *ptr
== '.'; ptr
++);
622 * We have an IPv4 address; break it up and create an IPv4 address...
625 if (sscanf(hostname
, "%u.%u.%u.%u", ip
, ip
+ 1, ip
+ 2, ip
+ 3) == 4 &&
626 ip
[0] <= 255 && ip
[1] <= 255 && ip
[2] <= 255 && ip
[3] <= 255)
628 first
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
632 first
->addr
.ipv4
.sin_family
= AF_INET
;
633 first
->addr
.ipv4
.sin_addr
.s_addr
= htonl((((((((unsigned)ip
[0] << 8) |
634 (unsigned)ip
[1]) << 8) |
635 (unsigned)ip
[2]) << 8) |
637 first
->addr
.ipv4
.sin_port
= htons(portnum
);
640 else if ((host
= gethostbyname(hostname
)) != NULL
&&
642 (host
->h_addrtype
== AF_INET
|| host
->h_addrtype
== AF_INET6
))
644 host
->h_addrtype
== AF_INET
)
645 # endif /* AF_INET6 */
647 for (i
= 0; host
->h_addr_list
[i
]; i
++)
650 * Copy the address over...
653 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
656 httpAddrFreeList(first
);
661 if (host
->h_addrtype
== AF_INET6
)
663 temp
->addr
.ipv6
.sin6_family
= AF_INET6
;
664 memcpy(&(temp
->addr
.ipv6
.sin6_addr
), host
->h_addr_list
[i
],
665 sizeof(temp
->addr
.ipv6
));
666 temp
->addr
.ipv6
.sin6_port
= htons(portnum
);
669 # endif /* AF_INET6 */
671 temp
->addr
.ipv4
.sin_family
= AF_INET
;
672 memcpy(&(temp
->addr
.ipv4
.sin_addr
), host
->h_addr_list
[i
],
673 sizeof(temp
->addr
.ipv4
));
674 temp
->addr
.ipv4
.sin_port
= htons(portnum
);
678 * Append the address to the list...
692 if (h_errno
== NO_RECOVERY
)
693 cg
->need_res_init
= 1;
695 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, hstrerror(h_errno
), 0);
698 #endif /* HAVE_GETADDRINFO */
702 * Detect some common errors and handle them sanely...
705 if (!addr
&& (!hostname
|| !_cups_strcasecmp(hostname
, "localhost")))
707 struct servent
*port
; /* Port number for service */
708 int portnum
; /* Port number */
712 * Lookup the service...
717 else if (isdigit(*service
& 255))
718 portnum
= atoi(service
);
719 else if ((port
= getservbyname(service
, NULL
)) != NULL
)
720 portnum
= ntohs(port
->s_port
);
721 else if (!strcmp(service
, "http"))
723 else if (!strcmp(service
, "https"))
725 else if (!strcmp(service
, "ipp") || !strcmp(service
, "ipps"))
727 else if (!strcmp(service
, "lpd"))
729 else if (!strcmp(service
, "socket"))
733 httpAddrFreeList(first
);
735 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unknown service name."), 1);
739 if (hostname
&& !_cups_strcasecmp(hostname
, "localhost"))
742 * Unfortunately, some users ignore all of the warnings in the
743 * /etc/hosts file and delete "localhost" from it. If we get here
744 * then we were unable to resolve the name, so use the IPv6 and/or
745 * IPv4 loopback interface addresses...
749 if (family
!= AF_INET
)
752 * Add [::1] to the address list...
755 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
758 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
759 httpAddrFreeList(first
);
763 temp
->addr
.ipv6
.sin6_family
= AF_INET6
;
764 temp
->addr
.ipv6
.sin6_port
= htons(portnum
);
766 temp
->addr
.ipv6
.sin6_addr
.u
.Byte
[15] = 1;
768 temp
->addr
.ipv6
.sin6_addr
.s6_addr32
[3] = htonl(1);
777 if (family
!= AF_INET6
)
778 #endif /* AF_INET6 */
781 * Add 127.0.0.1 to the address list...
784 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
787 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
788 httpAddrFreeList(first
);
792 temp
->addr
.ipv4
.sin_family
= AF_INET
;
793 temp
->addr
.ipv4
.sin_port
= htons(portnum
);
794 temp
->addr
.ipv4
.sin_addr
.s_addr
= htonl(0x7f000001);
806 * Provide one or more passive listening addresses...
810 if (family
!= AF_INET
)
813 * Add [::] to the address list...
816 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
819 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
820 httpAddrFreeList(first
);
824 temp
->addr
.ipv6
.sin6_family
= AF_INET6
;
825 temp
->addr
.ipv6
.sin6_port
= htons(portnum
);
833 if (family
!= AF_INET6
)
834 #endif /* AF_INET6 */
837 * Add 0.0.0.0 to the address list...
840 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
843 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
844 httpAddrFreeList(first
);
848 temp
->addr
.ipv4
.sin_family
= AF_INET
;
849 temp
->addr
.ipv4
.sin_port
= htons(portnum
);
861 * Return the address list...