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()");
232 pfd
.events
= POLLIN
| POLLOUT
;
234 nfds
= poll(&pfd
, 1, remaining
> 250 ? 250 : remaining
);
236 DEBUG_printf(("1httpAddrConnect2: poll() returned %d (%d)", nfds
,
241 FD_SET(*sock
, &input_set
);
242 output_set
= input_set
;
245 timeout
.tv_usec
= (remaining
> 250 ? 250 : remaining
) * 1000;
247 nfds
= select(*sock
+ 1, &input_set
, &output_set
, NULL
, &timeout
);
249 DEBUG_printf(("1httpAddrConnect2: select() returned %d (%d)", nfds
,
251 # endif /* HAVE_POLL */
254 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
255 WSAGetLastError() == WSAEWOULDBLOCK
));
257 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
263 if (!getpeername(*sock
, (struct sockaddr
*)&peer
, &len
))
265 DEBUG_printf(("1httpAddrConnect2: Connected to %s:%d...",
266 httpAddrString(&peer
, temp
, sizeof(temp
)),
267 httpAddrPort(&peer
)));
276 #endif /* O_NONBLOCK */
278 DEBUG_printf(("1httpAddrConnect2: Unable to connect to %s:%d: %s",
279 httpAddrString(&(addrlist
->addr
), temp
, sizeof(temp
)),
280 httpAddrPort(&(addrlist
->addr
)), strerror(errno
)));
283 if (errno
== EINPROGRESS
)
288 * Close this socket and move to the next address...
298 addrlist
= addrlist
->next
;
303 _cupsSetError(IPP_STATUS_ERROR_SERVICE_UNAVAILABLE
, "Connection failed", 0);
305 _cupsSetError(IPP_STATUS_ERROR_SERVICE_UNAVAILABLE
, strerror(errno
), 0);
314 * 'httpAddrCopyList()' - Copy an address list.
316 * @since CUPS 1.7/OS X 10.9@
319 http_addrlist_t
* /* O - New address list or @code NULL@ on error */
321 http_addrlist_t
*src
) /* I - Source address list */
323 http_addrlist_t
*dst
= NULL
, /* First list entry */
324 *prev
= NULL
, /* Previous list entry */
325 *current
= NULL
;/* Current list entry */
330 if ((current
= malloc(sizeof(http_addrlist_t
))) == NULL
)
337 current
= current
->next
;
345 memcpy(current
, src
, sizeof(http_addrlist_t
));
347 current
->next
= NULL
;
350 prev
->next
= current
;
363 * 'httpAddrFreeList()' - Free an address list.
365 * @since CUPS 1.2/OS X 10.5@
370 http_addrlist_t
*addrlist
) /* I - Address list to free */
372 http_addrlist_t
*next
; /* Next address in list */
376 * Free each address in the list...
381 next
= addrlist
->next
;
391 * 'httpAddrGetList()' - Get a list of addresses for a hostname.
393 * @since CUPS 1.2/OS X 10.5@
396 http_addrlist_t
* /* O - List of addresses or NULL */
397 httpAddrGetList(const char *hostname
, /* I - Hostname, IP address, or NULL for passive listen address */
398 int family
, /* I - Address family or AF_UNSPEC */
399 const char *service
) /* I - Service name or port number */
401 http_addrlist_t
*first
, /* First address in list */
402 *addr
, /* Current address in list */
403 *temp
; /* New address */
404 _cups_globals_t
*cg
= _cupsGlobals();
409 _cups_debug_printf("httpAddrGetList(hostname=\"%s\", family=AF_%s, "
411 hostname
? hostname
: "(nil)",
412 family
== AF_UNSPEC
? "UNSPEC" :
414 family
== AF_LOCAL
? "LOCAL" :
415 # endif /* AF_LOCAL */
417 family
== AF_INET6
? "INET6" :
418 # endif /* AF_INET6 */
419 family
== AF_INET
? "INET" : "???", service
);
424 * STR #2920: Initialize resolver after failure in cups-polld
426 * If the previous lookup failed, re-initialize the resolver to prevent
427 * temporary network errors from persisting. This *should* be handled by
428 * the resolver libraries, but apparently the glibc folks do not agree.
430 * We set a flag at the end of this function if we encounter an error that
431 * requires reinitialization of the resolver functions. We then call
432 * res_init() if the flag is set on the next call here or in httpAddrLookup().
435 if (cg
->need_res_init
)
439 cg
->need_res_init
= 0;
441 #endif /* HAVE_RES_INIT */
444 * Lookup the address the best way we can...
450 if (hostname
&& hostname
[0] == '/')
453 * Domain socket address...
456 if ((first
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
))) != NULL
)
458 first
->addr
.un
.sun_family
= AF_LOCAL
;
459 strlcpy(first
->addr
.un
.sun_path
, hostname
, sizeof(first
->addr
.un
.sun_path
));
463 #endif /* AF_LOCAL */
464 if (!hostname
|| _cups_strcasecmp(hostname
, "localhost"))
466 #ifdef HAVE_GETADDRINFO
467 struct addrinfo hints
, /* Address lookup hints */
468 *results
, /* Address lookup results */
469 *current
; /* Current result */
470 char ipv6
[64], /* IPv6 address */
471 *ipv6zone
; /* Pointer to zone separator */
472 int ipv6len
; /* Length of IPv6 address */
473 int error
; /* getaddrinfo() error */
477 * Lookup the address as needed...
480 memset(&hints
, 0, sizeof(hints
));
481 hints
.ai_family
= family
;
482 hints
.ai_flags
= hostname
? 0 : AI_PASSIVE
;
483 hints
.ai_socktype
= SOCK_STREAM
;
485 if (hostname
&& *hostname
== '[')
488 * Remove brackets from numeric IPv6 address...
491 if (!strncmp(hostname
, "[v1.", 4))
494 * Copy the newer address format which supports link-local addresses...
497 strlcpy(ipv6
, hostname
+ 4, sizeof(ipv6
));
498 if ((ipv6len
= (int)strlen(ipv6
) - 1) >= 0 && ipv6
[ipv6len
] == ']')
500 ipv6
[ipv6len
] = '\0';
504 * Convert "+zone" in address to "%zone"...
507 if ((ipv6zone
= strrchr(ipv6
, '+')) != NULL
)
514 * Copy the regular non-link-local IPv6 address...
517 strlcpy(ipv6
, hostname
+ 1, sizeof(ipv6
));
518 if ((ipv6len
= (int)strlen(ipv6
) - 1) >= 0 && ipv6
[ipv6len
] == ']')
520 ipv6
[ipv6len
] = '\0';
526 if ((error
= getaddrinfo(hostname
, service
, &hints
, &results
)) == 0)
529 * Copy the results to our own address list structure...
532 for (current
= results
; current
; current
= current
->ai_next
)
533 if (current
->ai_family
== AF_INET
|| current
->ai_family
== AF_INET6
)
536 * Copy the address over...
539 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
542 httpAddrFreeList(first
);
543 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
547 if (current
->ai_family
== AF_INET6
)
548 memcpy(&(temp
->addr
.ipv6
), current
->ai_addr
,
549 sizeof(temp
->addr
.ipv6
));
551 memcpy(&(temp
->addr
.ipv4
), current
->ai_addr
,
552 sizeof(temp
->addr
.ipv4
));
555 * Append the address to the list...
568 * Free the results from getaddrinfo()...
571 freeaddrinfo(results
);
575 if (error
== EAI_FAIL
)
576 cg
->need_res_init
= 1;
578 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, gai_strerror(error
), 0);
584 int i
; /* Looping vars */
585 unsigned ip
[4]; /* IPv4 address components */
586 const char *ptr
; /* Pointer into hostname */
587 struct hostent
*host
; /* Result of lookup */
588 struct servent
*port
; /* Port number for service */
589 int portnum
; /* Port number */
593 * Lookup the service...
598 else if (isdigit(*service
& 255))
599 portnum
= atoi(service
);
600 else if ((port
= getservbyname(service
, NULL
)) != NULL
)
601 portnum
= ntohs(port
->s_port
);
602 else if (!strcmp(service
, "http"))
604 else if (!strcmp(service
, "https"))
606 else if (!strcmp(service
, "ipp") || !strcmp(service
, "ipps"))
608 else if (!strcmp(service
, "lpd"))
610 else if (!strcmp(service
, "socket"))
616 * This code is needed because some operating systems have a
617 * buggy implementation of gethostbyname() that does not support
618 * IPv4 addresses. If the hostname string is an IPv4 address, then
619 * sscanf() is used to extract the IPv4 components. We then pack
620 * the components into an IPv4 address manually, since the
621 * inet_aton() function is deprecated. We use the htonl() macro
622 * to get the right byte order for the address.
625 for (ptr
= hostname
; isdigit(*ptr
& 255) || *ptr
== '.'; ptr
++);
630 * We have an IPv4 address; break it up and create an IPv4 address...
633 if (sscanf(hostname
, "%u.%u.%u.%u", ip
, ip
+ 1, ip
+ 2, ip
+ 3) == 4 &&
634 ip
[0] <= 255 && ip
[1] <= 255 && ip
[2] <= 255 && ip
[3] <= 255)
636 first
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
640 first
->addr
.ipv4
.sin_family
= AF_INET
;
641 first
->addr
.ipv4
.sin_addr
.s_addr
= htonl((((((((unsigned)ip
[0] << 8) |
642 (unsigned)ip
[1]) << 8) |
643 (unsigned)ip
[2]) << 8) |
645 first
->addr
.ipv4
.sin_port
= htons(portnum
);
648 else if ((host
= gethostbyname(hostname
)) != NULL
&&
650 (host
->h_addrtype
== AF_INET
|| host
->h_addrtype
== AF_INET6
))
652 host
->h_addrtype
== AF_INET
)
653 # endif /* AF_INET6 */
655 for (i
= 0; host
->h_addr_list
[i
]; i
++)
658 * Copy the address over...
661 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
664 httpAddrFreeList(first
);
669 if (host
->h_addrtype
== AF_INET6
)
671 temp
->addr
.ipv6
.sin6_family
= AF_INET6
;
672 memcpy(&(temp
->addr
.ipv6
.sin6_addr
), host
->h_addr_list
[i
],
673 sizeof(temp
->addr
.ipv6
));
674 temp
->addr
.ipv6
.sin6_port
= htons(portnum
);
677 # endif /* AF_INET6 */
679 temp
->addr
.ipv4
.sin_family
= AF_INET
;
680 memcpy(&(temp
->addr
.ipv4
.sin_addr
), host
->h_addr_list
[i
],
681 sizeof(temp
->addr
.ipv4
));
682 temp
->addr
.ipv4
.sin_port
= htons(portnum
);
686 * Append the address to the list...
700 if (h_errno
== NO_RECOVERY
)
701 cg
->need_res_init
= 1;
703 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, hstrerror(h_errno
), 0);
706 #endif /* HAVE_GETADDRINFO */
710 * Detect some common errors and handle them sanely...
713 if (!addr
&& (!hostname
|| !_cups_strcasecmp(hostname
, "localhost")))
715 struct servent
*port
; /* Port number for service */
716 int portnum
; /* Port number */
720 * Lookup the service...
725 else if (isdigit(*service
& 255))
726 portnum
= atoi(service
);
727 else if ((port
= getservbyname(service
, NULL
)) != NULL
)
728 portnum
= ntohs(port
->s_port
);
729 else if (!strcmp(service
, "http"))
731 else if (!strcmp(service
, "https"))
733 else if (!strcmp(service
, "ipp") || !strcmp(service
, "ipps"))
735 else if (!strcmp(service
, "lpd"))
737 else if (!strcmp(service
, "socket"))
741 httpAddrFreeList(first
);
743 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unknown service name."), 1);
747 if (hostname
&& !_cups_strcasecmp(hostname
, "localhost"))
750 * Unfortunately, some users ignore all of the warnings in the
751 * /etc/hosts file and delete "localhost" from it. If we get here
752 * then we were unable to resolve the name, so use the IPv6 and/or
753 * IPv4 loopback interface addresses...
757 if (family
!= AF_INET
)
760 * Add [::1] to the address list...
763 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
766 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
767 httpAddrFreeList(first
);
771 temp
->addr
.ipv6
.sin6_family
= AF_INET6
;
772 temp
->addr
.ipv6
.sin6_port
= htons(portnum
);
774 temp
->addr
.ipv6
.sin6_addr
.u
.Byte
[15] = 1;
776 temp
->addr
.ipv6
.sin6_addr
.s6_addr32
[3] = htonl(1);
785 if (family
!= AF_INET6
)
786 #endif /* AF_INET6 */
789 * Add 127.0.0.1 to the address list...
792 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
795 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
796 httpAddrFreeList(first
);
800 temp
->addr
.ipv4
.sin_family
= AF_INET
;
801 temp
->addr
.ipv4
.sin_port
= htons(portnum
);
802 temp
->addr
.ipv4
.sin_addr
.s_addr
= htonl(0x7f000001);
814 * Provide one or more passive listening addresses...
818 if (family
!= AF_INET
)
821 * Add [::] to the address list...
824 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
827 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
828 httpAddrFreeList(first
);
832 temp
->addr
.ipv6
.sin6_family
= AF_INET6
;
833 temp
->addr
.ipv6
.sin6_port
= htons(portnum
);
841 if (family
!= AF_INET6
)
842 #endif /* AF_INET6 */
845 * Add 0.0.0.0 to the address list...
848 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
851 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
852 httpAddrFreeList(first
);
856 temp
->addr
.ipv4
.sin_family
= AF_INET
;
857 temp
->addr
.ipv4
.sin_port
= htons(portnum
);
869 * Return the address list...