4 * HTTP address list routines for CUPS.
6 * Copyright 2007-2014 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * These coded instructions, statements, and computer programs are the
10 * property of Apple Inc. and are protected by Federal copyright
11 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
12 * which should have been included with this file. If this file is
13 * file is missing or damaged, see the license at "http://www.cups.org/".
15 * This file is subject to the Apple OS-Developed Software exception.
19 * Include necessary headers...
22 #include "cups-private.h"
25 #endif /* HAVE_RESOLV_H */
28 #endif /* HAVE_POLL */
35 * 'httpAddrConnect()' - Connect to any of the addresses in the list.
37 * @since CUPS 1.2/OS X 10.5@
40 http_addrlist_t
* /* O - Connected address or NULL on failure */
42 http_addrlist_t
*addrlist
, /* I - List of potential addresses */
43 int *sock
) /* O - Socket */
45 DEBUG_printf(("httpAddrConnect(addrlist=%p, sock=%p)", (void *)addrlist
, (void *)sock
));
47 return (httpAddrConnect2(addrlist
, sock
, 30000, NULL
));
52 * 'httpAddrConnect2()' - Connect to any of the addresses in the list with a
53 * timeout and optional cancel.
55 * @since CUPS 1.7/OS X 10.9@
58 http_addrlist_t
* /* O - Connected address or NULL on failure */
60 http_addrlist_t
*addrlist
, /* I - List of potential addresses */
61 int *sock
, /* O - Socket */
62 int msec
, /* I - Timeout in milliseconds */
63 int *cancel
) /* I - Pointer to "cancel" variable */
65 int val
; /* Socket option value */
67 socklen_t len
; /* Length of value */
68 http_addr_t peer
; /* Peer address */
69 int flags
, /* Socket flags */
70 remaining
; /* Remaining timeout */
71 int i
, /* Looping var */
72 nfds
, /* Number of file descriptors */
73 fds
[100], /* Socket file descriptors */
74 result
; /* Result from select() or poll() */
75 http_addrlist_t
*addrs
[100]; /* Addresses */
77 struct pollfd pfds
[100]; /* Polled file descriptors */
79 int max_fd
= -1; /* Highest file descriptor */
80 fd_set input_set
, /* select() input set */
81 output_set
; /* select() output set */
82 struct timeval timeout
; /* Timeout */
83 # endif /* HAVE_POLL */
84 #endif /* O_NONBLOCK */
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...
109 for (nfds
= 0; addrlist
&& nfds
< (int)(sizeof(fds
) / sizeof(fds
[0])); addrlist
= addrlist
->next
)
111 if (cancel
&& *cancel
)
116 httpAddrClose(NULL
, fds
[nfds
]);
123 * Create the socket...
126 DEBUG_printf(("2httpAddrConnect2: Trying %s:%d...", httpAddrString(&(addrlist
->addr
), temp
, sizeof(temp
)), httpAddrPort(&(addrlist
->addr
))));
128 if ((fds
[nfds
] = (int)socket(httpAddrFamily(&(addrlist
->addr
)), SOCK_STREAM
, 0)) < 0)
131 * Don't abort yet, as this could just be an issue with the local
132 * system not being configured with IPv4/IPv6/domain socket enabled...
143 setsockopt(fds
[nfds
], SOL_SOCKET
, SO_REUSEADDR
, CUPS_SOCAST
&val
, sizeof(val
));
147 setsockopt(fds
[nfds
], SOL_SOCKET
, SO_REUSEPORT
, CUPS_SOCAST
&val
, sizeof(val
));
148 #endif /* SO_REUSEPORT */
152 setsockopt(fds
[nfds
], SOL_SOCKET
, SO_NOSIGPIPE
, CUPS_SOCAST
&val
, sizeof(val
));
153 #endif /* SO_NOSIGPIPE */
156 * Using TCP_NODELAY improves responsiveness, especially on systems
157 * with a slow loopback interface...
161 setsockopt(fds
[nfds
], IPPROTO_TCP
, TCP_NODELAY
, CUPS_SOCAST
&val
, sizeof(val
));
165 * Close this socket when starting another process...
168 fcntl(fds
[nfds
], F_SETFD
, FD_CLOEXEC
);
169 #endif /* FD_CLOEXEC */
173 * Do an asynchronous connect by setting the socket non-blocking...
176 DEBUG_printf(("httpAddrConnect2: Setting non-blocking connect()"));
178 flags
= fcntl(fds
[nfds
], F_GETFL
, 0);
179 fcntl(fds
[nfds
], F_SETFL
, flags
| O_NONBLOCK
);
180 #endif /* O_NONBLOCK */
186 if (!connect(fds
[nfds
], &(addrlist
->addr
.addr
), (socklen_t
)httpAddrLength(&(addrlist
->addr
))))
188 DEBUG_printf(("1httpAddrConnect2: Connected to %s:%d...", httpAddrString(&(addrlist
->addr
), temp
, sizeof(temp
)), httpAddrPort(&(addrlist
->addr
))));
191 fcntl(fds
[nfds
], F_SETFL
, flags
);
192 #endif /* O_NONBLOCK */
199 httpAddrClose(NULL
, fds
[nfds
]);
206 if (WSAGetLastError() != WSAEINPROGRESS
&& WSAGetLastError() != WSAEWOULDBLOCK
)
208 if (errno
!= EINPROGRESS
&& errno
!= EWOULDBLOCK
)
211 DEBUG_printf(("1httpAddrConnect2: Unable to connect to %s:%d: %s", httpAddrString(&(addrlist
->addr
), temp
, sizeof(temp
)), httpAddrPort(&(addrlist
->addr
)), strerror(errno
)));
212 httpAddrClose(NULL
, fds
[nfds
]);
216 fcntl(fds
[nfds
], F_SETFL
, flags
);
219 if (fds
[nfds
] > max_fd
)
221 #endif /* !HAVE_POLL */
223 addrs
[nfds
] = addrlist
;
228 DEBUG_puts("1httpAddrConnect2: Finishing async connect()");
230 for (remaining
= msec
; remaining
> 0; remaining
-= 250)
234 if (cancel
&& *cancel
)
237 * Close this socket and return...
240 DEBUG_puts("1httpAddrConnect2: Canceled connect()");
245 httpAddrClose(NULL
, fds
[nfds
]);
254 for (i
= 0; i
< nfds
; i
++)
257 pfds
[i
].events
= POLLIN
| POLLOUT
;
260 result
= poll(pfds
, (nfds_t
)nfds
, remaining
> 250 ? 250 : remaining
);
262 DEBUG_printf(("1httpAddrConnect2: poll() returned %d (%d)", result
, errno
));
266 for (i
= 0; i
< nfds
; i
++)
267 FD_SET(fds
[i
], &input_set
);
268 output_set
= input_set
;
271 timeout
.tv_usec
= (remaining
> 250 ? 250 : remaining
) * 1000;
273 result
= select(max_fd
+ 1, &input_set
, &output_set
, NULL
, &timeout
);
275 DEBUG_printf(("1httpAddrConnect2: select() returned %d (%d)", result
, errno
));
276 # endif /* HAVE_POLL */
279 while (result
< 0 && (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
));
281 while (result
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
286 for (i
= 0; i
< nfds
; i
++)
289 DEBUG_printf(("pfds[%d].revents=%x\n", i
, pfds
[i
].revents
));
292 if (FD_ISSET(fds
[i
], &input
))
293 # endif /* HAVE_POLL */
297 if (!getpeername(fds
[i
], (struct sockaddr
*)&peer
, &len
))
299 DEBUG_printf(("1httpAddrConnect2: Connected to %s:%d...", httpAddrString(&peer
, temp
, sizeof(temp
)), httpAddrPort(&peer
)));
305 httpAddrClose(NULL
, fds
[i
]);
311 #endif /* O_NONBLOCK */
316 httpAddrClose(NULL
, fds
[nfds
]);
320 _cupsSetError(IPP_STATUS_ERROR_SERVICE_UNAVAILABLE
, "Connection failed", 0);
322 _cupsSetError(IPP_STATUS_ERROR_SERVICE_UNAVAILABLE
, strerror(errno
), 0);
330 * 'httpAddrCopyList()' - Copy an address list.
332 * @since CUPS 1.7/OS X 10.9@
335 http_addrlist_t
* /* O - New address list or @code NULL@ on error */
337 http_addrlist_t
*src
) /* I - Source address list */
339 http_addrlist_t
*dst
= NULL
, /* First list entry */
340 *prev
= NULL
, /* Previous list entry */
341 *current
= NULL
;/* Current list entry */
346 if ((current
= malloc(sizeof(http_addrlist_t
))) == NULL
)
353 current
= current
->next
;
361 memcpy(current
, src
, sizeof(http_addrlist_t
));
363 current
->next
= NULL
;
366 prev
->next
= current
;
379 * 'httpAddrFreeList()' - Free an address list.
381 * @since CUPS 1.2/OS X 10.5@
386 http_addrlist_t
*addrlist
) /* I - Address list to free */
388 http_addrlist_t
*next
; /* Next address in list */
392 * Free each address in the list...
397 next
= addrlist
->next
;
407 * 'httpAddrGetList()' - Get a list of addresses for a hostname.
409 * @since CUPS 1.2/OS X 10.5@
412 http_addrlist_t
* /* O - List of addresses or NULL */
413 httpAddrGetList(const char *hostname
, /* I - Hostname, IP address, or NULL for passive listen address */
414 int family
, /* I - Address family or AF_UNSPEC */
415 const char *service
) /* I - Service name or port number */
417 http_addrlist_t
*first
, /* First address in list */
418 *addr
, /* Current address in list */
419 *temp
; /* New address */
420 _cups_globals_t
*cg
= _cupsGlobals();
425 _cups_debug_printf("httpAddrGetList(hostname=\"%s\", family=AF_%s, "
427 hostname
? hostname
: "(nil)",
428 family
== AF_UNSPEC
? "UNSPEC" :
430 family
== AF_LOCAL
? "LOCAL" :
431 # endif /* AF_LOCAL */
433 family
== AF_INET6
? "INET6" :
434 # endif /* AF_INET6 */
435 family
== AF_INET
? "INET" : "???", service
);
440 * STR #2920: Initialize resolver after failure in cups-polld
442 * If the previous lookup failed, re-initialize the resolver to prevent
443 * temporary network errors from persisting. This *should* be handled by
444 * the resolver libraries, but apparently the glibc folks do not agree.
446 * We set a flag at the end of this function if we encounter an error that
447 * requires reinitialization of the resolver functions. We then call
448 * res_init() if the flag is set on the next call here or in httpAddrLookup().
451 if (cg
->need_res_init
)
455 cg
->need_res_init
= 0;
457 #endif /* HAVE_RES_INIT */
460 * Lookup the address the best way we can...
466 if (hostname
&& hostname
[0] == '/')
469 * Domain socket address...
472 if ((first
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
))) != NULL
)
475 first
->addr
.un
.sun_family
= AF_LOCAL
;
476 strlcpy(first
->addr
.un
.sun_path
, hostname
, sizeof(first
->addr
.un
.sun_path
));
480 #endif /* AF_LOCAL */
481 if (!hostname
|| _cups_strcasecmp(hostname
, "localhost"))
483 #ifdef HAVE_GETADDRINFO
484 struct addrinfo hints
, /* Address lookup hints */
485 *results
, /* Address lookup results */
486 *current
; /* Current result */
487 char ipv6
[64], /* IPv6 address */
488 *ipv6zone
; /* Pointer to zone separator */
489 int ipv6len
; /* Length of IPv6 address */
490 int error
; /* getaddrinfo() error */
494 * Lookup the address as needed...
497 memset(&hints
, 0, sizeof(hints
));
498 hints
.ai_family
= family
;
499 hints
.ai_flags
= hostname
? 0 : AI_PASSIVE
;
500 hints
.ai_socktype
= SOCK_STREAM
;
502 if (hostname
&& *hostname
== '[')
505 * Remove brackets from numeric IPv6 address...
508 if (!strncmp(hostname
, "[v1.", 4))
511 * Copy the newer address format which supports link-local addresses...
514 strlcpy(ipv6
, hostname
+ 4, sizeof(ipv6
));
515 if ((ipv6len
= (int)strlen(ipv6
) - 1) >= 0 && ipv6
[ipv6len
] == ']')
517 ipv6
[ipv6len
] = '\0';
521 * Convert "+zone" in address to "%zone"...
524 if ((ipv6zone
= strrchr(ipv6
, '+')) != NULL
)
531 * Copy the regular non-link-local IPv6 address...
534 strlcpy(ipv6
, hostname
+ 1, sizeof(ipv6
));
535 if ((ipv6len
= (int)strlen(ipv6
) - 1) >= 0 && ipv6
[ipv6len
] == ']')
537 ipv6
[ipv6len
] = '\0';
543 if ((error
= getaddrinfo(hostname
, service
, &hints
, &results
)) == 0)
546 * Copy the results to our own address list structure...
549 for (current
= results
; current
; current
= current
->ai_next
)
550 if (current
->ai_family
== AF_INET
|| current
->ai_family
== AF_INET6
)
553 * Copy the address over...
556 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
559 httpAddrFreeList(first
);
560 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
564 if (current
->ai_family
== AF_INET6
)
565 memcpy(&(temp
->addr
.ipv6
), current
->ai_addr
,
566 sizeof(temp
->addr
.ipv6
));
568 memcpy(&(temp
->addr
.ipv4
), current
->ai_addr
,
569 sizeof(temp
->addr
.ipv4
));
572 * Append the address to the list...
585 * Free the results from getaddrinfo()...
588 freeaddrinfo(results
);
592 if (error
== EAI_FAIL
)
593 cg
->need_res_init
= 1;
595 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, gai_strerror(error
), 0);
601 int i
; /* Looping vars */
602 unsigned ip
[4]; /* IPv4 address components */
603 const char *ptr
; /* Pointer into hostname */
604 struct hostent
*host
; /* Result of lookup */
605 struct servent
*port
; /* Port number for service */
606 int portnum
; /* Port number */
610 * Lookup the service...
615 else if (isdigit(*service
& 255))
616 portnum
= atoi(service
);
617 else if ((port
= getservbyname(service
, NULL
)) != NULL
)
618 portnum
= ntohs(port
->s_port
);
619 else if (!strcmp(service
, "http"))
621 else if (!strcmp(service
, "https"))
623 else if (!strcmp(service
, "ipp") || !strcmp(service
, "ipps"))
625 else if (!strcmp(service
, "lpd"))
627 else if (!strcmp(service
, "socket"))
633 * This code is needed because some operating systems have a
634 * buggy implementation of gethostbyname() that does not support
635 * IPv4 addresses. If the hostname string is an IPv4 address, then
636 * sscanf() is used to extract the IPv4 components. We then pack
637 * the components into an IPv4 address manually, since the
638 * inet_aton() function is deprecated. We use the htonl() macro
639 * to get the right byte order for the address.
642 for (ptr
= hostname
; isdigit(*ptr
& 255) || *ptr
== '.'; ptr
++);
647 * We have an IPv4 address; break it up and create an IPv4 address...
650 if (sscanf(hostname
, "%u.%u.%u.%u", ip
, ip
+ 1, ip
+ 2, ip
+ 3) == 4 &&
651 ip
[0] <= 255 && ip
[1] <= 255 && ip
[2] <= 255 && ip
[3] <= 255)
653 first
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
657 first
->addr
.ipv4
.sin_family
= AF_INET
;
658 first
->addr
.ipv4
.sin_addr
.s_addr
= htonl((((((((unsigned)ip
[0] << 8) |
659 (unsigned)ip
[1]) << 8) |
660 (unsigned)ip
[2]) << 8) |
662 first
->addr
.ipv4
.sin_port
= htons(portnum
);
665 else if ((host
= gethostbyname(hostname
)) != NULL
&&
667 (host
->h_addrtype
== AF_INET
|| host
->h_addrtype
== AF_INET6
))
669 host
->h_addrtype
== AF_INET
)
670 # endif /* AF_INET6 */
672 for (i
= 0; host
->h_addr_list
[i
]; i
++)
675 * Copy the address over...
678 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
681 httpAddrFreeList(first
);
686 if (host
->h_addrtype
== AF_INET6
)
688 temp
->addr
.ipv6
.sin6_family
= AF_INET6
;
689 memcpy(&(temp
->addr
.ipv6
.sin6_addr
), host
->h_addr_list
[i
],
690 sizeof(temp
->addr
.ipv6
));
691 temp
->addr
.ipv6
.sin6_port
= htons(portnum
);
694 # endif /* AF_INET6 */
696 temp
->addr
.ipv4
.sin_family
= AF_INET
;
697 memcpy(&(temp
->addr
.ipv4
.sin_addr
), host
->h_addr_list
[i
],
698 sizeof(temp
->addr
.ipv4
));
699 temp
->addr
.ipv4
.sin_port
= htons(portnum
);
703 * Append the address to the list...
717 if (h_errno
== NO_RECOVERY
)
718 cg
->need_res_init
= 1;
720 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, hstrerror(h_errno
), 0);
723 #endif /* HAVE_GETADDRINFO */
727 * Detect some common errors and handle them sanely...
730 if (!addr
&& (!hostname
|| !_cups_strcasecmp(hostname
, "localhost")))
732 struct servent
*port
; /* Port number for service */
733 int portnum
; /* Port number */
737 * Lookup the service...
742 else if (isdigit(*service
& 255))
743 portnum
= atoi(service
);
744 else if ((port
= getservbyname(service
, NULL
)) != NULL
)
745 portnum
= ntohs(port
->s_port
);
746 else if (!strcmp(service
, "http"))
748 else if (!strcmp(service
, "https"))
750 else if (!strcmp(service
, "ipp") || !strcmp(service
, "ipps"))
752 else if (!strcmp(service
, "lpd"))
754 else if (!strcmp(service
, "socket"))
758 httpAddrFreeList(first
);
760 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unknown service name."), 1);
764 if (hostname
&& !_cups_strcasecmp(hostname
, "localhost"))
767 * Unfortunately, some users ignore all of the warnings in the
768 * /etc/hosts file and delete "localhost" from it. If we get here
769 * then we were unable to resolve the name, so use the IPv6 and/or
770 * IPv4 loopback interface addresses...
774 if (family
!= AF_INET
)
777 * Add [::1] to the address list...
780 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
783 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
784 httpAddrFreeList(first
);
788 temp
->addr
.ipv6
.sin6_family
= AF_INET6
;
789 temp
->addr
.ipv6
.sin6_port
= htons(portnum
);
791 temp
->addr
.ipv6
.sin6_addr
.u
.Byte
[15] = 1;
793 temp
->addr
.ipv6
.sin6_addr
.s6_addr32
[3] = htonl(1);
802 if (family
!= AF_INET6
)
803 #endif /* AF_INET6 */
806 * Add 127.0.0.1 to the address list...
809 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
812 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
813 httpAddrFreeList(first
);
817 temp
->addr
.ipv4
.sin_family
= AF_INET
;
818 temp
->addr
.ipv4
.sin_port
= htons(portnum
);
819 temp
->addr
.ipv4
.sin_addr
.s_addr
= htonl(0x7f000001);
831 * Provide one or more passive listening addresses...
835 if (family
!= AF_INET
)
838 * Add [::] to the address list...
841 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
844 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
845 httpAddrFreeList(first
);
849 temp
->addr
.ipv6
.sin6_family
= AF_INET6
;
850 temp
->addr
.ipv6
.sin6_port
= htons(portnum
);
858 if (family
!= AF_INET6
)
859 #endif /* AF_INET6 */
862 * Add 0.0.0.0 to the address list...
865 temp
= (http_addrlist_t
*)calloc(1, sizeof(http_addrlist_t
));
868 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
869 httpAddrFreeList(first
);
873 temp
->addr
.ipv4
.sin_family
= AF_INET
;
874 temp
->addr
.ipv4
.sin_port
= htons(portnum
);
886 * Return the address list...