2 * HTTP support 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"
20 # elif defined(HAVE_POLL)
23 # include <sys/select.h>
25 #elif defined(HAVE_AVAHI)
26 # include <avahi-client/client.h>
27 # include <avahi-client/lookup.h>
28 # include <avahi-common/simple-watch.h>
29 #endif /* HAVE_DNSSD */
36 typedef struct _http_uribuf_s
/* URI buffer */
39 AvahiSimplePoll
*poll
; /* Poll state */
40 #endif /* HAVE_AVAHI */
41 char *buffer
; /* Pointer to buffer */
42 size_t bufsize
; /* Size of buffer */
43 int options
; /* Options passed to _httpResolveURI */
44 const char *resource
; /* Resource from URI */
45 const char *uuid
; /* UUID from URI */
53 static const char * const http_days
[7] =/* Days of the week */
63 static const char * const http_months
[12] =
64 { /* Months of the year */
78 static const char * const http_states
[] =
79 { /* HTTP state strings */
84 "HTTP_STATE_GET_SEND",
87 "HTTP_STATE_POST_RECV",
88 "HTTP_STATE_POST_SEND",
90 "HTTP_STATE_PUT_RECV",
95 "HTTP_STATE_UNKNOWN_METHOD",
96 "HTTP_STATE_UNKNOWN_VERSION"
104 static const char *http_copy_decode(char *dst
, const char *src
,
105 int dstsize
, const char *term
,
107 static char *http_copy_encode(char *dst
, const char *src
,
108 char *dstend
, const char *reserved
,
109 const char *term
, int encode
);
111 static void DNSSD_API
http_resolve_cb(DNSServiceRef sdRef
,
112 DNSServiceFlags flags
,
113 uint32_t interfaceIndex
,
114 DNSServiceErrorType errorCode
,
115 const char *fullName
,
116 const char *hostTarget
,
117 uint16_t port
, uint16_t txtLen
,
118 const unsigned char *txtRecord
,
120 #endif /* HAVE_DNSSD */
123 static void http_client_cb(AvahiClient
*client
,
124 AvahiClientState state
, void *simple_poll
);
125 static int http_poll_cb(struct pollfd
*pollfds
, unsigned int num_pollfds
,
126 int timeout
, void *context
);
127 static void http_resolve_cb(AvahiServiceResolver
*resolver
,
128 AvahiIfIndex interface
,
129 AvahiProtocol protocol
,
130 AvahiResolverEvent event
,
131 const char *name
, const char *type
,
132 const char *domain
, const char *host_name
,
133 const AvahiAddress
*address
, uint16_t port
,
134 AvahiStringList
*txt
,
135 AvahiLookupResultFlags flags
, void *context
);
136 #endif /* HAVE_AVAHI */
140 * 'httpAssembleURI()' - Assemble a uniform resource identifier from its
143 * This function escapes reserved characters in the URI depending on the
144 * value of the "encoding" argument. You should use this function in
145 * place of traditional string functions whenever you need to create a
148 * @since CUPS 1.2/macOS 10.5@
151 http_uri_status_t
/* O - URI status */
153 http_uri_coding_t encoding
, /* I - Encoding flags */
154 char *uri
, /* I - URI buffer */
155 int urilen
, /* I - Size of URI buffer */
156 const char *scheme
, /* I - Scheme name */
157 const char *username
, /* I - Username */
158 const char *host
, /* I - Hostname or address */
159 int port
, /* I - Port number */
160 const char *resource
) /* I - Resource */
162 char *ptr
, /* Pointer into URI buffer */
163 *end
; /* End of URI buffer */
167 * Range check input...
170 if (!uri
|| urilen
< 1 || !scheme
|| port
< 0)
175 return (HTTP_URI_STATUS_BAD_ARGUMENTS
);
179 * Assemble the URI starting with the scheme...
182 end
= uri
+ urilen
- 1;
183 ptr
= http_copy_encode(uri
, scheme
, end
, NULL
, NULL
, 0);
186 goto assemble_overflow
;
188 if (!strcmp(scheme
, "geo") || !strcmp(scheme
, "mailto") || !strcmp(scheme
, "tel"))
191 * geo:, mailto:, and tel: only have :, no //...
197 goto assemble_overflow
;
202 * Schemes other than geo:, mailto:, and tel: typically have //...
212 goto assemble_overflow
;
216 * Next the username and hostname, if any...
221 const char *hostptr
; /* Pointer into hostname */
222 int have_ipv6
; /* Do we have an IPv6 address? */
224 if (username
&& *username
)
227 * Add username@ first...
230 ptr
= http_copy_encode(ptr
, username
, end
, "/?#[]@", NULL
,
231 encoding
& HTTP_URI_CODING_USERNAME
);
234 goto assemble_overflow
;
239 goto assemble_overflow
;
243 * Then add the hostname. Since IPv6 is a particular pain to deal
244 * with, we have several special cases to deal with. If we get
245 * an IPv6 address with brackets around it, assume it is already in
246 * URI format. Since DNS-SD service names can sometimes look like
247 * raw IPv6 addresses, we specifically look for "._tcp" in the name,
252 have_ipv6
= strchr(host
, ':') && !strstr(host
, "._tcp");
253 *hostptr
&& have_ipv6
;
255 if (*hostptr
!= ':' && !isxdigit(*hostptr
& 255))
257 have_ipv6
= *hostptr
== '%';
264 * We have a raw IPv6 address...
267 if (strchr(host
, '%') && !(encoding
& HTTP_URI_CODING_RFC6874
))
270 * We have a link-local address, add "[v1." prefix...
281 goto assemble_overflow
;
286 * We have a normal (or RFC 6874 link-local) address, add "[" prefix...
292 goto assemble_overflow
;
296 * Copy the rest of the IPv6 address, and terminate with "]".
299 while (ptr
< end
&& *host
)
304 * Convert/encode zone separator
307 if (encoding
& HTTP_URI_CODING_RFC6874
)
309 if (ptr
>= (end
- 2))
310 goto assemble_overflow
;
326 goto assemble_overflow
;
331 goto assemble_overflow
;
336 * Otherwise, just copy the host string (the extra chars are not in the
337 * "reg-name" ABNF rule; anything <= SP or >= DEL plus % gets automatically
341 ptr
= http_copy_encode(ptr
, host
, end
, "\"#/:<>?@[\\]^`{|}", NULL
,
342 encoding
& HTTP_URI_CODING_HOSTNAME
);
345 goto assemble_overflow
;
349 * Finish things off with the port number...
354 snprintf(ptr
, (size_t)(end
- ptr
+ 1), ":%d", port
);
358 goto assemble_overflow
;
363 * Last but not least, add the resource string...
368 char *query
; /* Pointer to query string */
372 * Copy the resource string up to the query string if present...
375 query
= strchr(resource
, '?');
376 ptr
= http_copy_encode(ptr
, resource
, end
, NULL
, "?",
377 encoding
& HTTP_URI_CODING_RESOURCE
);
379 goto assemble_overflow
;
384 * Copy query string without encoding...
387 ptr
= http_copy_encode(ptr
, query
, end
, NULL
, NULL
,
388 encoding
& HTTP_URI_CODING_QUERY
);
390 goto assemble_overflow
;
396 goto assemble_overflow
;
399 * Nul-terminate the URI buffer and return with no errors...
404 return (HTTP_URI_STATUS_OK
);
407 * Clear the URI string and return an overflow error; I don't usually
408 * like goto's, but in this case it makes sense...
414 return (HTTP_URI_STATUS_OVERFLOW
);
419 * 'httpAssembleURIf()' - Assemble a uniform resource identifier from its
420 * components with a formatted resource.
422 * This function creates a formatted version of the resource string
423 * argument "resourcef" and escapes reserved characters in the URI
424 * depending on the value of the "encoding" argument. You should use
425 * this function in place of traditional string functions whenever
426 * you need to create a URI string.
428 * @since CUPS 1.2/macOS 10.5@
431 http_uri_status_t
/* O - URI status */
433 http_uri_coding_t encoding
, /* I - Encoding flags */
434 char *uri
, /* I - URI buffer */
435 int urilen
, /* I - Size of URI buffer */
436 const char *scheme
, /* I - Scheme name */
437 const char *username
, /* I - Username */
438 const char *host
, /* I - Hostname or address */
439 int port
, /* I - Port number */
440 const char *resourcef
, /* I - Printf-style resource */
441 ...) /* I - Additional arguments as needed */
443 va_list ap
; /* Pointer to additional arguments */
444 char resource
[1024]; /* Formatted resource string */
445 int bytes
; /* Bytes in formatted string */
449 * Range check input...
452 if (!uri
|| urilen
< 1 || !scheme
|| port
< 0 || !resourcef
)
457 return (HTTP_URI_STATUS_BAD_ARGUMENTS
);
461 * Format the resource string and assemble the URI...
464 va_start(ap
, resourcef
);
465 bytes
= vsnprintf(resource
, sizeof(resource
), resourcef
, ap
);
468 if ((size_t)bytes
>= sizeof(resource
))
471 return (HTTP_URI_STATUS_OVERFLOW
);
474 return (httpAssembleURI(encoding
, uri
, urilen
, scheme
, username
, host
,
480 * 'httpAssembleUUID()' - Assemble a name-based UUID URN conforming to RFC 4122.
482 * This function creates a unique 128-bit identifying number using the server
483 * name, port number, random data, and optionally an object name and/or object
484 * number. The result is formatted as a UUID URN as defined in RFC 4122.
486 * The buffer needs to be at least 46 bytes in size.
488 * @since CUPS 1.7/macOS 10.9@
491 char * /* I - UUID string */
492 httpAssembleUUID(const char *server
, /* I - Server name */
493 int port
, /* I - Port number */
494 const char *name
, /* I - Object name or NULL */
495 int number
, /* I - Object number or 0 */
496 char *buffer
, /* I - String buffer */
497 size_t bufsize
) /* I - Size of buffer */
499 char data
[1024]; /* Source string for MD5 */
500 unsigned char md5sum
[16]; /* MD5 digest/sum */
504 * Build a version 3 UUID conforming to RFC 4122.
506 * Start with the MD5 sum of the server, port, object name and
507 * number, and some random data on the end.
510 snprintf(data
, sizeof(data
), "%s:%d:%s:%d:%04x:%04x", server
,
511 port
, name
? name
: server
, number
,
512 (unsigned)CUPS_RAND() & 0xffff, (unsigned)CUPS_RAND() & 0xffff);
514 cupsHashData("md5", (unsigned char *)data
, strlen(data
), md5sum
, sizeof(md5sum
));
517 * Generate the UUID from the MD5...
520 snprintf(buffer
, bufsize
,
521 "urn:uuid:%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-"
522 "%02x%02x%02x%02x%02x%02x",
523 md5sum
[0], md5sum
[1], md5sum
[2], md5sum
[3], md5sum
[4], md5sum
[5],
524 (md5sum
[6] & 15) | 0x30, md5sum
[7], (md5sum
[8] & 0x3f) | 0x40,
525 md5sum
[9], md5sum
[10], md5sum
[11], md5sum
[12], md5sum
[13],
526 md5sum
[14], md5sum
[15]);
533 * 'httpDecode64()' - Base64-decode a string.
535 * This function is deprecated. Use the httpDecode64_2() function instead
536 * which provides buffer length arguments.
538 * @deprecated@ @exclude all@
541 char * /* O - Decoded string */
542 httpDecode64(char *out
, /* I - String to write to */
543 const char *in
) /* I - String to read from */
545 int outlen
; /* Output buffer length */
549 * Use the old maximum buffer size for binary compatibility...
554 return (httpDecode64_2(out
, &outlen
, in
));
559 * 'httpDecode64_2()' - Base64-decode a string.
561 * The caller must initialize "outlen" to the maximum size of the decoded
562 * string before calling @code httpDecode64_2@. On return "outlen" contains the
563 * decoded length of the string.
565 * @since CUPS 1.1.21/macOS 10.4@
568 char * /* O - Decoded string */
569 httpDecode64_2(char *out
, /* I - String to write to */
570 int *outlen
, /* IO - Size of output string */
571 const char *in
) /* I - String to read from */
573 int pos
; /* Bit position */
574 unsigned base64
; /* Value of this character */
575 char *outptr
, /* Output pointer */
576 *outend
; /* End of output buffer */
580 * Range check input...
583 if (!out
|| !outlen
|| *outlen
< 1 || !in
)
595 * Convert from base-64 to bytes...
598 for (outptr
= out
, outend
= out
+ *outlen
- 1, pos
= 0; *in
!= '\0'; in
++)
601 * Decode this character into a number from 0 to 63...
604 if (*in
>= 'A' && *in
<= 'Z')
605 base64
= (unsigned)(*in
- 'A');
606 else if (*in
>= 'a' && *in
<= 'z')
607 base64
= (unsigned)(*in
- 'a' + 26);
608 else if (*in
>= '0' && *in
<= '9')
609 base64
= (unsigned)(*in
- '0' + 52);
620 * Store the result in the appropriate chars...
627 *outptr
= (char)(base64
<< 2);
632 *outptr
++ |= (char)((base64
>> 4) & 3);
634 *outptr
= (char)((base64
<< 4) & 255);
639 *outptr
++ |= (char)((base64
>> 2) & 15);
641 *outptr
= (char)((base64
<< 6) & 255);
646 *outptr
++ |= (char)base64
;
655 * Return the decoded string and size...
658 *outlen
= (int)(outptr
- out
);
665 * 'httpEncode64()' - Base64-encode a string.
667 * This function is deprecated. Use the httpEncode64_2() function instead
668 * which provides buffer length arguments.
670 * @deprecated@ @exclude all@
673 char * /* O - Encoded string */
674 httpEncode64(char *out
, /* I - String to write to */
675 const char *in
) /* I - String to read from */
677 return (httpEncode64_2(out
, 512, in
, (int)strlen(in
)));
682 * 'httpEncode64_2()' - Base64-encode a string.
684 * @since CUPS 1.1.21/macOS 10.4@
687 char * /* O - Encoded string */
688 httpEncode64_2(char *out
, /* I - String to write to */
689 int outlen
, /* I - Maximum size of output string */
690 const char *in
, /* I - String to read from */
691 int inlen
) /* I - Size of input string */
693 char *outptr
, /* Output pointer */
694 *outend
; /* End of output buffer */
695 static const char base64
[] = /* Base64 characters... */
697 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
698 "abcdefghijklmnopqrstuvwxyz"
705 * Range check input...
708 if (!out
|| outlen
< 1 || !in
)
712 * Convert bytes to base-64...
715 for (outptr
= out
, outend
= out
+ outlen
- 1; inlen
> 0; in
++, inlen
--)
718 * Encode the up to 3 characters as 4 Base64 numbers...
722 *outptr
++ = base64
[(in
[0] & 255) >> 2];
727 *outptr
++ = base64
[(((in
[0] & 255) << 4) | ((in
[1] & 255) >> 4)) & 63];
729 *outptr
++ = base64
[((in
[0] & 255) << 4) & 63];
746 *outptr
++ = base64
[(((in
[0] & 255) << 2) | ((in
[1] & 255) >> 6)) & 63];
748 *outptr
++ = base64
[((in
[0] & 255) << 2) & 63];
761 *outptr
++ = base64
[in
[0] & 63];
767 * Return the encoded string...
775 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
777 * @deprecated@ @exclude all@
780 const char * /* O - Date/time string */
781 httpGetDateString(time_t t
) /* I - Time in seconds */
783 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
786 return (httpGetDateString2(t
, cg
->http_date
, sizeof(cg
->http_date
)));
791 * 'httpGetDateString2()' - Get a formatted date/time string from a time value.
793 * @since CUPS 1.2/macOS 10.5@
796 const char * /* O - Date/time string */
797 httpGetDateString2(time_t t
, /* I - Time in seconds */
798 char *s
, /* I - String buffer */
799 int slen
) /* I - Size of string buffer */
801 struct tm
*tdate
; /* UNIX date/time data */
806 snprintf(s
, (size_t)slen
, "%s, %02d %s %d %02d:%02d:%02d GMT", http_days
[tdate
->tm_wday
], tdate
->tm_mday
, http_months
[tdate
->tm_mon
], tdate
->tm_year
+ 1900, tdate
->tm_hour
, tdate
->tm_min
, tdate
->tm_sec
);
815 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
818 time_t /* O - Time in seconds */
819 httpGetDateTime(const char *s
) /* I - Date/time string */
821 int i
; /* Looping var */
822 char mon
[16]; /* Abbreviated month name */
823 int day
, year
; /* Day of month and year */
824 int hour
, min
, sec
; /* Time */
825 int days
; /* Number of days since 1970 */
826 static const int normal_days
[] = /* Days to a month, normal years */
827 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
828 static const int leap_days
[] = /* Days to a month, leap years */
829 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 };
832 DEBUG_printf(("2httpGetDateTime(s=\"%s\")", s
));
835 * Extract the date and time from the formatted string...
838 if (sscanf(s
, "%*s%d%15s%d%d:%d:%d", &day
, mon
, &year
, &hour
, &min
, &sec
) < 6)
841 DEBUG_printf(("4httpGetDateTime: day=%d, mon=\"%s\", year=%d, hour=%d, "
842 "min=%d, sec=%d", day
, mon
, year
, hour
, min
, sec
));
845 * Convert the month name to a number from 0 to 11.
848 for (i
= 0; i
< 12; i
++)
849 if (!_cups_strcasecmp(mon
, http_months
[i
]))
855 DEBUG_printf(("4httpGetDateTime: i=%d", i
));
858 * Now convert the date and time to a UNIX time value in seconds since
859 * 1970. We can't use mktime() since the timezone may not be UTC but
860 * the date/time string *is* UTC.
863 if ((year
& 3) == 0 && ((year
% 100) != 0 || (year
% 400) == 0))
864 days
= leap_days
[i
] + day
- 1;
866 days
= normal_days
[i
] + day
- 1;
868 DEBUG_printf(("4httpGetDateTime: days=%d", days
));
870 days
+= (year
- 1970) * 365 + /* 365 days per year (normally) */
871 ((year
- 1) / 4 - 492) - /* + leap days */
872 ((year
- 1) / 100 - 19) + /* - 100 year days */
873 ((year
- 1) / 400 - 4); /* + 400 year days */
875 DEBUG_printf(("4httpGetDateTime: days=%d\n", days
));
877 return (days
* 86400 + hour
* 3600 + min
* 60 + sec
);
882 * 'httpSeparate()' - Separate a Universal Resource Identifier into its
885 * This function is deprecated; use the httpSeparateURI() function instead.
887 * @deprecated@ @exclude all@
891 httpSeparate(const char *uri
, /* I - Universal Resource Identifier */
892 char *scheme
, /* O - Scheme [32] (http, https, etc.) */
893 char *username
, /* O - Username [1024] */
894 char *host
, /* O - Hostname [1024] */
895 int *port
, /* O - Port number to use */
896 char *resource
) /* O - Resource/filename [1024] */
898 httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, 32, username
,
899 HTTP_MAX_URI
, host
, HTTP_MAX_URI
, port
, resource
,
905 * 'httpSeparate2()' - Separate a Universal Resource Identifier into its
908 * This function is deprecated; use the httpSeparateURI() function instead.
910 * @since CUPS 1.1.21/macOS 10.4@
911 * @deprecated@ @exclude all@
915 httpSeparate2(const char *uri
, /* I - Universal Resource Identifier */
916 char *scheme
, /* O - Scheme (http, https, etc.) */
917 int schemelen
, /* I - Size of scheme buffer */
918 char *username
, /* O - Username */
919 int usernamelen
, /* I - Size of username buffer */
920 char *host
, /* O - Hostname */
921 int hostlen
, /* I - Size of hostname buffer */
922 int *port
, /* O - Port number to use */
923 char *resource
, /* O - Resource/filename */
924 int resourcelen
) /* I - Size of resource buffer */
926 httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, schemelen
, username
,
927 usernamelen
, host
, hostlen
, port
, resource
, resourcelen
);
932 * 'httpSeparateURI()' - Separate a Universal Resource Identifier into its
935 * @since CUPS 1.2/macOS 10.5@
938 http_uri_status_t
/* O - Result of separation */
940 http_uri_coding_t decoding
, /* I - Decoding flags */
941 const char *uri
, /* I - Universal Resource Identifier */
942 char *scheme
, /* O - Scheme (http, https, etc.) */
943 int schemelen
, /* I - Size of scheme buffer */
944 char *username
, /* O - Username */
945 int usernamelen
, /* I - Size of username buffer */
946 char *host
, /* O - Hostname */
947 int hostlen
, /* I - Size of hostname buffer */
948 int *port
, /* O - Port number to use */
949 char *resource
, /* O - Resource/filename */
950 int resourcelen
) /* I - Size of resource buffer */
952 char *ptr
, /* Pointer into string... */
953 *end
; /* End of string */
954 const char *sep
; /* Separator character */
955 http_uri_status_t status
; /* Result of separation */
959 * Initialize everything to blank...
962 if (scheme
&& schemelen
> 0)
965 if (username
&& usernamelen
> 0)
968 if (host
&& hostlen
> 0)
974 if (resource
&& resourcelen
> 0)
978 * Range check input...
981 if (!uri
|| !port
|| !scheme
|| schemelen
<= 0 || !username
||
982 usernamelen
<= 0 || !host
|| hostlen
<= 0 || !resource
||
984 return (HTTP_URI_STATUS_BAD_ARGUMENTS
);
987 return (HTTP_URI_STATUS_BAD_URI
);
990 * Grab the scheme portion of the URI...
993 status
= HTTP_URI_STATUS_OK
;
995 if (!strncmp(uri
, "//", 2))
998 * Workaround for HP IPP client bug...
1001 strlcpy(scheme
, "ipp", (size_t)schemelen
);
1002 status
= HTTP_URI_STATUS_MISSING_SCHEME
;
1004 else if (*uri
== '/')
1010 strlcpy(scheme
, "file", (size_t)schemelen
);
1011 status
= HTTP_URI_STATUS_MISSING_SCHEME
;
1016 * Standard URI with scheme...
1019 for (ptr
= scheme
, end
= scheme
+ schemelen
- 1;
1020 *uri
&& *uri
!= ':' && ptr
< end
;)
1021 if (strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1022 "abcdefghijklmnopqrstuvwxyz"
1023 "0123456789-+.", *uri
) != NULL
)
1030 if (*uri
!= ':' || *scheme
== '.' || !*scheme
)
1033 return (HTTP_URI_STATUS_BAD_SCHEME
);
1040 * Set the default port number...
1043 if (!strcmp(scheme
, "http"))
1045 else if (!strcmp(scheme
, "https"))
1047 else if (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps"))
1049 else if (!_cups_strcasecmp(scheme
, "lpd"))
1051 else if (!strcmp(scheme
, "socket")) /* Not yet registered with IANA... */
1053 else if (strcmp(scheme
, "file") && strcmp(scheme
, "mailto") && strcmp(scheme
, "tel"))
1054 status
= HTTP_URI_STATUS_UNKNOWN_SCHEME
;
1057 * Now see if we have a hostname...
1060 if (!strncmp(uri
, "//", 2))
1063 * Yes, extract it...
1069 * Grab the username, if any...
1072 if ((sep
= strpbrk(uri
, "@/")) != NULL
&& *sep
== '@')
1075 * Get a username:password combo...
1078 uri
= http_copy_decode(username
, uri
, usernamelen
, "@",
1079 decoding
& HTTP_URI_CODING_USERNAME
);
1084 return (HTTP_URI_STATUS_BAD_USERNAME
);
1091 * Then the hostname/IP address...
1097 * Grab IPv6 address...
1104 * Skip IPvFuture ("vXXXX.") prefix...
1109 while (isxdigit(*uri
& 255))
1115 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1121 uri
= http_copy_decode(host
, uri
, hostlen
, "]",
1122 decoding
& HTTP_URI_CODING_HOSTNAME
);
1127 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1137 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1142 for (ptr
= host
; *ptr
; ptr
++)
1146 * Convert zone separator to % and stop here...
1152 else if (*ptr
== '%')
1155 * Stop at zone separator (RFC 6874)
1160 else if (*ptr
!= ':' && *ptr
!= '.' && !isxdigit(*ptr
& 255))
1163 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1169 * Validate the hostname or IPv4 address first...
1172 for (ptr
= (char *)uri
; *ptr
; ptr
++)
1173 if (strchr(":?/", *ptr
))
1175 else if (!strchr("abcdefghijklmnopqrstuvwxyz" /* unreserved */
1176 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" /* unreserved */
1177 "0123456789" /* unreserved */
1178 "-._~" /* unreserved */
1179 "%" /* pct-encoded */
1180 "!$&'()*+,;=" /* sub-delims */
1181 "\\", *ptr
)) /* SMB domain */
1184 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1188 * Then copy the hostname or IPv4 address to the buffer...
1191 uri
= http_copy_decode(host
, uri
, hostlen
, ":?/",
1192 decoding
& HTTP_URI_CODING_HOSTNAME
);
1197 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1202 * Validate hostname for file scheme - only empty and localhost are
1206 if (!strcmp(scheme
, "file") && strcmp(host
, "localhost") && host
[0])
1209 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1213 * See if we have a port number...
1219 * Yes, collect the port number...
1222 if (!isdigit(uri
[1] & 255))
1225 return (HTTP_URI_STATUS_BAD_PORT
);
1228 *port
= (int)strtol(uri
+ 1, (char **)&uri
, 10);
1230 if (*port
<= 0 || *port
> 65535)
1233 return (HTTP_URI_STATUS_BAD_PORT
);
1236 if (*uri
!= '/' && *uri
)
1239 return (HTTP_URI_STATUS_BAD_PORT
);
1245 * The remaining portion is the resource string...
1248 if (*uri
== '?' || !*uri
)
1251 * Hostname but no path...
1254 status
= HTTP_URI_STATUS_MISSING_RESOURCE
;
1258 * Copy any query string...
1262 uri
= http_copy_decode(resource
+ 1, uri
, resourcelen
- 1, NULL
,
1263 decoding
& HTTP_URI_CODING_QUERY
);
1269 uri
= http_copy_decode(resource
, uri
, resourcelen
, "?",
1270 decoding
& HTTP_URI_CODING_RESOURCE
);
1272 if (uri
&& *uri
== '?')
1275 * Concatenate any query string...
1278 char *resptr
= resource
+ strlen(resource
);
1280 uri
= http_copy_decode(resptr
, uri
,
1281 resourcelen
- (int)(resptr
- resource
), NULL
,
1282 decoding
& HTTP_URI_CODING_QUERY
);
1289 return (HTTP_URI_STATUS_BAD_RESOURCE
);
1293 * Return the URI separation status...
1301 * '_httpSetDigestAuthString()' - Calculate a Digest authentication response
1302 * using the appropriate RFC 2068/2617/7616
1306 int /* O - 1 on success, 0 on failure */
1307 _httpSetDigestAuthString(
1308 http_t
*http
, /* I - HTTP connection */
1309 const char *nonce
, /* I - Nonce value */
1310 const char *method
, /* I - HTTP method */
1311 const char *resource
) /* I - HTTP resource path */
1313 char kd
[65], /* Final MD5/SHA-256 digest */
1314 ha1
[65], /* Hash of username:realm:password */
1315 ha2
[65], /* Hash of method:request-uri */
1316 username
[HTTP_MAX_VALUE
],
1317 /* username:password */
1318 *password
, /* Pointer to password */
1319 temp
[1024], /* Temporary string */
1320 digest
[1024]; /* Digest auth data */
1321 unsigned char hash
[32]; /* Hash buffer */
1322 size_t hashsize
; /* Size of hash */
1325 DEBUG_printf(("2_httpSetDigestAuthString(http=%p, nonce=\"%s\", method=\"%s\", resource=\"%s\")", http
, nonce
, method
, resource
));
1327 if (nonce
&& *nonce
&& strcmp(nonce
, http
->nonce
))
1329 strlcpy(http
->nonce
, nonce
, sizeof(http
->nonce
));
1331 if (nonce
== http
->nextnonce
)
1332 http
->nextnonce
[0] = '\0';
1334 http
->nonce_count
= 1;
1337 http
->nonce_count
++;
1339 strlcpy(username
, http
->userpass
, sizeof(username
));
1340 if ((password
= strchr(username
, ':')) != NULL
)
1345 if (http
->algorithm
[0])
1348 * Follow RFC 2617/7616...
1351 int i
; /* Looping var */
1352 char cnonce
[65]; /* cnonce value */
1353 const char *hashalg
; /* Hashing algorithm */
1355 for (i
= 0; i
< 64; i
++)
1356 cnonce
[i
] = "0123456789ABCDEF"[CUPS_RAND() & 15];
1359 if (!_cups_strcasecmp(http
->algorithm
, "MD5"))
1362 * RFC 2617 Digest with MD5
1367 else if (!_cups_strcasecmp(http
->algorithm
, "SHA-256"))
1370 * RFC 7616 Digest with SHA-256
1373 hashalg
= "sha2-256";
1378 * Some other algorithm we don't support, skip this one...
1385 * Calculate digest value...
1388 /* H(A1) = H(username:realm:password) */
1389 snprintf(temp
, sizeof(temp
), "%s:%s:%s", username
, http
->realm
, password
);
1390 hashsize
= (size_t)cupsHashData(hashalg
, (unsigned char *)temp
, strlen(temp
), hash
, sizeof(hash
));
1391 cupsHashString(hash
, hashsize
, ha1
, sizeof(ha1
));
1393 /* H(A2) = H(method:uri) */
1394 snprintf(temp
, sizeof(temp
), "%s:%s", method
, resource
);
1395 hashsize
= (size_t)cupsHashData(hashalg
, (unsigned char *)temp
, strlen(temp
), hash
, sizeof(hash
));
1396 cupsHashString(hash
, hashsize
, ha2
, sizeof(ha2
));
1398 /* KD = H(H(A1):nonce:nc:cnonce:qop:H(A2)) */
1399 snprintf(temp
, sizeof(temp
), "%s:%s:%08x:%s:%s:%s", ha1
, http
->nonce
, http
->nonce_count
, cnonce
, "auth", ha2
);
1400 hashsize
= (size_t)cupsHashData(hashalg
, (unsigned char *)temp
, strlen(temp
), hash
, sizeof(hash
));
1401 cupsHashString(hash
, hashsize
, kd
, sizeof(kd
));
1404 * Pass the RFC 2617/7616 WWW-Authenticate header...
1407 if (http
->opaque
[0])
1408 snprintf(digest
, sizeof(digest
), "username=\"%s\", realm=\"%s\", nonce=\"%s\", algorithm=%s, qop=auth, opaque=\"%s\", cnonce=\"%s\", nc=%08x, uri=\"%s\", response=\"%s\"", cupsUser(), http
->realm
, http
->nonce
, http
->algorithm
, http
->opaque
, cnonce
, http
->nonce_count
, resource
, kd
);
1410 snprintf(digest
, sizeof(digest
), "username=\"%s\", realm=\"%s\", nonce=\"%s\", algorithm=%s, qop=auth, cnonce=\"%s\", nc=%08x, uri=\"%s\", response=\"%s\"", username
, http
->realm
, http
->nonce
, http
->algorithm
, cnonce
, http
->nonce_count
, resource
, kd
);
1415 * Use old RFC 2069 Digest method...
1418 /* H(A1) = H(username:realm:password) */
1419 snprintf(temp
, sizeof(temp
), "%s:%s:%s", username
, http
->realm
, password
);
1420 hashsize
= (size_t)cupsHashData("md5", (unsigned char *)temp
, strlen(temp
), hash
, sizeof(hash
));
1421 cupsHashString(hash
, hashsize
, ha1
, sizeof(ha1
));
1423 /* H(A2) = H(method:uri) */
1424 snprintf(temp
, sizeof(temp
), "%s:%s", method
, resource
);
1425 hashsize
= (size_t)cupsHashData("md5", (unsigned char *)temp
, strlen(temp
), hash
, sizeof(hash
));
1426 cupsHashString(hash
, hashsize
, ha2
, sizeof(ha2
));
1428 /* KD = H(H(A1):nonce:H(A2)) */
1429 snprintf(temp
, sizeof(temp
), "%s:%s:%s", ha1
, http
->nonce
, ha2
);
1430 hashsize
= (size_t)cupsHashData("md5", (unsigned char *)temp
, strlen(temp
), hash
, sizeof(hash
));
1431 cupsHashString(hash
, hashsize
, kd
, sizeof(kd
));
1434 * Pass the old RFC 2069 WWW-Authenticate header...
1437 snprintf(digest
, sizeof(digest
), "username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"", username
, http
->realm
, http
->nonce
, resource
, kd
);
1440 httpSetAuthString(http
, "Digest", digest
);
1447 * 'httpStateString()' - Return the string describing a HTTP state value.
1449 * @since CUPS 2.0/OS 10.10@
1452 const char * /* O - State string */
1453 httpStateString(http_state_t state
) /* I - HTTP state value */
1455 if (state
< HTTP_STATE_ERROR
|| state
> HTTP_STATE_UNKNOWN_VERSION
)
1456 return ("HTTP_STATE_???");
1458 return (http_states
[state
- HTTP_STATE_ERROR
]);
1463 * '_httpStatus()' - Return the localized string describing a HTTP status code.
1465 * The returned string is localized using the passed message catalog.
1468 const char * /* O - Localized status string */
1469 _httpStatus(cups_lang_t
*lang
, /* I - Language */
1470 http_status_t status
) /* I - HTTP status code */
1472 const char *s
; /* Status string */
1477 case HTTP_STATUS_ERROR
:
1478 s
= strerror(errno
);
1480 case HTTP_STATUS_CONTINUE
:
1483 case HTTP_STATUS_SWITCHING_PROTOCOLS
:
1484 s
= _("Switching Protocols");
1486 case HTTP_STATUS_OK
:
1489 case HTTP_STATUS_CREATED
:
1492 case HTTP_STATUS_ACCEPTED
:
1495 case HTTP_STATUS_NO_CONTENT
:
1496 s
= _("No Content");
1498 case HTTP_STATUS_MOVED_PERMANENTLY
:
1499 s
= _("Moved Permanently");
1501 case HTTP_STATUS_FOUND
:
1504 case HTTP_STATUS_SEE_OTHER
:
1507 case HTTP_STATUS_NOT_MODIFIED
:
1508 s
= _("Not Modified");
1510 case HTTP_STATUS_BAD_REQUEST
:
1511 s
= _("Bad Request");
1513 case HTTP_STATUS_UNAUTHORIZED
:
1514 case HTTP_STATUS_CUPS_AUTHORIZATION_CANCELED
:
1515 s
= _("Unauthorized");
1517 case HTTP_STATUS_FORBIDDEN
:
1520 case HTTP_STATUS_NOT_FOUND
:
1523 case HTTP_STATUS_REQUEST_TOO_LARGE
:
1524 s
= _("Request Entity Too Large");
1526 case HTTP_STATUS_URI_TOO_LONG
:
1527 s
= _("URI Too Long");
1529 case HTTP_STATUS_UPGRADE_REQUIRED
:
1530 s
= _("Upgrade Required");
1532 case HTTP_STATUS_NOT_IMPLEMENTED
:
1533 s
= _("Not Implemented");
1535 case HTTP_STATUS_NOT_SUPPORTED
:
1536 s
= _("Not Supported");
1538 case HTTP_STATUS_EXPECTATION_FAILED
:
1539 s
= _("Expectation Failed");
1541 case HTTP_STATUS_SERVICE_UNAVAILABLE
:
1542 s
= _("Service Unavailable");
1544 case HTTP_STATUS_SERVER_ERROR
:
1545 s
= _("Internal Server Error");
1547 case HTTP_STATUS_CUPS_PKI_ERROR
:
1548 s
= _("SSL/TLS Negotiation Error");
1550 case HTTP_STATUS_CUPS_WEBIF_DISABLED
:
1551 s
= _("Web Interface is Disabled");
1559 return (_cupsLangString(lang
, s
));
1564 * 'httpStatus()' - Return a short string describing a HTTP status code.
1566 * The returned string is localized to the current POSIX locale and is based
1567 * on the status strings defined in RFC 7231.
1570 const char * /* O - Localized status string */
1571 httpStatus(http_status_t status
) /* I - HTTP status code */
1573 _cups_globals_t
*cg
= _cupsGlobals(); /* Global data */
1576 if (!cg
->lang_default
)
1577 cg
->lang_default
= cupsLangDefault();
1579 return (_httpStatus(cg
->lang_default
, status
));
1583 * 'httpURIStatusString()' - Return a string describing a URI status code.
1585 * @since CUPS 2.0/OS 10.10@
1588 const char * /* O - Localized status string */
1589 httpURIStatusString(
1590 http_uri_status_t status
) /* I - URI status code */
1592 const char *s
; /* Status string */
1593 _cups_globals_t
*cg
= _cupsGlobals(); /* Global data */
1596 if (!cg
->lang_default
)
1597 cg
->lang_default
= cupsLangDefault();
1601 case HTTP_URI_STATUS_OVERFLOW
:
1602 s
= _("URI too large");
1604 case HTTP_URI_STATUS_BAD_ARGUMENTS
:
1605 s
= _("Bad arguments to function");
1607 case HTTP_URI_STATUS_BAD_RESOURCE
:
1608 s
= _("Bad resource in URI");
1610 case HTTP_URI_STATUS_BAD_PORT
:
1611 s
= _("Bad port number in URI");
1613 case HTTP_URI_STATUS_BAD_HOSTNAME
:
1614 s
= _("Bad hostname/address in URI");
1616 case HTTP_URI_STATUS_BAD_USERNAME
:
1617 s
= _("Bad username in URI");
1619 case HTTP_URI_STATUS_BAD_SCHEME
:
1620 s
= _("Bad scheme in URI");
1622 case HTTP_URI_STATUS_BAD_URI
:
1623 s
= _("Bad/empty URI");
1625 case HTTP_URI_STATUS_OK
:
1628 case HTTP_URI_STATUS_MISSING_SCHEME
:
1629 s
= _("Missing scheme in URI");
1631 case HTTP_URI_STATUS_UNKNOWN_SCHEME
:
1632 s
= _("Unknown scheme in URI");
1634 case HTTP_URI_STATUS_MISSING_RESOURCE
:
1635 s
= _("Missing resource in URI");
1643 return (_cupsLangString(cg
->lang_default
, s
));
1647 #ifndef HAVE_HSTRERROR
1649 * '_cups_hstrerror()' - hstrerror() emulation function for Solaris and others.
1652 const char * /* O - Error string */
1653 _cups_hstrerror(int error
) /* I - Error number */
1655 static const char * const errors
[] = /* Error strings */
1660 "Unrecoverable lookup error.",
1661 "No data associated with name."
1665 if (error
< 0 || error
> 4)
1666 return ("Unknown hostname lookup error.");
1668 return (errors
[error
]);
1670 #endif /* !HAVE_HSTRERROR */
1674 * '_httpDecodeURI()' - Percent-decode a HTTP request URI.
1677 char * /* O - Decoded URI or NULL on error */
1678 _httpDecodeURI(char *dst
, /* I - Destination buffer */
1679 const char *src
, /* I - Source URI */
1680 size_t dstsize
) /* I - Size of destination buffer */
1682 if (http_copy_decode(dst
, src
, (int)dstsize
, NULL
, 1))
1690 * '_httpEncodeURI()' - Percent-encode a HTTP request URI.
1693 char * /* O - Encoded URI */
1694 _httpEncodeURI(char *dst
, /* I - Destination buffer */
1695 const char *src
, /* I - Source URI */
1696 size_t dstsize
) /* I - Size of destination buffer */
1698 http_copy_encode(dst
, src
, dst
+ dstsize
- 1, NULL
, NULL
, 1);
1704 * '_httpResolveURI()' - Resolve a DNS-SD URI.
1707 const char * /* O - Resolved URI */
1709 const char *uri
, /* I - DNS-SD URI */
1710 char *resolved_uri
, /* I - Buffer for resolved URI */
1711 size_t resolved_size
, /* I - Size of URI buffer */
1712 int options
, /* I - Resolve options */
1713 int (*cb
)(void *context
), /* I - Continue callback function */
1714 void *context
) /* I - Context pointer for callback */
1716 char scheme
[32], /* URI components... */
1722 http_uri_status_t status
; /* URI decode status */
1726 DEBUG_printf(("_httpResolveURI(uri=\"%s\", resolved_uri=%p, resolved_size=" CUPS_LLFMT
", options=0x%x, cb=%p, context=%p)", uri
, (void *)resolved_uri
, CUPS_LLCAST resolved_size
, options
, (void *)cb
, context
));
1729 * Get the device URI...
1733 if ((status
= httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
,
1734 sizeof(scheme
), userpass
, sizeof(userpass
),
1735 hostname
, sizeof(hostname
), &port
, resource
,
1736 sizeof(resource
))) < HTTP_URI_STATUS_OK
)
1738 if (httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
,
1739 sizeof(scheme
), userpass
, sizeof(userpass
),
1740 hostname
, sizeof(hostname
), &port
, resource
,
1741 sizeof(resource
)) < HTTP_URI_STATUS_OK
)
1744 if (options
& _HTTP_RESOLVE_STDERR
)
1745 _cupsLangPrintFilter(stderr
, "ERROR", _("Bad device-uri \"%s\"."), uri
);
1747 DEBUG_printf(("2_httpResolveURI: httpSeparateURI returned %d!", status
));
1748 DEBUG_puts("2_httpResolveURI: Returning NULL");
1753 * Resolve it as needed...
1756 if (strstr(hostname
, "._tcp"))
1758 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
1759 char *regtype
, /* Pointer to type in hostname */
1760 *domain
, /* Pointer to domain in hostname */
1761 *uuid
, /* Pointer to UUID in URI */
1762 *uuidend
; /* Pointer to end of UUID in URI */
1763 _http_uribuf_t uribuf
; /* URI buffer */
1764 int offline
= 0; /* offline-report state set? */
1767 # pragma comment(lib, "dnssd.lib")
1769 DNSServiceRef ref
, /* DNS-SD master service reference */
1770 domainref
= NULL
,/* DNS-SD service reference for domain */
1771 ippref
= NULL
, /* DNS-SD service reference for network IPP */
1772 ippsref
= NULL
, /* DNS-SD service reference for network IPPS */
1773 localref
; /* DNS-SD service reference for .local */
1774 int extrasent
= 0; /* Send the domain/IPP/IPPS resolves? */
1776 struct pollfd polldata
; /* Polling data */
1777 # else /* select() */
1778 fd_set input_set
; /* Input set for select() */
1779 struct timeval stimeout
; /* Timeout value for select() */
1780 # endif /* HAVE_POLL */
1781 # elif defined(HAVE_AVAHI)
1782 AvahiClient
*client
; /* Client information */
1783 int error
; /* Status */
1784 # endif /* HAVE_DNSSD */
1786 if (options
& _HTTP_RESOLVE_STDERR
)
1787 fprintf(stderr
, "DEBUG: Resolving \"%s\"...\n", hostname
);
1790 * Separate the hostname into service name, registration type, and domain...
1793 for (regtype
= strstr(hostname
, "._tcp") - 2;
1796 if (regtype
[0] == '.' && regtype
[1] == '_')
1799 * Found ._servicetype in front of ._tcp...
1806 if (regtype
<= hostname
)
1808 DEBUG_puts("2_httpResolveURI: Bad hostname, returning NULL");
1812 for (domain
= strchr(regtype
, '.');
1814 domain
= strchr(domain
+ 1, '.'))
1815 if (domain
[1] != '_')
1821 if ((uuid
= strstr(resource
, "?uuid=")) != NULL
)
1825 if ((uuidend
= strchr(uuid
, '&')) != NULL
)
1829 resolved_uri
[0] = '\0';
1831 uribuf
.buffer
= resolved_uri
;
1832 uribuf
.bufsize
= resolved_size
;
1833 uribuf
.options
= options
;
1834 uribuf
.resource
= resource
;
1837 DEBUG_printf(("2_httpResolveURI: Resolving hostname=\"%s\", regtype=\"%s\", "
1838 "domain=\"%s\"\n", hostname
, regtype
, domain
));
1839 if (options
& _HTTP_RESOLVE_STDERR
)
1841 fputs("STATE: +connecting-to-device\n", stderr
);
1842 fprintf(stderr
, "DEBUG: Resolving \"%s\", regtype=\"%s\", "
1843 "domain=\"local.\"...\n", hostname
, regtype
);
1849 if (DNSServiceCreateConnection(&ref
) == kDNSServiceErr_NoError
)
1851 uint32_t myinterface
= kDNSServiceInterfaceIndexAny
;
1852 /* Lookup on any interface */
1854 if (!strcmp(scheme
, "ippusb"))
1855 myinterface
= kDNSServiceInterfaceIndexLocalOnly
;
1858 if (DNSServiceResolve(&localref
,
1859 kDNSServiceFlagsShareConnection
, myinterface
,
1860 hostname
, regtype
, "local.", http_resolve_cb
,
1861 &uribuf
) == kDNSServiceErr_NoError
)
1863 int fds
; /* Number of ready descriptors */
1864 time_t timeout
, /* Poll timeout */
1865 start_time
= time(NULL
),/* Start time */
1866 end_time
= start_time
+ 90;
1869 while (time(NULL
) < end_time
)
1871 if (options
& _HTTP_RESOLVE_STDERR
)
1872 _cupsLangPrintFilter(stderr
, "INFO", _("Looking for printer."));
1874 if (cb
&& !(*cb
)(context
))
1876 DEBUG_puts("2_httpResolveURI: callback returned 0 (stop)");
1881 * Wakeup every 2 seconds to emit a "looking for printer" message...
1884 if ((timeout
= end_time
- time(NULL
)) > 2)
1888 polldata
.fd
= DNSServiceRefSockFD(ref
);
1889 polldata
.events
= POLLIN
;
1891 fds
= poll(&polldata
, 1, (int)(1000 * timeout
));
1893 # else /* select() */
1894 FD_ZERO(&input_set
);
1895 FD_SET(DNSServiceRefSockFD(ref
), &input_set
);
1898 stimeout
.tv_sec
= (long)timeout
;
1900 stimeout
.tv_sec
= timeout
;
1902 stimeout
.tv_usec
= 0;
1904 fds
= select(DNSServiceRefSockFD(ref
)+1, &input_set
, NULL
, NULL
,
1906 # endif /* HAVE_POLL */
1910 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1912 DEBUG_printf(("2_httpResolveURI: poll error: %s", strerror(errno
)));
1919 * Wait 2 seconds for a response to the local resolve; if nothing
1920 * comes in, do an additional domain resolution...
1923 if (extrasent
== 0 && domain
&& _cups_strcasecmp(domain
, "local."))
1925 if (options
& _HTTP_RESOLVE_STDERR
)
1927 "DEBUG: Resolving \"%s\", regtype=\"%s\", "
1928 "domain=\"%s\"...\n", hostname
, regtype
,
1929 domain
? domain
: "");
1932 if (DNSServiceResolve(&domainref
,
1933 kDNSServiceFlagsShareConnection
,
1934 myinterface
, hostname
, regtype
, domain
,
1936 &uribuf
) == kDNSServiceErr_NoError
)
1939 else if (extrasent
== 0 && !strcmp(scheme
, "ippusb"))
1941 if (options
& _HTTP_RESOLVE_STDERR
)
1942 fprintf(stderr
, "DEBUG: Resolving \"%s\", regtype=\"_ipps._tcp\", domain=\"local.\"...\n", hostname
);
1945 if (DNSServiceResolve(&ippsref
,
1946 kDNSServiceFlagsShareConnection
,
1947 kDNSServiceInterfaceIndexAny
, hostname
,
1948 "_ipps._tcp", domain
, http_resolve_cb
,
1949 &uribuf
) == kDNSServiceErr_NoError
)
1952 else if (extrasent
== 1 && !strcmp(scheme
, "ippusb"))
1954 if (options
& _HTTP_RESOLVE_STDERR
)
1955 fprintf(stderr
, "DEBUG: Resolving \"%s\", regtype=\"_ipp._tcp\", domain=\"local.\"...\n", hostname
);
1958 if (DNSServiceResolve(&ippref
,
1959 kDNSServiceFlagsShareConnection
,
1960 kDNSServiceInterfaceIndexAny
, hostname
,
1961 "_ipp._tcp", domain
, http_resolve_cb
,
1962 &uribuf
) == kDNSServiceErr_NoError
)
1967 * If it hasn't resolved within 5 seconds set the offline-report
1968 * printer-state-reason...
1971 if ((options
& _HTTP_RESOLVE_STDERR
) && offline
== 0 &&
1972 time(NULL
) > (start_time
+ 5))
1974 fputs("STATE: +offline-report\n", stderr
);
1980 if (DNSServiceProcessResult(ref
) == kDNSServiceErr_NoError
&&
1992 DNSServiceRefDeallocate(domainref
);
1994 DNSServiceRefDeallocate(ippref
);
1996 DNSServiceRefDeallocate(ippsref
);
1999 DNSServiceRefDeallocate(localref
);
2002 DNSServiceRefDeallocate(ref
);
2004 # else /* HAVE_AVAHI */
2005 if ((uribuf
.poll
= avahi_simple_poll_new()) != NULL
)
2007 avahi_simple_poll_set_func(uribuf
.poll
, http_poll_cb
, NULL
);
2009 if ((client
= avahi_client_new(avahi_simple_poll_get(uribuf
.poll
),
2011 &uribuf
, &error
)) != NULL
)
2013 if (avahi_service_resolver_new(client
, AVAHI_IF_UNSPEC
,
2014 AVAHI_PROTO_UNSPEC
, hostname
,
2015 regtype
, "local.", AVAHI_PROTO_UNSPEC
, 0,
2016 http_resolve_cb
, &uribuf
) != NULL
)
2018 time_t start_time
= time(NULL
),
2020 end_time
= start_time
+ 90;
2022 int pstatus
; /* Poll status */
2024 pstatus
= avahi_simple_poll_iterate(uribuf
.poll
, 2000);
2026 if (pstatus
== 0 && !resolved_uri
[0] && domain
&&
2027 _cups_strcasecmp(domain
, "local."))
2030 * Resolve for .local hasn't returned anything, try the listed
2034 avahi_service_resolver_new(client
, AVAHI_IF_UNSPEC
,
2035 AVAHI_PROTO_UNSPEC
, hostname
,
2036 regtype
, domain
, AVAHI_PROTO_UNSPEC
, 0,
2037 http_resolve_cb
, &uribuf
);
2040 while (!pstatus
&& !resolved_uri
[0] && time(NULL
) < end_time
)
2042 if ((pstatus
= avahi_simple_poll_iterate(uribuf
.poll
, 2000)) != 0)
2046 * If it hasn't resolved within 5 seconds set the offline-report
2047 * printer-state-reason...
2050 if ((options
& _HTTP_RESOLVE_STDERR
) && offline
== 0 &&
2051 time(NULL
) > (start_time
+ 5))
2053 fputs("STATE: +offline-report\n", stderr
);
2059 * Collect the result (if we got one).
2062 if (resolved_uri
[0])
2066 avahi_client_free(client
);
2069 avahi_simple_poll_free(uribuf
.poll
);
2071 # endif /* HAVE_DNSSD */
2073 if (options
& _HTTP_RESOLVE_STDERR
)
2077 fprintf(stderr
, "DEBUG: Resolved as \"%s\"...\n", uri
);
2078 fputs("STATE: -connecting-to-device,offline-report\n", stderr
);
2082 fputs("DEBUG: Unable to resolve URI\n", stderr
);
2083 fputs("STATE: -connecting-to-device\n", stderr
);
2087 #else /* HAVE_DNSSD || HAVE_AVAHI */
2089 * No DNS-SD support...
2093 #endif /* HAVE_DNSSD || HAVE_AVAHI */
2095 if ((options
& _HTTP_RESOLVE_STDERR
) && !uri
)
2096 _cupsLangPrintFilter(stderr
, "INFO", _("Unable to find printer."));
2101 * Nothing more to do...
2104 strlcpy(resolved_uri
, uri
, resolved_size
);
2108 DEBUG_printf(("2_httpResolveURI: Returning \"%s\"", uri
));
2116 * 'http_client_cb()' - Client callback for resolving URI.
2121 AvahiClient
*client
, /* I - Client information */
2122 AvahiClientState state
, /* I - Current state */
2123 void *context
) /* I - Pointer to URI buffer */
2125 DEBUG_printf(("7http_client_cb(client=%p, state=%d, context=%p)", client
,
2129 * If the connection drops, quit.
2132 if (state
== AVAHI_CLIENT_FAILURE
)
2134 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
2137 avahi_simple_poll_quit(uribuf
->poll
);
2140 #endif /* HAVE_AVAHI */
2144 * 'http_copy_decode()' - Copy and decode a URI.
2147 static const char * /* O - New source pointer or NULL on error */
2148 http_copy_decode(char *dst
, /* O - Destination buffer */
2149 const char *src
, /* I - Source pointer */
2150 int dstsize
, /* I - Destination size */
2151 const char *term
, /* I - Terminating characters */
2152 int decode
) /* I - Decode %-encoded values */
2154 char *ptr
, /* Pointer into buffer */
2155 *end
; /* End of buffer */
2156 int quoted
; /* Quoted character */
2160 * Copy the src to the destination until we hit a terminating character
2161 * or the end of the string.
2164 for (ptr
= dst
, end
= dst
+ dstsize
- 1;
2165 *src
&& (!term
|| !strchr(term
, *src
));
2169 if (*src
== '%' && decode
)
2171 if (isxdigit(src
[1] & 255) && isxdigit(src
[2] & 255))
2174 * Grab a hex-encoded character...
2179 quoted
= (tolower(*src
) - 'a' + 10) << 4;
2181 quoted
= (*src
- '0') << 4;
2185 quoted
|= tolower(*src
) - 'a' + 10;
2187 quoted
|= *src
- '0';
2189 *ptr
++ = (char)quoted
;
2194 * Bad hex-encoded character...
2201 else if ((*src
& 255) <= 0x20 || (*src
& 255) >= 0x7f)
2217 * 'http_copy_encode()' - Copy and encode a URI.
2220 static char * /* O - End of current URI */
2221 http_copy_encode(char *dst
, /* O - Destination buffer */
2222 const char *src
, /* I - Source pointer */
2223 char *dstend
, /* I - End of destination buffer */
2224 const char *reserved
, /* I - Extra reserved characters */
2225 const char *term
, /* I - Terminating characters */
2226 int encode
) /* I - %-encode reserved chars? */
2228 static const char hex
[] = "0123456789ABCDEF";
2231 while (*src
&& dst
< dstend
)
2233 if (term
&& *src
== *term
)
2236 if (encode
&& (*src
== '%' || *src
<= ' ' || *src
& 128 ||
2237 (reserved
&& strchr(reserved
, *src
))))
2240 * Hex encode reserved characters...
2243 if ((dst
+ 2) >= dstend
)
2247 *dst
++ = hex
[(*src
>> 4) & 15];
2248 *dst
++ = hex
[*src
& 15];
2267 * 'http_resolve_cb()' - Build a device URI for the given service name.
2270 static void DNSSD_API
2272 DNSServiceRef sdRef
, /* I - Service reference */
2273 DNSServiceFlags flags
, /* I - Results flags */
2274 uint32_t interfaceIndex
, /* I - Interface number */
2275 DNSServiceErrorType errorCode
, /* I - Error, if any */
2276 const char *fullName
, /* I - Full service name */
2277 const char *hostTarget
, /* I - Hostname */
2278 uint16_t port
, /* I - Port number */
2279 uint16_t txtLen
, /* I - Length of TXT record */
2280 const unsigned char *txtRecord
, /* I - TXT record data */
2281 void *context
) /* I - Pointer to URI buffer */
2283 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
2285 const char *scheme
, /* URI scheme */
2286 *hostptr
, /* Pointer into hostTarget */
2287 *reskey
, /* "rp" or "rfo" */
2288 *resdefault
; /* Default path */
2289 char resource
[257], /* Remote path */
2290 fqdn
[256]; /* FQDN of the .local name */
2291 const void *value
; /* Value from TXT record */
2292 uint8_t valueLen
; /* Length of value */
2295 DEBUG_printf(("4http_resolve_cb(sdRef=%p, flags=%x, interfaceIndex=%u, errorCode=%d, fullName=\"%s\", hostTarget=\"%s\", port=%u, txtLen=%u, txtRecord=%p, context=%p)", (void *)sdRef
, flags
, interfaceIndex
, errorCode
, fullName
, hostTarget
, port
, txtLen
, (void *)txtRecord
, context
));
2298 * If we have a UUID, compare it...
2302 (value
= TXTRecordGetValuePtr(txtLen
, txtRecord
, "UUID",
2303 &valueLen
)) != NULL
)
2305 char uuid
[256]; /* UUID value */
2307 memcpy(uuid
, value
, valueLen
);
2308 uuid
[valueLen
] = '\0';
2310 if (_cups_strcasecmp(uuid
, uribuf
->uuid
))
2312 if (uribuf
->options
& _HTTP_RESOLVE_STDERR
)
2313 fprintf(stderr
, "DEBUG: Found UUID %s, looking for %s.", uuid
,
2316 DEBUG_printf(("5http_resolve_cb: Found UUID %s, looking for %s.", uuid
,
2323 * Figure out the scheme from the full name...
2326 if (strstr(fullName
, "._ipps") || strstr(fullName
, "._ipp-tls"))
2328 else if (strstr(fullName
, "._ipp") || strstr(fullName
, "._fax-ipp"))
2330 else if (strstr(fullName
, "._http."))
2332 else if (strstr(fullName
, "._https."))
2334 else if (strstr(fullName
, "._printer."))
2336 else if (strstr(fullName
, "._pdl-datastream."))
2339 scheme
= "riousbprint";
2342 * Extract the "remote printer" key from the TXT record...
2345 if ((uribuf
->options
& _HTTP_RESOLVE_FAXOUT
) &&
2346 (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")) &&
2347 !TXTRecordGetValuePtr(txtLen
, txtRecord
, "printer-type", &valueLen
))
2350 resdefault
= "/ipp/faxout";
2358 if ((value
= TXTRecordGetValuePtr(txtLen
, txtRecord
, reskey
,
2359 &valueLen
)) != NULL
)
2361 if (((char *)value
)[0] == '/')
2364 * Value (incorrectly) has a leading slash already...
2367 memcpy(resource
, value
, valueLen
);
2368 resource
[valueLen
] = '\0';
2373 * Convert to resource by concatenating with a leading "/"...
2377 memcpy(resource
+ 1, value
, valueLen
);
2378 resource
[valueLen
+ 1] = '\0';
2384 * Use the default value...
2387 strlcpy(resource
, resdefault
, sizeof(resource
));
2391 * Lookup the FQDN if needed...
2394 if ((uribuf
->options
& _HTTP_RESOLVE_FQDN
) &&
2395 (hostptr
= hostTarget
+ strlen(hostTarget
) - 7) > hostTarget
&&
2396 !_cups_strcasecmp(hostptr
, ".local."))
2399 * OK, we got a .local name but the caller needs a real domain. Start by
2400 * getting the IP address of the .local name and then do reverse-lookups...
2403 http_addrlist_t
*addrlist
, /* List of addresses */
2404 *addr
; /* Current address */
2406 DEBUG_printf(("5http_resolve_cb: Looking up \"%s\".", hostTarget
));
2408 snprintf(fqdn
, sizeof(fqdn
), "%d", ntohs(port
));
2409 if ((addrlist
= httpAddrGetList(hostTarget
, AF_UNSPEC
, fqdn
)) != NULL
)
2411 for (addr
= addrlist
; addr
; addr
= addr
->next
)
2413 int error
= getnameinfo(&(addr
->addr
.addr
), (socklen_t
)httpAddrLength(&(addr
->addr
)), fqdn
, sizeof(fqdn
), NULL
, 0, NI_NAMEREQD
);
2417 DEBUG_printf(("5http_resolve_cb: Found \"%s\".", fqdn
));
2419 if ((hostptr
= fqdn
+ strlen(fqdn
) - 6) <= fqdn
||
2420 _cups_strcasecmp(hostptr
, ".local"))
2428 DEBUG_printf(("5http_resolve_cb: \"%s\" did not resolve: %d",
2429 httpAddrString(&(addr
->addr
), fqdn
, sizeof(fqdn
)),
2434 httpAddrFreeList(addrlist
);
2439 * Assemble the final device URI...
2442 if ((!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")) &&
2443 !strcmp(uribuf
->resource
, "/cups"))
2444 httpAssembleURIf(HTTP_URI_CODING_ALL
, uribuf
->buffer
, (int)uribuf
->bufsize
, scheme
, NULL
, hostTarget
, ntohs(port
), "%s?snmp=false", resource
);
2446 httpAssembleURI(HTTP_URI_CODING_ALL
, uribuf
->buffer
, (int)uribuf
->bufsize
, scheme
, NULL
, hostTarget
, ntohs(port
), resource
);
2448 DEBUG_printf(("5http_resolve_cb: Resolved URI is \"%s\"...", uribuf
->buffer
));
2451 #elif defined(HAVE_AVAHI)
2453 * 'http_poll_cb()' - Wait for input on the specified file descriptors.
2455 * Note: This function is needed because avahi_simple_poll_iterate is broken
2456 * and always uses a timeout of 0 (!) milliseconds.
2457 * (Avahi Ticket #364)
2462 static int /* O - Number of file descriptors matching */
2464 struct pollfd
*pollfds
, /* I - File descriptors */
2465 unsigned int num_pollfds
, /* I - Number of file descriptors */
2466 int timeout
, /* I - Timeout in milliseconds (used) */
2467 void *context
) /* I - User data (unused) */
2472 return (poll(pollfds
, num_pollfds
, 2000));
2477 * 'http_resolve_cb()' - Build a device URI for the given service name.
2482 AvahiServiceResolver
*resolver
, /* I - Resolver (unused) */
2483 AvahiIfIndex interface
, /* I - Interface index (unused) */
2484 AvahiProtocol protocol
, /* I - Network protocol (unused) */
2485 AvahiResolverEvent event
, /* I - Event (found, etc.) */
2486 const char *name
, /* I - Service name */
2487 const char *type
, /* I - Registration type */
2488 const char *domain
, /* I - Domain (unused) */
2489 const char *hostTarget
, /* I - Hostname */
2490 const AvahiAddress
*address
, /* I - Address (unused) */
2491 uint16_t port
, /* I - Port number */
2492 AvahiStringList
*txt
, /* I - TXT record */
2493 AvahiLookupResultFlags flags
, /* I - Lookup flags (unused) */
2494 void *context
) /* I - Pointer to URI buffer */
2496 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
2498 const char *scheme
, /* URI scheme */
2499 *hostptr
, /* Pointer into hostTarget */
2500 *reskey
, /* "rp" or "rfo" */
2501 *resdefault
; /* Default path */
2502 char resource
[257], /* Remote path */
2503 fqdn
[256]; /* FQDN of the .local name */
2504 AvahiStringList
*pair
; /* Current TXT record key/value pair */
2505 char *value
; /* Value for "rp" key */
2506 size_t valueLen
= 0; /* Length of "rp" key */
2509 DEBUG_printf(("4http_resolve_cb(resolver=%p, "
2510 "interface=%d, protocol=%d, event=%d, name=\"%s\", "
2511 "type=\"%s\", domain=\"%s\", hostTarget=\"%s\", address=%p, "
2512 "port=%d, txt=%p, flags=%d, context=%p)",
2513 resolver
, interface
, protocol
, event
, name
, type
, domain
,
2514 hostTarget
, address
, port
, txt
, flags
, context
));
2516 if (event
!= AVAHI_RESOLVER_FOUND
)
2518 avahi_service_resolver_free(resolver
);
2519 avahi_simple_poll_quit(uribuf
->poll
);
2524 * If we have a UUID, compare it...
2527 if (uribuf
->uuid
&& (pair
= avahi_string_list_find(txt
, "UUID")) != NULL
)
2529 char uuid
[256]; /* UUID value */
2531 avahi_string_list_get_pair(pair
, NULL
, &value
, &valueLen
);
2533 memcpy(uuid
, value
, valueLen
);
2534 uuid
[valueLen
] = '\0';
2536 if (_cups_strcasecmp(uuid
, uribuf
->uuid
))
2538 if (uribuf
->options
& _HTTP_RESOLVE_STDERR
)
2539 fprintf(stderr
, "DEBUG: Found UUID %s, looking for %s.", uuid
,
2542 DEBUG_printf(("5http_resolve_cb: Found UUID %s, looking for %s.", uuid
,
2549 * Figure out the scheme from the full name...
2552 if (strstr(type
, "_ipp."))
2554 else if (strstr(type
, "_printer."))
2556 else if (strstr(type
, "_pdl-datastream."))
2559 scheme
= "riousbprint";
2561 if (!strncmp(type
, "_ipps.", 6) || !strncmp(type
, "_ipp-tls.", 9))
2563 else if (!strncmp(type
, "_ipp.", 5) || !strncmp(type
, "_fax-ipp.", 9))
2565 else if (!strncmp(type
, "_http.", 6))
2567 else if (!strncmp(type
, "_https.", 7))
2569 else if (!strncmp(type
, "_printer.", 9))
2571 else if (!strncmp(type
, "_pdl-datastream.", 16))
2575 avahi_service_resolver_free(resolver
);
2576 avahi_simple_poll_quit(uribuf
->poll
);
2581 * Extract the remote resource key from the TXT record...
2584 if ((uribuf
->options
& _HTTP_RESOLVE_FAXOUT
) &&
2585 (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")) &&
2586 !avahi_string_list_find(txt
, "printer-type"))
2589 resdefault
= "/ipp/faxout";
2597 if ((pair
= avahi_string_list_find(txt
, reskey
)) != NULL
)
2599 avahi_string_list_get_pair(pair
, NULL
, &value
, &valueLen
);
2601 if (value
[0] == '/')
2604 * Value (incorrectly) has a leading slash already...
2607 memcpy(resource
, value
, valueLen
);
2608 resource
[valueLen
] = '\0';
2613 * Convert to resource by concatenating with a leading "/"...
2617 memcpy(resource
+ 1, value
, valueLen
);
2618 resource
[valueLen
+ 1] = '\0';
2624 * Use the default value...
2627 strlcpy(resource
, resdefault
, sizeof(resource
));
2631 * Lookup the FQDN if needed...
2634 if ((uribuf
->options
& _HTTP_RESOLVE_FQDN
) &&
2635 (hostptr
= hostTarget
+ strlen(hostTarget
) - 6) > hostTarget
&&
2636 !_cups_strcasecmp(hostptr
, ".local"))
2639 * OK, we got a .local name but the caller needs a real domain. Start by
2640 * getting the IP address of the .local name and then do reverse-lookups...
2643 http_addrlist_t
*addrlist
, /* List of addresses */
2644 *addr
; /* Current address */
2646 DEBUG_printf(("5http_resolve_cb: Looking up \"%s\".", hostTarget
));
2648 snprintf(fqdn
, sizeof(fqdn
), "%d", ntohs(port
));
2649 if ((addrlist
= httpAddrGetList(hostTarget
, AF_UNSPEC
, fqdn
)) != NULL
)
2651 for (addr
= addrlist
; addr
; addr
= addr
->next
)
2653 int error
= getnameinfo(&(addr
->addr
.addr
), (socklen_t
)httpAddrLength(&(addr
->addr
)), fqdn
, sizeof(fqdn
), NULL
, 0, NI_NAMEREQD
);
2657 DEBUG_printf(("5http_resolve_cb: Found \"%s\".", fqdn
));
2659 if ((hostptr
= fqdn
+ strlen(fqdn
) - 6) <= fqdn
||
2660 _cups_strcasecmp(hostptr
, ".local"))
2668 DEBUG_printf(("5http_resolve_cb: \"%s\" did not resolve: %d",
2669 httpAddrString(&(addr
->addr
), fqdn
, sizeof(fqdn
)),
2674 httpAddrFreeList(addrlist
);
2679 * Assemble the final device URI using the resolved hostname...
2682 httpAssembleURI(HTTP_URI_CODING_ALL
, uribuf
->buffer
, (int)uribuf
->bufsize
, scheme
,
2683 NULL
, hostTarget
, port
, resource
);
2684 DEBUG_printf(("5http_resolve_cb: Resolved URI is \"%s\".", uribuf
->buffer
));
2686 avahi_simple_poll_quit(uribuf
->poll
);
2688 #endif /* HAVE_DNSSD */