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"
16 #include "debug-internal.h"
21 # elif defined(HAVE_POLL)
24 # include <sys/select.h>
26 #elif defined(HAVE_AVAHI)
27 # include <avahi-client/client.h>
28 # include <avahi-client/lookup.h>
29 # include <avahi-common/simple-watch.h>
30 #endif /* HAVE_DNSSD */
37 typedef struct _http_uribuf_s
/* URI buffer */
40 AvahiSimplePoll
*poll
; /* Poll state */
41 #endif /* HAVE_AVAHI */
42 char *buffer
; /* Pointer to buffer */
43 size_t bufsize
; /* Size of buffer */
44 int options
; /* Options passed to _httpResolveURI */
45 const char *resource
; /* Resource from URI */
46 const char *uuid
; /* UUID from URI */
54 static const char * const http_days
[7] =/* Days of the week */
64 static const char * const http_months
[12] =
65 { /* Months of the year */
79 static const char * const http_states
[] =
80 { /* HTTP state strings */
85 "HTTP_STATE_GET_SEND",
88 "HTTP_STATE_POST_RECV",
89 "HTTP_STATE_POST_SEND",
91 "HTTP_STATE_PUT_RECV",
96 "HTTP_STATE_UNKNOWN_METHOD",
97 "HTTP_STATE_UNKNOWN_VERSION"
105 static const char *http_copy_decode(char *dst
, const char *src
,
106 int dstsize
, const char *term
,
108 static char *http_copy_encode(char *dst
, const char *src
,
109 char *dstend
, const char *reserved
,
110 const char *term
, int encode
);
112 static void DNSSD_API
http_resolve_cb(DNSServiceRef sdRef
,
113 DNSServiceFlags flags
,
114 uint32_t interfaceIndex
,
115 DNSServiceErrorType errorCode
,
116 const char *fullName
,
117 const char *hostTarget
,
118 uint16_t port
, uint16_t txtLen
,
119 const unsigned char *txtRecord
,
121 #endif /* HAVE_DNSSD */
124 static void http_client_cb(AvahiClient
*client
,
125 AvahiClientState state
, void *simple_poll
);
126 static int http_poll_cb(struct pollfd
*pollfds
, unsigned int num_pollfds
,
127 int timeout
, void *context
);
128 static void http_resolve_cb(AvahiServiceResolver
*resolver
,
129 AvahiIfIndex interface
,
130 AvahiProtocol protocol
,
131 AvahiResolverEvent event
,
132 const char *name
, const char *type
,
133 const char *domain
, const char *host_name
,
134 const AvahiAddress
*address
, uint16_t port
,
135 AvahiStringList
*txt
,
136 AvahiLookupResultFlags flags
, void *context
);
137 #endif /* HAVE_AVAHI */
141 * 'httpAssembleURI()' - Assemble a uniform resource identifier from its
144 * This function escapes reserved characters in the URI depending on the
145 * value of the "encoding" argument. You should use this function in
146 * place of traditional string functions whenever you need to create a
149 * @since CUPS 1.2/macOS 10.5@
152 http_uri_status_t
/* O - URI status */
154 http_uri_coding_t encoding
, /* I - Encoding flags */
155 char *uri
, /* I - URI buffer */
156 int urilen
, /* I - Size of URI buffer */
157 const char *scheme
, /* I - Scheme name */
158 const char *username
, /* I - Username */
159 const char *host
, /* I - Hostname or address */
160 int port
, /* I - Port number */
161 const char *resource
) /* I - Resource */
163 char *ptr
, /* Pointer into URI buffer */
164 *end
; /* End of URI buffer */
168 * Range check input...
171 if (!uri
|| urilen
< 1 || !scheme
|| port
< 0)
176 return (HTTP_URI_STATUS_BAD_ARGUMENTS
);
180 * Assemble the URI starting with the scheme...
183 end
= uri
+ urilen
- 1;
184 ptr
= http_copy_encode(uri
, scheme
, end
, NULL
, NULL
, 0);
187 goto assemble_overflow
;
189 if (!strcmp(scheme
, "geo") || !strcmp(scheme
, "mailto") || !strcmp(scheme
, "tel"))
192 * geo:, mailto:, and tel: only have :, no //...
198 goto assemble_overflow
;
203 * Schemes other than geo:, mailto:, and tel: typically have //...
213 goto assemble_overflow
;
217 * Next the username and hostname, if any...
222 const char *hostptr
; /* Pointer into hostname */
223 int have_ipv6
; /* Do we have an IPv6 address? */
225 if (username
&& *username
)
228 * Add username@ first...
231 ptr
= http_copy_encode(ptr
, username
, end
, "/?#[]@", NULL
,
232 encoding
& HTTP_URI_CODING_USERNAME
);
235 goto assemble_overflow
;
240 goto assemble_overflow
;
244 * Then add the hostname. Since IPv6 is a particular pain to deal
245 * with, we have several special cases to deal with. If we get
246 * an IPv6 address with brackets around it, assume it is already in
247 * URI format. Since DNS-SD service names can sometimes look like
248 * raw IPv6 addresses, we specifically look for "._tcp" in the name,
253 have_ipv6
= strchr(host
, ':') && !strstr(host
, "._tcp");
254 *hostptr
&& have_ipv6
;
256 if (*hostptr
!= ':' && !isxdigit(*hostptr
& 255))
258 have_ipv6
= *hostptr
== '%';
265 * We have a raw IPv6 address...
268 if (strchr(host
, '%') && !(encoding
& HTTP_URI_CODING_RFC6874
))
271 * We have a link-local address, add "[v1." prefix...
282 goto assemble_overflow
;
287 * We have a normal (or RFC 6874 link-local) address, add "[" prefix...
293 goto assemble_overflow
;
297 * Copy the rest of the IPv6 address, and terminate with "]".
300 while (ptr
< end
&& *host
)
305 * Convert/encode zone separator
308 if (encoding
& HTTP_URI_CODING_RFC6874
)
310 if (ptr
>= (end
- 2))
311 goto assemble_overflow
;
327 goto assemble_overflow
;
332 goto assemble_overflow
;
337 * Otherwise, just copy the host string (the extra chars are not in the
338 * "reg-name" ABNF rule; anything <= SP or >= DEL plus % gets automatically
342 ptr
= http_copy_encode(ptr
, host
, end
, "\"#/:<>?@[\\]^`{|}", NULL
,
343 encoding
& HTTP_URI_CODING_HOSTNAME
);
346 goto assemble_overflow
;
350 * Finish things off with the port number...
355 snprintf(ptr
, (size_t)(end
- ptr
+ 1), ":%d", port
);
359 goto assemble_overflow
;
364 * Last but not least, add the resource string...
369 char *query
; /* Pointer to query string */
373 * Copy the resource string up to the query string if present...
376 query
= strchr(resource
, '?');
377 ptr
= http_copy_encode(ptr
, resource
, end
, NULL
, "?",
378 encoding
& HTTP_URI_CODING_RESOURCE
);
380 goto assemble_overflow
;
385 * Copy query string without encoding...
388 ptr
= http_copy_encode(ptr
, query
, end
, NULL
, NULL
,
389 encoding
& HTTP_URI_CODING_QUERY
);
391 goto assemble_overflow
;
397 goto assemble_overflow
;
400 * Nul-terminate the URI buffer and return with no errors...
405 return (HTTP_URI_STATUS_OK
);
408 * Clear the URI string and return an overflow error; I don't usually
409 * like goto's, but in this case it makes sense...
415 return (HTTP_URI_STATUS_OVERFLOW
);
420 * 'httpAssembleURIf()' - Assemble a uniform resource identifier from its
421 * components with a formatted resource.
423 * This function creates a formatted version of the resource string
424 * argument "resourcef" and escapes reserved characters in the URI
425 * depending on the value of the "encoding" argument. You should use
426 * this function in place of traditional string functions whenever
427 * you need to create a URI string.
429 * @since CUPS 1.2/macOS 10.5@
432 http_uri_status_t
/* O - URI status */
434 http_uri_coding_t encoding
, /* I - Encoding flags */
435 char *uri
, /* I - URI buffer */
436 int urilen
, /* I - Size of URI buffer */
437 const char *scheme
, /* I - Scheme name */
438 const char *username
, /* I - Username */
439 const char *host
, /* I - Hostname or address */
440 int port
, /* I - Port number */
441 const char *resourcef
, /* I - Printf-style resource */
442 ...) /* I - Additional arguments as needed */
444 va_list ap
; /* Pointer to additional arguments */
445 char resource
[1024]; /* Formatted resource string */
446 int bytes
; /* Bytes in formatted string */
450 * Range check input...
453 if (!uri
|| urilen
< 1 || !scheme
|| port
< 0 || !resourcef
)
458 return (HTTP_URI_STATUS_BAD_ARGUMENTS
);
462 * Format the resource string and assemble the URI...
465 va_start(ap
, resourcef
);
466 bytes
= vsnprintf(resource
, sizeof(resource
), resourcef
, ap
);
469 if ((size_t)bytes
>= sizeof(resource
))
472 return (HTTP_URI_STATUS_OVERFLOW
);
475 return (httpAssembleURI(encoding
, uri
, urilen
, scheme
, username
, host
,
481 * 'httpAssembleUUID()' - Assemble a name-based UUID URN conforming to RFC 4122.
483 * This function creates a unique 128-bit identifying number using the server
484 * name, port number, random data, and optionally an object name and/or object
485 * number. The result is formatted as a UUID URN as defined in RFC 4122.
487 * The buffer needs to be at least 46 bytes in size.
489 * @since CUPS 1.7/macOS 10.9@
492 char * /* I - UUID string */
493 httpAssembleUUID(const char *server
, /* I - Server name */
494 int port
, /* I - Port number */
495 const char *name
, /* I - Object name or NULL */
496 int number
, /* I - Object number or 0 */
497 char *buffer
, /* I - String buffer */
498 size_t bufsize
) /* I - Size of buffer */
500 char data
[1024]; /* Source string for MD5 */
501 unsigned char md5sum
[16]; /* MD5 digest/sum */
505 * Build a version 3 UUID conforming to RFC 4122.
507 * Start with the MD5 sum of the server, port, object name and
508 * number, and some random data on the end.
511 snprintf(data
, sizeof(data
), "%s:%d:%s:%d:%04x:%04x", server
,
512 port
, name
? name
: server
, number
,
513 (unsigned)CUPS_RAND() & 0xffff, (unsigned)CUPS_RAND() & 0xffff);
515 cupsHashData("md5", (unsigned char *)data
, strlen(data
), md5sum
, sizeof(md5sum
));
518 * Generate the UUID from the MD5...
521 snprintf(buffer
, bufsize
,
522 "urn:uuid:%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-"
523 "%02x%02x%02x%02x%02x%02x",
524 md5sum
[0], md5sum
[1], md5sum
[2], md5sum
[3], md5sum
[4], md5sum
[5],
525 (md5sum
[6] & 15) | 0x30, md5sum
[7], (md5sum
[8] & 0x3f) | 0x40,
526 md5sum
[9], md5sum
[10], md5sum
[11], md5sum
[12], md5sum
[13],
527 md5sum
[14], md5sum
[15]);
534 * 'httpDecode64()' - Base64-decode a string.
536 * This function is deprecated. Use the httpDecode64_2() function instead
537 * which provides buffer length arguments.
539 * @deprecated@ @exclude all@
542 char * /* O - Decoded string */
543 httpDecode64(char *out
, /* I - String to write to */
544 const char *in
) /* I - String to read from */
546 int outlen
; /* Output buffer length */
550 * Use the old maximum buffer size for binary compatibility...
555 return (httpDecode64_2(out
, &outlen
, in
));
560 * 'httpDecode64_2()' - Base64-decode a string.
562 * The caller must initialize "outlen" to the maximum size of the decoded
563 * string before calling @code httpDecode64_2@. On return "outlen" contains the
564 * decoded length of the string.
566 * @since CUPS 1.1.21/macOS 10.4@
569 char * /* O - Decoded string */
570 httpDecode64_2(char *out
, /* I - String to write to */
571 int *outlen
, /* IO - Size of output string */
572 const char *in
) /* I - String to read from */
574 int pos
; /* Bit position */
575 unsigned base64
; /* Value of this character */
576 char *outptr
, /* Output pointer */
577 *outend
; /* End of output buffer */
581 * Range check input...
584 if (!out
|| !outlen
|| *outlen
< 1 || !in
)
596 * Convert from base-64 to bytes...
599 for (outptr
= out
, outend
= out
+ *outlen
- 1, pos
= 0; *in
!= '\0'; in
++)
602 * Decode this character into a number from 0 to 63...
605 if (*in
>= 'A' && *in
<= 'Z')
606 base64
= (unsigned)(*in
- 'A');
607 else if (*in
>= 'a' && *in
<= 'z')
608 base64
= (unsigned)(*in
- 'a' + 26);
609 else if (*in
>= '0' && *in
<= '9')
610 base64
= (unsigned)(*in
- '0' + 52);
621 * Store the result in the appropriate chars...
628 *outptr
= (char)(base64
<< 2);
633 *outptr
++ |= (char)((base64
>> 4) & 3);
635 *outptr
= (char)((base64
<< 4) & 255);
640 *outptr
++ |= (char)((base64
>> 2) & 15);
642 *outptr
= (char)((base64
<< 6) & 255);
647 *outptr
++ |= (char)base64
;
656 * Return the decoded string and size...
659 *outlen
= (int)(outptr
- out
);
666 * 'httpEncode64()' - Base64-encode a string.
668 * This function is deprecated. Use the httpEncode64_2() function instead
669 * which provides buffer length arguments.
671 * @deprecated@ @exclude all@
674 char * /* O - Encoded string */
675 httpEncode64(char *out
, /* I - String to write to */
676 const char *in
) /* I - String to read from */
678 return (httpEncode64_2(out
, 512, in
, (int)strlen(in
)));
683 * 'httpEncode64_2()' - Base64-encode a string.
685 * @since CUPS 1.1.21/macOS 10.4@
688 char * /* O - Encoded string */
689 httpEncode64_2(char *out
, /* I - String to write to */
690 int outlen
, /* I - Maximum size of output string */
691 const char *in
, /* I - String to read from */
692 int inlen
) /* I - Size of input string */
694 char *outptr
, /* Output pointer */
695 *outend
; /* End of output buffer */
696 static const char base64
[] = /* Base64 characters... */
698 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
699 "abcdefghijklmnopqrstuvwxyz"
706 * Range check input...
709 if (!out
|| outlen
< 1 || !in
)
713 * Convert bytes to base-64...
716 for (outptr
= out
, outend
= out
+ outlen
- 1; inlen
> 0; in
++, inlen
--)
719 * Encode the up to 3 characters as 4 Base64 numbers...
723 *outptr
++ = base64
[(in
[0] & 255) >> 2];
728 *outptr
++ = base64
[(((in
[0] & 255) << 4) | ((in
[1] & 255) >> 4)) & 63];
730 *outptr
++ = base64
[((in
[0] & 255) << 4) & 63];
747 *outptr
++ = base64
[(((in
[0] & 255) << 2) | ((in
[1] & 255) >> 6)) & 63];
749 *outptr
++ = base64
[((in
[0] & 255) << 2) & 63];
762 *outptr
++ = base64
[in
[0] & 63];
768 * Return the encoded string...
776 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
778 * @deprecated@ @exclude all@
781 const char * /* O - Date/time string */
782 httpGetDateString(time_t t
) /* I - Time in seconds */
784 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
787 return (httpGetDateString2(t
, cg
->http_date
, sizeof(cg
->http_date
)));
792 * 'httpGetDateString2()' - Get a formatted date/time string from a time value.
794 * @since CUPS 1.2/macOS 10.5@
797 const char * /* O - Date/time string */
798 httpGetDateString2(time_t t
, /* I - Time in seconds */
799 char *s
, /* I - String buffer */
800 int slen
) /* I - Size of string buffer */
802 struct tm
*tdate
; /* UNIX date/time data */
807 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
);
816 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
819 time_t /* O - Time in seconds */
820 httpGetDateTime(const char *s
) /* I - Date/time string */
822 int i
; /* Looping var */
823 char mon
[16]; /* Abbreviated month name */
824 int day
, year
; /* Day of month and year */
825 int hour
, min
, sec
; /* Time */
826 int days
; /* Number of days since 1970 */
827 static const int normal_days
[] = /* Days to a month, normal years */
828 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
829 static const int leap_days
[] = /* Days to a month, leap years */
830 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 };
833 DEBUG_printf(("2httpGetDateTime(s=\"%s\")", s
));
836 * Extract the date and time from the formatted string...
839 if (sscanf(s
, "%*s%d%15s%d%d:%d:%d", &day
, mon
, &year
, &hour
, &min
, &sec
) < 6)
842 DEBUG_printf(("4httpGetDateTime: day=%d, mon=\"%s\", year=%d, hour=%d, "
843 "min=%d, sec=%d", day
, mon
, year
, hour
, min
, sec
));
846 * Convert the month name to a number from 0 to 11.
849 for (i
= 0; i
< 12; i
++)
850 if (!_cups_strcasecmp(mon
, http_months
[i
]))
856 DEBUG_printf(("4httpGetDateTime: i=%d", i
));
859 * Now convert the date and time to a UNIX time value in seconds since
860 * 1970. We can't use mktime() since the timezone may not be UTC but
861 * the date/time string *is* UTC.
864 if ((year
& 3) == 0 && ((year
% 100) != 0 || (year
% 400) == 0))
865 days
= leap_days
[i
] + day
- 1;
867 days
= normal_days
[i
] + day
- 1;
869 DEBUG_printf(("4httpGetDateTime: days=%d", days
));
871 days
+= (year
- 1970) * 365 + /* 365 days per year (normally) */
872 ((year
- 1) / 4 - 492) - /* + leap days */
873 ((year
- 1) / 100 - 19) + /* - 100 year days */
874 ((year
- 1) / 400 - 4); /* + 400 year days */
876 DEBUG_printf(("4httpGetDateTime: days=%d\n", days
));
878 return (days
* 86400 + hour
* 3600 + min
* 60 + sec
);
883 * 'httpSeparate()' - Separate a Universal Resource Identifier into its
886 * This function is deprecated; use the httpSeparateURI() function instead.
888 * @deprecated@ @exclude all@
892 httpSeparate(const char *uri
, /* I - Universal Resource Identifier */
893 char *scheme
, /* O - Scheme [32] (http, https, etc.) */
894 char *username
, /* O - Username [1024] */
895 char *host
, /* O - Hostname [1024] */
896 int *port
, /* O - Port number to use */
897 char *resource
) /* O - Resource/filename [1024] */
899 httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, 32, username
,
900 HTTP_MAX_URI
, host
, HTTP_MAX_URI
, port
, resource
,
906 * 'httpSeparate2()' - Separate a Universal Resource Identifier into its
909 * This function is deprecated; use the httpSeparateURI() function instead.
911 * @since CUPS 1.1.21/macOS 10.4@
912 * @deprecated@ @exclude all@
916 httpSeparate2(const char *uri
, /* I - Universal Resource Identifier */
917 char *scheme
, /* O - Scheme (http, https, etc.) */
918 int schemelen
, /* I - Size of scheme buffer */
919 char *username
, /* O - Username */
920 int usernamelen
, /* I - Size of username buffer */
921 char *host
, /* O - Hostname */
922 int hostlen
, /* I - Size of hostname buffer */
923 int *port
, /* O - Port number to use */
924 char *resource
, /* O - Resource/filename */
925 int resourcelen
) /* I - Size of resource buffer */
927 httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, schemelen
, username
,
928 usernamelen
, host
, hostlen
, port
, resource
, resourcelen
);
933 * 'httpSeparateURI()' - Separate a Universal Resource Identifier into its
936 * @since CUPS 1.2/macOS 10.5@
939 http_uri_status_t
/* O - Result of separation */
941 http_uri_coding_t decoding
, /* I - Decoding flags */
942 const char *uri
, /* I - Universal Resource Identifier */
943 char *scheme
, /* O - Scheme (http, https, etc.) */
944 int schemelen
, /* I - Size of scheme buffer */
945 char *username
, /* O - Username */
946 int usernamelen
, /* I - Size of username buffer */
947 char *host
, /* O - Hostname */
948 int hostlen
, /* I - Size of hostname buffer */
949 int *port
, /* O - Port number to use */
950 char *resource
, /* O - Resource/filename */
951 int resourcelen
) /* I - Size of resource buffer */
953 char *ptr
, /* Pointer into string... */
954 *end
; /* End of string */
955 const char *sep
; /* Separator character */
956 http_uri_status_t status
; /* Result of separation */
960 * Initialize everything to blank...
963 if (scheme
&& schemelen
> 0)
966 if (username
&& usernamelen
> 0)
969 if (host
&& hostlen
> 0)
975 if (resource
&& resourcelen
> 0)
979 * Range check input...
982 if (!uri
|| !port
|| !scheme
|| schemelen
<= 0 || !username
||
983 usernamelen
<= 0 || !host
|| hostlen
<= 0 || !resource
||
985 return (HTTP_URI_STATUS_BAD_ARGUMENTS
);
988 return (HTTP_URI_STATUS_BAD_URI
);
991 * Grab the scheme portion of the URI...
994 status
= HTTP_URI_STATUS_OK
;
996 if (!strncmp(uri
, "//", 2))
999 * Workaround for HP IPP client bug...
1002 strlcpy(scheme
, "ipp", (size_t)schemelen
);
1003 status
= HTTP_URI_STATUS_MISSING_SCHEME
;
1005 else if (*uri
== '/')
1011 strlcpy(scheme
, "file", (size_t)schemelen
);
1012 status
= HTTP_URI_STATUS_MISSING_SCHEME
;
1017 * Standard URI with scheme...
1020 for (ptr
= scheme
, end
= scheme
+ schemelen
- 1;
1021 *uri
&& *uri
!= ':' && ptr
< end
;)
1022 if (strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1023 "abcdefghijklmnopqrstuvwxyz"
1024 "0123456789-+.", *uri
) != NULL
)
1031 if (*uri
!= ':' || *scheme
== '.' || !*scheme
)
1034 return (HTTP_URI_STATUS_BAD_SCHEME
);
1041 * Set the default port number...
1044 if (!strcmp(scheme
, "http"))
1046 else if (!strcmp(scheme
, "https"))
1048 else if (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps"))
1050 else if (!_cups_strcasecmp(scheme
, "lpd"))
1052 else if (!strcmp(scheme
, "socket")) /* Not yet registered with IANA... */
1054 else if (strcmp(scheme
, "file") && strcmp(scheme
, "mailto") && strcmp(scheme
, "tel"))
1055 status
= HTTP_URI_STATUS_UNKNOWN_SCHEME
;
1058 * Now see if we have a hostname...
1061 if (!strncmp(uri
, "//", 2))
1064 * Yes, extract it...
1070 * Grab the username, if any...
1073 if ((sep
= strpbrk(uri
, "@/")) != NULL
&& *sep
== '@')
1076 * Get a username:password combo...
1079 uri
= http_copy_decode(username
, uri
, usernamelen
, "@",
1080 decoding
& HTTP_URI_CODING_USERNAME
);
1085 return (HTTP_URI_STATUS_BAD_USERNAME
);
1092 * Then the hostname/IP address...
1098 * Grab IPv6 address...
1105 * Skip IPvFuture ("vXXXX.") prefix...
1110 while (isxdigit(*uri
& 255))
1116 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1122 uri
= http_copy_decode(host
, uri
, hostlen
, "]",
1123 decoding
& HTTP_URI_CODING_HOSTNAME
);
1128 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1138 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1143 for (ptr
= host
; *ptr
; ptr
++)
1147 * Convert zone separator to % and stop here...
1153 else if (*ptr
== '%')
1156 * Stop at zone separator (RFC 6874)
1161 else if (*ptr
!= ':' && *ptr
!= '.' && !isxdigit(*ptr
& 255))
1164 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1170 * Validate the hostname or IPv4 address first...
1173 for (ptr
= (char *)uri
; *ptr
; ptr
++)
1174 if (strchr(":?/", *ptr
))
1176 else if (!strchr("abcdefghijklmnopqrstuvwxyz" /* unreserved */
1177 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" /* unreserved */
1178 "0123456789" /* unreserved */
1179 "-._~" /* unreserved */
1180 "%" /* pct-encoded */
1181 "!$&'()*+,;=" /* sub-delims */
1182 "\\", *ptr
)) /* SMB domain */
1185 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1189 * Then copy the hostname or IPv4 address to the buffer...
1192 uri
= http_copy_decode(host
, uri
, hostlen
, ":?/",
1193 decoding
& HTTP_URI_CODING_HOSTNAME
);
1198 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1203 * Validate hostname for file scheme - only empty and localhost are
1207 if (!strcmp(scheme
, "file") && strcmp(host
, "localhost") && host
[0])
1210 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1214 * See if we have a port number...
1220 * Yes, collect the port number...
1223 if (!isdigit(uri
[1] & 255))
1226 return (HTTP_URI_STATUS_BAD_PORT
);
1229 *port
= (int)strtol(uri
+ 1, (char **)&uri
, 10);
1231 if (*port
<= 0 || *port
> 65535)
1234 return (HTTP_URI_STATUS_BAD_PORT
);
1237 if (*uri
!= '/' && *uri
)
1240 return (HTTP_URI_STATUS_BAD_PORT
);
1246 * The remaining portion is the resource string...
1249 if (*uri
== '?' || !*uri
)
1252 * Hostname but no path...
1255 status
= HTTP_URI_STATUS_MISSING_RESOURCE
;
1259 * Copy any query string...
1263 uri
= http_copy_decode(resource
+ 1, uri
, resourcelen
- 1, NULL
,
1264 decoding
& HTTP_URI_CODING_QUERY
);
1270 uri
= http_copy_decode(resource
, uri
, resourcelen
, "?",
1271 decoding
& HTTP_URI_CODING_RESOURCE
);
1273 if (uri
&& *uri
== '?')
1276 * Concatenate any query string...
1279 char *resptr
= resource
+ strlen(resource
);
1281 uri
= http_copy_decode(resptr
, uri
,
1282 resourcelen
- (int)(resptr
- resource
), NULL
,
1283 decoding
& HTTP_URI_CODING_QUERY
);
1290 return (HTTP_URI_STATUS_BAD_RESOURCE
);
1294 * Return the URI separation status...
1302 * '_httpSetDigestAuthString()' - Calculate a Digest authentication response
1303 * using the appropriate RFC 2068/2617/7616
1307 int /* O - 1 on success, 0 on failure */
1308 _httpSetDigestAuthString(
1309 http_t
*http
, /* I - HTTP connection */
1310 const char *nonce
, /* I - Nonce value */
1311 const char *method
, /* I - HTTP method */
1312 const char *resource
) /* I - HTTP resource path */
1314 char kd
[65], /* Final MD5/SHA-256 digest */
1315 ha1
[65], /* Hash of username:realm:password */
1316 ha2
[65], /* Hash of method:request-uri */
1317 username
[HTTP_MAX_VALUE
],
1318 /* username:password */
1319 *password
, /* Pointer to password */
1320 temp
[1024], /* Temporary string */
1321 digest
[1024]; /* Digest auth data */
1322 unsigned char hash
[32]; /* Hash buffer */
1323 size_t hashsize
; /* Size of hash */
1326 DEBUG_printf(("2_httpSetDigestAuthString(http=%p, nonce=\"%s\", method=\"%s\", resource=\"%s\")", (void *)http
, nonce
, method
, resource
));
1328 if (nonce
&& *nonce
&& strcmp(nonce
, http
->nonce
))
1330 strlcpy(http
->nonce
, nonce
, sizeof(http
->nonce
));
1332 if (nonce
== http
->nextnonce
)
1333 http
->nextnonce
[0] = '\0';
1335 http
->nonce_count
= 1;
1338 http
->nonce_count
++;
1340 strlcpy(username
, http
->userpass
, sizeof(username
));
1341 if ((password
= strchr(username
, ':')) != NULL
)
1346 if (http
->algorithm
[0])
1349 * Follow RFC 2617/7616...
1352 int i
; /* Looping var */
1353 char cnonce
[65]; /* cnonce value */
1354 const char *hashalg
; /* Hashing algorithm */
1356 for (i
= 0; i
< 64; i
++)
1357 cnonce
[i
] = "0123456789ABCDEF"[CUPS_RAND() & 15];
1360 if (!_cups_strcasecmp(http
->algorithm
, "MD5"))
1363 * RFC 2617 Digest with MD5
1368 else if (!_cups_strcasecmp(http
->algorithm
, "SHA-256"))
1371 * RFC 7616 Digest with SHA-256
1374 hashalg
= "sha2-256";
1379 * Some other algorithm we don't support, skip this one...
1386 * Calculate digest value...
1389 /* H(A1) = H(username:realm:password) */
1390 snprintf(temp
, sizeof(temp
), "%s:%s:%s", username
, http
->realm
, password
);
1391 hashsize
= (size_t)cupsHashData(hashalg
, (unsigned char *)temp
, strlen(temp
), hash
, sizeof(hash
));
1392 cupsHashString(hash
, hashsize
, ha1
, sizeof(ha1
));
1394 /* H(A2) = H(method:uri) */
1395 snprintf(temp
, sizeof(temp
), "%s:%s", method
, resource
);
1396 hashsize
= (size_t)cupsHashData(hashalg
, (unsigned char *)temp
, strlen(temp
), hash
, sizeof(hash
));
1397 cupsHashString(hash
, hashsize
, ha2
, sizeof(ha2
));
1399 /* KD = H(H(A1):nonce:nc:cnonce:qop:H(A2)) */
1400 snprintf(temp
, sizeof(temp
), "%s:%s:%08x:%s:%s:%s", ha1
, http
->nonce
, http
->nonce_count
, cnonce
, "auth", ha2
);
1401 hashsize
= (size_t)cupsHashData(hashalg
, (unsigned char *)temp
, strlen(temp
), hash
, sizeof(hash
));
1402 cupsHashString(hash
, hashsize
, kd
, sizeof(kd
));
1405 * Pass the RFC 2617/7616 WWW-Authenticate header...
1408 if (http
->opaque
[0])
1409 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
);
1411 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
);
1416 * Use old RFC 2069 Digest method...
1419 /* H(A1) = H(username:realm:password) */
1420 snprintf(temp
, sizeof(temp
), "%s:%s:%s", username
, http
->realm
, password
);
1421 hashsize
= (size_t)cupsHashData("md5", (unsigned char *)temp
, strlen(temp
), hash
, sizeof(hash
));
1422 cupsHashString(hash
, hashsize
, ha1
, sizeof(ha1
));
1424 /* H(A2) = H(method:uri) */
1425 snprintf(temp
, sizeof(temp
), "%s:%s", method
, resource
);
1426 hashsize
= (size_t)cupsHashData("md5", (unsigned char *)temp
, strlen(temp
), hash
, sizeof(hash
));
1427 cupsHashString(hash
, hashsize
, ha2
, sizeof(ha2
));
1429 /* KD = H(H(A1):nonce:H(A2)) */
1430 snprintf(temp
, sizeof(temp
), "%s:%s:%s", ha1
, http
->nonce
, ha2
);
1431 hashsize
= (size_t)cupsHashData("md5", (unsigned char *)temp
, strlen(temp
), hash
, sizeof(hash
));
1432 cupsHashString(hash
, hashsize
, kd
, sizeof(kd
));
1435 * Pass the old RFC 2069 WWW-Authenticate header...
1438 snprintf(digest
, sizeof(digest
), "username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"", username
, http
->realm
, http
->nonce
, resource
, kd
);
1441 httpSetAuthString(http
, "Digest", digest
);
1448 * 'httpStateString()' - Return the string describing a HTTP state value.
1450 * @since CUPS 2.0/OS 10.10@
1453 const char * /* O - State string */
1454 httpStateString(http_state_t state
) /* I - HTTP state value */
1456 if (state
< HTTP_STATE_ERROR
|| state
> HTTP_STATE_UNKNOWN_VERSION
)
1457 return ("HTTP_STATE_???");
1459 return (http_states
[state
- HTTP_STATE_ERROR
]);
1464 * '_httpStatus()' - Return the localized string describing a HTTP status code.
1466 * The returned string is localized using the passed message catalog.
1469 const char * /* O - Localized status string */
1470 _httpStatus(cups_lang_t
*lang
, /* I - Language */
1471 http_status_t status
) /* I - HTTP status code */
1473 const char *s
; /* Status string */
1478 case HTTP_STATUS_ERROR
:
1479 s
= strerror(errno
);
1481 case HTTP_STATUS_CONTINUE
:
1484 case HTTP_STATUS_SWITCHING_PROTOCOLS
:
1485 s
= _("Switching Protocols");
1487 case HTTP_STATUS_OK
:
1490 case HTTP_STATUS_CREATED
:
1493 case HTTP_STATUS_ACCEPTED
:
1496 case HTTP_STATUS_NO_CONTENT
:
1497 s
= _("No Content");
1499 case HTTP_STATUS_MOVED_PERMANENTLY
:
1500 s
= _("Moved Permanently");
1502 case HTTP_STATUS_FOUND
:
1505 case HTTP_STATUS_SEE_OTHER
:
1508 case HTTP_STATUS_NOT_MODIFIED
:
1509 s
= _("Not Modified");
1511 case HTTP_STATUS_BAD_REQUEST
:
1512 s
= _("Bad Request");
1514 case HTTP_STATUS_UNAUTHORIZED
:
1515 case HTTP_STATUS_CUPS_AUTHORIZATION_CANCELED
:
1516 s
= _("Unauthorized");
1518 case HTTP_STATUS_FORBIDDEN
:
1521 case HTTP_STATUS_NOT_FOUND
:
1524 case HTTP_STATUS_REQUEST_TOO_LARGE
:
1525 s
= _("Request Entity Too Large");
1527 case HTTP_STATUS_URI_TOO_LONG
:
1528 s
= _("URI Too Long");
1530 case HTTP_STATUS_UPGRADE_REQUIRED
:
1531 s
= _("Upgrade Required");
1533 case HTTP_STATUS_NOT_IMPLEMENTED
:
1534 s
= _("Not Implemented");
1536 case HTTP_STATUS_NOT_SUPPORTED
:
1537 s
= _("Not Supported");
1539 case HTTP_STATUS_EXPECTATION_FAILED
:
1540 s
= _("Expectation Failed");
1542 case HTTP_STATUS_SERVICE_UNAVAILABLE
:
1543 s
= _("Service Unavailable");
1545 case HTTP_STATUS_SERVER_ERROR
:
1546 s
= _("Internal Server Error");
1548 case HTTP_STATUS_CUPS_PKI_ERROR
:
1549 s
= _("SSL/TLS Negotiation Error");
1551 case HTTP_STATUS_CUPS_WEBIF_DISABLED
:
1552 s
= _("Web Interface is Disabled");
1560 return (_cupsLangString(lang
, s
));
1565 * 'httpStatus()' - Return a short string describing a HTTP status code.
1567 * The returned string is localized to the current POSIX locale and is based
1568 * on the status strings defined in RFC 7231.
1571 const char * /* O - Localized status string */
1572 httpStatus(http_status_t status
) /* I - HTTP status code */
1574 _cups_globals_t
*cg
= _cupsGlobals(); /* Global data */
1577 if (!cg
->lang_default
)
1578 cg
->lang_default
= cupsLangDefault();
1580 return (_httpStatus(cg
->lang_default
, status
));
1584 * 'httpURIStatusString()' - Return a string describing a URI status code.
1586 * @since CUPS 2.0/OS 10.10@
1589 const char * /* O - Localized status string */
1590 httpURIStatusString(
1591 http_uri_status_t status
) /* I - URI status code */
1593 const char *s
; /* Status string */
1594 _cups_globals_t
*cg
= _cupsGlobals(); /* Global data */
1597 if (!cg
->lang_default
)
1598 cg
->lang_default
= cupsLangDefault();
1602 case HTTP_URI_STATUS_OVERFLOW
:
1603 s
= _("URI too large");
1605 case HTTP_URI_STATUS_BAD_ARGUMENTS
:
1606 s
= _("Bad arguments to function");
1608 case HTTP_URI_STATUS_BAD_RESOURCE
:
1609 s
= _("Bad resource in URI");
1611 case HTTP_URI_STATUS_BAD_PORT
:
1612 s
= _("Bad port number in URI");
1614 case HTTP_URI_STATUS_BAD_HOSTNAME
:
1615 s
= _("Bad hostname/address in URI");
1617 case HTTP_URI_STATUS_BAD_USERNAME
:
1618 s
= _("Bad username in URI");
1620 case HTTP_URI_STATUS_BAD_SCHEME
:
1621 s
= _("Bad scheme in URI");
1623 case HTTP_URI_STATUS_BAD_URI
:
1624 s
= _("Bad/empty URI");
1626 case HTTP_URI_STATUS_OK
:
1629 case HTTP_URI_STATUS_MISSING_SCHEME
:
1630 s
= _("Missing scheme in URI");
1632 case HTTP_URI_STATUS_UNKNOWN_SCHEME
:
1633 s
= _("Unknown scheme in URI");
1635 case HTTP_URI_STATUS_MISSING_RESOURCE
:
1636 s
= _("Missing resource in URI");
1644 return (_cupsLangString(cg
->lang_default
, s
));
1648 #ifndef HAVE_HSTRERROR
1650 * '_cups_hstrerror()' - hstrerror() emulation function for Solaris and others.
1653 const char * /* O - Error string */
1654 _cups_hstrerror(int error
) /* I - Error number */
1656 static const char * const errors
[] = /* Error strings */
1661 "Unrecoverable lookup error.",
1662 "No data associated with name."
1666 if (error
< 0 || error
> 4)
1667 return ("Unknown hostname lookup error.");
1669 return (errors
[error
]);
1671 #endif /* !HAVE_HSTRERROR */
1675 * '_httpDecodeURI()' - Percent-decode a HTTP request URI.
1678 char * /* O - Decoded URI or NULL on error */
1679 _httpDecodeURI(char *dst
, /* I - Destination buffer */
1680 const char *src
, /* I - Source URI */
1681 size_t dstsize
) /* I - Size of destination buffer */
1683 if (http_copy_decode(dst
, src
, (int)dstsize
, NULL
, 1))
1691 * '_httpEncodeURI()' - Percent-encode a HTTP request URI.
1694 char * /* O - Encoded URI */
1695 _httpEncodeURI(char *dst
, /* I - Destination buffer */
1696 const char *src
, /* I - Source URI */
1697 size_t dstsize
) /* I - Size of destination buffer */
1699 http_copy_encode(dst
, src
, dst
+ dstsize
- 1, NULL
, NULL
, 1);
1705 * '_httpResolveURI()' - Resolve a DNS-SD URI.
1708 const char * /* O - Resolved URI */
1710 const char *uri
, /* I - DNS-SD URI */
1711 char *resolved_uri
, /* I - Buffer for resolved URI */
1712 size_t resolved_size
, /* I - Size of URI buffer */
1713 int options
, /* I - Resolve options */
1714 int (*cb
)(void *context
), /* I - Continue callback function */
1715 void *context
) /* I - Context pointer for callback */
1717 char scheme
[32], /* URI components... */
1723 http_uri_status_t status
; /* URI decode status */
1727 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
));
1730 * Get the device URI...
1734 if ((status
= httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
,
1735 sizeof(scheme
), userpass
, sizeof(userpass
),
1736 hostname
, sizeof(hostname
), &port
, resource
,
1737 sizeof(resource
))) < HTTP_URI_STATUS_OK
)
1739 if (httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
,
1740 sizeof(scheme
), userpass
, sizeof(userpass
),
1741 hostname
, sizeof(hostname
), &port
, resource
,
1742 sizeof(resource
)) < HTTP_URI_STATUS_OK
)
1745 if (options
& _HTTP_RESOLVE_STDERR
)
1746 _cupsLangPrintFilter(stderr
, "ERROR", _("Bad device-uri \"%s\"."), uri
);
1748 DEBUG_printf(("2_httpResolveURI: httpSeparateURI returned %d!", status
));
1749 DEBUG_puts("2_httpResolveURI: Returning NULL");
1754 * Resolve it as needed...
1757 if (strstr(hostname
, "._tcp"))
1759 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
1760 char *regtype
, /* Pointer to type in hostname */
1761 *domain
, /* Pointer to domain in hostname */
1762 *uuid
, /* Pointer to UUID in URI */
1763 *uuidend
; /* Pointer to end of UUID in URI */
1764 _http_uribuf_t uribuf
; /* URI buffer */
1765 int offline
= 0; /* offline-report state set? */
1767 DNSServiceRef ref
, /* DNS-SD master service reference */
1768 domainref
= NULL
,/* DNS-SD service reference for domain */
1769 ippref
= NULL
, /* DNS-SD service reference for network IPP */
1770 ippsref
= NULL
, /* DNS-SD service reference for network IPPS */
1771 localref
; /* DNS-SD service reference for .local */
1772 int extrasent
= 0; /* Send the domain/IPP/IPPS resolves? */
1774 struct pollfd polldata
; /* Polling data */
1775 # else /* select() */
1776 fd_set input_set
; /* Input set for select() */
1777 struct timeval stimeout
; /* Timeout value for select() */
1778 # endif /* HAVE_POLL */
1779 # elif defined(HAVE_AVAHI)
1780 AvahiClient
*client
; /* Client information */
1781 int error
; /* Status */
1782 # endif /* HAVE_DNSSD */
1784 if (options
& _HTTP_RESOLVE_STDERR
)
1785 fprintf(stderr
, "DEBUG: Resolving \"%s\"...\n", hostname
);
1788 * Separate the hostname into service name, registration type, and domain...
1791 for (regtype
= strstr(hostname
, "._tcp") - 2;
1794 if (regtype
[0] == '.' && regtype
[1] == '_')
1797 * Found ._servicetype in front of ._tcp...
1804 if (regtype
<= hostname
)
1806 DEBUG_puts("2_httpResolveURI: Bad hostname, returning NULL");
1810 for (domain
= strchr(regtype
, '.');
1812 domain
= strchr(domain
+ 1, '.'))
1813 if (domain
[1] != '_')
1819 if ((uuid
= strstr(resource
, "?uuid=")) != NULL
)
1823 if ((uuidend
= strchr(uuid
, '&')) != NULL
)
1827 resolved_uri
[0] = '\0';
1829 uribuf
.buffer
= resolved_uri
;
1830 uribuf
.bufsize
= resolved_size
;
1831 uribuf
.options
= options
;
1832 uribuf
.resource
= resource
;
1835 DEBUG_printf(("2_httpResolveURI: Resolving hostname=\"%s\", regtype=\"%s\", "
1836 "domain=\"%s\"\n", hostname
, regtype
, domain
));
1837 if (options
& _HTTP_RESOLVE_STDERR
)
1839 fputs("STATE: +connecting-to-device\n", stderr
);
1840 fprintf(stderr
, "DEBUG: Resolving \"%s\", regtype=\"%s\", "
1841 "domain=\"local.\"...\n", hostname
, regtype
);
1847 if (DNSServiceCreateConnection(&ref
) == kDNSServiceErr_NoError
)
1849 uint32_t myinterface
= kDNSServiceInterfaceIndexAny
;
1850 /* Lookup on any interface */
1852 if (!strcmp(scheme
, "ippusb"))
1853 myinterface
= kDNSServiceInterfaceIndexLocalOnly
;
1856 if (DNSServiceResolve(&localref
,
1857 kDNSServiceFlagsShareConnection
, myinterface
,
1858 hostname
, regtype
, "local.", http_resolve_cb
,
1859 &uribuf
) == kDNSServiceErr_NoError
)
1861 int fds
; /* Number of ready descriptors */
1862 time_t timeout
, /* Poll timeout */
1863 start_time
= time(NULL
),/* Start time */
1864 end_time
= start_time
+ 90;
1867 while (time(NULL
) < end_time
)
1869 if (options
& _HTTP_RESOLVE_STDERR
)
1870 _cupsLangPrintFilter(stderr
, "INFO", _("Looking for printer."));
1872 if (cb
&& !(*cb
)(context
))
1874 DEBUG_puts("2_httpResolveURI: callback returned 0 (stop)");
1879 * Wakeup every 2 seconds to emit a "looking for printer" message...
1882 if ((timeout
= end_time
- time(NULL
)) > 2)
1886 polldata
.fd
= DNSServiceRefSockFD(ref
);
1887 polldata
.events
= POLLIN
;
1889 fds
= poll(&polldata
, 1, (int)(1000 * timeout
));
1891 # else /* select() */
1892 FD_ZERO(&input_set
);
1893 FD_SET(DNSServiceRefSockFD(ref
), &input_set
);
1896 stimeout
.tv_sec
= (long)timeout
;
1898 stimeout
.tv_sec
= timeout
;
1899 # endif /* _WIN32 */
1900 stimeout
.tv_usec
= 0;
1902 fds
= select(DNSServiceRefSockFD(ref
)+1, &input_set
, NULL
, NULL
,
1904 # endif /* HAVE_POLL */
1908 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1910 DEBUG_printf(("2_httpResolveURI: poll error: %s", strerror(errno
)));
1917 * Wait 2 seconds for a response to the local resolve; if nothing
1918 * comes in, do an additional domain resolution...
1921 if (extrasent
== 0 && domain
&& _cups_strcasecmp(domain
, "local."))
1923 if (options
& _HTTP_RESOLVE_STDERR
)
1925 "DEBUG: Resolving \"%s\", regtype=\"%s\", "
1926 "domain=\"%s\"...\n", hostname
, regtype
,
1927 domain
? domain
: "");
1930 if (DNSServiceResolve(&domainref
,
1931 kDNSServiceFlagsShareConnection
,
1932 myinterface
, hostname
, regtype
, domain
,
1934 &uribuf
) == kDNSServiceErr_NoError
)
1937 else if (extrasent
== 0 && !strcmp(scheme
, "ippusb"))
1939 if (options
& _HTTP_RESOLVE_STDERR
)
1940 fprintf(stderr
, "DEBUG: Resolving \"%s\", regtype=\"_ipps._tcp\", domain=\"local.\"...\n", hostname
);
1943 if (DNSServiceResolve(&ippsref
,
1944 kDNSServiceFlagsShareConnection
,
1945 kDNSServiceInterfaceIndexAny
, hostname
,
1946 "_ipps._tcp", domain
, http_resolve_cb
,
1947 &uribuf
) == kDNSServiceErr_NoError
)
1950 else if (extrasent
== 1 && !strcmp(scheme
, "ippusb"))
1952 if (options
& _HTTP_RESOLVE_STDERR
)
1953 fprintf(stderr
, "DEBUG: Resolving \"%s\", regtype=\"_ipp._tcp\", domain=\"local.\"...\n", hostname
);
1956 if (DNSServiceResolve(&ippref
,
1957 kDNSServiceFlagsShareConnection
,
1958 kDNSServiceInterfaceIndexAny
, hostname
,
1959 "_ipp._tcp", domain
, http_resolve_cb
,
1960 &uribuf
) == kDNSServiceErr_NoError
)
1965 * If it hasn't resolved within 5 seconds set the offline-report
1966 * printer-state-reason...
1969 if ((options
& _HTTP_RESOLVE_STDERR
) && offline
== 0 &&
1970 time(NULL
) > (start_time
+ 5))
1972 fputs("STATE: +offline-report\n", stderr
);
1978 if (DNSServiceProcessResult(ref
) == kDNSServiceErr_NoError
&&
1990 DNSServiceRefDeallocate(domainref
);
1992 DNSServiceRefDeallocate(ippref
);
1994 DNSServiceRefDeallocate(ippsref
);
1997 DNSServiceRefDeallocate(localref
);
2000 DNSServiceRefDeallocate(ref
);
2002 # else /* HAVE_AVAHI */
2003 if ((uribuf
.poll
= avahi_simple_poll_new()) != NULL
)
2005 avahi_simple_poll_set_func(uribuf
.poll
, http_poll_cb
, NULL
);
2007 if ((client
= avahi_client_new(avahi_simple_poll_get(uribuf
.poll
),
2009 &uribuf
, &error
)) != NULL
)
2011 if (avahi_service_resolver_new(client
, AVAHI_IF_UNSPEC
,
2012 AVAHI_PROTO_UNSPEC
, hostname
,
2013 regtype
, "local.", AVAHI_PROTO_UNSPEC
, 0,
2014 http_resolve_cb
, &uribuf
) != NULL
)
2016 time_t start_time
= time(NULL
),
2018 end_time
= start_time
+ 90;
2020 int pstatus
; /* Poll status */
2022 pstatus
= avahi_simple_poll_iterate(uribuf
.poll
, 2000);
2024 if (pstatus
== 0 && !resolved_uri
[0] && domain
&&
2025 _cups_strcasecmp(domain
, "local."))
2028 * Resolve for .local hasn't returned anything, try the listed
2032 avahi_service_resolver_new(client
, AVAHI_IF_UNSPEC
,
2033 AVAHI_PROTO_UNSPEC
, hostname
,
2034 regtype
, domain
, AVAHI_PROTO_UNSPEC
, 0,
2035 http_resolve_cb
, &uribuf
);
2038 while (!pstatus
&& !resolved_uri
[0] && time(NULL
) < end_time
)
2040 if ((pstatus
= avahi_simple_poll_iterate(uribuf
.poll
, 2000)) != 0)
2044 * If it hasn't resolved within 5 seconds set the offline-report
2045 * printer-state-reason...
2048 if ((options
& _HTTP_RESOLVE_STDERR
) && offline
== 0 &&
2049 time(NULL
) > (start_time
+ 5))
2051 fputs("STATE: +offline-report\n", stderr
);
2057 * Collect the result (if we got one).
2060 if (resolved_uri
[0])
2064 avahi_client_free(client
);
2067 avahi_simple_poll_free(uribuf
.poll
);
2069 # endif /* HAVE_DNSSD */
2071 if (options
& _HTTP_RESOLVE_STDERR
)
2075 fprintf(stderr
, "DEBUG: Resolved as \"%s\"...\n", uri
);
2076 fputs("STATE: -connecting-to-device,offline-report\n", stderr
);
2080 fputs("DEBUG: Unable to resolve URI\n", stderr
);
2081 fputs("STATE: -connecting-to-device\n", stderr
);
2085 #else /* HAVE_DNSSD || HAVE_AVAHI */
2087 * No DNS-SD support...
2091 #endif /* HAVE_DNSSD || HAVE_AVAHI */
2093 if ((options
& _HTTP_RESOLVE_STDERR
) && !uri
)
2094 _cupsLangPrintFilter(stderr
, "INFO", _("Unable to find printer."));
2099 * Nothing more to do...
2102 strlcpy(resolved_uri
, uri
, resolved_size
);
2106 DEBUG_printf(("2_httpResolveURI: Returning \"%s\"", uri
));
2114 * 'http_client_cb()' - Client callback for resolving URI.
2119 AvahiClient
*client
, /* I - Client information */
2120 AvahiClientState state
, /* I - Current state */
2121 void *context
) /* I - Pointer to URI buffer */
2123 DEBUG_printf(("7http_client_cb(client=%p, state=%d, context=%p)", client
,
2127 * If the connection drops, quit.
2130 if (state
== AVAHI_CLIENT_FAILURE
)
2132 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
2135 avahi_simple_poll_quit(uribuf
->poll
);
2138 #endif /* HAVE_AVAHI */
2142 * 'http_copy_decode()' - Copy and decode a URI.
2145 static const char * /* O - New source pointer or NULL on error */
2146 http_copy_decode(char *dst
, /* O - Destination buffer */
2147 const char *src
, /* I - Source pointer */
2148 int dstsize
, /* I - Destination size */
2149 const char *term
, /* I - Terminating characters */
2150 int decode
) /* I - Decode %-encoded values */
2152 char *ptr
, /* Pointer into buffer */
2153 *end
; /* End of buffer */
2154 int quoted
; /* Quoted character */
2158 * Copy the src to the destination until we hit a terminating character
2159 * or the end of the string.
2162 for (ptr
= dst
, end
= dst
+ dstsize
- 1;
2163 *src
&& (!term
|| !strchr(term
, *src
));
2167 if (*src
== '%' && decode
)
2169 if (isxdigit(src
[1] & 255) && isxdigit(src
[2] & 255))
2172 * Grab a hex-encoded character...
2177 quoted
= (tolower(*src
) - 'a' + 10) << 4;
2179 quoted
= (*src
- '0') << 4;
2183 quoted
|= tolower(*src
) - 'a' + 10;
2185 quoted
|= *src
- '0';
2187 *ptr
++ = (char)quoted
;
2192 * Bad hex-encoded character...
2199 else if ((*src
& 255) <= 0x20 || (*src
& 255) >= 0x7f)
2215 * 'http_copy_encode()' - Copy and encode a URI.
2218 static char * /* O - End of current URI */
2219 http_copy_encode(char *dst
, /* O - Destination buffer */
2220 const char *src
, /* I - Source pointer */
2221 char *dstend
, /* I - End of destination buffer */
2222 const char *reserved
, /* I - Extra reserved characters */
2223 const char *term
, /* I - Terminating characters */
2224 int encode
) /* I - %-encode reserved chars? */
2226 static const char hex
[] = "0123456789ABCDEF";
2229 while (*src
&& dst
< dstend
)
2231 if (term
&& *src
== *term
)
2234 if (encode
&& (*src
== '%' || *src
<= ' ' || *src
& 128 ||
2235 (reserved
&& strchr(reserved
, *src
))))
2238 * Hex encode reserved characters...
2241 if ((dst
+ 2) >= dstend
)
2245 *dst
++ = hex
[(*src
>> 4) & 15];
2246 *dst
++ = hex
[*src
& 15];
2265 * 'http_resolve_cb()' - Build a device URI for the given service name.
2268 static void DNSSD_API
2270 DNSServiceRef sdRef
, /* I - Service reference */
2271 DNSServiceFlags flags
, /* I - Results flags */
2272 uint32_t interfaceIndex
, /* I - Interface number */
2273 DNSServiceErrorType errorCode
, /* I - Error, if any */
2274 const char *fullName
, /* I - Full service name */
2275 const char *hostTarget
, /* I - Hostname */
2276 uint16_t port
, /* I - Port number */
2277 uint16_t txtLen
, /* I - Length of TXT record */
2278 const unsigned char *txtRecord
, /* I - TXT record data */
2279 void *context
) /* I - Pointer to URI buffer */
2281 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
2283 const char *scheme
, /* URI scheme */
2284 *hostptr
, /* Pointer into hostTarget */
2285 *reskey
, /* "rp" or "rfo" */
2286 *resdefault
; /* Default path */
2287 char resource
[257], /* Remote path */
2288 fqdn
[256]; /* FQDN of the .local name */
2289 const void *value
; /* Value from TXT record */
2290 uint8_t valueLen
; /* Length of value */
2293 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
));
2296 * If we have a UUID, compare it...
2300 (value
= TXTRecordGetValuePtr(txtLen
, txtRecord
, "UUID",
2301 &valueLen
)) != NULL
)
2303 char uuid
[256]; /* UUID value */
2305 memcpy(uuid
, value
, valueLen
);
2306 uuid
[valueLen
] = '\0';
2308 if (_cups_strcasecmp(uuid
, uribuf
->uuid
))
2310 if (uribuf
->options
& _HTTP_RESOLVE_STDERR
)
2311 fprintf(stderr
, "DEBUG: Found UUID %s, looking for %s.", uuid
,
2314 DEBUG_printf(("5http_resolve_cb: Found UUID %s, looking for %s.", uuid
,
2321 * Figure out the scheme from the full name...
2324 if (strstr(fullName
, "._ipps") || strstr(fullName
, "._ipp-tls"))
2326 else if (strstr(fullName
, "._ipp") || strstr(fullName
, "._fax-ipp"))
2328 else if (strstr(fullName
, "._http."))
2330 else if (strstr(fullName
, "._https."))
2332 else if (strstr(fullName
, "._printer."))
2334 else if (strstr(fullName
, "._pdl-datastream."))
2337 scheme
= "riousbprint";
2340 * Extract the "remote printer" key from the TXT record...
2343 if ((uribuf
->options
& _HTTP_RESOLVE_FAXOUT
) &&
2344 (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")) &&
2345 !TXTRecordGetValuePtr(txtLen
, txtRecord
, "printer-type", &valueLen
))
2348 resdefault
= "/ipp/faxout";
2356 if ((value
= TXTRecordGetValuePtr(txtLen
, txtRecord
, reskey
,
2357 &valueLen
)) != NULL
)
2359 if (((char *)value
)[0] == '/')
2362 * Value (incorrectly) has a leading slash already...
2365 memcpy(resource
, value
, valueLen
);
2366 resource
[valueLen
] = '\0';
2371 * Convert to resource by concatenating with a leading "/"...
2375 memcpy(resource
+ 1, value
, valueLen
);
2376 resource
[valueLen
+ 1] = '\0';
2382 * Use the default value...
2385 strlcpy(resource
, resdefault
, sizeof(resource
));
2389 * Lookup the FQDN if needed...
2392 if ((uribuf
->options
& _HTTP_RESOLVE_FQDN
) &&
2393 (hostptr
= hostTarget
+ strlen(hostTarget
) - 7) > hostTarget
&&
2394 !_cups_strcasecmp(hostptr
, ".local."))
2397 * OK, we got a .local name but the caller needs a real domain. Start by
2398 * getting the IP address of the .local name and then do reverse-lookups...
2401 http_addrlist_t
*addrlist
, /* List of addresses */
2402 *addr
; /* Current address */
2404 DEBUG_printf(("5http_resolve_cb: Looking up \"%s\".", hostTarget
));
2406 snprintf(fqdn
, sizeof(fqdn
), "%d", ntohs(port
));
2407 if ((addrlist
= httpAddrGetList(hostTarget
, AF_UNSPEC
, fqdn
)) != NULL
)
2409 for (addr
= addrlist
; addr
; addr
= addr
->next
)
2411 int error
= getnameinfo(&(addr
->addr
.addr
), (socklen_t
)httpAddrLength(&(addr
->addr
)), fqdn
, sizeof(fqdn
), NULL
, 0, NI_NAMEREQD
);
2415 DEBUG_printf(("5http_resolve_cb: Found \"%s\".", fqdn
));
2417 if ((hostptr
= fqdn
+ strlen(fqdn
) - 6) <= fqdn
||
2418 _cups_strcasecmp(hostptr
, ".local"))
2426 DEBUG_printf(("5http_resolve_cb: \"%s\" did not resolve: %d",
2427 httpAddrString(&(addr
->addr
), fqdn
, sizeof(fqdn
)),
2432 httpAddrFreeList(addrlist
);
2437 * Assemble the final device URI...
2440 if ((!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")) &&
2441 !strcmp(uribuf
->resource
, "/cups"))
2442 httpAssembleURIf(HTTP_URI_CODING_ALL
, uribuf
->buffer
, (int)uribuf
->bufsize
, scheme
, NULL
, hostTarget
, ntohs(port
), "%s?snmp=false", resource
);
2444 httpAssembleURI(HTTP_URI_CODING_ALL
, uribuf
->buffer
, (int)uribuf
->bufsize
, scheme
, NULL
, hostTarget
, ntohs(port
), resource
);
2446 DEBUG_printf(("5http_resolve_cb: Resolved URI is \"%s\"...", uribuf
->buffer
));
2449 #elif defined(HAVE_AVAHI)
2451 * 'http_poll_cb()' - Wait for input on the specified file descriptors.
2453 * Note: This function is needed because avahi_simple_poll_iterate is broken
2454 * and always uses a timeout of 0 (!) milliseconds.
2455 * (Avahi Ticket #364)
2460 static int /* O - Number of file descriptors matching */
2462 struct pollfd
*pollfds
, /* I - File descriptors */
2463 unsigned int num_pollfds
, /* I - Number of file descriptors */
2464 int timeout
, /* I - Timeout in milliseconds (used) */
2465 void *context
) /* I - User data (unused) */
2470 return (poll(pollfds
, num_pollfds
, 2000));
2475 * 'http_resolve_cb()' - Build a device URI for the given service name.
2480 AvahiServiceResolver
*resolver
, /* I - Resolver (unused) */
2481 AvahiIfIndex interface
, /* I - Interface index (unused) */
2482 AvahiProtocol protocol
, /* I - Network protocol (unused) */
2483 AvahiResolverEvent event
, /* I - Event (found, etc.) */
2484 const char *name
, /* I - Service name */
2485 const char *type
, /* I - Registration type */
2486 const char *domain
, /* I - Domain (unused) */
2487 const char *hostTarget
, /* I - Hostname */
2488 const AvahiAddress
*address
, /* I - Address (unused) */
2489 uint16_t port
, /* I - Port number */
2490 AvahiStringList
*txt
, /* I - TXT record */
2491 AvahiLookupResultFlags flags
, /* I - Lookup flags (unused) */
2492 void *context
) /* I - Pointer to URI buffer */
2494 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
2496 const char *scheme
, /* URI scheme */
2497 *hostptr
, /* Pointer into hostTarget */
2498 *reskey
, /* "rp" or "rfo" */
2499 *resdefault
; /* Default path */
2500 char resource
[257], /* Remote path */
2501 fqdn
[256]; /* FQDN of the .local name */
2502 AvahiStringList
*pair
; /* Current TXT record key/value pair */
2503 char *value
; /* Value for "rp" key */
2504 size_t valueLen
= 0; /* Length of "rp" key */
2507 DEBUG_printf(("4http_resolve_cb(resolver=%p, "
2508 "interface=%d, protocol=%d, event=%d, name=\"%s\", "
2509 "type=\"%s\", domain=\"%s\", hostTarget=\"%s\", address=%p, "
2510 "port=%d, txt=%p, flags=%d, context=%p)",
2511 resolver
, interface
, protocol
, event
, name
, type
, domain
,
2512 hostTarget
, address
, port
, txt
, flags
, context
));
2514 if (event
!= AVAHI_RESOLVER_FOUND
)
2516 avahi_service_resolver_free(resolver
);
2517 avahi_simple_poll_quit(uribuf
->poll
);
2522 * If we have a UUID, compare it...
2525 if (uribuf
->uuid
&& (pair
= avahi_string_list_find(txt
, "UUID")) != NULL
)
2527 char uuid
[256]; /* UUID value */
2529 avahi_string_list_get_pair(pair
, NULL
, &value
, &valueLen
);
2531 memcpy(uuid
, value
, valueLen
);
2532 uuid
[valueLen
] = '\0';
2534 if (_cups_strcasecmp(uuid
, uribuf
->uuid
))
2536 if (uribuf
->options
& _HTTP_RESOLVE_STDERR
)
2537 fprintf(stderr
, "DEBUG: Found UUID %s, looking for %s.", uuid
,
2540 DEBUG_printf(("5http_resolve_cb: Found UUID %s, looking for %s.", uuid
,
2547 * Figure out the scheme from the full name...
2550 if (strstr(type
, "_ipp."))
2552 else if (strstr(type
, "_printer."))
2554 else if (strstr(type
, "_pdl-datastream."))
2557 scheme
= "riousbprint";
2559 if (!strncmp(type
, "_ipps.", 6) || !strncmp(type
, "_ipp-tls.", 9))
2561 else if (!strncmp(type
, "_ipp.", 5) || !strncmp(type
, "_fax-ipp.", 9))
2563 else if (!strncmp(type
, "_http.", 6))
2565 else if (!strncmp(type
, "_https.", 7))
2567 else if (!strncmp(type
, "_printer.", 9))
2569 else if (!strncmp(type
, "_pdl-datastream.", 16))
2573 avahi_service_resolver_free(resolver
);
2574 avahi_simple_poll_quit(uribuf
->poll
);
2579 * Extract the remote resource key from the TXT record...
2582 if ((uribuf
->options
& _HTTP_RESOLVE_FAXOUT
) &&
2583 (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")) &&
2584 !avahi_string_list_find(txt
, "printer-type"))
2587 resdefault
= "/ipp/faxout";
2595 if ((pair
= avahi_string_list_find(txt
, reskey
)) != NULL
)
2597 avahi_string_list_get_pair(pair
, NULL
, &value
, &valueLen
);
2599 if (value
[0] == '/')
2602 * Value (incorrectly) has a leading slash already...
2605 memcpy(resource
, value
, valueLen
);
2606 resource
[valueLen
] = '\0';
2611 * Convert to resource by concatenating with a leading "/"...
2615 memcpy(resource
+ 1, value
, valueLen
);
2616 resource
[valueLen
+ 1] = '\0';
2622 * Use the default value...
2625 strlcpy(resource
, resdefault
, sizeof(resource
));
2629 * Lookup the FQDN if needed...
2632 if ((uribuf
->options
& _HTTP_RESOLVE_FQDN
) &&
2633 (hostptr
= hostTarget
+ strlen(hostTarget
) - 6) > hostTarget
&&
2634 !_cups_strcasecmp(hostptr
, ".local"))
2637 * OK, we got a .local name but the caller needs a real domain. Start by
2638 * getting the IP address of the .local name and then do reverse-lookups...
2641 http_addrlist_t
*addrlist
, /* List of addresses */
2642 *addr
; /* Current address */
2644 DEBUG_printf(("5http_resolve_cb: Looking up \"%s\".", hostTarget
));
2646 snprintf(fqdn
, sizeof(fqdn
), "%d", ntohs(port
));
2647 if ((addrlist
= httpAddrGetList(hostTarget
, AF_UNSPEC
, fqdn
)) != NULL
)
2649 for (addr
= addrlist
; addr
; addr
= addr
->next
)
2651 int error
= getnameinfo(&(addr
->addr
.addr
), (socklen_t
)httpAddrLength(&(addr
->addr
)), fqdn
, sizeof(fqdn
), NULL
, 0, NI_NAMEREQD
);
2655 DEBUG_printf(("5http_resolve_cb: Found \"%s\".", fqdn
));
2657 if ((hostptr
= fqdn
+ strlen(fqdn
) - 6) <= fqdn
||
2658 _cups_strcasecmp(hostptr
, ".local"))
2666 DEBUG_printf(("5http_resolve_cb: \"%s\" did not resolve: %d",
2667 httpAddrString(&(addr
->addr
), fqdn
, sizeof(fqdn
)),
2672 httpAddrFreeList(addrlist
);
2677 * Assemble the final device URI using the resolved hostname...
2680 httpAssembleURI(HTTP_URI_CODING_ALL
, uribuf
->buffer
, (int)uribuf
->bufsize
, scheme
,
2681 NULL
, hostTarget
, port
, resource
);
2682 DEBUG_printf(("5http_resolve_cb: Resolved URI is \"%s\".", uribuf
->buffer
));
2684 avahi_simple_poll_quit(uribuf
->poll
);
2686 #endif /* HAVE_DNSSD */