2 * HTTP address list routines for CUPS.
4 * Copyright 2007-2017 by Apple Inc.
5 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
7 * Licensed under Apache License v2.0. See the file "LICENSE" for more information.
11 * Include necessary headers...
14 #include "cups-private.h"
17 #endif /* HAVE_RESOLV_H */
20 #endif /* HAVE_POLL */
27 * 'httpAddrConnect()' - Connect to any of the addresses in the list.
29 * @since CUPS 1.2/macOS 10.5@ @exclude all@
32 http_addrlist_t
* /* O - Connected address or NULL on failure */
34 http_addrlist_t
*addrlist
, /* I - List of potential addresses */
35 int *sock
) /* O - Socket */
37 DEBUG_printf(("httpAddrConnect(addrlist=%p, sock=%p)", (void *)addrlist
, (void *)sock
));
39 return (httpAddrConnect2(addrlist
, sock
, 30000, NULL
));
44 * 'httpAddrConnect2()' - Connect to any of the addresses in the list with a
45 * timeout and optional cancel.
47 * @since CUPS 1.7/macOS 10.9@
50 http_addrlist_t
* /* O - Connected address or NULL on failure */
52 http_addrlist_t
*addrlist
, /* I - List of potential addresses */
53 int *sock
, /* O - Socket */
54 int msec
, /* I - Timeout in milliseconds */
55 int *cancel
) /* I - Pointer to "cancel" variable */
57 int val
; /* Socket option value */
59 int flags
; /* Socket flags */
61 int remaining
; /* Remaining timeout */
62 int i
, j
, /* Looping vars */
63 nfds
, /* Number of file descriptors */
64 fds
[100], /* Socket file descriptors */
65 result
; /* Result from select() or poll() */
66 http_addrlist_t
*addrs
[100]; /* Addresses */
68 int max_fd
= -1; /* Highest file descriptor */
69 #endif /* !HAVE_POLL */
72 struct pollfd pfds
[100]; /* Polled file descriptors */
74 fd_set input_set
, /* select() input set */
75 output_set
, /* select() output set */
76 error_set
; /* select() error set */
77 struct timeval timeout
; /* Timeout */
78 # endif /* HAVE_POLL */
79 #endif /* O_NONBLOCK */
81 socklen_t len
; /* Length of value */
82 http_addr_t peer
; /* Peer address */
83 char temp
[256]; /* Temporary address string */
87 DEBUG_printf(("httpAddrConnect2(addrlist=%p, sock=%p, msec=%d, cancel=%p)", (void *)addrlist
, (void *)sock
, msec
, (void *)cancel
));
92 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
96 if (cancel
&& *cancel
)
103 * Loop through each address until we connect or run out of addresses...
109 while (remaining
> 0)
111 if (cancel
&& *cancel
)
116 httpAddrClose(NULL
, fds
[nfds
]);
122 if (addrlist
&& nfds
< (int)(sizeof(fds
) / sizeof(fds
[0])))
125 * Create the socket...
128 DEBUG_printf(("2httpAddrConnect2: Trying %s:%d...", httpAddrString(&(addrlist
->addr
), temp
, sizeof(temp
)), httpAddrPort(&(addrlist
->addr
))));
130 if ((fds
[nfds
] = (int)socket(httpAddrFamily(&(addrlist
->addr
)), SOCK_STREAM
, 0)) < 0)
133 * Don't abort yet, as this could just be an issue with the local
134 * system not being configured with IPv4/IPv6/domain socket enabled.
136 * Just skip this address...
139 addrlist
= addrlist
->next
;
148 setsockopt(fds
[nfds
], SOL_SOCKET
, SO_REUSEADDR
, CUPS_SOCAST
&val
, sizeof(val
));
152 setsockopt(fds
[nfds
], SOL_SOCKET
, SO_REUSEPORT
, CUPS_SOCAST
&val
, sizeof(val
));
153 #endif /* SO_REUSEPORT */
157 setsockopt(fds
[nfds
], SOL_SOCKET
, SO_NOSIGPIPE
, CUPS_SOCAST
&val
, sizeof(val
));
158 #endif /* SO_NOSIGPIPE */
161 * Using TCP_NODELAY improves responsiveness, especially on systems
162 * with a slow loopback interface...
166 setsockopt(fds
[nfds
], IPPROTO_TCP
, TCP_NODELAY
, CUPS_SOCAST
&val
, sizeof(val
));
170 * Close this socket when starting another process...
173 fcntl(fds
[nfds
], F_SETFD
, FD_CLOEXEC
);
174 #endif /* FD_CLOEXEC */
178 * Do an asynchronous connect by setting the socket non-blocking...
181 DEBUG_printf(("httpAddrConnect2: Setting non-blocking connect()"));
183 flags
= fcntl(fds
[nfds
], F_GETFL
, 0);
184 fcntl(fds
[nfds
], F_SETFL
, flags
| O_NONBLOCK
);
185 #endif /* O_NONBLOCK */
191 if (!connect(fds
[nfds
], &(addrlist
->addr
.addr
), (socklen_t
)httpAddrLength(&(addrlist
->addr
))))
193 DEBUG_printf(("1httpAddrConnect2: Connected to %s:%d...", httpAddrString(&(addrlist
->addr
), temp
, sizeof(temp
)), httpAddrPort(&(addrlist
->addr
))));
196 fcntl(fds
[nfds
], F_SETFL
, flags
);
197 #endif /* O_NONBLOCK */
204 httpAddrClose(NULL
, fds
[nfds
]);
211 if (WSAGetLastError() != WSAEINPROGRESS
&& WSAGetLastError() != WSAEWOULDBLOCK
)
213 if (errno
!= EINPROGRESS
&& errno
!= EWOULDBLOCK
)
216 DEBUG_printf(("1httpAddrConnect2: Unable to connect to %s:%d: %s", httpAddrString(&(addrlist
->addr
), temp
, sizeof(temp
)), httpAddrPort(&(addrlist
->addr
)), strerror(errno
)));
217 httpAddrClose(NULL
, fds
[nfds
]);
218 addrlist
= addrlist
->next
;
223 fcntl(fds
[nfds
], F_SETFL
, flags
);
227 if (fds
[nfds
] > max_fd
)
229 #endif /* !HAVE_POLL */
231 addrs
[nfds
] = addrlist
;
233 addrlist
= addrlist
->next
;
236 if (!addrlist
&& nfds
== 0)
240 * See if we can connect to any of the addresses so far...
244 DEBUG_puts("1httpAddrConnect2: Finishing async connect()");
248 if (cancel
&& *cancel
)
251 * Close this socket and return...
254 DEBUG_puts("1httpAddrConnect2: Canceled connect()");
259 httpAddrClose(NULL
, fds
[nfds
]);
268 for (i
= 0; i
< nfds
; i
++)
271 pfds
[i
].events
= POLLIN
| POLLOUT
;
274 result
= poll(pfds
, (nfds_t
)nfds
, addrlist
? 100 : remaining
> 250 ? 250 : remaining
);
276 DEBUG_printf(("1httpAddrConnect2: poll() returned %d (%d)", result
, errno
));
280 for (i
= 0; i
< nfds
; i
++)
281 FD_SET(fds
[i
], &input_set
);
282 output_set
= input_set
;
283 error_set
= input_set
;
286 timeout
.tv_usec
= (addrlist
? 100 : remaining
> 250 ? 250 : remaining
) * 1000;
288 result
= select(max_fd
+ 1, &input_set
, &output_set
, &error_set
, &timeout
);
290 DEBUG_printf(("1httpAddrConnect2: select() returned %d (%d)", result
, errno
));
291 # endif /* HAVE_POLL */
294 while (result
< 0 && (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
));
296 while (result
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
301 http_addrlist_t
*connaddr
= NULL
; /* Connected address, if any */
303 for (i
= 0; i
< nfds
; i
++)
306 DEBUG_printf(("pfds[%d].revents=%x\n", i
, pfds
[i
].revents
));
307 if (pfds
[i
].revents
&& !(pfds
[i
].revents
& (POLLERR
| POLLHUP
)))
309 if (FD_ISSET(fds
[i
], &input_set
) && !FD_ISSET(fds
[i
], &error_set
))
310 # endif /* HAVE_POLL */
317 if (!getpeername(fds
[i
], (struct sockaddr
*)&peer
, &len
))
318 DEBUG_printf(("1httpAddrConnect2: Connected to %s:%d...", httpAddrString(&peer
, temp
, sizeof(temp
)), httpAddrPort(&peer
)));
324 else if (pfds
[i
].revents
& (POLLERR
| POLLHUP
))
326 else if (FD_ISSET(fds
[i
], &error_set
))
327 # endif /* HAVE_POLL */
330 * Error on socket, remove from the "pool"...
333 httpAddrClose(NULL
, fds
[i
]);
337 memmove(fds
+ i
, fds
+ i
+ 1, (size_t)(nfds
- i
) * (sizeof(fds
[0])));
338 memmove(addrs
+ i
, addrs
+ i
+ 1, (size_t)(nfds
- i
) * (sizeof(addrs
[0])));
347 * Connected on one address, close all of the other sockets we have so
351 for (j
= 0; j
< i
; j
++)
352 httpAddrClose(NULL
, fds
[j
]);
354 for (j
++; j
< nfds
; j
++)
355 httpAddrClose(NULL
, fds
[j
]);
360 #endif /* O_NONBLOCK */
371 httpAddrClose(NULL
, fds
[nfds
]);
375 _cupsSetError(IPP_STATUS_ERROR_SERVICE_UNAVAILABLE
, "Connection failed", 0);
377 _cupsSetError(IPP_STATUS_ERROR_SERVICE_UNAVAILABLE
, strerror(errno
), 0);
385 * 'httpAddrCopyList()' - Copy an address list.
387 * @since CUPS 1.7/macOS 10.9@
390 http_addrlist_t
* /* O - New address list or @code NULL@ on error */
392 http_addrlist_t
*src
) /* I - Source address list */
394 http_addrlist_t
*dst
= NULL
, /* First list entry */
395 *prev
= NULL
, /* Previous list entry */
396 *current
= NULL
;/* Current list entry */
401 if ((current
= malloc(sizeof(http_addrlist_t
))) == NULL
)
408 current
= current
->next
;
416 memcpy(current
, src
, sizeof(http_addrlist_t
));
418 current
->next
= NULL
;
421 prev
->next
= current
;
434 * 'httpAddrFreeList()' - Free an address list.
436 * @since CUPS 1.2/macOS 10.5@
441 http_addrlist_t
*addrlist
) /* I - Address list to free */
443 http_addrlist_t
*next
; /* Next address in list */
447 * Free each address in the list...
452 next
= addrlist
->next
;
462 * 'httpAddrGetList()' - Get a list of addresses for a hostname.
464 * @since CUPS 1.2/macOS 10.5@
467 http_addrlist_t
* /* O - List of addresses or NULL */
468 httpAddrGetList(const char *hostname
, /* I - Hostname, IP address, or NULL for passive listen address */
469 int family
, /* I - Address family or AF_UNSPEC */
470 const char *service
) /* I - Service name or port number */
472 http_addrlist_t
*first
, /* First address in list */
473 *addr
, /* Current address in list */
474 *temp
; /* New address */
475 _cups_globals_t
*cg
= _cupsGlobals();
480 _cups_debug_printf("httpAddrGetList(hostname=\"%s\", family=AF_%s, "
482 hostname
? hostname
: "(nil)",
483 family
== AF_UNSPEC
? "UNSPEC" :
485 family
== AF_LOCAL
? "LOCAL" :
486 # endif /* AF_LOCAL */
488 family
== AF_INET6
? "INET6" :
489 # endif /* AF_INET6 */
490 family
== AF_INET
? "INET" : "???", service
);
495 * STR #2920: Initialize resolver after failure in cups-polld
497 * If the previous lookup failed, re-initialize the resolver to prevent
498 * temporary network errors from persisting. This *should* be handled by
499 * the resolver libraries, but apparently the glibc folks do not agree.
501 * We set a flag at the end of this function if we encounter an error that
502 * requires reinitialization of the resolver functions. We then call
503 * res_init() if the flag is set on the next call here or in httpAddrLookup().
506 if (cg
->need_res_init
)
510 cg
->need_res_init
= 0;
512 #endif /* HAVE_RES_INIT */
515 * Lookup the address the best way we can...
521 if (hostname
&& hostname
[0] == '/')
524 * Domain socket address...
527 if ((first
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
))) != NULL
)
530 first
->addr
.un
.sun_family
= AF_LOCAL
;
531 strlcpy(first
->addr
.un
.sun_path
, hostname
, sizeof(first
->addr
.un
.sun_path
));
535 #endif /* AF_LOCAL */
536 if (!hostname
|| _cups_strcasecmp(hostname
, "localhost"))
538 #ifdef HAVE_GETADDRINFO
539 struct addrinfo hints
, /* Address lookup hints */
540 *results
, /* Address lookup results */
541 *current
; /* Current result */
542 char ipv6
[64], /* IPv6 address */
543 *ipv6zone
; /* Pointer to zone separator */
544 int ipv6len
; /* Length of IPv6 address */
545 int error
; /* getaddrinfo() error */
549 * Lookup the address as needed...
552 memset(&hints
, 0, sizeof(hints
));
553 hints
.ai_family
= family
;
554 hints
.ai_flags
= hostname
? 0 : AI_PASSIVE
;
555 hints
.ai_socktype
= SOCK_STREAM
;
557 if (hostname
&& *hostname
== '[')
560 * Remove brackets from numeric IPv6 address...
563 if (!strncmp(hostname
, "[v1.", 4))
566 * Copy the newer address format which supports link-local addresses...
569 strlcpy(ipv6
, hostname
+ 4, sizeof(ipv6
));
570 if ((ipv6len
= (int)strlen(ipv6
) - 1) >= 0 && ipv6
[ipv6len
] == ']')
572 ipv6
[ipv6len
] = '\0';
576 * Convert "+zone" in address to "%zone"...
579 if ((ipv6zone
= strrchr(ipv6
, '+')) != NULL
)
586 * Copy the regular non-link-local IPv6 address...
589 strlcpy(ipv6
, hostname
+ 1, sizeof(ipv6
));
590 if ((ipv6len
= (int)strlen(ipv6
) - 1) >= 0 && ipv6
[ipv6len
] == ']')
592 ipv6
[ipv6len
] = '\0';
598 if ((error
= getaddrinfo(hostname
, service
, &hints
, &results
)) == 0)
601 * Copy the results to our own address list structure...
604 for (current
= results
; current
; current
= current
->ai_next
)
605 if (current
->ai_family
== AF_INET
|| current
->ai_family
== AF_INET6
)
608 * Copy the address over...
611 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
614 httpAddrFreeList(first
);
615 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
619 if (current
->ai_family
== AF_INET6
)
620 memcpy(&(temp
->addr
.ipv6
), current
->ai_addr
,
621 sizeof(temp
->addr
.ipv6
));
623 memcpy(&(temp
->addr
.ipv4
), current
->ai_addr
,
624 sizeof(temp
->addr
.ipv4
));
627 * Append the address to the list...
640 * Free the results from getaddrinfo()...
643 freeaddrinfo(results
);
647 if (error
== EAI_FAIL
)
648 cg
->need_res_init
= 1;
650 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, gai_strerror(error
), 0);
656 int i
; /* Looping vars */
657 unsigned ip
[4]; /* IPv4 address components */
658 const char *ptr
; /* Pointer into hostname */
659 struct hostent
*host
; /* Result of lookup */
660 struct servent
*port
; /* Port number for service */
661 int portnum
; /* Port number */
665 * Lookup the service...
670 else if (isdigit(*service
& 255))
671 portnum
= atoi(service
);
672 else if ((port
= getservbyname(service
, NULL
)) != NULL
)
673 portnum
= ntohs(port
->s_port
);
674 else if (!strcmp(service
, "http"))
676 else if (!strcmp(service
, "https"))
678 else if (!strcmp(service
, "ipp") || !strcmp(service
, "ipps"))
680 else if (!strcmp(service
, "lpd"))
682 else if (!strcmp(service
, "socket"))
688 * This code is needed because some operating systems have a
689 * buggy implementation of gethostbyname() that does not support
690 * IPv4 addresses. If the hostname string is an IPv4 address, then
691 * sscanf() is used to extract the IPv4 components. We then pack
692 * the components into an IPv4 address manually, since the
693 * inet_aton() function is deprecated. We use the htonl() macro
694 * to get the right byte order for the address.
697 for (ptr
= hostname
; isdigit(*ptr
& 255) || *ptr
== '.'; ptr
++);
702 * We have an IPv4 address; break it up and create an IPv4 address...
705 if (sscanf(hostname
, "%u.%u.%u.%u", ip
, ip
+ 1, ip
+ 2, ip
+ 3) == 4 &&
706 ip
[0] <= 255 && ip
[1] <= 255 && ip
[2] <= 255 && ip
[3] <= 255)
708 first
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
712 first
->addr
.ipv4
.sin_family
= AF_INET
;
713 first
->addr
.ipv4
.sin_addr
.s_addr
= htonl((((((((unsigned)ip
[0] << 8) |
714 (unsigned)ip
[1]) << 8) |
715 (unsigned)ip
[2]) << 8) |
717 first
->addr
.ipv4
.sin_port
= htons(portnum
);
720 else if ((host
= gethostbyname(hostname
)) != NULL
&&
722 (host
->h_addrtype
== AF_INET
|| host
->h_addrtype
== AF_INET6
))
724 host
->h_addrtype
== AF_INET
)
725 # endif /* AF_INET6 */
727 for (i
= 0; host
->h_addr_list
[i
]; i
++)
730 * Copy the address over...
733 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
736 httpAddrFreeList(first
);
741 if (host
->h_addrtype
== AF_INET6
)
743 temp
->addr
.ipv6
.sin6_family
= AF_INET6
;
744 memcpy(&(temp
->addr
.ipv6
.sin6_addr
), host
->h_addr_list
[i
],
745 sizeof(temp
->addr
.ipv6
));
746 temp
->addr
.ipv6
.sin6_port
= htons(portnum
);
749 # endif /* AF_INET6 */
751 temp
->addr
.ipv4
.sin_family
= AF_INET
;
752 memcpy(&(temp
->addr
.ipv4
.sin_addr
), host
->h_addr_list
[i
],
753 sizeof(temp
->addr
.ipv4
));
754 temp
->addr
.ipv4
.sin_port
= htons(portnum
);
758 * Append the address to the list...
772 if (h_errno
== NO_RECOVERY
)
773 cg
->need_res_init
= 1;
775 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, hstrerror(h_errno
), 0);
778 #endif /* HAVE_GETADDRINFO */
782 * Detect some common errors and handle them sanely...
785 if (!addr
&& (!hostname
|| !_cups_strcasecmp(hostname
, "localhost")))
787 struct servent
*port
; /* Port number for service */
788 int portnum
; /* Port number */
792 * Lookup the service...
797 else if (isdigit(*service
& 255))
798 portnum
= atoi(service
);
799 else if ((port
= getservbyname(service
, NULL
)) != NULL
)
800 portnum
= ntohs(port
->s_port
);
801 else if (!strcmp(service
, "http"))
803 else if (!strcmp(service
, "https"))
805 else if (!strcmp(service
, "ipp") || !strcmp(service
, "ipps"))
807 else if (!strcmp(service
, "lpd"))
809 else if (!strcmp(service
, "socket"))
813 httpAddrFreeList(first
);
815 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unknown service name."), 1);
819 if (hostname
&& !_cups_strcasecmp(hostname
, "localhost"))
822 * Unfortunately, some users ignore all of the warnings in the
823 * /etc/hosts file and delete "localhost" from it. If we get here
824 * then we were unable to resolve the name, so use the IPv6 and/or
825 * IPv4 loopback interface addresses...
829 if (family
!= AF_INET
)
832 * Add [::1] to the address list...
835 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
838 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
839 httpAddrFreeList(first
);
843 temp
->addr
.ipv6
.sin6_family
= AF_INET6
;
844 temp
->addr
.ipv6
.sin6_port
= htons(portnum
);
846 temp
->addr
.ipv6
.sin6_addr
.u
.Byte
[15] = 1;
848 temp
->addr
.ipv6
.sin6_addr
.s6_addr32
[3] = htonl(1);
857 if (family
!= AF_INET6
)
858 #endif /* AF_INET6 */
861 * Add 127.0.0.1 to the address list...
864 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
867 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
868 httpAddrFreeList(first
);
872 temp
->addr
.ipv4
.sin_family
= AF_INET
;
873 temp
->addr
.ipv4
.sin_port
= htons(portnum
);
874 temp
->addr
.ipv4
.sin_addr
.s_addr
= htonl(0x7f000001);
886 * Provide one or more passive listening addresses...
890 if (family
!= AF_INET
)
893 * Add [::] to the address list...
896 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
899 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
900 httpAddrFreeList(first
);
904 temp
->addr
.ipv6
.sin6_family
= AF_INET6
;
905 temp
->addr
.ipv6
.sin6_port
= htons(portnum
);
913 if (family
!= AF_INET6
)
914 #endif /* AF_INET6 */
917 * Add 0.0.0.0 to the address list...
920 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
923 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
924 httpAddrFreeList(first
);
928 temp
->addr
.ipv4
.sin_family
= AF_INET
;
929 temp
->addr
.ipv4
.sin_port
= htons(portnum
);
941 * Return the address list...