2 * HTTP address list routines for CUPS.
4 * Copyright 2007-2016 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/macOS 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/macOS 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 int flags
, /* Socket flags */
66 remaining
; /* Remaining timeout */
67 int i
, /* Looping var */
68 nfds
, /* Number of file descriptors */
69 fds
[100], /* Socket file descriptors */
70 result
; /* Result from select() or poll() */
71 http_addrlist_t
*addrs
[100]; /* Addresses */
73 struct pollfd pfds
[100]; /* Polled file descriptors */
75 int max_fd
= -1; /* Highest file descriptor */
76 fd_set input_set
, /* select() input set */
77 output_set
; /* select() output set */
78 struct timeval timeout
; /* Timeout */
79 # endif /* HAVE_POLL */
80 #endif /* O_NONBLOCK */
82 socklen_t len
; /* Length of value */
83 http_addr_t peer
; /* Peer address */
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...
110 while (remaining
> 0)
112 if (cancel
&& *cancel
)
117 httpAddrClose(NULL
, fds
[nfds
]);
123 if (addrlist
&& nfds
< (int)(sizeof(fds
) / sizeof(fds
[0])))
126 * Create the socket...
129 DEBUG_printf(("2httpAddrConnect2: Trying %s:%d...", httpAddrString(&(addrlist
->addr
), temp
, sizeof(temp
)), httpAddrPort(&(addrlist
->addr
))));
131 if ((fds
[nfds
] = (int)socket(httpAddrFamily(&(addrlist
->addr
)), SOCK_STREAM
, 0)) < 0)
134 * Don't abort yet, as this could just be an issue with the local
135 * system not being configured with IPv4/IPv6/domain socket enabled.
137 * Just skip this address...
140 addrlist
= addrlist
->next
;
149 setsockopt(fds
[nfds
], SOL_SOCKET
, SO_REUSEADDR
, CUPS_SOCAST
&val
, sizeof(val
));
153 setsockopt(fds
[nfds
], SOL_SOCKET
, SO_REUSEPORT
, CUPS_SOCAST
&val
, sizeof(val
));
154 #endif /* SO_REUSEPORT */
158 setsockopt(fds
[nfds
], SOL_SOCKET
, SO_NOSIGPIPE
, CUPS_SOCAST
&val
, sizeof(val
));
159 #endif /* SO_NOSIGPIPE */
162 * Using TCP_NODELAY improves responsiveness, especially on systems
163 * with a slow loopback interface...
167 setsockopt(fds
[nfds
], IPPROTO_TCP
, TCP_NODELAY
, CUPS_SOCAST
&val
, sizeof(val
));
171 * Close this socket when starting another process...
174 fcntl(fds
[nfds
], F_SETFD
, FD_CLOEXEC
);
175 #endif /* FD_CLOEXEC */
179 * Do an asynchronous connect by setting the socket non-blocking...
182 DEBUG_printf(("httpAddrConnect2: Setting non-blocking connect()"));
184 flags
= fcntl(fds
[nfds
], F_GETFL
, 0);
185 fcntl(fds
[nfds
], F_SETFL
, flags
| O_NONBLOCK
);
186 #endif /* O_NONBLOCK */
192 if (!connect(fds
[nfds
], &(addrlist
->addr
.addr
), (socklen_t
)httpAddrLength(&(addrlist
->addr
))))
194 DEBUG_printf(("1httpAddrConnect2: Connected to %s:%d...", httpAddrString(&(addrlist
->addr
), temp
, sizeof(temp
)), httpAddrPort(&(addrlist
->addr
))));
197 fcntl(fds
[nfds
], F_SETFL
, flags
);
198 #endif /* O_NONBLOCK */
205 httpAddrClose(NULL
, fds
[nfds
]);
212 if (WSAGetLastError() != WSAEINPROGRESS
&& WSAGetLastError() != WSAEWOULDBLOCK
)
214 if (errno
!= EINPROGRESS
&& errno
!= EWOULDBLOCK
)
217 DEBUG_printf(("1httpAddrConnect2: Unable to connect to %s:%d: %s", httpAddrString(&(addrlist
->addr
), temp
, sizeof(temp
)), httpAddrPort(&(addrlist
->addr
)), strerror(errno
)));
218 httpAddrClose(NULL
, fds
[nfds
]);
219 addrlist
= addrlist
->next
;
223 fcntl(fds
[nfds
], F_SETFL
, flags
);
226 if (fds
[nfds
] > max_fd
)
228 #endif /* !HAVE_POLL */
230 addrs
[nfds
] = addrlist
;
232 addrlist
= addrlist
->next
;
236 * See if we can connect to any of the addresses so far...
240 DEBUG_puts("1httpAddrConnect2: Finishing async connect()");
244 if (cancel
&& *cancel
)
247 * Close this socket and return...
250 DEBUG_puts("1httpAddrConnect2: Canceled connect()");
255 httpAddrClose(NULL
, fds
[nfds
]);
264 for (i
= 0; i
< nfds
; i
++)
267 pfds
[i
].events
= POLLIN
| POLLOUT
;
270 result
= poll(pfds
, (nfds_t
)nfds
, addrlist
? 100 : remaining
> 250 ? 250 : remaining
);
272 DEBUG_printf(("1httpAddrConnect2: poll() returned %d (%d)", result
, errno
));
276 for (i
= 0; i
< nfds
; i
++)
277 FD_SET(fds
[i
], &input_set
);
278 output_set
= input_set
;
281 timeout
.tv_usec
= (addrlist
? 100 : remaining
> 250 ? 250 : remaining
) * 1000;
283 result
= select(max_fd
+ 1, &input_set
, &output_set
, NULL
, &timeout
);
285 DEBUG_printf(("1httpAddrConnect2: select() returned %d (%d)", result
, errno
));
286 # endif /* HAVE_POLL */
289 while (result
< 0 && (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
));
291 while (result
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
296 for (i
= 0; i
< nfds
; i
++)
299 DEBUG_printf(("pfds[%d].revents=%x\n", i
, pfds
[i
].revents
));
302 if (FD_ISSET(fds
[i
], &input
))
303 # endif /* HAVE_POLL */
310 if (!getpeername(fds
[i
], (struct sockaddr
*)&peer
, &len
))
311 DEBUG_printf(("1httpAddrConnect2: Connected to %s:%d...", httpAddrString(&peer
, temp
, sizeof(temp
)), httpAddrPort(&peer
)));
315 httpAddrClose(NULL
, fds
[i
]);
320 #endif /* O_NONBLOCK */
331 httpAddrClose(NULL
, fds
[nfds
]);
335 _cupsSetError(IPP_STATUS_ERROR_SERVICE_UNAVAILABLE
, "Connection failed", 0);
337 _cupsSetError(IPP_STATUS_ERROR_SERVICE_UNAVAILABLE
, strerror(errno
), 0);
345 * 'httpAddrCopyList()' - Copy an address list.
347 * @since CUPS 1.7/macOS 10.9@
350 http_addrlist_t
* /* O - New address list or @code NULL@ on error */
352 http_addrlist_t
*src
) /* I - Source address list */
354 http_addrlist_t
*dst
= NULL
, /* First list entry */
355 *prev
= NULL
, /* Previous list entry */
356 *current
= NULL
;/* Current list entry */
361 if ((current
= malloc(sizeof(http_addrlist_t
))) == NULL
)
368 current
= current
->next
;
376 memcpy(current
, src
, sizeof(http_addrlist_t
));
378 current
->next
= NULL
;
381 prev
->next
= current
;
394 * 'httpAddrFreeList()' - Free an address list.
396 * @since CUPS 1.2/macOS 10.5@
401 http_addrlist_t
*addrlist
) /* I - Address list to free */
403 http_addrlist_t
*next
; /* Next address in list */
407 * Free each address in the list...
412 next
= addrlist
->next
;
422 * 'httpAddrGetList()' - Get a list of addresses for a hostname.
424 * @since CUPS 1.2/macOS 10.5@
427 http_addrlist_t
* /* O - List of addresses or NULL */
428 httpAddrGetList(const char *hostname
, /* I - Hostname, IP address, or NULL for passive listen address */
429 int family
, /* I - Address family or AF_UNSPEC */
430 const char *service
) /* I - Service name or port number */
432 http_addrlist_t
*first
, /* First address in list */
433 *addr
, /* Current address in list */
434 *temp
; /* New address */
435 _cups_globals_t
*cg
= _cupsGlobals();
440 _cups_debug_printf("httpAddrGetList(hostname=\"%s\", family=AF_%s, "
442 hostname
? hostname
: "(nil)",
443 family
== AF_UNSPEC
? "UNSPEC" :
445 family
== AF_LOCAL
? "LOCAL" :
446 # endif /* AF_LOCAL */
448 family
== AF_INET6
? "INET6" :
449 # endif /* AF_INET6 */
450 family
== AF_INET
? "INET" : "???", service
);
455 * STR #2920: Initialize resolver after failure in cups-polld
457 * If the previous lookup failed, re-initialize the resolver to prevent
458 * temporary network errors from persisting. This *should* be handled by
459 * the resolver libraries, but apparently the glibc folks do not agree.
461 * We set a flag at the end of this function if we encounter an error that
462 * requires reinitialization of the resolver functions. We then call
463 * res_init() if the flag is set on the next call here or in httpAddrLookup().
466 if (cg
->need_res_init
)
470 cg
->need_res_init
= 0;
472 #endif /* HAVE_RES_INIT */
475 * Lookup the address the best way we can...
481 if (hostname
&& hostname
[0] == '/')
484 * Domain socket address...
487 if ((first
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
))) != NULL
)
490 first
->addr
.un
.sun_family
= AF_LOCAL
;
491 strlcpy(first
->addr
.un
.sun_path
, hostname
, sizeof(first
->addr
.un
.sun_path
));
495 #endif /* AF_LOCAL */
496 if (!hostname
|| _cups_strcasecmp(hostname
, "localhost"))
498 #ifdef HAVE_GETADDRINFO
499 struct addrinfo hints
, /* Address lookup hints */
500 *results
, /* Address lookup results */
501 *current
; /* Current result */
502 char ipv6
[64], /* IPv6 address */
503 *ipv6zone
; /* Pointer to zone separator */
504 int ipv6len
; /* Length of IPv6 address */
505 int error
; /* getaddrinfo() error */
509 * Lookup the address as needed...
512 memset(&hints
, 0, sizeof(hints
));
513 hints
.ai_family
= family
;
514 hints
.ai_flags
= hostname
? 0 : AI_PASSIVE
;
515 hints
.ai_socktype
= SOCK_STREAM
;
517 if (hostname
&& *hostname
== '[')
520 * Remove brackets from numeric IPv6 address...
523 if (!strncmp(hostname
, "[v1.", 4))
526 * Copy the newer address format which supports link-local addresses...
529 strlcpy(ipv6
, hostname
+ 4, sizeof(ipv6
));
530 if ((ipv6len
= (int)strlen(ipv6
) - 1) >= 0 && ipv6
[ipv6len
] == ']')
532 ipv6
[ipv6len
] = '\0';
536 * Convert "+zone" in address to "%zone"...
539 if ((ipv6zone
= strrchr(ipv6
, '+')) != NULL
)
546 * Copy the regular non-link-local IPv6 address...
549 strlcpy(ipv6
, hostname
+ 1, sizeof(ipv6
));
550 if ((ipv6len
= (int)strlen(ipv6
) - 1) >= 0 && ipv6
[ipv6len
] == ']')
552 ipv6
[ipv6len
] = '\0';
558 if ((error
= getaddrinfo(hostname
, service
, &hints
, &results
)) == 0)
561 * Copy the results to our own address list structure...
564 for (current
= results
; current
; current
= current
->ai_next
)
565 if (current
->ai_family
== AF_INET
|| current
->ai_family
== AF_INET6
)
568 * Copy the address over...
571 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
574 httpAddrFreeList(first
);
575 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
579 if (current
->ai_family
== AF_INET6
)
580 memcpy(&(temp
->addr
.ipv6
), current
->ai_addr
,
581 sizeof(temp
->addr
.ipv6
));
583 memcpy(&(temp
->addr
.ipv4
), current
->ai_addr
,
584 sizeof(temp
->addr
.ipv4
));
587 * Append the address to the list...
600 * Free the results from getaddrinfo()...
603 freeaddrinfo(results
);
607 if (error
== EAI_FAIL
)
608 cg
->need_res_init
= 1;
610 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, gai_strerror(error
), 0);
616 int i
; /* Looping vars */
617 unsigned ip
[4]; /* IPv4 address components */
618 const char *ptr
; /* Pointer into hostname */
619 struct hostent
*host
; /* Result of lookup */
620 struct servent
*port
; /* Port number for service */
621 int portnum
; /* Port number */
625 * Lookup the service...
630 else if (isdigit(*service
& 255))
631 portnum
= atoi(service
);
632 else if ((port
= getservbyname(service
, NULL
)) != NULL
)
633 portnum
= ntohs(port
->s_port
);
634 else if (!strcmp(service
, "http"))
636 else if (!strcmp(service
, "https"))
638 else if (!strcmp(service
, "ipp") || !strcmp(service
, "ipps"))
640 else if (!strcmp(service
, "lpd"))
642 else if (!strcmp(service
, "socket"))
648 * This code is needed because some operating systems have a
649 * buggy implementation of gethostbyname() that does not support
650 * IPv4 addresses. If the hostname string is an IPv4 address, then
651 * sscanf() is used to extract the IPv4 components. We then pack
652 * the components into an IPv4 address manually, since the
653 * inet_aton() function is deprecated. We use the htonl() macro
654 * to get the right byte order for the address.
657 for (ptr
= hostname
; isdigit(*ptr
& 255) || *ptr
== '.'; ptr
++);
662 * We have an IPv4 address; break it up and create an IPv4 address...
665 if (sscanf(hostname
, "%u.%u.%u.%u", ip
, ip
+ 1, ip
+ 2, ip
+ 3) == 4 &&
666 ip
[0] <= 255 && ip
[1] <= 255 && ip
[2] <= 255 && ip
[3] <= 255)
668 first
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
672 first
->addr
.ipv4
.sin_family
= AF_INET
;
673 first
->addr
.ipv4
.sin_addr
.s_addr
= htonl((((((((unsigned)ip
[0] << 8) |
674 (unsigned)ip
[1]) << 8) |
675 (unsigned)ip
[2]) << 8) |
677 first
->addr
.ipv4
.sin_port
= htons(portnum
);
680 else if ((host
= gethostbyname(hostname
)) != NULL
&&
682 (host
->h_addrtype
== AF_INET
|| host
->h_addrtype
== AF_INET6
))
684 host
->h_addrtype
== AF_INET
)
685 # endif /* AF_INET6 */
687 for (i
= 0; host
->h_addr_list
[i
]; i
++)
690 * Copy the address over...
693 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
696 httpAddrFreeList(first
);
701 if (host
->h_addrtype
== AF_INET6
)
703 temp
->addr
.ipv6
.sin6_family
= AF_INET6
;
704 memcpy(&(temp
->addr
.ipv6
.sin6_addr
), host
->h_addr_list
[i
],
705 sizeof(temp
->addr
.ipv6
));
706 temp
->addr
.ipv6
.sin6_port
= htons(portnum
);
709 # endif /* AF_INET6 */
711 temp
->addr
.ipv4
.sin_family
= AF_INET
;
712 memcpy(&(temp
->addr
.ipv4
.sin_addr
), host
->h_addr_list
[i
],
713 sizeof(temp
->addr
.ipv4
));
714 temp
->addr
.ipv4
.sin_port
= htons(portnum
);
718 * Append the address to the list...
732 if (h_errno
== NO_RECOVERY
)
733 cg
->need_res_init
= 1;
735 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, hstrerror(h_errno
), 0);
738 #endif /* HAVE_GETADDRINFO */
742 * Detect some common errors and handle them sanely...
745 if (!addr
&& (!hostname
|| !_cups_strcasecmp(hostname
, "localhost")))
747 struct servent
*port
; /* Port number for service */
748 int portnum
; /* Port number */
752 * Lookup the service...
757 else if (isdigit(*service
& 255))
758 portnum
= atoi(service
);
759 else if ((port
= getservbyname(service
, NULL
)) != NULL
)
760 portnum
= ntohs(port
->s_port
);
761 else if (!strcmp(service
, "http"))
763 else if (!strcmp(service
, "https"))
765 else if (!strcmp(service
, "ipp") || !strcmp(service
, "ipps"))
767 else if (!strcmp(service
, "lpd"))
769 else if (!strcmp(service
, "socket"))
773 httpAddrFreeList(first
);
775 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unknown service name."), 1);
779 if (hostname
&& !_cups_strcasecmp(hostname
, "localhost"))
782 * Unfortunately, some users ignore all of the warnings in the
783 * /etc/hosts file and delete "localhost" from it. If we get here
784 * then we were unable to resolve the name, so use the IPv6 and/or
785 * IPv4 loopback interface addresses...
789 if (family
!= AF_INET
)
792 * Add [::1] to the address list...
795 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
798 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
799 httpAddrFreeList(first
);
803 temp
->addr
.ipv6
.sin6_family
= AF_INET6
;
804 temp
->addr
.ipv6
.sin6_port
= htons(portnum
);
806 temp
->addr
.ipv6
.sin6_addr
.u
.Byte
[15] = 1;
808 temp
->addr
.ipv6
.sin6_addr
.s6_addr32
[3] = htonl(1);
817 if (family
!= AF_INET6
)
818 #endif /* AF_INET6 */
821 * Add 127.0.0.1 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
.ipv4
.sin_family
= AF_INET
;
833 temp
->addr
.ipv4
.sin_port
= htons(portnum
);
834 temp
->addr
.ipv4
.sin_addr
.s_addr
= htonl(0x7f000001);
846 * Provide one or more passive listening addresses...
850 if (family
!= AF_INET
)
853 * Add [::] 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
.ipv6
.sin6_family
= AF_INET6
;
865 temp
->addr
.ipv6
.sin6_port
= htons(portnum
);
873 if (family
!= AF_INET6
)
874 #endif /* AF_INET6 */
877 * Add 0.0.0.0 to the address list...
880 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
883 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
884 httpAddrFreeList(first
);
888 temp
->addr
.ipv4
.sin_family
= AF_INET
;
889 temp
->addr
.ipv4
.sin_port
= htons(portnum
);
901 * Return the address list...