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 flags
; /* Socket flags */
62 int remaining
; /* Remaining timeout */
63 int i
, j
, /* Looping vars */
64 nfds
, /* Number of file descriptors */
65 fds
[100], /* Socket file descriptors */
66 result
; /* Result from select() or poll() */
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 */
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
;
224 fcntl(fds
[nfds
], F_SETFL
, flags
);
228 if (fds
[nfds
] > max_fd
)
230 #endif /* !HAVE_POLL */
232 addrs
[nfds
] = addrlist
;
234 addrlist
= addrlist
->next
;
237 if (!addrlist
&& nfds
== 0)
241 * See if we can connect to any of the addresses so far...
245 DEBUG_puts("1httpAddrConnect2: Finishing async connect()");
249 if (cancel
&& *cancel
)
252 * Close this socket and return...
255 DEBUG_puts("1httpAddrConnect2: Canceled connect()");
260 httpAddrClose(NULL
, fds
[nfds
]);
269 for (i
= 0; i
< nfds
; i
++)
272 pfds
[i
].events
= POLLIN
| POLLOUT
;
275 result
= poll(pfds
, (nfds_t
)nfds
, addrlist
? 100 : remaining
> 250 ? 250 : remaining
);
277 DEBUG_printf(("1httpAddrConnect2: poll() returned %d (%d)", result
, errno
));
281 for (i
= 0; i
< nfds
; i
++)
282 FD_SET(fds
[i
], &input_set
);
283 output_set
= input_set
;
284 error_set
= input_set
;
287 timeout
.tv_usec
= (addrlist
? 100 : remaining
> 250 ? 250 : remaining
) * 1000;
289 result
= select(max_fd
+ 1, &input_set
, &output_set
, &error_set
, &timeout
);
291 DEBUG_printf(("1httpAddrConnect2: select() returned %d (%d)", result
, errno
));
292 # endif /* HAVE_POLL */
295 while (result
< 0 && (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
));
297 while (result
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
302 http_addrlist_t
*connaddr
= NULL
; /* Connected address, if any */
304 for (i
= 0; i
< nfds
; i
++)
307 DEBUG_printf(("pfds[%d].revents=%x\n", i
, pfds
[i
].revents
));
308 if (pfds
[i
].revents
&& !(pfds
[i
].revents
& (POLLERR
| POLLHUP
)))
310 if (FD_ISSET(fds
[i
], &input_set
) && !FD_ISSET(fds
[i
], &error_set
))
311 # endif /* HAVE_POLL */
318 if (!getpeername(fds
[i
], (struct sockaddr
*)&peer
, &len
))
319 DEBUG_printf(("1httpAddrConnect2: Connected to %s:%d...", httpAddrString(&peer
, temp
, sizeof(temp
)), httpAddrPort(&peer
)));
325 else if (pfds
[i
].revents
& (POLLERR
| POLLHUP
))
327 else if (FD_ISSET(fds
[i
], &error_set
))
328 # endif /* HAVE_POLL */
331 * Error on socket, remove from the "pool"...
334 httpAddrClose(NULL
, fds
[i
]);
338 memmove(fds
+ i
, fds
+ i
+ 1, (size_t)(nfds
- i
) * (sizeof(fds
[0])));
339 memmove(addrs
+ i
, addrs
+ i
+ 1, (size_t)(nfds
- i
) * (sizeof(addrs
[0])));
348 * Connected on one address, close all of the other sockets we have so
352 for (j
= 0; j
< i
; j
++)
353 httpAddrClose(NULL
, fds
[j
]);
355 for (j
++; j
< nfds
; j
++)
356 httpAddrClose(NULL
, fds
[j
]);
361 #endif /* O_NONBLOCK */
372 httpAddrClose(NULL
, fds
[nfds
]);
376 _cupsSetError(IPP_STATUS_ERROR_SERVICE_UNAVAILABLE
, "Connection failed", 0);
378 _cupsSetError(IPP_STATUS_ERROR_SERVICE_UNAVAILABLE
, strerror(errno
), 0);
386 * 'httpAddrCopyList()' - Copy an address list.
388 * @since CUPS 1.7/macOS 10.9@
391 http_addrlist_t
* /* O - New address list or @code NULL@ on error */
393 http_addrlist_t
*src
) /* I - Source address list */
395 http_addrlist_t
*dst
= NULL
, /* First list entry */
396 *prev
= NULL
, /* Previous list entry */
397 *current
= NULL
;/* Current list entry */
402 if ((current
= malloc(sizeof(http_addrlist_t
))) == NULL
)
409 current
= current
->next
;
417 memcpy(current
, src
, sizeof(http_addrlist_t
));
419 current
->next
= NULL
;
422 prev
->next
= current
;
435 * 'httpAddrFreeList()' - Free an address list.
437 * @since CUPS 1.2/macOS 10.5@
442 http_addrlist_t
*addrlist
) /* I - Address list to free */
444 http_addrlist_t
*next
; /* Next address in list */
448 * Free each address in the list...
453 next
= addrlist
->next
;
463 * 'httpAddrGetList()' - Get a list of addresses for a hostname.
465 * @since CUPS 1.2/macOS 10.5@
468 http_addrlist_t
* /* O - List of addresses or NULL */
469 httpAddrGetList(const char *hostname
, /* I - Hostname, IP address, or NULL for passive listen address */
470 int family
, /* I - Address family or AF_UNSPEC */
471 const char *service
) /* I - Service name or port number */
473 http_addrlist_t
*first
, /* First address in list */
474 *addr
, /* Current address in list */
475 *temp
; /* New address */
476 _cups_globals_t
*cg
= _cupsGlobals();
481 _cups_debug_printf("httpAddrGetList(hostname=\"%s\", family=AF_%s, "
483 hostname
? hostname
: "(nil)",
484 family
== AF_UNSPEC
? "UNSPEC" :
486 family
== AF_LOCAL
? "LOCAL" :
487 # endif /* AF_LOCAL */
489 family
== AF_INET6
? "INET6" :
490 # endif /* AF_INET6 */
491 family
== AF_INET
? "INET" : "???", service
);
496 * STR #2920: Initialize resolver after failure in cups-polld
498 * If the previous lookup failed, re-initialize the resolver to prevent
499 * temporary network errors from persisting. This *should* be handled by
500 * the resolver libraries, but apparently the glibc folks do not agree.
502 * We set a flag at the end of this function if we encounter an error that
503 * requires reinitialization of the resolver functions. We then call
504 * res_init() if the flag is set on the next call here or in httpAddrLookup().
507 if (cg
->need_res_init
)
511 cg
->need_res_init
= 0;
513 #endif /* HAVE_RES_INIT */
516 * Lookup the address the best way we can...
522 if (hostname
&& hostname
[0] == '/')
525 * Domain socket address...
528 if ((first
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
))) != NULL
)
531 first
->addr
.un
.sun_family
= AF_LOCAL
;
532 strlcpy(first
->addr
.un
.sun_path
, hostname
, sizeof(first
->addr
.un
.sun_path
));
536 #endif /* AF_LOCAL */
537 if (!hostname
|| _cups_strcasecmp(hostname
, "localhost"))
539 #ifdef HAVE_GETADDRINFO
540 struct addrinfo hints
, /* Address lookup hints */
541 *results
, /* Address lookup results */
542 *current
; /* Current result */
543 char ipv6
[64], /* IPv6 address */
544 *ipv6zone
; /* Pointer to zone separator */
545 int ipv6len
; /* Length of IPv6 address */
546 int error
; /* getaddrinfo() error */
550 * Lookup the address as needed...
553 memset(&hints
, 0, sizeof(hints
));
554 hints
.ai_family
= family
;
555 hints
.ai_flags
= hostname
? 0 : AI_PASSIVE
;
556 hints
.ai_socktype
= SOCK_STREAM
;
558 if (hostname
&& *hostname
== '[')
561 * Remove brackets from numeric IPv6 address...
564 if (!strncmp(hostname
, "[v1.", 4))
567 * Copy the newer address format which supports link-local addresses...
570 strlcpy(ipv6
, hostname
+ 4, sizeof(ipv6
));
571 if ((ipv6len
= (int)strlen(ipv6
) - 1) >= 0 && ipv6
[ipv6len
] == ']')
573 ipv6
[ipv6len
] = '\0';
577 * Convert "+zone" in address to "%zone"...
580 if ((ipv6zone
= strrchr(ipv6
, '+')) != NULL
)
587 * Copy the regular non-link-local IPv6 address...
590 strlcpy(ipv6
, hostname
+ 1, sizeof(ipv6
));
591 if ((ipv6len
= (int)strlen(ipv6
) - 1) >= 0 && ipv6
[ipv6len
] == ']')
593 ipv6
[ipv6len
] = '\0';
599 if ((error
= getaddrinfo(hostname
, service
, &hints
, &results
)) == 0)
602 * Copy the results to our own address list structure...
605 for (current
= results
; current
; current
= current
->ai_next
)
606 if (current
->ai_family
== AF_INET
|| current
->ai_family
== AF_INET6
)
609 * Copy the address over...
612 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
615 httpAddrFreeList(first
);
616 freeaddrinfo(results
);
617 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
621 if (current
->ai_family
== AF_INET6
)
622 memcpy(&(temp
->addr
.ipv6
), current
->ai_addr
,
623 sizeof(temp
->addr
.ipv6
));
625 memcpy(&(temp
->addr
.ipv4
), current
->ai_addr
,
626 sizeof(temp
->addr
.ipv4
));
629 * Append the address to the list...
642 * Free the results from getaddrinfo()...
645 freeaddrinfo(results
);
649 if (error
== EAI_FAIL
)
650 cg
->need_res_init
= 1;
652 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, gai_strerror(error
), 0);
658 int i
; /* Looping vars */
659 unsigned ip
[4]; /* IPv4 address components */
660 const char *ptr
; /* Pointer into hostname */
661 struct hostent
*host
; /* Result of lookup */
662 struct servent
*port
; /* Port number for service */
663 int portnum
; /* Port number */
667 * Lookup the service...
672 else if (isdigit(*service
& 255))
673 portnum
= atoi(service
);
674 else if ((port
= getservbyname(service
, NULL
)) != NULL
)
675 portnum
= ntohs(port
->s_port
);
676 else if (!strcmp(service
, "http"))
678 else if (!strcmp(service
, "https"))
680 else if (!strcmp(service
, "ipp") || !strcmp(service
, "ipps"))
682 else if (!strcmp(service
, "lpd"))
684 else if (!strcmp(service
, "socket"))
690 * This code is needed because some operating systems have a
691 * buggy implementation of gethostbyname() that does not support
692 * IPv4 addresses. If the hostname string is an IPv4 address, then
693 * sscanf() is used to extract the IPv4 components. We then pack
694 * the components into an IPv4 address manually, since the
695 * inet_aton() function is deprecated. We use the htonl() macro
696 * to get the right byte order for the address.
699 for (ptr
= hostname
; isdigit(*ptr
& 255) || *ptr
== '.'; ptr
++);
704 * We have an IPv4 address; break it up and create an IPv4 address...
707 if (sscanf(hostname
, "%u.%u.%u.%u", ip
, ip
+ 1, ip
+ 2, ip
+ 3) == 4 &&
708 ip
[0] <= 255 && ip
[1] <= 255 && ip
[2] <= 255 && ip
[3] <= 255)
710 first
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
714 first
->addr
.ipv4
.sin_family
= AF_INET
;
715 first
->addr
.ipv4
.sin_addr
.s_addr
= htonl((((((((unsigned)ip
[0] << 8) |
716 (unsigned)ip
[1]) << 8) |
717 (unsigned)ip
[2]) << 8) |
719 first
->addr
.ipv4
.sin_port
= htons(portnum
);
722 else if ((host
= gethostbyname(hostname
)) != NULL
&&
724 (host
->h_addrtype
== AF_INET
|| host
->h_addrtype
== AF_INET6
))
726 host
->h_addrtype
== AF_INET
)
727 # endif /* AF_INET6 */
729 for (i
= 0; host
->h_addr_list
[i
]; i
++)
732 * Copy the address over...
735 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
738 httpAddrFreeList(first
);
743 if (host
->h_addrtype
== AF_INET6
)
745 temp
->addr
.ipv6
.sin6_family
= AF_INET6
;
746 memcpy(&(temp
->addr
.ipv6
.sin6_addr
), host
->h_addr_list
[i
],
747 sizeof(temp
->addr
.ipv6
));
748 temp
->addr
.ipv6
.sin6_port
= htons(portnum
);
751 # endif /* AF_INET6 */
753 temp
->addr
.ipv4
.sin_family
= AF_INET
;
754 memcpy(&(temp
->addr
.ipv4
.sin_addr
), host
->h_addr_list
[i
],
755 sizeof(temp
->addr
.ipv4
));
756 temp
->addr
.ipv4
.sin_port
= htons(portnum
);
760 * Append the address to the list...
774 if (h_errno
== NO_RECOVERY
)
775 cg
->need_res_init
= 1;
777 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, hstrerror(h_errno
), 0);
780 #endif /* HAVE_GETADDRINFO */
784 * Detect some common errors and handle them sanely...
787 if (!addr
&& (!hostname
|| !_cups_strcasecmp(hostname
, "localhost")))
789 struct servent
*port
; /* Port number for service */
790 int portnum
; /* Port number */
794 * Lookup the service...
799 else if (isdigit(*service
& 255))
800 portnum
= atoi(service
);
801 else if ((port
= getservbyname(service
, NULL
)) != NULL
)
802 portnum
= ntohs(port
->s_port
);
803 else if (!strcmp(service
, "http"))
805 else if (!strcmp(service
, "https"))
807 else if (!strcmp(service
, "ipp") || !strcmp(service
, "ipps"))
809 else if (!strcmp(service
, "lpd"))
811 else if (!strcmp(service
, "socket"))
815 httpAddrFreeList(first
);
817 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unknown service name."), 1);
821 if (hostname
&& !_cups_strcasecmp(hostname
, "localhost"))
824 * Unfortunately, some users ignore all of the warnings in the
825 * /etc/hosts file and delete "localhost" from it. If we get here
826 * then we were unable to resolve the name, so use the IPv6 and/or
827 * IPv4 loopback interface addresses...
831 if (family
!= AF_INET
)
834 * Add [::1] to the address list...
837 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
840 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
841 httpAddrFreeList(first
);
845 temp
->addr
.ipv6
.sin6_family
= AF_INET6
;
846 temp
->addr
.ipv6
.sin6_port
= htons(portnum
);
848 temp
->addr
.ipv6
.sin6_addr
.u
.Byte
[15] = 1;
850 temp
->addr
.ipv6
.sin6_addr
.s6_addr32
[3] = htonl(1);
859 if (family
!= AF_INET6
)
860 #endif /* AF_INET6 */
863 * Add 127.0.0.1 to the address list...
866 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
869 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
870 httpAddrFreeList(first
);
874 temp
->addr
.ipv4
.sin_family
= AF_INET
;
875 temp
->addr
.ipv4
.sin_port
= htons(portnum
);
876 temp
->addr
.ipv4
.sin_addr
.s_addr
= htonl(0x7f000001);
888 * Provide one or more passive listening addresses...
892 if (family
!= AF_INET
)
895 * Add [::] to the address list...
898 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
901 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
902 httpAddrFreeList(first
);
906 temp
->addr
.ipv6
.sin6_family
= AF_INET6
;
907 temp
->addr
.ipv6
.sin6_port
= htons(portnum
);
915 if (family
!= AF_INET6
)
916 #endif /* AF_INET6 */
919 * Add 0.0.0.0 to the address list...
922 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
925 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
926 httpAddrFreeList(first
);
930 temp
->addr
.ipv4
.sin_family
= AF_INET
;
931 temp
->addr
.ipv4
.sin_port
= htons(portnum
);
943 * Return the address list...