2 * HTTP address list routines for CUPS.
4 * Copyright 2007-2014 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 * file is 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/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)", (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/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 */
69 int i
, /* Looping var */
70 nfds
, /* Number of file descriptors */
71 fds
[100], /* Socket file descriptors */
72 result
; /* Result from select() or poll() */
73 http_addrlist_t
*addrs
[100]; /* Addresses */
75 struct pollfd pfds
[100]; /* Polled file descriptors */
77 int max_fd
= -1; /* Highest file descriptor */
78 fd_set input_set
, /* select() input set */
79 output_set
; /* select() output set */
80 struct timeval timeout
; /* Timeout */
81 # endif /* HAVE_POLL */
82 #endif /* O_NONBLOCK */
84 char temp
[256]; /* Temporary address string */
88 DEBUG_printf(("httpAddrConnect2(addrlist=%p, sock=%p, msec=%d, cancel=%p)", (void *)addrlist
, (void *)sock
, msec
, (void *)cancel
));
93 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
97 if (cancel
&& *cancel
)
104 * Loop through each address until we connect or run out of addresses...
107 for (nfds
= 0; addrlist
&& nfds
< (int)(sizeof(fds
) / sizeof(fds
[0])); addrlist
= addrlist
->next
)
109 if (cancel
&& *cancel
)
114 httpAddrClose(NULL
, fds
[nfds
]);
121 * Create the socket...
124 DEBUG_printf(("2httpAddrConnect2: Trying %s:%d...", httpAddrString(&(addrlist
->addr
), temp
, sizeof(temp
)), httpAddrPort(&(addrlist
->addr
))));
126 if ((fds
[nfds
] = (int)socket(httpAddrFamily(&(addrlist
->addr
)), SOCK_STREAM
, 0)) < 0)
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...
141 setsockopt(fds
[nfds
], SOL_SOCKET
, SO_REUSEADDR
, CUPS_SOCAST
&val
, sizeof(val
));
145 setsockopt(fds
[nfds
], SOL_SOCKET
, SO_REUSEPORT
, CUPS_SOCAST
&val
, sizeof(val
));
146 #endif /* SO_REUSEPORT */
150 setsockopt(fds
[nfds
], SOL_SOCKET
, SO_NOSIGPIPE
, CUPS_SOCAST
&val
, sizeof(val
));
151 #endif /* SO_NOSIGPIPE */
154 * Using TCP_NODELAY improves responsiveness, especially on systems
155 * with a slow loopback interface...
159 setsockopt(fds
[nfds
], IPPROTO_TCP
, TCP_NODELAY
, CUPS_SOCAST
&val
, sizeof(val
));
163 * Close this socket when starting another process...
166 fcntl(fds
[nfds
], F_SETFD
, FD_CLOEXEC
);
167 #endif /* FD_CLOEXEC */
171 * Do an asynchronous connect by setting the socket non-blocking...
174 DEBUG_printf(("httpAddrConnect2: Setting non-blocking connect()"));
176 flags
= fcntl(fds
[nfds
], F_GETFL
, 0);
177 fcntl(fds
[nfds
], F_SETFL
, flags
| O_NONBLOCK
);
178 #endif /* O_NONBLOCK */
184 if (!connect(fds
[nfds
], &(addrlist
->addr
.addr
), (socklen_t
)httpAddrLength(&(addrlist
->addr
))))
186 DEBUG_printf(("1httpAddrConnect2: Connected to %s:%d...", httpAddrString(&(addrlist
->addr
), temp
, sizeof(temp
)), httpAddrPort(&(addrlist
->addr
))));
189 fcntl(fds
[nfds
], F_SETFL
, flags
);
190 #endif /* O_NONBLOCK */
197 httpAddrClose(NULL
, fds
[nfds
]);
204 if (WSAGetLastError() != WSAEINPROGRESS
&& WSAGetLastError() != WSAEWOULDBLOCK
)
206 if (errno
!= EINPROGRESS
&& errno
!= EWOULDBLOCK
)
209 DEBUG_printf(("1httpAddrConnect2: Unable to connect to %s:%d: %s", httpAddrString(&(addrlist
->addr
), temp
, sizeof(temp
)), httpAddrPort(&(addrlist
->addr
)), strerror(errno
)));
210 httpAddrClose(NULL
, fds
[nfds
]);
214 fcntl(fds
[nfds
], F_SETFL
, flags
);
217 if (fds
[nfds
] > max_fd
)
219 #endif /* !HAVE_POLL */
221 addrs
[nfds
] = addrlist
;
226 DEBUG_puts("1httpAddrConnect2: Finishing async connect()");
228 for (remaining
= msec
; remaining
> 0; remaining
-= 250)
232 if (cancel
&& *cancel
)
235 * Close this socket and return...
238 DEBUG_puts("1httpAddrConnect2: Canceled connect()");
243 httpAddrClose(NULL
, fds
[nfds
]);
252 for (i
= 0; i
< nfds
; i
++)
255 pfds
[i
].events
= POLLIN
| POLLOUT
;
258 result
= poll(pfds
, (nfds_t
)nfds
, remaining
> 250 ? 250 : remaining
);
260 DEBUG_printf(("1httpAddrConnect2: poll() returned %d (%d)", result
, errno
));
264 for (i
= 0; i
< nfds
; i
++)
265 FD_SET(fds
[i
], &input_set
);
266 output_set
= input_set
;
269 timeout
.tv_usec
= (remaining
> 250 ? 250 : remaining
) * 1000;
271 result
= select(max_fd
+ 1, &input_set
, &output_set
, NULL
, &timeout
);
273 DEBUG_printf(("1httpAddrConnect2: select() returned %d (%d)", result
, errno
));
274 # endif /* HAVE_POLL */
277 while (result
< 0 && (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
));
279 while (result
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
284 for (i
= 0; i
< nfds
; i
++)
287 DEBUG_printf(("pfds[%d].revents=%x\n", i
, pfds
[i
].revents
));
290 if (FD_ISSET(fds
[i
], &input
))
291 # endif /* HAVE_POLL */
295 if (!getpeername(fds
[i
], (struct sockaddr
*)&peer
, &len
))
297 DEBUG_printf(("1httpAddrConnect2: Connected to %s:%d...", httpAddrString(&peer
, temp
, sizeof(temp
)), httpAddrPort(&peer
)));
303 httpAddrClose(NULL
, fds
[i
]);
309 #endif /* O_NONBLOCK */
314 httpAddrClose(NULL
, fds
[nfds
]);
318 _cupsSetError(IPP_STATUS_ERROR_SERVICE_UNAVAILABLE
, "Connection failed", 0);
320 _cupsSetError(IPP_STATUS_ERROR_SERVICE_UNAVAILABLE
, strerror(errno
), 0);
328 * 'httpAddrCopyList()' - Copy an address list.
330 * @since CUPS 1.7/OS X 10.9@
333 http_addrlist_t
* /* O - New address list or @code NULL@ on error */
335 http_addrlist_t
*src
) /* I - Source address list */
337 http_addrlist_t
*dst
= NULL
, /* First list entry */
338 *prev
= NULL
, /* Previous list entry */
339 *current
= NULL
;/* Current list entry */
344 if ((current
= malloc(sizeof(http_addrlist_t
))) == NULL
)
351 current
= current
->next
;
359 memcpy(current
, src
, sizeof(http_addrlist_t
));
361 current
->next
= NULL
;
364 prev
->next
= current
;
377 * 'httpAddrFreeList()' - Free an address list.
379 * @since CUPS 1.2/OS X 10.5@
384 http_addrlist_t
*addrlist
) /* I - Address list to free */
386 http_addrlist_t
*next
; /* Next address in list */
390 * Free each address in the list...
395 next
= addrlist
->next
;
405 * 'httpAddrGetList()' - Get a list of addresses for a hostname.
407 * @since CUPS 1.2/OS X 10.5@
410 http_addrlist_t
* /* O - List of addresses or NULL */
411 httpAddrGetList(const char *hostname
, /* I - Hostname, IP address, or NULL for passive listen address */
412 int family
, /* I - Address family or AF_UNSPEC */
413 const char *service
) /* I - Service name or port number */
415 http_addrlist_t
*first
, /* First address in list */
416 *addr
, /* Current address in list */
417 *temp
; /* New address */
418 _cups_globals_t
*cg
= _cupsGlobals();
423 _cups_debug_printf("httpAddrGetList(hostname=\"%s\", family=AF_%s, "
425 hostname
? hostname
: "(nil)",
426 family
== AF_UNSPEC
? "UNSPEC" :
428 family
== AF_LOCAL
? "LOCAL" :
429 # endif /* AF_LOCAL */
431 family
== AF_INET6
? "INET6" :
432 # endif /* AF_INET6 */
433 family
== AF_INET
? "INET" : "???", service
);
438 * STR #2920: Initialize resolver after failure in cups-polld
440 * If the previous lookup failed, re-initialize the resolver to prevent
441 * temporary network errors from persisting. This *should* be handled by
442 * the resolver libraries, but apparently the glibc folks do not agree.
444 * We set a flag at the end of this function if we encounter an error that
445 * requires reinitialization of the resolver functions. We then call
446 * res_init() if the flag is set on the next call here or in httpAddrLookup().
449 if (cg
->need_res_init
)
453 cg
->need_res_init
= 0;
455 #endif /* HAVE_RES_INIT */
458 * Lookup the address the best way we can...
464 if (hostname
&& hostname
[0] == '/')
467 * Domain socket address...
470 if ((first
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
))) != NULL
)
473 first
->addr
.un
.sun_family
= AF_LOCAL
;
474 strlcpy(first
->addr
.un
.sun_path
, hostname
, sizeof(first
->addr
.un
.sun_path
));
478 #endif /* AF_LOCAL */
479 if (!hostname
|| _cups_strcasecmp(hostname
, "localhost"))
481 #ifdef HAVE_GETADDRINFO
482 struct addrinfo hints
, /* Address lookup hints */
483 *results
, /* Address lookup results */
484 *current
; /* Current result */
485 char ipv6
[64], /* IPv6 address */
486 *ipv6zone
; /* Pointer to zone separator */
487 int ipv6len
; /* Length of IPv6 address */
488 int error
; /* getaddrinfo() error */
492 * Lookup the address as needed...
495 memset(&hints
, 0, sizeof(hints
));
496 hints
.ai_family
= family
;
497 hints
.ai_flags
= hostname
? 0 : AI_PASSIVE
;
498 hints
.ai_socktype
= SOCK_STREAM
;
500 if (hostname
&& *hostname
== '[')
503 * Remove brackets from numeric IPv6 address...
506 if (!strncmp(hostname
, "[v1.", 4))
509 * Copy the newer address format which supports link-local addresses...
512 strlcpy(ipv6
, hostname
+ 4, sizeof(ipv6
));
513 if ((ipv6len
= (int)strlen(ipv6
) - 1) >= 0 && ipv6
[ipv6len
] == ']')
515 ipv6
[ipv6len
] = '\0';
519 * Convert "+zone" in address to "%zone"...
522 if ((ipv6zone
= strrchr(ipv6
, '+')) != NULL
)
529 * Copy the regular non-link-local IPv6 address...
532 strlcpy(ipv6
, hostname
+ 1, sizeof(ipv6
));
533 if ((ipv6len
= (int)strlen(ipv6
) - 1) >= 0 && ipv6
[ipv6len
] == ']')
535 ipv6
[ipv6len
] = '\0';
541 if ((error
= getaddrinfo(hostname
, service
, &hints
, &results
)) == 0)
544 * Copy the results to our own address list structure...
547 for (current
= results
; current
; current
= current
->ai_next
)
548 if (current
->ai_family
== AF_INET
|| current
->ai_family
== AF_INET6
)
551 * Copy the address over...
554 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
557 httpAddrFreeList(first
);
558 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
562 if (current
->ai_family
== AF_INET6
)
563 memcpy(&(temp
->addr
.ipv6
), current
->ai_addr
,
564 sizeof(temp
->addr
.ipv6
));
566 memcpy(&(temp
->addr
.ipv4
), current
->ai_addr
,
567 sizeof(temp
->addr
.ipv4
));
570 * Append the address to the list...
583 * Free the results from getaddrinfo()...
586 freeaddrinfo(results
);
590 if (error
== EAI_FAIL
)
591 cg
->need_res_init
= 1;
593 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, gai_strerror(error
), 0);
599 int i
; /* Looping vars */
600 unsigned ip
[4]; /* IPv4 address components */
601 const char *ptr
; /* Pointer into hostname */
602 struct hostent
*host
; /* Result of lookup */
603 struct servent
*port
; /* Port number for service */
604 int portnum
; /* Port number */
608 * Lookup the service...
613 else if (isdigit(*service
& 255))
614 portnum
= atoi(service
);
615 else if ((port
= getservbyname(service
, NULL
)) != NULL
)
616 portnum
= ntohs(port
->s_port
);
617 else if (!strcmp(service
, "http"))
619 else if (!strcmp(service
, "https"))
621 else if (!strcmp(service
, "ipp") || !strcmp(service
, "ipps"))
623 else if (!strcmp(service
, "lpd"))
625 else if (!strcmp(service
, "socket"))
631 * This code is needed because some operating systems have a
632 * buggy implementation of gethostbyname() that does not support
633 * IPv4 addresses. If the hostname string is an IPv4 address, then
634 * sscanf() is used to extract the IPv4 components. We then pack
635 * the components into an IPv4 address manually, since the
636 * inet_aton() function is deprecated. We use the htonl() macro
637 * to get the right byte order for the address.
640 for (ptr
= hostname
; isdigit(*ptr
& 255) || *ptr
== '.'; ptr
++);
645 * We have an IPv4 address; break it up and create an IPv4 address...
648 if (sscanf(hostname
, "%u.%u.%u.%u", ip
, ip
+ 1, ip
+ 2, ip
+ 3) == 4 &&
649 ip
[0] <= 255 && ip
[1] <= 255 && ip
[2] <= 255 && ip
[3] <= 255)
651 first
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
655 first
->addr
.ipv4
.sin_family
= AF_INET
;
656 first
->addr
.ipv4
.sin_addr
.s_addr
= htonl((((((((unsigned)ip
[0] << 8) |
657 (unsigned)ip
[1]) << 8) |
658 (unsigned)ip
[2]) << 8) |
660 first
->addr
.ipv4
.sin_port
= htons(portnum
);
663 else if ((host
= gethostbyname(hostname
)) != NULL
&&
665 (host
->h_addrtype
== AF_INET
|| host
->h_addrtype
== AF_INET6
))
667 host
->h_addrtype
== AF_INET
)
668 # endif /* AF_INET6 */
670 for (i
= 0; host
->h_addr_list
[i
]; i
++)
673 * Copy the address over...
676 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
679 httpAddrFreeList(first
);
684 if (host
->h_addrtype
== AF_INET6
)
686 temp
->addr
.ipv6
.sin6_family
= AF_INET6
;
687 memcpy(&(temp
->addr
.ipv6
.sin6_addr
), host
->h_addr_list
[i
],
688 sizeof(temp
->addr
.ipv6
));
689 temp
->addr
.ipv6
.sin6_port
= htons(portnum
);
692 # endif /* AF_INET6 */
694 temp
->addr
.ipv4
.sin_family
= AF_INET
;
695 memcpy(&(temp
->addr
.ipv4
.sin_addr
), host
->h_addr_list
[i
],
696 sizeof(temp
->addr
.ipv4
));
697 temp
->addr
.ipv4
.sin_port
= htons(portnum
);
701 * Append the address to the list...
715 if (h_errno
== NO_RECOVERY
)
716 cg
->need_res_init
= 1;
718 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, hstrerror(h_errno
), 0);
721 #endif /* HAVE_GETADDRINFO */
725 * Detect some common errors and handle them sanely...
728 if (!addr
&& (!hostname
|| !_cups_strcasecmp(hostname
, "localhost")))
730 struct servent
*port
; /* Port number for service */
731 int portnum
; /* Port number */
735 * Lookup the service...
740 else if (isdigit(*service
& 255))
741 portnum
= atoi(service
);
742 else if ((port
= getservbyname(service
, NULL
)) != NULL
)
743 portnum
= ntohs(port
->s_port
);
744 else if (!strcmp(service
, "http"))
746 else if (!strcmp(service
, "https"))
748 else if (!strcmp(service
, "ipp") || !strcmp(service
, "ipps"))
750 else if (!strcmp(service
, "lpd"))
752 else if (!strcmp(service
, "socket"))
756 httpAddrFreeList(first
);
758 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unknown service name."), 1);
762 if (hostname
&& !_cups_strcasecmp(hostname
, "localhost"))
765 * Unfortunately, some users ignore all of the warnings in the
766 * /etc/hosts file and delete "localhost" from it. If we get here
767 * then we were unable to resolve the name, so use the IPv6 and/or
768 * IPv4 loopback interface addresses...
772 if (family
!= AF_INET
)
775 * Add [::1] to the address list...
778 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
781 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
782 httpAddrFreeList(first
);
786 temp
->addr
.ipv6
.sin6_family
= AF_INET6
;
787 temp
->addr
.ipv6
.sin6_port
= htons(portnum
);
789 temp
->addr
.ipv6
.sin6_addr
.u
.Byte
[15] = 1;
791 temp
->addr
.ipv6
.sin6_addr
.s6_addr32
[3] = htonl(1);
800 if (family
!= AF_INET6
)
801 #endif /* AF_INET6 */
804 * Add 127.0.0.1 to the address list...
807 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
810 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
811 httpAddrFreeList(first
);
815 temp
->addr
.ipv4
.sin_family
= AF_INET
;
816 temp
->addr
.ipv4
.sin_port
= htons(portnum
);
817 temp
->addr
.ipv4
.sin_addr
.s_addr
= htonl(0x7f000001);
829 * Provide one or more passive listening addresses...
833 if (family
!= AF_INET
)
836 * Add [::] to the address list...
839 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
842 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
843 httpAddrFreeList(first
);
847 temp
->addr
.ipv6
.sin6_family
= AF_INET6
;
848 temp
->addr
.ipv6
.sin6_port
= htons(portnum
);
856 if (family
!= AF_INET6
)
857 #endif /* AF_INET6 */
860 * Add 0.0.0.0 to the address list...
863 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
866 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
867 httpAddrFreeList(first
);
871 temp
->addr
.ipv4
.sin_family
= AF_INET
;
872 temp
->addr
.ipv4
.sin_port
= htons(portnum
);
884 * Return the address list...