2 * HTTP address list routines for CUPS.
4 * Copyright 2007-2018 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
12 * Include necessary headers...
15 #include "cups-private.h"
18 #endif /* HAVE_RESOLV_H */
21 #endif /* HAVE_POLL */
28 * 'httpAddrConnect()' - Connect to any of the addresses in the list.
30 * @since CUPS 1.2/macOS 10.5@ @exclude all@
33 http_addrlist_t
* /* O - Connected address or NULL on failure */
35 http_addrlist_t
*addrlist
, /* I - List of potential addresses */
36 int *sock
) /* O - Socket */
38 DEBUG_printf(("httpAddrConnect(addrlist=%p, sock=%p)", (void *)addrlist
, (void *)sock
));
40 return (httpAddrConnect2(addrlist
, sock
, 30000, NULL
));
45 * 'httpAddrConnect2()' - Connect to any of the addresses in the list with a
46 * timeout and optional cancel.
48 * @since CUPS 1.7/macOS 10.9@
51 http_addrlist_t
* /* O - Connected address or NULL on failure */
53 http_addrlist_t
*addrlist
, /* I - List of potential addresses */
54 int *sock
, /* O - Socket */
55 int msec
, /* I - Timeout in milliseconds */
56 int *cancel
) /* I - Pointer to "cancel" variable */
58 int val
; /* Socket option value */
60 int i
, j
, /* Looping vars */
61 flags
, /* Socket flags */
62 result
; /* Result from select() or poll() */
64 int remaining
; /* Remaining timeout */
65 int nfds
, /* Number of file descriptors */
66 fds
[100]; /* Socket file descriptors */
67 http_addrlist_t
*addrs
[100]; /* Addresses */
69 int max_fd
= -1; /* Highest file descriptor */
70 #endif /* !HAVE_POLL */
73 struct pollfd pfds
[100]; /* Polled file descriptors */
75 fd_set input_set
, /* select() input set */
76 output_set
, /* select() output set */
77 error_set
; /* select() error set */
78 struct timeval timeout
; /* Timeout */
79 # endif /* HAVE_POLL */
80 #endif /* O_NONBLOCK */
83 socklen_t len
; /* Length of value */
84 http_addr_t peer
; /* Peer address */
86 char temp
[256]; /* Temporary address string */
90 DEBUG_printf(("httpAddrConnect2(addrlist=%p, sock=%p, msec=%d, cancel=%p)", (void *)addrlist
, (void *)sock
, msec
, (void *)cancel
));
95 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
99 if (cancel
&& *cancel
)
106 * Loop through each address until we connect or run out of addresses...
112 while (remaining
> 0)
114 if (cancel
&& *cancel
)
119 httpAddrClose(NULL
, fds
[nfds
]);
125 if (addrlist
&& nfds
< (int)(sizeof(fds
) / sizeof(fds
[0])))
128 * Create the socket...
131 DEBUG_printf(("2httpAddrConnect2: Trying %s:%d...", httpAddrString(&(addrlist
->addr
), temp
, sizeof(temp
)), httpAddrPort(&(addrlist
->addr
))));
133 if ((fds
[nfds
] = (int)socket(httpAddrFamily(&(addrlist
->addr
)), SOCK_STREAM
, 0)) < 0)
136 * Don't abort yet, as this could just be an issue with the local
137 * system not being configured with IPv4/IPv6/domain socket enabled.
139 * Just skip this address...
142 addrlist
= addrlist
->next
;
151 setsockopt(fds
[nfds
], SOL_SOCKET
, SO_REUSEADDR
, CUPS_SOCAST
&val
, sizeof(val
));
155 setsockopt(fds
[nfds
], SOL_SOCKET
, SO_REUSEPORT
, CUPS_SOCAST
&val
, sizeof(val
));
156 #endif /* SO_REUSEPORT */
160 setsockopt(fds
[nfds
], SOL_SOCKET
, SO_NOSIGPIPE
, CUPS_SOCAST
&val
, sizeof(val
));
161 #endif /* SO_NOSIGPIPE */
164 * Using TCP_NODELAY improves responsiveness, especially on systems
165 * with a slow loopback interface...
169 setsockopt(fds
[nfds
], IPPROTO_TCP
, TCP_NODELAY
, CUPS_SOCAST
&val
, sizeof(val
));
173 * Close this socket when starting another process...
176 fcntl(fds
[nfds
], F_SETFD
, FD_CLOEXEC
);
177 #endif /* FD_CLOEXEC */
181 * Do an asynchronous connect by setting the socket non-blocking...
184 DEBUG_printf(("httpAddrConnect2: Setting non-blocking connect()"));
186 flags
= fcntl(fds
[nfds
], F_GETFL
, 0);
187 fcntl(fds
[nfds
], F_SETFL
, flags
| O_NONBLOCK
);
188 #endif /* O_NONBLOCK */
194 if (!connect(fds
[nfds
], &(addrlist
->addr
.addr
), (socklen_t
)httpAddrLength(&(addrlist
->addr
))))
196 DEBUG_printf(("1httpAddrConnect2: Connected to %s:%d...", httpAddrString(&(addrlist
->addr
), temp
, sizeof(temp
)), httpAddrPort(&(addrlist
->addr
))));
199 fcntl(fds
[nfds
], F_SETFL
, flags
);
200 #endif /* O_NONBLOCK */
207 httpAddrClose(NULL
, fds
[nfds
]);
214 if (WSAGetLastError() != WSAEINPROGRESS
&& WSAGetLastError() != WSAEWOULDBLOCK
)
216 if (errno
!= EINPROGRESS
&& errno
!= EWOULDBLOCK
)
219 DEBUG_printf(("1httpAddrConnect2: Unable to connect to %s:%d: %s", httpAddrString(&(addrlist
->addr
), temp
, sizeof(temp
)), httpAddrPort(&(addrlist
->addr
)), strerror(errno
)));
220 httpAddrClose(NULL
, fds
[nfds
]);
221 addrlist
= addrlist
->next
;
226 fcntl(fds
[nfds
], F_SETFL
, flags
);
230 if (fds
[nfds
] > max_fd
)
232 #endif /* !HAVE_POLL */
234 addrs
[nfds
] = addrlist
;
236 addrlist
= addrlist
->next
;
239 if (!addrlist
&& nfds
== 0)
243 * See if we can connect to any of the addresses so far...
247 DEBUG_puts("1httpAddrConnect2: Finishing async connect()");
251 if (cancel
&& *cancel
)
254 * Close this socket and return...
257 DEBUG_puts("1httpAddrConnect2: Canceled connect()");
262 httpAddrClose(NULL
, fds
[nfds
]);
271 for (i
= 0; i
< nfds
; i
++)
274 pfds
[i
].events
= POLLIN
| POLLOUT
;
277 result
= poll(pfds
, (nfds_t
)nfds
, addrlist
? 100 : remaining
> 250 ? 250 : remaining
);
279 DEBUG_printf(("1httpAddrConnect2: poll() returned %d (%d)", result
, errno
));
283 for (i
= 0; i
< nfds
; i
++)
284 FD_SET(fds
[i
], &input_set
);
285 output_set
= input_set
;
286 error_set
= input_set
;
289 timeout
.tv_usec
= (addrlist
? 100 : remaining
> 250 ? 250 : remaining
) * 1000;
291 result
= select(max_fd
+ 1, &input_set
, &output_set
, &error_set
, &timeout
);
293 DEBUG_printf(("1httpAddrConnect2: select() returned %d (%d)", result
, errno
));
294 # endif /* HAVE_POLL */
297 while (result
< 0 && (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
));
299 while (result
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
304 http_addrlist_t
*connaddr
= NULL
; /* Connected address, if any */
306 for (i
= 0; i
< nfds
; i
++)
309 DEBUG_printf(("pfds[%d].revents=%x\n", i
, pfds
[i
].revents
));
310 if (pfds
[i
].revents
&& !(pfds
[i
].revents
& (POLLERR
| POLLHUP
)))
312 if (FD_ISSET(fds
[i
], &input_set
) && !FD_ISSET(fds
[i
], &error_set
))
313 # endif /* HAVE_POLL */
320 if (!getpeername(fds
[i
], (struct sockaddr
*)&peer
, &len
))
321 DEBUG_printf(("1httpAddrConnect2: Connected to %s:%d...", httpAddrString(&peer
, temp
, sizeof(temp
)), httpAddrPort(&peer
)));
327 else if (pfds
[i
].revents
& (POLLERR
| POLLHUP
))
329 else if (FD_ISSET(fds
[i
], &error_set
))
330 # endif /* HAVE_POLL */
333 * Error on socket, remove from the "pool"...
336 httpAddrClose(NULL
, fds
[i
]);
340 memmove(fds
+ i
, fds
+ i
+ 1, (size_t)(nfds
- i
) * (sizeof(fds
[0])));
341 memmove(addrs
+ i
, addrs
+ i
+ 1, (size_t)(nfds
- i
) * (sizeof(addrs
[0])));
350 * Connected on one address, close all of the other sockets we have so
354 for (j
= 0; j
< i
; j
++)
355 httpAddrClose(NULL
, fds
[j
]);
357 for (j
++; j
< nfds
; j
++)
358 httpAddrClose(NULL
, fds
[j
]);
363 #endif /* O_NONBLOCK */
374 httpAddrClose(NULL
, fds
[nfds
]);
378 _cupsSetError(IPP_STATUS_ERROR_SERVICE_UNAVAILABLE
, "Connection failed", 0);
380 _cupsSetError(IPP_STATUS_ERROR_SERVICE_UNAVAILABLE
, strerror(errno
), 0);
388 * 'httpAddrCopyList()' - Copy an address list.
390 * @since CUPS 1.7/macOS 10.9@
393 http_addrlist_t
* /* O - New address list or @code NULL@ on error */
395 http_addrlist_t
*src
) /* I - Source address list */
397 http_addrlist_t
*dst
= NULL
, /* First list entry */
398 *prev
= NULL
, /* Previous list entry */
399 *current
= NULL
;/* Current list entry */
404 if ((current
= malloc(sizeof(http_addrlist_t
))) == NULL
)
411 current
= current
->next
;
419 memcpy(current
, src
, sizeof(http_addrlist_t
));
421 current
->next
= NULL
;
424 prev
->next
= current
;
437 * 'httpAddrFreeList()' - Free an address list.
439 * @since CUPS 1.2/macOS 10.5@
444 http_addrlist_t
*addrlist
) /* I - Address list to free */
446 http_addrlist_t
*next
; /* Next address in list */
450 * Free each address in the list...
455 next
= addrlist
->next
;
465 * 'httpAddrGetList()' - Get a list of addresses for a hostname.
467 * @since CUPS 1.2/macOS 10.5@
470 http_addrlist_t
* /* O - List of addresses or NULL */
471 httpAddrGetList(const char *hostname
, /* I - Hostname, IP address, or NULL for passive listen address */
472 int family
, /* I - Address family or AF_UNSPEC */
473 const char *service
) /* I - Service name or port number */
475 http_addrlist_t
*first
, /* First address in list */
476 *addr
, /* Current address in list */
477 *temp
; /* New address */
478 _cups_globals_t
*cg
= _cupsGlobals();
483 _cups_debug_printf("httpAddrGetList(hostname=\"%s\", family=AF_%s, "
485 hostname
? hostname
: "(nil)",
486 family
== AF_UNSPEC
? "UNSPEC" :
488 family
== AF_LOCAL
? "LOCAL" :
489 # endif /* AF_LOCAL */
491 family
== AF_INET6
? "INET6" :
492 # endif /* AF_INET6 */
493 family
== AF_INET
? "INET" : "???", service
);
498 * STR #2920: Initialize resolver after failure in cups-polld
500 * If the previous lookup failed, re-initialize the resolver to prevent
501 * temporary network errors from persisting. This *should* be handled by
502 * the resolver libraries, but apparently the glibc folks do not agree.
504 * We set a flag at the end of this function if we encounter an error that
505 * requires reinitialization of the resolver functions. We then call
506 * res_init() if the flag is set on the next call here or in httpAddrLookup().
509 if (cg
->need_res_init
)
513 cg
->need_res_init
= 0;
515 #endif /* HAVE_RES_INIT */
518 * Lookup the address the best way we can...
524 if (hostname
&& hostname
[0] == '/')
527 * Domain socket address...
530 if ((first
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
))) != NULL
)
533 first
->addr
.un
.sun_family
= AF_LOCAL
;
534 strlcpy(first
->addr
.un
.sun_path
, hostname
, sizeof(first
->addr
.un
.sun_path
));
538 #endif /* AF_LOCAL */
539 if (!hostname
|| _cups_strcasecmp(hostname
, "localhost"))
541 #ifdef HAVE_GETADDRINFO
542 struct addrinfo hints
, /* Address lookup hints */
543 *results
, /* Address lookup results */
544 *current
; /* Current result */
545 char ipv6
[64], /* IPv6 address */
546 *ipv6zone
; /* Pointer to zone separator */
547 int ipv6len
; /* Length of IPv6 address */
548 int error
; /* getaddrinfo() error */
552 * Lookup the address as needed...
555 memset(&hints
, 0, sizeof(hints
));
556 hints
.ai_family
= family
;
557 hints
.ai_flags
= hostname
? 0 : AI_PASSIVE
;
558 hints
.ai_socktype
= SOCK_STREAM
;
560 if (hostname
&& *hostname
== '[')
563 * Remove brackets from numeric IPv6 address...
566 if (!strncmp(hostname
, "[v1.", 4))
569 * Copy the newer address format which supports link-local addresses...
572 strlcpy(ipv6
, hostname
+ 4, sizeof(ipv6
));
573 if ((ipv6len
= (int)strlen(ipv6
) - 1) >= 0 && ipv6
[ipv6len
] == ']')
575 ipv6
[ipv6len
] = '\0';
579 * Convert "+zone" in address to "%zone"...
582 if ((ipv6zone
= strrchr(ipv6
, '+')) != NULL
)
589 * Copy the regular non-link-local IPv6 address...
592 strlcpy(ipv6
, hostname
+ 1, sizeof(ipv6
));
593 if ((ipv6len
= (int)strlen(ipv6
) - 1) >= 0 && ipv6
[ipv6len
] == ']')
595 ipv6
[ipv6len
] = '\0';
601 if ((error
= getaddrinfo(hostname
, service
, &hints
, &results
)) == 0)
604 * Copy the results to our own address list structure...
607 for (current
= results
; current
; current
= current
->ai_next
)
608 if (current
->ai_family
== AF_INET
|| current
->ai_family
== AF_INET6
)
611 * Copy the address over...
614 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
617 httpAddrFreeList(first
);
618 freeaddrinfo(results
);
619 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
623 if (current
->ai_family
== AF_INET6
)
624 memcpy(&(temp
->addr
.ipv6
), current
->ai_addr
,
625 sizeof(temp
->addr
.ipv6
));
627 memcpy(&(temp
->addr
.ipv4
), current
->ai_addr
,
628 sizeof(temp
->addr
.ipv4
));
631 * Append the address to the list...
644 * Free the results from getaddrinfo()...
647 freeaddrinfo(results
);
651 if (error
== EAI_FAIL
)
652 cg
->need_res_init
= 1;
654 # ifdef _WIN32 /* Really, Microsoft?!? */
655 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, gai_strerrorA(error
), 0);
657 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, gai_strerror(error
), 0);
664 int i
; /* Looping vars */
665 unsigned ip
[4]; /* IPv4 address components */
666 const char *ptr
; /* Pointer into hostname */
667 struct hostent
*host
; /* Result of lookup */
668 struct servent
*port
; /* Port number for service */
669 int portnum
; /* Port number */
673 * Lookup the service...
678 else if (isdigit(*service
& 255))
679 portnum
= atoi(service
);
680 else if ((port
= getservbyname(service
, NULL
)) != NULL
)
681 portnum
= ntohs(port
->s_port
);
682 else if (!strcmp(service
, "http"))
684 else if (!strcmp(service
, "https"))
686 else if (!strcmp(service
, "ipp") || !strcmp(service
, "ipps"))
688 else if (!strcmp(service
, "lpd"))
690 else if (!strcmp(service
, "socket"))
696 * This code is needed because some operating systems have a
697 * buggy implementation of gethostbyname() that does not support
698 * IPv4 addresses. If the hostname string is an IPv4 address, then
699 * sscanf() is used to extract the IPv4 components. We then pack
700 * the components into an IPv4 address manually, since the
701 * inet_aton() function is deprecated. We use the htonl() macro
702 * to get the right byte order for the address.
705 for (ptr
= hostname
; isdigit(*ptr
& 255) || *ptr
== '.'; ptr
++);
710 * We have an IPv4 address; break it up and create an IPv4 address...
713 if (sscanf(hostname
, "%u.%u.%u.%u", ip
, ip
+ 1, ip
+ 2, ip
+ 3) == 4 &&
714 ip
[0] <= 255 && ip
[1] <= 255 && ip
[2] <= 255 && ip
[3] <= 255)
716 first
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
720 first
->addr
.ipv4
.sin_family
= AF_INET
;
721 first
->addr
.ipv4
.sin_addr
.s_addr
= htonl((((((((unsigned)ip
[0] << 8) |
722 (unsigned)ip
[1]) << 8) |
723 (unsigned)ip
[2]) << 8) |
725 first
->addr
.ipv4
.sin_port
= htons(portnum
);
728 else if ((host
= gethostbyname(hostname
)) != NULL
&&
730 (host
->h_addrtype
== AF_INET
|| host
->h_addrtype
== AF_INET6
))
732 host
->h_addrtype
== AF_INET
)
733 # endif /* AF_INET6 */
735 for (i
= 0; host
->h_addr_list
[i
]; i
++)
738 * Copy the address over...
741 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
744 httpAddrFreeList(first
);
749 if (host
->h_addrtype
== AF_INET6
)
751 temp
->addr
.ipv6
.sin6_family
= AF_INET6
;
752 memcpy(&(temp
->addr
.ipv6
.sin6_addr
), host
->h_addr_list
[i
],
753 sizeof(temp
->addr
.ipv6
));
754 temp
->addr
.ipv6
.sin6_port
= htons(portnum
);
757 # endif /* AF_INET6 */
759 temp
->addr
.ipv4
.sin_family
= AF_INET
;
760 memcpy(&(temp
->addr
.ipv4
.sin_addr
), host
->h_addr_list
[i
],
761 sizeof(temp
->addr
.ipv4
));
762 temp
->addr
.ipv4
.sin_port
= htons(portnum
);
766 * Append the address to the list...
780 if (h_errno
== NO_RECOVERY
)
781 cg
->need_res_init
= 1;
783 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, hstrerror(h_errno
), 0);
786 #endif /* HAVE_GETADDRINFO */
790 * Detect some common errors and handle them sanely...
793 if (!addr
&& (!hostname
|| !_cups_strcasecmp(hostname
, "localhost")))
795 struct servent
*port
; /* Port number for service */
796 int portnum
; /* Port number */
800 * Lookup the service...
805 else if (isdigit(*service
& 255))
806 portnum
= atoi(service
);
807 else if ((port
= getservbyname(service
, NULL
)) != NULL
)
808 portnum
= ntohs(port
->s_port
);
809 else if (!strcmp(service
, "http"))
811 else if (!strcmp(service
, "https"))
813 else if (!strcmp(service
, "ipp") || !strcmp(service
, "ipps"))
815 else if (!strcmp(service
, "lpd"))
817 else if (!strcmp(service
, "socket"))
821 httpAddrFreeList(first
);
823 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unknown service name."), 1);
827 if (hostname
&& !_cups_strcasecmp(hostname
, "localhost"))
830 * Unfortunately, some users ignore all of the warnings in the
831 * /etc/hosts file and delete "localhost" from it. If we get here
832 * then we were unable to resolve the name, so use the IPv6 and/or
833 * IPv4 loopback interface addresses...
837 if (family
!= AF_INET
)
840 * Add [::1] to the address list...
843 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
846 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
847 httpAddrFreeList(first
);
851 temp
->addr
.ipv6
.sin6_family
= AF_INET6
;
852 temp
->addr
.ipv6
.sin6_port
= htons(portnum
);
854 temp
->addr
.ipv6
.sin6_addr
.u
.Byte
[15] = 1;
856 temp
->addr
.ipv6
.sin6_addr
.s6_addr32
[3] = htonl(1);
865 if (family
!= AF_INET6
)
866 #endif /* AF_INET6 */
869 * Add 127.0.0.1 to the address list...
872 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
875 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
876 httpAddrFreeList(first
);
880 temp
->addr
.ipv4
.sin_family
= AF_INET
;
881 temp
->addr
.ipv4
.sin_port
= htons(portnum
);
882 temp
->addr
.ipv4
.sin_addr
.s_addr
= htonl(0x7f000001);
894 * Provide one or more passive listening addresses...
898 if (family
!= AF_INET
)
901 * Add [::] to the address list...
904 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
907 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
908 httpAddrFreeList(first
);
912 temp
->addr
.ipv6
.sin6_family
= AF_INET6
;
913 temp
->addr
.ipv6
.sin6_port
= htons(portnum
);
921 if (family
!= AF_INET6
)
922 #endif /* AF_INET6 */
925 * Add 0.0.0.0 to the address list...
928 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
931 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
932 httpAddrFreeList(first
);
936 temp
->addr
.ipv4
.sin_family
= AF_INET
;
937 temp
->addr
.ipv4
.sin_port
= htons(portnum
);
949 * Return the address list...