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 * httpAddrConnect() - Connect to any of the addresses in the list.
18 * httpAddrConnect2() - Connect to any of the addresses in the list with a
19 * timeout and optional cancel.
20 * httpAddrCopyList() - Copy an address list.
21 * httpAddrFreeList() - Free an address list.
22 * httpAddrGetList() - Get a list of addresses for a hostname.
26 * Include necessary headers...
29 #include "cups-private.h"
32 #endif /* HAVE_RESOLV_H */
35 #endif /* HAVE_POLL */
42 * 'httpAddrConnect()' - Connect to any of the addresses in the list.
44 * @since CUPS 1.2/OS X 10.5@
47 http_addrlist_t
* /* O - Connected address or NULL on failure */
49 http_addrlist_t
*addrlist
, /* I - List of potential addresses */
50 int *sock
) /* O - Socket */
52 DEBUG_printf(("httpAddrConnect(addrlist=%p, sock=%p)", addrlist
, sock
));
54 return (httpAddrConnect2(addrlist
, sock
, 30000, NULL
));
59 * 'httpAddrConnect2()' - Connect to any of the addresses in the list with a
60 * timeout and optional cancel.
65 http_addrlist_t
* /* O - Connected address or NULL on failure */
67 http_addrlist_t
*addrlist
, /* I - List of potential addresses */
68 int *sock
, /* O - Socket */
69 int msec
, /* I - Timeout in milliseconds */
70 int *cancel
) /* I - Pointer to "cancel" variable */
72 int val
; /* Socket option value */
74 socklen_t len
; /* Length of value */
75 http_addr_t peer
; /* Peer address */
76 int flags
, /* Socket flags */
77 remaining
; /* Remaining timeout */
79 struct pollfd pfd
; /* Polled file descriptor */
81 fd_set input_set
, /* select() input set */
82 output_set
; /* select() output set */
83 struct timeval timeout
; /* Timeout */
84 # endif /* HAVE_POLL */
85 int nfds
; /* Result from select()/poll() */
86 #endif /* O_NONBLOCK */
88 char temp
[256]; /* Temporary address string */
92 DEBUG_printf(("httpAddrConnect2(addrlist=%p, sock=%p, msec=%d, cancel=%p)",
93 addrlist
, sock
, msec
, cancel
));
98 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
102 if (cancel
&& *cancel
)
105 if (msec
<= 0 || getenv("CUPS_DISABLE_ASYNC_CONNECT"))
109 * Loop through each address until we connect or run out of addresses...
114 if (cancel
&& *cancel
)
118 * Create the socket...
121 DEBUG_printf(("2httpAddrConnect2: Trying %s:%d...",
122 httpAddrString(&(addrlist
->addr
), temp
, sizeof(temp
)),
123 httpAddrPort(&(addrlist
->addr
))));
125 if ((*sock
= (int)socket(_httpAddrFamily(&(addrlist
->addr
)), SOCK_STREAM
,
129 * Don't abort yet, as this could just be an issue with the local
130 * system not being configured with IPv4/IPv6/domain socket enabled...
133 addrlist
= addrlist
->next
;
142 setsockopt(*sock
, SOL_SOCKET
, SO_REUSEADDR
, CUPS_SOCAST
&val
, sizeof(val
));
146 setsockopt(*sock
, SOL_SOCKET
, SO_REUSEPORT
, CUPS_SOCAST
&val
, sizeof(val
));
147 #endif /* SO_REUSEPORT */
151 setsockopt(*sock
, SOL_SOCKET
, SO_NOSIGPIPE
, CUPS_SOCAST
&val
, sizeof(val
));
152 #endif /* SO_NOSIGPIPE */
155 * Using TCP_NODELAY improves responsiveness, especially on systems
156 * with a slow loopback interface...
160 setsockopt(*sock
, IPPROTO_TCP
, TCP_NODELAY
, CUPS_SOCAST
&val
, sizeof(val
));
164 * Close this socket when starting another process...
167 fcntl(*sock
, F_SETFD
, FD_CLOEXEC
);
168 #endif /* FD_CLOEXEC */
172 * Do an asynchronous connect by setting the socket non-blocking...
175 DEBUG_printf(("httpAddrConnect2: Setting non-blocking connect()"));
177 flags
= fcntl(*sock
, F_GETFL
, 0);
180 DEBUG_puts("httpAddrConnect2: Setting non-blocking connect()");
182 fcntl(*sock
, F_SETFL
, flags
| O_NONBLOCK
);
184 #endif /* O_NONBLOCK */
190 if (!connect(*sock
, &(addrlist
->addr
.addr
),
191 httpAddrLength(&(addrlist
->addr
))))
193 DEBUG_printf(("1httpAddrConnect2: Connected to %s:%d...",
194 httpAddrString(&(addrlist
->addr
), temp
, sizeof(temp
)),
195 httpAddrPort(&(addrlist
->addr
))));
198 fcntl(*sock
, F_SETFL
, flags
);
199 #endif /* O_NONBLOCK */
206 if (WSAGetLastError() == WSAEINPROGRESS
||
207 WSAGetLastError() == WSAEWOULDBLOCK
)
209 if (errno
== EINPROGRESS
|| errno
== EWOULDBLOCK
)
212 DEBUG_puts("1httpAddrConnect2: Finishing async connect()");
214 fcntl(*sock
, F_SETFL
, flags
);
216 for (remaining
= msec
; remaining
> 0; remaining
-= 250)
220 if (cancel
&& *cancel
)
223 * Close this socket and return...
226 DEBUG_puts("1httpAddrConnect2: Canceled connect()");
241 pfd
.events
= POLLIN
| POLLOUT
;
243 nfds
= poll(&pfd
, 1, remaining
> 250 ? 250 : remaining
);
245 DEBUG_printf(("1httpAddrConnect2: poll() returned %d (%d)", nfds
,
250 FD_SET(*sock
, &input_set
);
251 output_set
= input_set
;
254 timeout
.tv_usec
= (remaining
> 250 ? 250 : remaining
) * 1000;
256 nfds
= select(*sock
+ 1, &input_set
, &output_set
, NULL
, &timeout
);
258 DEBUG_printf(("1httpAddrConnect2: select() returned %d (%d)", nfds
,
260 # endif /* HAVE_POLL */
263 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
264 WSAGetLastError() == WSAEWOULDBLOCK
));
266 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
272 if (!getpeername(*sock
, (struct sockaddr
*)&peer
, &len
))
274 DEBUG_printf(("1httpAddrConnect2: Connected to %s:%d...",
275 httpAddrString(&peer
, temp
, sizeof(temp
)),
276 httpAddrPort(&peer
)));
285 #endif /* O_NONBLOCK */
287 DEBUG_printf(("1httpAddrConnect2: Unable to connect to %s:%d: %s",
288 httpAddrString(&(addrlist
->addr
), temp
, sizeof(temp
)),
289 httpAddrPort(&(addrlist
->addr
)), strerror(errno
)));
292 if (errno
== EINPROGRESS
)
297 * Close this socket and move to the next address...
307 addrlist
= addrlist
->next
;
312 _cupsSetError(IPP_STATUS_ERROR_SERVICE_UNAVAILABLE
, "Connection failed", 0);
314 _cupsSetError(IPP_STATUS_ERROR_SERVICE_UNAVAILABLE
, strerror(errno
), 0);
323 * 'httpAddrCopyList()' - Copy an address list.
328 http_addrlist_t
* /* O - New address list or @code NULL@ on error */
330 http_addrlist_t
*src
) /* I - Source address list */
332 http_addrlist_t
*dst
= NULL
, /* First list entry */
333 *prev
= NULL
, /* Previous list entry */
334 *current
= NULL
;/* Current list entry */
339 if ((current
= malloc(sizeof(http_addrlist_t
))) == NULL
)
346 current
= current
->next
;
354 memcpy(current
, src
, sizeof(http_addrlist_t
));
356 current
->next
= NULL
;
359 prev
->next
= current
;
372 * 'httpAddrFreeList()' - Free an address list.
374 * @since CUPS 1.2/OS X 10.5@
379 http_addrlist_t
*addrlist
) /* I - Address list to free */
381 http_addrlist_t
*next
; /* Next address in list */
385 * Free each address in the list...
390 next
= addrlist
->next
;
400 * 'httpAddrGetList()' - Get a list of addresses for a hostname.
402 * @since CUPS 1.2/OS X 10.5@
405 http_addrlist_t
* /* O - List of addresses or NULL */
406 httpAddrGetList(const char *hostname
, /* I - Hostname, IP address, or NULL for passive listen address */
407 int family
, /* I - Address family or AF_UNSPEC */
408 const char *service
) /* I - Service name or port number */
410 http_addrlist_t
*first
, /* First address in list */
411 *addr
, /* Current address in list */
412 *temp
; /* New address */
413 _cups_globals_t
*cg
= _cupsGlobals();
418 _cups_debug_printf("httpAddrGetList(hostname=\"%s\", family=AF_%s, "
420 hostname
? hostname
: "(nil)",
421 family
== AF_UNSPEC
? "UNSPEC" :
423 family
== AF_LOCAL
? "LOCAL" :
424 # endif /* AF_LOCAL */
426 family
== AF_INET6
? "INET6" :
427 # endif /* AF_INET6 */
428 family
== AF_INET
? "INET" : "???", service
);
433 * STR #2920: Initialize resolver after failure in cups-polld
435 * If the previous lookup failed, re-initialize the resolver to prevent
436 * temporary network errors from persisting. This *should* be handled by
437 * the resolver libraries, but apparently the glibc folks do not agree.
439 * We set a flag at the end of this function if we encounter an error that
440 * requires reinitialization of the resolver functions. We then call
441 * res_init() if the flag is set on the next call here or in httpAddrLookup().
444 if (cg
->need_res_init
)
448 cg
->need_res_init
= 0;
450 #endif /* HAVE_RES_INIT */
453 * Lookup the address the best way we can...
459 if (hostname
&& hostname
[0] == '/')
462 * Domain socket address...
465 if ((first
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
))) != NULL
)
467 first
->addr
.un
.sun_family
= AF_LOCAL
;
468 strlcpy(first
->addr
.un
.sun_path
, hostname
, sizeof(first
->addr
.un
.sun_path
));
472 #endif /* AF_LOCAL */
473 if (!hostname
|| _cups_strcasecmp(hostname
, "localhost"))
475 #ifdef HAVE_GETADDRINFO
476 struct addrinfo hints
, /* Address lookup hints */
477 *results
, /* Address lookup results */
478 *current
; /* Current result */
479 char ipv6
[64], /* IPv6 address */
480 *ipv6zone
; /* Pointer to zone separator */
481 int ipv6len
; /* Length of IPv6 address */
482 int error
; /* getaddrinfo() error */
486 * Lookup the address as needed...
489 memset(&hints
, 0, sizeof(hints
));
490 hints
.ai_family
= family
;
491 hints
.ai_flags
= hostname
? 0 : AI_PASSIVE
;
492 hints
.ai_socktype
= SOCK_STREAM
;
494 if (hostname
&& *hostname
== '[')
497 * Remove brackets from numeric IPv6 address...
500 if (!strncmp(hostname
, "[v1.", 4))
503 * Copy the newer address format which supports link-local addresses...
506 strlcpy(ipv6
, hostname
+ 4, sizeof(ipv6
));
507 if ((ipv6len
= (int)strlen(ipv6
) - 1) >= 0 && ipv6
[ipv6len
] == ']')
509 ipv6
[ipv6len
] = '\0';
513 * Convert "+zone" in address to "%zone"...
516 if ((ipv6zone
= strrchr(ipv6
, '+')) != NULL
)
523 * Copy the regular non-link-local IPv6 address...
526 strlcpy(ipv6
, hostname
+ 1, sizeof(ipv6
));
527 if ((ipv6len
= (int)strlen(ipv6
) - 1) >= 0 && ipv6
[ipv6len
] == ']')
529 ipv6
[ipv6len
] = '\0';
535 if ((error
= getaddrinfo(hostname
, service
, &hints
, &results
)) == 0)
538 * Copy the results to our own address list structure...
541 for (current
= results
; current
; current
= current
->ai_next
)
542 if (current
->ai_family
== AF_INET
|| current
->ai_family
== AF_INET6
)
545 * Copy the address over...
548 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
551 httpAddrFreeList(first
);
552 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
556 if (current
->ai_family
== AF_INET6
)
557 memcpy(&(temp
->addr
.ipv6
), current
->ai_addr
,
558 sizeof(temp
->addr
.ipv6
));
560 memcpy(&(temp
->addr
.ipv4
), current
->ai_addr
,
561 sizeof(temp
->addr
.ipv4
));
564 * Append the address to the list...
577 * Free the results from getaddrinfo()...
580 freeaddrinfo(results
);
584 if (error
== EAI_FAIL
)
585 cg
->need_res_init
= 1;
587 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, gai_strerror(error
), 0);
593 int i
; /* Looping vars */
594 unsigned ip
[4]; /* IPv4 address components */
595 const char *ptr
; /* Pointer into hostname */
596 struct hostent
*host
; /* Result of lookup */
597 struct servent
*port
; /* Port number for service */
598 int portnum
; /* Port number */
602 * Lookup the service...
607 else if (isdigit(*service
& 255))
608 portnum
= atoi(service
);
609 else if ((port
= getservbyname(service
, NULL
)) != NULL
)
610 portnum
= ntohs(port
->s_port
);
611 else if (!strcmp(service
, "http"))
613 else if (!strcmp(service
, "https"))
615 else if (!strcmp(service
, "ipp") || !strcmp(service
, "ipps"))
617 else if (!strcmp(service
, "lpd"))
619 else if (!strcmp(service
, "socket"))
625 * This code is needed because some operating systems have a
626 * buggy implementation of gethostbyname() that does not support
627 * IPv4 addresses. If the hostname string is an IPv4 address, then
628 * sscanf() is used to extract the IPv4 components. We then pack
629 * the components into an IPv4 address manually, since the
630 * inet_aton() function is deprecated. We use the htonl() macro
631 * to get the right byte order for the address.
634 for (ptr
= hostname
; isdigit(*ptr
& 255) || *ptr
== '.'; ptr
++);
639 * We have an IPv4 address; break it up and create an IPv4 address...
642 if (sscanf(hostname
, "%u.%u.%u.%u", ip
, ip
+ 1, ip
+ 2, ip
+ 3) == 4 &&
643 ip
[0] <= 255 && ip
[1] <= 255 && ip
[2] <= 255 && ip
[3] <= 255)
645 first
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
649 first
->addr
.ipv4
.sin_family
= AF_INET
;
650 first
->addr
.ipv4
.sin_addr
.s_addr
= htonl(((((((ip
[0] << 8) |
652 ip
[2]) << 8) | ip
[3]));
653 first
->addr
.ipv4
.sin_port
= htons(portnum
);
656 else if ((host
= gethostbyname(hostname
)) != NULL
&&
658 (host
->h_addrtype
== AF_INET
|| host
->h_addrtype
== AF_INET6
))
660 host
->h_addrtype
== AF_INET
)
661 # endif /* AF_INET6 */
663 for (i
= 0; host
->h_addr_list
[i
]; i
++)
666 * Copy the address over...
669 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
672 httpAddrFreeList(first
);
677 if (host
->h_addrtype
== AF_INET6
)
679 temp
->addr
.ipv6
.sin6_family
= AF_INET6
;
680 memcpy(&(temp
->addr
.ipv6
.sin6_addr
), host
->h_addr_list
[i
],
681 sizeof(temp
->addr
.ipv6
));
682 temp
->addr
.ipv6
.sin6_port
= htons(portnum
);
685 # endif /* AF_INET6 */
687 temp
->addr
.ipv4
.sin_family
= AF_INET
;
688 memcpy(&(temp
->addr
.ipv4
.sin_addr
), host
->h_addr_list
[i
],
689 sizeof(temp
->addr
.ipv4
));
690 temp
->addr
.ipv4
.sin_port
= htons(portnum
);
694 * Append the address to the list...
708 if (h_errno
== NO_RECOVERY
)
709 cg
->need_res_init
= 1;
711 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, hstrerror(h_errno
), 0);
714 #endif /* HAVE_GETADDRINFO */
718 * Detect some common errors and handle them sanely...
721 if (!addr
&& (!hostname
|| !_cups_strcasecmp(hostname
, "localhost")))
723 struct servent
*port
; /* Port number for service */
724 int portnum
; /* Port number */
728 * Lookup the service...
733 else if (isdigit(*service
& 255))
734 portnum
= atoi(service
);
735 else if ((port
= getservbyname(service
, NULL
)) != NULL
)
736 portnum
= ntohs(port
->s_port
);
737 else if (!strcmp(service
, "http"))
739 else if (!strcmp(service
, "https"))
741 else if (!strcmp(service
, "ipp") || !strcmp(service
, "ipps"))
743 else if (!strcmp(service
, "lpd"))
745 else if (!strcmp(service
, "socket"))
749 httpAddrFreeList(first
);
751 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unknown service name."), 1);
755 if (hostname
&& !_cups_strcasecmp(hostname
, "localhost"))
758 * Unfortunately, some users ignore all of the warnings in the
759 * /etc/hosts file and delete "localhost" from it. If we get here
760 * then we were unable to resolve the name, so use the IPv6 and/or
761 * IPv4 loopback interface addresses...
765 if (family
!= AF_INET
)
768 * Add [::1] to the address list...
771 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
774 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
775 httpAddrFreeList(first
);
779 temp
->addr
.ipv6
.sin6_family
= AF_INET6
;
780 temp
->addr
.ipv6
.sin6_port
= htons(portnum
);
782 temp
->addr
.ipv6
.sin6_addr
.u
.Byte
[15] = 1;
784 temp
->addr
.ipv6
.sin6_addr
.s6_addr32
[3] = htonl(1);
793 if (family
!= AF_INET6
)
794 #endif /* AF_INET6 */
797 * Add 127.0.0.1 to the address list...
800 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
803 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
804 httpAddrFreeList(first
);
808 temp
->addr
.ipv4
.sin_family
= AF_INET
;
809 temp
->addr
.ipv4
.sin_port
= htons(portnum
);
810 temp
->addr
.ipv4
.sin_addr
.s_addr
= htonl(0x7f000001);
822 * Provide one or more passive listening addresses...
826 if (family
!= AF_INET
)
829 * Add [::] to the address list...
832 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
835 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
836 httpAddrFreeList(first
);
840 temp
->addr
.ipv6
.sin6_family
= AF_INET6
;
841 temp
->addr
.ipv6
.sin6_port
= htons(portnum
);
849 if (family
!= AF_INET6
)
850 #endif /* AF_INET6 */
853 * Add 0.0.0.0 to the address list...
856 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
859 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
860 httpAddrFreeList(first
);
864 temp
->addr
.ipv4
.sin_family
= AF_INET
;
865 temp
->addr
.ipv4
.sin_port
= htons(portnum
);
877 * Return the address list...