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 * These coded instructions, statements, and computer programs are the
8 * property of Apple Inc. and are protected by Federal copyright
9 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
10 * which should have been included with this file. If this file is
11 * missing or damaged, see the license at "http://www.cups.org/".
13 * This file is subject to the Apple OS-Developed Software exception.
17 * Include necessary headers...
20 #include "cups-private.h"
25 # elif defined(HAVE_POLL)
28 # include <sys/select.h>
30 #elif defined(HAVE_AVAHI)
31 # include <avahi-client/client.h>
32 # include <avahi-client/lookup.h>
33 # include <avahi-common/simple-watch.h>
34 #endif /* HAVE_DNSSD */
41 typedef struct _http_uribuf_s
/* URI buffer */
44 AvahiSimplePoll
*poll
; /* Poll state */
45 #endif /* HAVE_AVAHI */
46 char *buffer
; /* Pointer to buffer */
47 size_t bufsize
; /* Size of buffer */
48 int options
; /* Options passed to _httpResolveURI */
49 const char *resource
; /* Resource from URI */
50 const char *uuid
; /* UUID from URI */
58 static const char * const http_days
[7] =/* Days of the week */
68 static const char * const http_months
[12] =
69 { /* Months of the year */
83 static const char * const http_states
[] =
84 { /* HTTP state strings */
89 "HTTP_STATE_GET_SEND",
92 "HTTP_STATE_POST_RECV",
93 "HTTP_STATE_POST_SEND",
95 "HTTP_STATE_PUT_RECV",
100 "HTTP_STATE_UNKNOWN_METHOD",
101 "HTTP_STATE_UNKNOWN_VERSION"
109 static const char *http_copy_decode(char *dst
, const char *src
,
110 int dstsize
, const char *term
,
112 static char *http_copy_encode(char *dst
, const char *src
,
113 char *dstend
, const char *reserved
,
114 const char *term
, int encode
);
116 static void DNSSD_API
http_resolve_cb(DNSServiceRef sdRef
,
117 DNSServiceFlags flags
,
118 uint32_t interfaceIndex
,
119 DNSServiceErrorType errorCode
,
120 const char *fullName
,
121 const char *hostTarget
,
122 uint16_t port
, uint16_t txtLen
,
123 const unsigned char *txtRecord
,
125 #endif /* HAVE_DNSSD */
128 static void http_client_cb(AvahiClient
*client
,
129 AvahiClientState state
, void *simple_poll
);
130 static int http_poll_cb(struct pollfd
*pollfds
, unsigned int num_pollfds
,
131 int timeout
, void *context
);
132 static void http_resolve_cb(AvahiServiceResolver
*resolver
,
133 AvahiIfIndex interface
,
134 AvahiProtocol protocol
,
135 AvahiResolverEvent event
,
136 const char *name
, const char *type
,
137 const char *domain
, const char *host_name
,
138 const AvahiAddress
*address
, uint16_t port
,
139 AvahiStringList
*txt
,
140 AvahiLookupResultFlags flags
, void *context
);
141 #endif /* HAVE_AVAHI */
145 * 'httpAssembleURI()' - Assemble a uniform resource identifier from its
148 * This function escapes reserved characters in the URI depending on the
149 * value of the "encoding" argument. You should use this function in
150 * place of traditional string functions whenever you need to create a
153 * @since CUPS 1.2/macOS 10.5@
156 http_uri_status_t
/* O - URI status */
158 http_uri_coding_t encoding
, /* I - Encoding flags */
159 char *uri
, /* I - URI buffer */
160 int urilen
, /* I - Size of URI buffer */
161 const char *scheme
, /* I - Scheme name */
162 const char *username
, /* I - Username */
163 const char *host
, /* I - Hostname or address */
164 int port
, /* I - Port number */
165 const char *resource
) /* I - Resource */
167 char *ptr
, /* Pointer into URI buffer */
168 *end
; /* End of URI buffer */
172 * Range check input...
175 if (!uri
|| urilen
< 1 || !scheme
|| port
< 0)
180 return (HTTP_URI_STATUS_BAD_ARGUMENTS
);
184 * Assemble the URI starting with the scheme...
187 end
= uri
+ urilen
- 1;
188 ptr
= http_copy_encode(uri
, scheme
, end
, NULL
, NULL
, 0);
191 goto assemble_overflow
;
193 if (!strcmp(scheme
, "geo") || !strcmp(scheme
, "mailto") || !strcmp(scheme
, "tel"))
196 * geo:, mailto:, and tel: only have :, no //...
202 goto assemble_overflow
;
207 * Schemes other than geo:, mailto:, and tel: typically have //...
217 goto assemble_overflow
;
221 * Next the username and hostname, if any...
226 const char *hostptr
; /* Pointer into hostname */
227 int have_ipv6
; /* Do we have an IPv6 address? */
229 if (username
&& *username
)
232 * Add username@ first...
235 ptr
= http_copy_encode(ptr
, username
, end
, "/?#[]@", NULL
,
236 encoding
& HTTP_URI_CODING_USERNAME
);
239 goto assemble_overflow
;
244 goto assemble_overflow
;
248 * Then add the hostname. Since IPv6 is a particular pain to deal
249 * with, we have several special cases to deal with. If we get
250 * an IPv6 address with brackets around it, assume it is already in
251 * URI format. Since DNS-SD service names can sometimes look like
252 * raw IPv6 addresses, we specifically look for "._tcp" in the name,
257 have_ipv6
= strchr(host
, ':') && !strstr(host
, "._tcp");
258 *hostptr
&& have_ipv6
;
260 if (*hostptr
!= ':' && !isxdigit(*hostptr
& 255))
262 have_ipv6
= *hostptr
== '%';
269 * We have a raw IPv6 address...
272 if (strchr(host
, '%') && !(encoding
& HTTP_URI_CODING_RFC6874
))
275 * We have a link-local address, add "[v1." prefix...
286 goto assemble_overflow
;
291 * We have a normal (or RFC 6874 link-local) address, add "[" prefix...
297 goto assemble_overflow
;
301 * Copy the rest of the IPv6 address, and terminate with "]".
304 while (ptr
< end
&& *host
)
309 * Convert/encode zone separator
312 if (encoding
& HTTP_URI_CODING_RFC6874
)
314 if (ptr
>= (end
- 2))
315 goto assemble_overflow
;
331 goto assemble_overflow
;
336 goto assemble_overflow
;
341 * Otherwise, just copy the host string (the extra chars are not in the
342 * "reg-name" ABNF rule; anything <= SP or >= DEL plus % gets automatically
346 ptr
= http_copy_encode(ptr
, host
, end
, "\"#/:<>?@[\\]^`{|}", NULL
,
347 encoding
& HTTP_URI_CODING_HOSTNAME
);
350 goto assemble_overflow
;
354 * Finish things off with the port number...
359 snprintf(ptr
, (size_t)(end
- ptr
+ 1), ":%d", port
);
363 goto assemble_overflow
;
368 * Last but not least, add the resource string...
373 char *query
; /* Pointer to query string */
377 * Copy the resource string up to the query string if present...
380 query
= strchr(resource
, '?');
381 ptr
= http_copy_encode(ptr
, resource
, end
, NULL
, "?",
382 encoding
& HTTP_URI_CODING_RESOURCE
);
384 goto assemble_overflow
;
389 * Copy query string without encoding...
392 ptr
= http_copy_encode(ptr
, query
, end
, NULL
, NULL
,
393 encoding
& HTTP_URI_CODING_QUERY
);
395 goto assemble_overflow
;
401 goto assemble_overflow
;
404 * Nul-terminate the URI buffer and return with no errors...
409 return (HTTP_URI_STATUS_OK
);
412 * Clear the URI string and return an overflow error; I don't usually
413 * like goto's, but in this case it makes sense...
419 return (HTTP_URI_STATUS_OVERFLOW
);
424 * 'httpAssembleURIf()' - Assemble a uniform resource identifier from its
425 * components with a formatted resource.
427 * This function creates a formatted version of the resource string
428 * argument "resourcef" and escapes reserved characters in the URI
429 * depending on the value of the "encoding" argument. You should use
430 * this function in place of traditional string functions whenever
431 * you need to create a URI string.
433 * @since CUPS 1.2/macOS 10.5@
436 http_uri_status_t
/* O - URI status */
438 http_uri_coding_t encoding
, /* I - Encoding flags */
439 char *uri
, /* I - URI buffer */
440 int urilen
, /* I - Size of URI buffer */
441 const char *scheme
, /* I - Scheme name */
442 const char *username
, /* I - Username */
443 const char *host
, /* I - Hostname or address */
444 int port
, /* I - Port number */
445 const char *resourcef
, /* I - Printf-style resource */
446 ...) /* I - Additional arguments as needed */
448 va_list ap
; /* Pointer to additional arguments */
449 char resource
[1024]; /* Formatted resource string */
450 int bytes
; /* Bytes in formatted string */
454 * Range check input...
457 if (!uri
|| urilen
< 1 || !scheme
|| port
< 0 || !resourcef
)
462 return (HTTP_URI_STATUS_BAD_ARGUMENTS
);
466 * Format the resource string and assemble the URI...
469 va_start(ap
, resourcef
);
470 bytes
= vsnprintf(resource
, sizeof(resource
), resourcef
, ap
);
473 if ((size_t)bytes
>= sizeof(resource
))
476 return (HTTP_URI_STATUS_OVERFLOW
);
479 return (httpAssembleURI(encoding
, uri
, urilen
, scheme
, username
, host
,
485 * 'httpAssembleUUID()' - Assemble a name-based UUID URN conforming to RFC 4122.
487 * This function creates a unique 128-bit identifying number using the server
488 * name, port number, random data, and optionally an object name and/or object
489 * number. The result is formatted as a UUID URN as defined in RFC 4122.
491 * The buffer needs to be at least 46 bytes in size.
493 * @since CUPS 1.7/macOS 10.9@
496 char * /* I - UUID string */
497 httpAssembleUUID(const char *server
, /* I - Server name */
498 int port
, /* I - Port number */
499 const char *name
, /* I - Object name or NULL */
500 int number
, /* I - Object number or 0 */
501 char *buffer
, /* I - String buffer */
502 size_t bufsize
) /* I - Size of buffer */
504 char data
[1024]; /* Source string for MD5 */
505 unsigned char md5sum
[16]; /* MD5 digest/sum */
509 * Build a version 3 UUID conforming to RFC 4122.
511 * Start with the MD5 sum of the server, port, object name and
512 * number, and some random data on the end.
515 snprintf(data
, sizeof(data
), "%s:%d:%s:%d:%04x:%04x", server
,
516 port
, name
? name
: server
, number
,
517 (unsigned)CUPS_RAND() & 0xffff, (unsigned)CUPS_RAND() & 0xffff);
519 cupsHashData("md5", (unsigned char *)data
, strlen(data
), md5sum
, sizeof(md5sum
));
522 * Generate the UUID from the MD5...
525 snprintf(buffer
, bufsize
,
526 "urn:uuid:%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-"
527 "%02x%02x%02x%02x%02x%02x",
528 md5sum
[0], md5sum
[1], md5sum
[2], md5sum
[3], md5sum
[4], md5sum
[5],
529 (md5sum
[6] & 15) | 0x30, md5sum
[7], (md5sum
[8] & 0x3f) | 0x40,
530 md5sum
[9], md5sum
[10], md5sum
[11], md5sum
[12], md5sum
[13],
531 md5sum
[14], md5sum
[15]);
538 * 'httpDecode64()' - Base64-decode a string.
540 * This function is deprecated. Use the httpDecode64_2() function instead
541 * which provides buffer length arguments.
543 * @deprecated@ @exclude all@
546 char * /* O - Decoded string */
547 httpDecode64(char *out
, /* I - String to write to */
548 const char *in
) /* I - String to read from */
550 int outlen
; /* Output buffer length */
554 * Use the old maximum buffer size for binary compatibility...
559 return (httpDecode64_2(out
, &outlen
, in
));
564 * 'httpDecode64_2()' - Base64-decode a string.
566 * The caller must initialize "outlen" to the maximum size of the decoded
567 * string before calling @code httpDecode64_2@. On return "outlen" contains the
568 * decoded length of the string.
570 * @since CUPS 1.1.21/macOS 10.4@
573 char * /* O - Decoded string */
574 httpDecode64_2(char *out
, /* I - String to write to */
575 int *outlen
, /* IO - Size of output string */
576 const char *in
) /* I - String to read from */
578 int pos
; /* Bit position */
579 unsigned base64
; /* Value of this character */
580 char *outptr
, /* Output pointer */
581 *outend
; /* End of output buffer */
585 * Range check input...
588 if (!out
|| !outlen
|| *outlen
< 1 || !in
)
600 * Convert from base-64 to bytes...
603 for (outptr
= out
, outend
= out
+ *outlen
- 1, pos
= 0; *in
!= '\0'; in
++)
606 * Decode this character into a number from 0 to 63...
609 if (*in
>= 'A' && *in
<= 'Z')
610 base64
= (unsigned)(*in
- 'A');
611 else if (*in
>= 'a' && *in
<= 'z')
612 base64
= (unsigned)(*in
- 'a' + 26);
613 else if (*in
>= '0' && *in
<= '9')
614 base64
= (unsigned)(*in
- '0' + 52);
625 * Store the result in the appropriate chars...
632 *outptr
= (char)(base64
<< 2);
637 *outptr
++ |= (char)((base64
>> 4) & 3);
639 *outptr
= (char)((base64
<< 4) & 255);
644 *outptr
++ |= (char)((base64
>> 2) & 15);
646 *outptr
= (char)((base64
<< 6) & 255);
651 *outptr
++ |= (char)base64
;
660 * Return the decoded string and size...
663 *outlen
= (int)(outptr
- out
);
670 * '_httpDigest()' - Calculate a Digest authentication response using the
671 * appropriate RFC 2068/2617/7616 algorithm.
674 char * /* O - Response string */
675 _httpDigest(char *buffer
, /* I - Response buffer */
676 size_t bufsize
, /* I - Size of response buffer */
677 const char *algorithm
, /* I - algorithm value or `NULL` */
678 const char *username
, /* I - username value */
679 const char *realm
, /* I - realm value */
680 const char *password
, /* I - password value */
681 const char *nonce
, /* I - nonce value */
682 unsigned nc
, /* I - nc value */
683 const char *cnonce
, /* I - cnonce value or `NULL` */
684 const char *qop
, /* I - qop value */
685 const char *method
, /* I - HTTP method */
686 const char *resource
) /* I - HTTP resource path */
688 char ha1
[65], /* Hash of username:realm:password */
689 ha2
[65], /* Hash of method:request-uri */
690 temp
[1024]; /* Temporary string */
691 unsigned char hash
[32]; /* Hash buffer */
692 const char *hashalg
; /* Hashing algorithm */
693 size_t hashsize
; /* Size of hash */
696 DEBUG_printf(("2_httpDigest(buffer=%p, bufsize=" CUPS_LLFMT
", algorithm=\%s\", username=\"%s\", realm=\"%s\", password=\"%d chars\", nonce=\"%s\", nc=%u, cnonce=\"%s\", qop=\"%s\", method=\"%s\", resource=\"%s\")", buffer
, CUPS_LLCAST bufsize
, algorithm
, username
, realm
, (int)strlen(password
), nonce
, nc
, cnonce
, qop
, method
, resource
));
701 * Follow RFC 2617/7616...
704 if (!_cups_strcasecmp(algorithm
, "MD5"))
707 * RFC 2617 Digest with MD5
712 else if (!_cups_strcasecmp(algorithm
, "SHA-256"))
715 * RFC 7616 Digest with SHA-256
718 hashalg
= "sha2-256";
723 * Some other algorithm we don't support, skip this one...
732 * Calculate digest value...
735 /* H(A1) = H(username:realm:password) */
736 snprintf(temp
, sizeof(temp
), "%s:%s:%s", username
, realm
, password
);
737 hashsize
= (size_t)cupsHashData(hashalg
, (unsigned char *)temp
, strlen(temp
), hash
, sizeof(hash
));
738 cupsHashString(hash
, hashsize
, ha1
, sizeof(ha1
));
740 /* H(A2) = H(method:uri) */
741 snprintf(temp
, sizeof(temp
), "%s:%s", method
, resource
);
742 hashsize
= (size_t)cupsHashData(hashalg
, (unsigned char *)temp
, strlen(temp
), hash
, sizeof(hash
));
743 cupsHashString(hash
, hashsize
, ha2
, sizeof(ha2
));
745 /* KD = H(H(A1):nonce:nc:cnonce:qop:H(A2)) */
746 snprintf(temp
, sizeof(temp
), "%s:%s:%08x:%s:%s:%s", ha1
, nonce
, nc
, cnonce
, qop
, ha2
);
747 hashsize
= (size_t)cupsHashData(hashalg
, (unsigned char *)temp
, strlen(temp
), hash
, sizeof(hash
));
748 cupsHashString(hash
, hashsize
, buffer
, bufsize
);
753 * Use old RFC 2069 Digest method...
756 /* H(A1) = H(username:realm:password) */
757 snprintf(temp
, sizeof(temp
), "%s:%s:%s", username
, realm
, password
);
758 hashsize
= (size_t)cupsHashData("md5", (unsigned char *)temp
, strlen(temp
), hash
, sizeof(hash
));
759 cupsHashString(hash
, hashsize
, ha1
, sizeof(ha1
));
761 /* H(A2) = H(method:uri) */
762 snprintf(temp
, sizeof(temp
), "%s:%s", method
, resource
);
763 hashsize
= (size_t)cupsHashData("md5", (unsigned char *)temp
, strlen(temp
), hash
, sizeof(hash
));
764 cupsHashString(hash
, hashsize
, ha2
, sizeof(ha2
));
766 /* KD = H(H(A1):nonce:H(A2)) */
767 snprintf(temp
, sizeof(temp
), "%s:%s:%s", ha1
, nonce
, ha2
);
768 hashsize
= (size_t)cupsHashData("md5", (unsigned char *)temp
, strlen(temp
), hash
, sizeof(hash
));
769 cupsHashString(hash
, hashsize
, buffer
, bufsize
);
777 * 'httpEncode64()' - Base64-encode a string.
779 * This function is deprecated. Use the httpEncode64_2() function instead
780 * which provides buffer length arguments.
782 * @deprecated@ @exclude all@
785 char * /* O - Encoded string */
786 httpEncode64(char *out
, /* I - String to write to */
787 const char *in
) /* I - String to read from */
789 return (httpEncode64_2(out
, 512, in
, (int)strlen(in
)));
794 * 'httpEncode64_2()' - Base64-encode a string.
796 * @since CUPS 1.1.21/macOS 10.4@
799 char * /* O - Encoded string */
800 httpEncode64_2(char *out
, /* I - String to write to */
801 int outlen
, /* I - Maximum size of output string */
802 const char *in
, /* I - String to read from */
803 int inlen
) /* I - Size of input string */
805 char *outptr
, /* Output pointer */
806 *outend
; /* End of output buffer */
807 static const char base64
[] = /* Base64 characters... */
809 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
810 "abcdefghijklmnopqrstuvwxyz"
817 * Range check input...
820 if (!out
|| outlen
< 1 || !in
)
824 * Convert bytes to base-64...
827 for (outptr
= out
, outend
= out
+ outlen
- 1; inlen
> 0; in
++, inlen
--)
830 * Encode the up to 3 characters as 4 Base64 numbers...
834 *outptr
++ = base64
[(in
[0] & 255) >> 2];
839 *outptr
++ = base64
[(((in
[0] & 255) << 4) | ((in
[1] & 255) >> 4)) & 63];
841 *outptr
++ = base64
[((in
[0] & 255) << 4) & 63];
858 *outptr
++ = base64
[(((in
[0] & 255) << 2) | ((in
[1] & 255) >> 6)) & 63];
860 *outptr
++ = base64
[((in
[0] & 255) << 2) & 63];
873 *outptr
++ = base64
[in
[0] & 63];
879 * Return the encoded string...
887 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
889 * @deprecated@ @exclude all@
892 const char * /* O - Date/time string */
893 httpGetDateString(time_t t
) /* I - Time in seconds */
895 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
898 return (httpGetDateString2(t
, cg
->http_date
, sizeof(cg
->http_date
)));
903 * 'httpGetDateString2()' - Get a formatted date/time string from a time value.
905 * @since CUPS 1.2/macOS 10.5@
908 const char * /* O - Date/time string */
909 httpGetDateString2(time_t t
, /* I - Time in seconds */
910 char *s
, /* I - String buffer */
911 int slen
) /* I - Size of string buffer */
913 struct tm
*tdate
; /* UNIX date/time data */
918 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
);
927 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
930 time_t /* O - Time in seconds */
931 httpGetDateTime(const char *s
) /* I - Date/time string */
933 int i
; /* Looping var */
934 char mon
[16]; /* Abbreviated month name */
935 int day
, year
; /* Day of month and year */
936 int hour
, min
, sec
; /* Time */
937 int days
; /* Number of days since 1970 */
938 static const int normal_days
[] = /* Days to a month, normal years */
939 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
940 static const int leap_days
[] = /* Days to a month, leap years */
941 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 };
944 DEBUG_printf(("2httpGetDateTime(s=\"%s\")", s
));
947 * Extract the date and time from the formatted string...
950 if (sscanf(s
, "%*s%d%15s%d%d:%d:%d", &day
, mon
, &year
, &hour
, &min
, &sec
) < 6)
953 DEBUG_printf(("4httpGetDateTime: day=%d, mon=\"%s\", year=%d, hour=%d, "
954 "min=%d, sec=%d", day
, mon
, year
, hour
, min
, sec
));
957 * Convert the month name to a number from 0 to 11.
960 for (i
= 0; i
< 12; i
++)
961 if (!_cups_strcasecmp(mon
, http_months
[i
]))
967 DEBUG_printf(("4httpGetDateTime: i=%d", i
));
970 * Now convert the date and time to a UNIX time value in seconds since
971 * 1970. We can't use mktime() since the timezone may not be UTC but
972 * the date/time string *is* UTC.
975 if ((year
& 3) == 0 && ((year
% 100) != 0 || (year
% 400) == 0))
976 days
= leap_days
[i
] + day
- 1;
978 days
= normal_days
[i
] + day
- 1;
980 DEBUG_printf(("4httpGetDateTime: days=%d", days
));
982 days
+= (year
- 1970) * 365 + /* 365 days per year (normally) */
983 ((year
- 1) / 4 - 492) - /* + leap days */
984 ((year
- 1) / 100 - 19) + /* - 100 year days */
985 ((year
- 1) / 400 - 4); /* + 400 year days */
987 DEBUG_printf(("4httpGetDateTime: days=%d\n", days
));
989 return (days
* 86400 + hour
* 3600 + min
* 60 + sec
);
994 * 'httpSeparate()' - Separate a Universal Resource Identifier into its
997 * This function is deprecated; use the httpSeparateURI() function instead.
999 * @deprecated@ @exclude all@
1003 httpSeparate(const char *uri
, /* I - Universal Resource Identifier */
1004 char *scheme
, /* O - Scheme [32] (http, https, etc.) */
1005 char *username
, /* O - Username [1024] */
1006 char *host
, /* O - Hostname [1024] */
1007 int *port
, /* O - Port number to use */
1008 char *resource
) /* O - Resource/filename [1024] */
1010 httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, 32, username
,
1011 HTTP_MAX_URI
, host
, HTTP_MAX_URI
, port
, resource
,
1017 * 'httpSeparate2()' - Separate a Universal Resource Identifier into its
1020 * This function is deprecated; use the httpSeparateURI() function instead.
1022 * @since CUPS 1.1.21/macOS 10.4@
1023 * @deprecated@ @exclude all@
1027 httpSeparate2(const char *uri
, /* I - Universal Resource Identifier */
1028 char *scheme
, /* O - Scheme (http, https, etc.) */
1029 int schemelen
, /* I - Size of scheme buffer */
1030 char *username
, /* O - Username */
1031 int usernamelen
, /* I - Size of username buffer */
1032 char *host
, /* O - Hostname */
1033 int hostlen
, /* I - Size of hostname buffer */
1034 int *port
, /* O - Port number to use */
1035 char *resource
, /* O - Resource/filename */
1036 int resourcelen
) /* I - Size of resource buffer */
1038 httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, schemelen
, username
,
1039 usernamelen
, host
, hostlen
, port
, resource
, resourcelen
);
1044 * 'httpSeparateURI()' - Separate a Universal Resource Identifier into its
1047 * @since CUPS 1.2/macOS 10.5@
1050 http_uri_status_t
/* O - Result of separation */
1052 http_uri_coding_t decoding
, /* I - Decoding flags */
1053 const char *uri
, /* I - Universal Resource Identifier */
1054 char *scheme
, /* O - Scheme (http, https, etc.) */
1055 int schemelen
, /* I - Size of scheme buffer */
1056 char *username
, /* O - Username */
1057 int usernamelen
, /* I - Size of username buffer */
1058 char *host
, /* O - Hostname */
1059 int hostlen
, /* I - Size of hostname buffer */
1060 int *port
, /* O - Port number to use */
1061 char *resource
, /* O - Resource/filename */
1062 int resourcelen
) /* I - Size of resource buffer */
1064 char *ptr
, /* Pointer into string... */
1065 *end
; /* End of string */
1066 const char *sep
; /* Separator character */
1067 http_uri_status_t status
; /* Result of separation */
1071 * Initialize everything to blank...
1074 if (scheme
&& schemelen
> 0)
1077 if (username
&& usernamelen
> 0)
1080 if (host
&& hostlen
> 0)
1086 if (resource
&& resourcelen
> 0)
1090 * Range check input...
1093 if (!uri
|| !port
|| !scheme
|| schemelen
<= 0 || !username
||
1094 usernamelen
<= 0 || !host
|| hostlen
<= 0 || !resource
||
1096 return (HTTP_URI_STATUS_BAD_ARGUMENTS
);
1099 return (HTTP_URI_STATUS_BAD_URI
);
1102 * Grab the scheme portion of the URI...
1105 status
= HTTP_URI_STATUS_OK
;
1107 if (!strncmp(uri
, "//", 2))
1110 * Workaround for HP IPP client bug...
1113 strlcpy(scheme
, "ipp", (size_t)schemelen
);
1114 status
= HTTP_URI_STATUS_MISSING_SCHEME
;
1116 else if (*uri
== '/')
1122 strlcpy(scheme
, "file", (size_t)schemelen
);
1123 status
= HTTP_URI_STATUS_MISSING_SCHEME
;
1128 * Standard URI with scheme...
1131 for (ptr
= scheme
, end
= scheme
+ schemelen
- 1;
1132 *uri
&& *uri
!= ':' && ptr
< end
;)
1133 if (strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1134 "abcdefghijklmnopqrstuvwxyz"
1135 "0123456789-+.", *uri
) != NULL
)
1142 if (*uri
!= ':' || *scheme
== '.' || !*scheme
)
1145 return (HTTP_URI_STATUS_BAD_SCHEME
);
1152 * Set the default port number...
1155 if (!strcmp(scheme
, "http"))
1157 else if (!strcmp(scheme
, "https"))
1159 else if (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps"))
1161 else if (!_cups_strcasecmp(scheme
, "lpd"))
1163 else if (!strcmp(scheme
, "socket")) /* Not yet registered with IANA... */
1165 else if (strcmp(scheme
, "file") && strcmp(scheme
, "mailto") && strcmp(scheme
, "tel"))
1166 status
= HTTP_URI_STATUS_UNKNOWN_SCHEME
;
1169 * Now see if we have a hostname...
1172 if (!strncmp(uri
, "//", 2))
1175 * Yes, extract it...
1181 * Grab the username, if any...
1184 if ((sep
= strpbrk(uri
, "@/")) != NULL
&& *sep
== '@')
1187 * Get a username:password combo...
1190 uri
= http_copy_decode(username
, uri
, usernamelen
, "@",
1191 decoding
& HTTP_URI_CODING_USERNAME
);
1196 return (HTTP_URI_STATUS_BAD_USERNAME
);
1203 * Then the hostname/IP address...
1209 * Grab IPv6 address...
1216 * Skip IPvFuture ("vXXXX.") prefix...
1221 while (isxdigit(*uri
& 255))
1227 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1233 uri
= http_copy_decode(host
, uri
, hostlen
, "]",
1234 decoding
& HTTP_URI_CODING_HOSTNAME
);
1239 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1249 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1254 for (ptr
= host
; *ptr
; ptr
++)
1258 * Convert zone separator to % and stop here...
1264 else if (*ptr
== '%')
1267 * Stop at zone separator (RFC 6874)
1272 else if (*ptr
!= ':' && *ptr
!= '.' && !isxdigit(*ptr
& 255))
1275 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1281 * Validate the hostname or IPv4 address first...
1284 for (ptr
= (char *)uri
; *ptr
; ptr
++)
1285 if (strchr(":?/", *ptr
))
1287 else if (!strchr("abcdefghijklmnopqrstuvwxyz" /* unreserved */
1288 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" /* unreserved */
1289 "0123456789" /* unreserved */
1290 "-._~" /* unreserved */
1291 "%" /* pct-encoded */
1292 "!$&'()*+,;=" /* sub-delims */
1293 "\\", *ptr
)) /* SMB domain */
1296 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1300 * Then copy the hostname or IPv4 address to the buffer...
1303 uri
= http_copy_decode(host
, uri
, hostlen
, ":?/",
1304 decoding
& HTTP_URI_CODING_HOSTNAME
);
1309 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1314 * Validate hostname for file scheme - only empty and localhost are
1318 if (!strcmp(scheme
, "file") && strcmp(host
, "localhost") && host
[0])
1321 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1325 * See if we have a port number...
1331 * Yes, collect the port number...
1334 if (!isdigit(uri
[1] & 255))
1337 return (HTTP_URI_STATUS_BAD_PORT
);
1340 *port
= (int)strtol(uri
+ 1, (char **)&uri
, 10);
1342 if (*port
<= 0 || *port
> 65535)
1345 return (HTTP_URI_STATUS_BAD_PORT
);
1348 if (*uri
!= '/' && *uri
)
1351 return (HTTP_URI_STATUS_BAD_PORT
);
1357 * The remaining portion is the resource string...
1360 if (*uri
== '?' || !*uri
)
1363 * Hostname but no path...
1366 status
= HTTP_URI_STATUS_MISSING_RESOURCE
;
1370 * Copy any query string...
1374 uri
= http_copy_decode(resource
+ 1, uri
, resourcelen
- 1, NULL
,
1375 decoding
& HTTP_URI_CODING_QUERY
);
1381 uri
= http_copy_decode(resource
, uri
, resourcelen
, "?",
1382 decoding
& HTTP_URI_CODING_RESOURCE
);
1384 if (uri
&& *uri
== '?')
1387 * Concatenate any query string...
1390 char *resptr
= resource
+ strlen(resource
);
1392 uri
= http_copy_decode(resptr
, uri
,
1393 resourcelen
- (int)(resptr
- resource
), NULL
,
1394 decoding
& HTTP_URI_CODING_QUERY
);
1401 return (HTTP_URI_STATUS_BAD_RESOURCE
);
1405 * Return the URI separation status...
1413 * 'httpStateString()' - Return the string describing a HTTP state value.
1415 * @since CUPS 2.0/OS 10.10@
1418 const char * /* O - State string */
1419 httpStateString(http_state_t state
) /* I - HTTP state value */
1421 if (state
< HTTP_STATE_ERROR
|| state
> HTTP_STATE_UNKNOWN_VERSION
)
1422 return ("HTTP_STATE_???");
1424 return (http_states
[state
- HTTP_STATE_ERROR
]);
1429 * '_httpStatus()' - Return the localized string describing a HTTP status code.
1431 * The returned string is localized using the passed message catalog.
1434 const char * /* O - Localized status string */
1435 _httpStatus(cups_lang_t
*lang
, /* I - Language */
1436 http_status_t status
) /* I - HTTP status code */
1438 const char *s
; /* Status string */
1443 case HTTP_STATUS_ERROR
:
1444 s
= strerror(errno
);
1446 case HTTP_STATUS_CONTINUE
:
1449 case HTTP_STATUS_SWITCHING_PROTOCOLS
:
1450 s
= _("Switching Protocols");
1452 case HTTP_STATUS_OK
:
1455 case HTTP_STATUS_CREATED
:
1458 case HTTP_STATUS_ACCEPTED
:
1461 case HTTP_STATUS_NO_CONTENT
:
1462 s
= _("No Content");
1464 case HTTP_STATUS_MOVED_PERMANENTLY
:
1465 s
= _("Moved Permanently");
1467 case HTTP_STATUS_FOUND
:
1470 case HTTP_STATUS_SEE_OTHER
:
1473 case HTTP_STATUS_NOT_MODIFIED
:
1474 s
= _("Not Modified");
1476 case HTTP_STATUS_BAD_REQUEST
:
1477 s
= _("Bad Request");
1479 case HTTP_STATUS_UNAUTHORIZED
:
1480 case HTTP_STATUS_CUPS_AUTHORIZATION_CANCELED
:
1481 s
= _("Unauthorized");
1483 case HTTP_STATUS_FORBIDDEN
:
1486 case HTTP_STATUS_NOT_FOUND
:
1489 case HTTP_STATUS_REQUEST_TOO_LARGE
:
1490 s
= _("Request Entity Too Large");
1492 case HTTP_STATUS_URI_TOO_LONG
:
1493 s
= _("URI Too Long");
1495 case HTTP_STATUS_UPGRADE_REQUIRED
:
1496 s
= _("Upgrade Required");
1498 case HTTP_STATUS_NOT_IMPLEMENTED
:
1499 s
= _("Not Implemented");
1501 case HTTP_STATUS_NOT_SUPPORTED
:
1502 s
= _("Not Supported");
1504 case HTTP_STATUS_EXPECTATION_FAILED
:
1505 s
= _("Expectation Failed");
1507 case HTTP_STATUS_SERVICE_UNAVAILABLE
:
1508 s
= _("Service Unavailable");
1510 case HTTP_STATUS_SERVER_ERROR
:
1511 s
= _("Internal Server Error");
1513 case HTTP_STATUS_CUPS_PKI_ERROR
:
1514 s
= _("SSL/TLS Negotiation Error");
1516 case HTTP_STATUS_CUPS_WEBIF_DISABLED
:
1517 s
= _("Web Interface is Disabled");
1525 return (_cupsLangString(lang
, s
));
1530 * 'httpStatus()' - Return a short string describing a HTTP status code.
1532 * The returned string is localized to the current POSIX locale and is based
1533 * on the status strings defined in RFC 7231.
1536 const char * /* O - Localized status string */
1537 httpStatus(http_status_t status
) /* I - HTTP status code */
1539 _cups_globals_t
*cg
= _cupsGlobals(); /* Global data */
1542 if (!cg
->lang_default
)
1543 cg
->lang_default
= cupsLangDefault();
1545 return (_httpStatus(cg
->lang_default
, status
));
1549 * 'httpURIStatusString()' - Return a string describing a URI status code.
1551 * @since CUPS 2.0/OS 10.10@
1554 const char * /* O - Localized status string */
1555 httpURIStatusString(
1556 http_uri_status_t status
) /* I - URI status code */
1558 const char *s
; /* Status string */
1559 _cups_globals_t
*cg
= _cupsGlobals(); /* Global data */
1562 if (!cg
->lang_default
)
1563 cg
->lang_default
= cupsLangDefault();
1567 case HTTP_URI_STATUS_OVERFLOW
:
1568 s
= _("URI too large");
1570 case HTTP_URI_STATUS_BAD_ARGUMENTS
:
1571 s
= _("Bad arguments to function");
1573 case HTTP_URI_STATUS_BAD_RESOURCE
:
1574 s
= _("Bad resource in URI");
1576 case HTTP_URI_STATUS_BAD_PORT
:
1577 s
= _("Bad port number in URI");
1579 case HTTP_URI_STATUS_BAD_HOSTNAME
:
1580 s
= _("Bad hostname/address in URI");
1582 case HTTP_URI_STATUS_BAD_USERNAME
:
1583 s
= _("Bad username in URI");
1585 case HTTP_URI_STATUS_BAD_SCHEME
:
1586 s
= _("Bad scheme in URI");
1588 case HTTP_URI_STATUS_BAD_URI
:
1589 s
= _("Bad/empty URI");
1591 case HTTP_URI_STATUS_OK
:
1594 case HTTP_URI_STATUS_MISSING_SCHEME
:
1595 s
= _("Missing scheme in URI");
1597 case HTTP_URI_STATUS_UNKNOWN_SCHEME
:
1598 s
= _("Unknown scheme in URI");
1600 case HTTP_URI_STATUS_MISSING_RESOURCE
:
1601 s
= _("Missing resource in URI");
1609 return (_cupsLangString(cg
->lang_default
, s
));
1613 #ifndef HAVE_HSTRERROR
1615 * '_cups_hstrerror()' - hstrerror() emulation function for Solaris and others.
1618 const char * /* O - Error string */
1619 _cups_hstrerror(int error
) /* I - Error number */
1621 static const char * const errors
[] = /* Error strings */
1626 "Unrecoverable lookup error.",
1627 "No data associated with name."
1631 if (error
< 0 || error
> 4)
1632 return ("Unknown hostname lookup error.");
1634 return (errors
[error
]);
1636 #endif /* !HAVE_HSTRERROR */
1640 * '_httpDecodeURI()' - Percent-decode a HTTP request URI.
1643 char * /* O - Decoded URI or NULL on error */
1644 _httpDecodeURI(char *dst
, /* I - Destination buffer */
1645 const char *src
, /* I - Source URI */
1646 size_t dstsize
) /* I - Size of destination buffer */
1648 if (http_copy_decode(dst
, src
, (int)dstsize
, NULL
, 1))
1656 * '_httpEncodeURI()' - Percent-encode a HTTP request URI.
1659 char * /* O - Encoded URI */
1660 _httpEncodeURI(char *dst
, /* I - Destination buffer */
1661 const char *src
, /* I - Source URI */
1662 size_t dstsize
) /* I - Size of destination buffer */
1664 http_copy_encode(dst
, src
, dst
+ dstsize
- 1, NULL
, NULL
, 1);
1670 * '_httpResolveURI()' - Resolve a DNS-SD URI.
1673 const char * /* O - Resolved URI */
1675 const char *uri
, /* I - DNS-SD URI */
1676 char *resolved_uri
, /* I - Buffer for resolved URI */
1677 size_t resolved_size
, /* I - Size of URI buffer */
1678 int options
, /* I - Resolve options */
1679 int (*cb
)(void *context
), /* I - Continue callback function */
1680 void *context
) /* I - Context pointer for callback */
1682 char scheme
[32], /* URI components... */
1688 http_uri_status_t status
; /* URI decode status */
1692 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
));
1695 * Get the device URI...
1699 if ((status
= httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
,
1700 sizeof(scheme
), userpass
, sizeof(userpass
),
1701 hostname
, sizeof(hostname
), &port
, resource
,
1702 sizeof(resource
))) < HTTP_URI_STATUS_OK
)
1704 if (httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
,
1705 sizeof(scheme
), userpass
, sizeof(userpass
),
1706 hostname
, sizeof(hostname
), &port
, resource
,
1707 sizeof(resource
)) < HTTP_URI_STATUS_OK
)
1710 if (options
& _HTTP_RESOLVE_STDERR
)
1711 _cupsLangPrintFilter(stderr
, "ERROR", _("Bad device-uri \"%s\"."), uri
);
1713 DEBUG_printf(("2_httpResolveURI: httpSeparateURI returned %d!", status
));
1714 DEBUG_puts("2_httpResolveURI: Returning NULL");
1719 * Resolve it as needed...
1722 if (strstr(hostname
, "._tcp"))
1724 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
1725 char *regtype
, /* Pointer to type in hostname */
1726 *domain
, /* Pointer to domain in hostname */
1727 *uuid
, /* Pointer to UUID in URI */
1728 *uuidend
; /* Pointer to end of UUID in URI */
1729 _http_uribuf_t uribuf
; /* URI buffer */
1730 int offline
= 0; /* offline-report state set? */
1733 # pragma comment(lib, "dnssd.lib")
1735 DNSServiceRef ref
, /* DNS-SD master service reference */
1736 domainref
= NULL
,/* DNS-SD service reference for domain */
1737 ippref
= NULL
, /* DNS-SD service reference for network IPP */
1738 ippsref
= NULL
, /* DNS-SD service reference for network IPPS */
1739 localref
; /* DNS-SD service reference for .local */
1740 int extrasent
= 0; /* Send the domain/IPP/IPPS resolves? */
1742 struct pollfd polldata
; /* Polling data */
1743 # else /* select() */
1744 fd_set input_set
; /* Input set for select() */
1745 struct timeval stimeout
; /* Timeout value for select() */
1746 # endif /* HAVE_POLL */
1747 # elif defined(HAVE_AVAHI)
1748 AvahiClient
*client
; /* Client information */
1749 int error
; /* Status */
1750 # endif /* HAVE_DNSSD */
1752 if (options
& _HTTP_RESOLVE_STDERR
)
1753 fprintf(stderr
, "DEBUG: Resolving \"%s\"...\n", hostname
);
1756 * Separate the hostname into service name, registration type, and domain...
1759 for (regtype
= strstr(hostname
, "._tcp") - 2;
1762 if (regtype
[0] == '.' && regtype
[1] == '_')
1765 * Found ._servicetype in front of ._tcp...
1772 if (regtype
<= hostname
)
1774 DEBUG_puts("2_httpResolveURI: Bad hostname, returning NULL");
1778 for (domain
= strchr(regtype
, '.');
1780 domain
= strchr(domain
+ 1, '.'))
1781 if (domain
[1] != '_')
1787 if ((uuid
= strstr(resource
, "?uuid=")) != NULL
)
1791 if ((uuidend
= strchr(uuid
, '&')) != NULL
)
1795 resolved_uri
[0] = '\0';
1797 uribuf
.buffer
= resolved_uri
;
1798 uribuf
.bufsize
= resolved_size
;
1799 uribuf
.options
= options
;
1800 uribuf
.resource
= resource
;
1803 DEBUG_printf(("2_httpResolveURI: Resolving hostname=\"%s\", regtype=\"%s\", "
1804 "domain=\"%s\"\n", hostname
, regtype
, domain
));
1805 if (options
& _HTTP_RESOLVE_STDERR
)
1807 fputs("STATE: +connecting-to-device\n", stderr
);
1808 fprintf(stderr
, "DEBUG: Resolving \"%s\", regtype=\"%s\", "
1809 "domain=\"local.\"...\n", hostname
, regtype
);
1815 if (DNSServiceCreateConnection(&ref
) == kDNSServiceErr_NoError
)
1817 uint32_t myinterface
= kDNSServiceInterfaceIndexAny
;
1818 /* Lookup on any interface */
1820 if (!strcmp(scheme
, "ippusb"))
1821 myinterface
= kDNSServiceInterfaceIndexLocalOnly
;
1824 if (DNSServiceResolve(&localref
,
1825 kDNSServiceFlagsShareConnection
, myinterface
,
1826 hostname
, regtype
, "local.", http_resolve_cb
,
1827 &uribuf
) == kDNSServiceErr_NoError
)
1829 int fds
; /* Number of ready descriptors */
1830 time_t timeout
, /* Poll timeout */
1831 start_time
= time(NULL
),/* Start time */
1832 end_time
= start_time
+ 90;
1835 while (time(NULL
) < end_time
)
1837 if (options
& _HTTP_RESOLVE_STDERR
)
1838 _cupsLangPrintFilter(stderr
, "INFO", _("Looking for printer."));
1840 if (cb
&& !(*cb
)(context
))
1842 DEBUG_puts("2_httpResolveURI: callback returned 0 (stop)");
1847 * Wakeup every 2 seconds to emit a "looking for printer" message...
1850 if ((timeout
= end_time
- time(NULL
)) > 2)
1854 polldata
.fd
= DNSServiceRefSockFD(ref
);
1855 polldata
.events
= POLLIN
;
1857 fds
= poll(&polldata
, 1, (int)(1000 * timeout
));
1859 # else /* select() */
1860 FD_ZERO(&input_set
);
1861 FD_SET(DNSServiceRefSockFD(ref
), &input_set
);
1864 stimeout
.tv_sec
= (long)timeout
;
1866 stimeout
.tv_sec
= timeout
;
1868 stimeout
.tv_usec
= 0;
1870 fds
= select(DNSServiceRefSockFD(ref
)+1, &input_set
, NULL
, NULL
,
1872 # endif /* HAVE_POLL */
1876 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1878 DEBUG_printf(("2_httpResolveURI: poll error: %s", strerror(errno
)));
1885 * Wait 2 seconds for a response to the local resolve; if nothing
1886 * comes in, do an additional domain resolution...
1889 if (extrasent
== 0 && domain
&& _cups_strcasecmp(domain
, "local."))
1891 if (options
& _HTTP_RESOLVE_STDERR
)
1893 "DEBUG: Resolving \"%s\", regtype=\"%s\", "
1894 "domain=\"%s\"...\n", hostname
, regtype
,
1895 domain
? domain
: "");
1898 if (DNSServiceResolve(&domainref
,
1899 kDNSServiceFlagsShareConnection
,
1900 myinterface
, hostname
, regtype
, domain
,
1902 &uribuf
) == kDNSServiceErr_NoError
)
1905 else if (extrasent
== 0 && !strcmp(scheme
, "ippusb"))
1907 if (options
& _HTTP_RESOLVE_STDERR
)
1908 fprintf(stderr
, "DEBUG: Resolving \"%s\", regtype=\"_ipps._tcp\", domain=\"local.\"...\n", hostname
);
1911 if (DNSServiceResolve(&ippsref
,
1912 kDNSServiceFlagsShareConnection
,
1913 kDNSServiceInterfaceIndexAny
, hostname
,
1914 "_ipps._tcp", domain
, http_resolve_cb
,
1915 &uribuf
) == kDNSServiceErr_NoError
)
1918 else if (extrasent
== 1 && !strcmp(scheme
, "ippusb"))
1920 if (options
& _HTTP_RESOLVE_STDERR
)
1921 fprintf(stderr
, "DEBUG: Resolving \"%s\", regtype=\"_ipp._tcp\", domain=\"local.\"...\n", hostname
);
1924 if (DNSServiceResolve(&ippref
,
1925 kDNSServiceFlagsShareConnection
,
1926 kDNSServiceInterfaceIndexAny
, hostname
,
1927 "_ipp._tcp", domain
, http_resolve_cb
,
1928 &uribuf
) == kDNSServiceErr_NoError
)
1933 * If it hasn't resolved within 5 seconds set the offline-report
1934 * printer-state-reason...
1937 if ((options
& _HTTP_RESOLVE_STDERR
) && offline
== 0 &&
1938 time(NULL
) > (start_time
+ 5))
1940 fputs("STATE: +offline-report\n", stderr
);
1946 if (DNSServiceProcessResult(ref
) == kDNSServiceErr_NoError
&&
1958 DNSServiceRefDeallocate(domainref
);
1960 DNSServiceRefDeallocate(ippref
);
1962 DNSServiceRefDeallocate(ippsref
);
1965 DNSServiceRefDeallocate(localref
);
1968 DNSServiceRefDeallocate(ref
);
1970 # else /* HAVE_AVAHI */
1971 if ((uribuf
.poll
= avahi_simple_poll_new()) != NULL
)
1973 avahi_simple_poll_set_func(uribuf
.poll
, http_poll_cb
, NULL
);
1975 if ((client
= avahi_client_new(avahi_simple_poll_get(uribuf
.poll
),
1977 &uribuf
, &error
)) != NULL
)
1979 if (avahi_service_resolver_new(client
, AVAHI_IF_UNSPEC
,
1980 AVAHI_PROTO_UNSPEC
, hostname
,
1981 regtype
, "local.", AVAHI_PROTO_UNSPEC
, 0,
1982 http_resolve_cb
, &uribuf
) != NULL
)
1984 time_t start_time
= time(NULL
),
1986 end_time
= start_time
+ 90;
1988 int pstatus
; /* Poll status */
1990 pstatus
= avahi_simple_poll_iterate(uribuf
.poll
, 2000);
1992 if (pstatus
== 0 && !resolved_uri
[0] && domain
&&
1993 _cups_strcasecmp(domain
, "local."))
1996 * Resolve for .local hasn't returned anything, try the listed
2000 avahi_service_resolver_new(client
, AVAHI_IF_UNSPEC
,
2001 AVAHI_PROTO_UNSPEC
, hostname
,
2002 regtype
, domain
, AVAHI_PROTO_UNSPEC
, 0,
2003 http_resolve_cb
, &uribuf
);
2006 while (!pstatus
&& !resolved_uri
[0] && time(NULL
) < end_time
)
2008 if ((pstatus
= avahi_simple_poll_iterate(uribuf
.poll
, 2000)) != 0)
2012 * If it hasn't resolved within 5 seconds set the offline-report
2013 * printer-state-reason...
2016 if ((options
& _HTTP_RESOLVE_STDERR
) && offline
== 0 &&
2017 time(NULL
) > (start_time
+ 5))
2019 fputs("STATE: +offline-report\n", stderr
);
2025 * Collect the result (if we got one).
2028 if (resolved_uri
[0])
2032 avahi_client_free(client
);
2035 avahi_simple_poll_free(uribuf
.poll
);
2037 # endif /* HAVE_DNSSD */
2039 if (options
& _HTTP_RESOLVE_STDERR
)
2043 fprintf(stderr
, "DEBUG: Resolved as \"%s\"...\n", uri
);
2044 fputs("STATE: -connecting-to-device,offline-report\n", stderr
);
2048 fputs("DEBUG: Unable to resolve URI\n", stderr
);
2049 fputs("STATE: -connecting-to-device\n", stderr
);
2053 #else /* HAVE_DNSSD || HAVE_AVAHI */
2055 * No DNS-SD support...
2059 #endif /* HAVE_DNSSD || HAVE_AVAHI */
2061 if ((options
& _HTTP_RESOLVE_STDERR
) && !uri
)
2062 _cupsLangPrintFilter(stderr
, "INFO", _("Unable to find printer."));
2067 * Nothing more to do...
2070 strlcpy(resolved_uri
, uri
, resolved_size
);
2074 DEBUG_printf(("2_httpResolveURI: Returning \"%s\"", uri
));
2082 * 'http_client_cb()' - Client callback for resolving URI.
2087 AvahiClient
*client
, /* I - Client information */
2088 AvahiClientState state
, /* I - Current state */
2089 void *context
) /* I - Pointer to URI buffer */
2091 DEBUG_printf(("7http_client_cb(client=%p, state=%d, context=%p)", client
,
2095 * If the connection drops, quit.
2098 if (state
== AVAHI_CLIENT_FAILURE
)
2100 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
2103 avahi_simple_poll_quit(uribuf
->poll
);
2106 #endif /* HAVE_AVAHI */
2110 * 'http_copy_decode()' - Copy and decode a URI.
2113 static const char * /* O - New source pointer or NULL on error */
2114 http_copy_decode(char *dst
, /* O - Destination buffer */
2115 const char *src
, /* I - Source pointer */
2116 int dstsize
, /* I - Destination size */
2117 const char *term
, /* I - Terminating characters */
2118 int decode
) /* I - Decode %-encoded values */
2120 char *ptr
, /* Pointer into buffer */
2121 *end
; /* End of buffer */
2122 int quoted
; /* Quoted character */
2126 * Copy the src to the destination until we hit a terminating character
2127 * or the end of the string.
2130 for (ptr
= dst
, end
= dst
+ dstsize
- 1;
2131 *src
&& (!term
|| !strchr(term
, *src
));
2135 if (*src
== '%' && decode
)
2137 if (isxdigit(src
[1] & 255) && isxdigit(src
[2] & 255))
2140 * Grab a hex-encoded character...
2145 quoted
= (tolower(*src
) - 'a' + 10) << 4;
2147 quoted
= (*src
- '0') << 4;
2151 quoted
|= tolower(*src
) - 'a' + 10;
2153 quoted
|= *src
- '0';
2155 *ptr
++ = (char)quoted
;
2160 * Bad hex-encoded character...
2167 else if ((*src
& 255) <= 0x20 || (*src
& 255) >= 0x7f)
2183 * 'http_copy_encode()' - Copy and encode a URI.
2186 static char * /* O - End of current URI */
2187 http_copy_encode(char *dst
, /* O - Destination buffer */
2188 const char *src
, /* I - Source pointer */
2189 char *dstend
, /* I - End of destination buffer */
2190 const char *reserved
, /* I - Extra reserved characters */
2191 const char *term
, /* I - Terminating characters */
2192 int encode
) /* I - %-encode reserved chars? */
2194 static const char hex
[] = "0123456789ABCDEF";
2197 while (*src
&& dst
< dstend
)
2199 if (term
&& *src
== *term
)
2202 if (encode
&& (*src
== '%' || *src
<= ' ' || *src
& 128 ||
2203 (reserved
&& strchr(reserved
, *src
))))
2206 * Hex encode reserved characters...
2209 if ((dst
+ 2) >= dstend
)
2213 *dst
++ = hex
[(*src
>> 4) & 15];
2214 *dst
++ = hex
[*src
& 15];
2233 * 'http_resolve_cb()' - Build a device URI for the given service name.
2236 static void DNSSD_API
2238 DNSServiceRef sdRef
, /* I - Service reference */
2239 DNSServiceFlags flags
, /* I - Results flags */
2240 uint32_t interfaceIndex
, /* I - Interface number */
2241 DNSServiceErrorType errorCode
, /* I - Error, if any */
2242 const char *fullName
, /* I - Full service name */
2243 const char *hostTarget
, /* I - Hostname */
2244 uint16_t port
, /* I - Port number */
2245 uint16_t txtLen
, /* I - Length of TXT record */
2246 const unsigned char *txtRecord
, /* I - TXT record data */
2247 void *context
) /* I - Pointer to URI buffer */
2249 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
2251 const char *scheme
, /* URI scheme */
2252 *hostptr
, /* Pointer into hostTarget */
2253 *reskey
, /* "rp" or "rfo" */
2254 *resdefault
; /* Default path */
2255 char resource
[257], /* Remote path */
2256 fqdn
[256]; /* FQDN of the .local name */
2257 const void *value
; /* Value from TXT record */
2258 uint8_t valueLen
; /* Length of value */
2261 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
));
2264 * If we have a UUID, compare it...
2268 (value
= TXTRecordGetValuePtr(txtLen
, txtRecord
, "UUID",
2269 &valueLen
)) != NULL
)
2271 char uuid
[256]; /* UUID value */
2273 memcpy(uuid
, value
, valueLen
);
2274 uuid
[valueLen
] = '\0';
2276 if (_cups_strcasecmp(uuid
, uribuf
->uuid
))
2278 if (uribuf
->options
& _HTTP_RESOLVE_STDERR
)
2279 fprintf(stderr
, "DEBUG: Found UUID %s, looking for %s.", uuid
,
2282 DEBUG_printf(("5http_resolve_cb: Found UUID %s, looking for %s.", uuid
,
2289 * Figure out the scheme from the full name...
2292 if (strstr(fullName
, "._ipps") || strstr(fullName
, "._ipp-tls"))
2294 else if (strstr(fullName
, "._ipp") || strstr(fullName
, "._fax-ipp"))
2296 else if (strstr(fullName
, "._http."))
2298 else if (strstr(fullName
, "._https."))
2300 else if (strstr(fullName
, "._printer."))
2302 else if (strstr(fullName
, "._pdl-datastream."))
2305 scheme
= "riousbprint";
2308 * Extract the "remote printer" key from the TXT record...
2311 if ((uribuf
->options
& _HTTP_RESOLVE_FAXOUT
) &&
2312 (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")) &&
2313 !TXTRecordGetValuePtr(txtLen
, txtRecord
, "printer-type", &valueLen
))
2316 resdefault
= "/ipp/faxout";
2324 if ((value
= TXTRecordGetValuePtr(txtLen
, txtRecord
, reskey
,
2325 &valueLen
)) != NULL
)
2327 if (((char *)value
)[0] == '/')
2330 * Value (incorrectly) has a leading slash already...
2333 memcpy(resource
, value
, valueLen
);
2334 resource
[valueLen
] = '\0';
2339 * Convert to resource by concatenating with a leading "/"...
2343 memcpy(resource
+ 1, value
, valueLen
);
2344 resource
[valueLen
+ 1] = '\0';
2350 * Use the default value...
2353 strlcpy(resource
, resdefault
, sizeof(resource
));
2357 * Lookup the FQDN if needed...
2360 if ((uribuf
->options
& _HTTP_RESOLVE_FQDN
) &&
2361 (hostptr
= hostTarget
+ strlen(hostTarget
) - 7) > hostTarget
&&
2362 !_cups_strcasecmp(hostptr
, ".local."))
2365 * OK, we got a .local name but the caller needs a real domain. Start by
2366 * getting the IP address of the .local name and then do reverse-lookups...
2369 http_addrlist_t
*addrlist
, /* List of addresses */
2370 *addr
; /* Current address */
2372 DEBUG_printf(("5http_resolve_cb: Looking up \"%s\".", hostTarget
));
2374 snprintf(fqdn
, sizeof(fqdn
), "%d", ntohs(port
));
2375 if ((addrlist
= httpAddrGetList(hostTarget
, AF_UNSPEC
, fqdn
)) != NULL
)
2377 for (addr
= addrlist
; addr
; addr
= addr
->next
)
2379 int error
= getnameinfo(&(addr
->addr
.addr
), (socklen_t
)httpAddrLength(&(addr
->addr
)), fqdn
, sizeof(fqdn
), NULL
, 0, NI_NAMEREQD
);
2383 DEBUG_printf(("5http_resolve_cb: Found \"%s\".", fqdn
));
2385 if ((hostptr
= fqdn
+ strlen(fqdn
) - 6) <= fqdn
||
2386 _cups_strcasecmp(hostptr
, ".local"))
2394 DEBUG_printf(("5http_resolve_cb: \"%s\" did not resolve: %d",
2395 httpAddrString(&(addr
->addr
), fqdn
, sizeof(fqdn
)),
2400 httpAddrFreeList(addrlist
);
2405 * Assemble the final device URI...
2408 if ((!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")) &&
2409 !strcmp(uribuf
->resource
, "/cups"))
2410 httpAssembleURIf(HTTP_URI_CODING_ALL
, uribuf
->buffer
, (int)uribuf
->bufsize
, scheme
, NULL
, hostTarget
, ntohs(port
), "%s?snmp=false", resource
);
2412 httpAssembleURI(HTTP_URI_CODING_ALL
, uribuf
->buffer
, (int)uribuf
->bufsize
, scheme
, NULL
, hostTarget
, ntohs(port
), resource
);
2414 DEBUG_printf(("5http_resolve_cb: Resolved URI is \"%s\"...", uribuf
->buffer
));
2417 #elif defined(HAVE_AVAHI)
2419 * 'http_poll_cb()' - Wait for input on the specified file descriptors.
2421 * Note: This function is needed because avahi_simple_poll_iterate is broken
2422 * and always uses a timeout of 0 (!) milliseconds.
2423 * (Avahi Ticket #364)
2428 static int /* O - Number of file descriptors matching */
2430 struct pollfd
*pollfds
, /* I - File descriptors */
2431 unsigned int num_pollfds
, /* I - Number of file descriptors */
2432 int timeout
, /* I - Timeout in milliseconds (used) */
2433 void *context
) /* I - User data (unused) */
2438 return (poll(pollfds
, num_pollfds
, 2000));
2443 * 'http_resolve_cb()' - Build a device URI for the given service name.
2448 AvahiServiceResolver
*resolver
, /* I - Resolver (unused) */
2449 AvahiIfIndex interface
, /* I - Interface index (unused) */
2450 AvahiProtocol protocol
, /* I - Network protocol (unused) */
2451 AvahiResolverEvent event
, /* I - Event (found, etc.) */
2452 const char *name
, /* I - Service name */
2453 const char *type
, /* I - Registration type */
2454 const char *domain
, /* I - Domain (unused) */
2455 const char *hostTarget
, /* I - Hostname */
2456 const AvahiAddress
*address
, /* I - Address (unused) */
2457 uint16_t port
, /* I - Port number */
2458 AvahiStringList
*txt
, /* I - TXT record */
2459 AvahiLookupResultFlags flags
, /* I - Lookup flags (unused) */
2460 void *context
) /* I - Pointer to URI buffer */
2462 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
2464 const char *scheme
, /* URI scheme */
2465 *hostptr
, /* Pointer into hostTarget */
2466 *reskey
, /* "rp" or "rfo" */
2467 *resdefault
; /* Default path */
2468 char resource
[257], /* Remote path */
2469 fqdn
[256]; /* FQDN of the .local name */
2470 AvahiStringList
*pair
; /* Current TXT record key/value pair */
2471 char *value
; /* Value for "rp" key */
2472 size_t valueLen
= 0; /* Length of "rp" key */
2475 DEBUG_printf(("4http_resolve_cb(resolver=%p, "
2476 "interface=%d, protocol=%d, event=%d, name=\"%s\", "
2477 "type=\"%s\", domain=\"%s\", hostTarget=\"%s\", address=%p, "
2478 "port=%d, txt=%p, flags=%d, context=%p)",
2479 resolver
, interface
, protocol
, event
, name
, type
, domain
,
2480 hostTarget
, address
, port
, txt
, flags
, context
));
2482 if (event
!= AVAHI_RESOLVER_FOUND
)
2484 avahi_service_resolver_free(resolver
);
2485 avahi_simple_poll_quit(uribuf
->poll
);
2490 * If we have a UUID, compare it...
2493 if (uribuf
->uuid
&& (pair
= avahi_string_list_find(txt
, "UUID")) != NULL
)
2495 char uuid
[256]; /* UUID value */
2497 avahi_string_list_get_pair(pair
, NULL
, &value
, &valueLen
);
2499 memcpy(uuid
, value
, valueLen
);
2500 uuid
[valueLen
] = '\0';
2502 if (_cups_strcasecmp(uuid
, uribuf
->uuid
))
2504 if (uribuf
->options
& _HTTP_RESOLVE_STDERR
)
2505 fprintf(stderr
, "DEBUG: Found UUID %s, looking for %s.", uuid
,
2508 DEBUG_printf(("5http_resolve_cb: Found UUID %s, looking for %s.", uuid
,
2515 * Figure out the scheme from the full name...
2518 if (strstr(type
, "_ipp."))
2520 else if (strstr(type
, "_printer."))
2522 else if (strstr(type
, "_pdl-datastream."))
2525 scheme
= "riousbprint";
2527 if (!strncmp(type
, "_ipps.", 6) || !strncmp(type
, "_ipp-tls.", 9))
2529 else if (!strncmp(type
, "_ipp.", 5) || !strncmp(type
, "_fax-ipp.", 9))
2531 else if (!strncmp(type
, "_http.", 6))
2533 else if (!strncmp(type
, "_https.", 7))
2535 else if (!strncmp(type
, "_printer.", 9))
2537 else if (!strncmp(type
, "_pdl-datastream.", 16))
2541 avahi_service_resolver_free(resolver
);
2542 avahi_simple_poll_quit(uribuf
->poll
);
2547 * Extract the remote resource key from the TXT record...
2550 if ((uribuf
->options
& _HTTP_RESOLVE_FAXOUT
) &&
2551 (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")) &&
2552 !avahi_string_list_find(txt
, "printer-type"))
2555 resdefault
= "/ipp/faxout";
2563 if ((pair
= avahi_string_list_find(txt
, reskey
)) != NULL
)
2565 avahi_string_list_get_pair(pair
, NULL
, &value
, &valueLen
);
2567 if (value
[0] == '/')
2570 * Value (incorrectly) has a leading slash already...
2573 memcpy(resource
, value
, valueLen
);
2574 resource
[valueLen
] = '\0';
2579 * Convert to resource by concatenating with a leading "/"...
2583 memcpy(resource
+ 1, value
, valueLen
);
2584 resource
[valueLen
+ 1] = '\0';
2590 * Use the default value...
2593 strlcpy(resource
, resdefault
, sizeof(resource
));
2597 * Lookup the FQDN if needed...
2600 if ((uribuf
->options
& _HTTP_RESOLVE_FQDN
) &&
2601 (hostptr
= hostTarget
+ strlen(hostTarget
) - 6) > hostTarget
&&
2602 !_cups_strcasecmp(hostptr
, ".local"))
2605 * OK, we got a .local name but the caller needs a real domain. Start by
2606 * getting the IP address of the .local name and then do reverse-lookups...
2609 http_addrlist_t
*addrlist
, /* List of addresses */
2610 *addr
; /* Current address */
2612 DEBUG_printf(("5http_resolve_cb: Looking up \"%s\".", hostTarget
));
2614 snprintf(fqdn
, sizeof(fqdn
), "%d", ntohs(port
));
2615 if ((addrlist
= httpAddrGetList(hostTarget
, AF_UNSPEC
, fqdn
)) != NULL
)
2617 for (addr
= addrlist
; addr
; addr
= addr
->next
)
2619 int error
= getnameinfo(&(addr
->addr
.addr
), (socklen_t
)httpAddrLength(&(addr
->addr
)), fqdn
, sizeof(fqdn
), NULL
, 0, NI_NAMEREQD
);
2623 DEBUG_printf(("5http_resolve_cb: Found \"%s\".", fqdn
));
2625 if ((hostptr
= fqdn
+ strlen(fqdn
) - 6) <= fqdn
||
2626 _cups_strcasecmp(hostptr
, ".local"))
2634 DEBUG_printf(("5http_resolve_cb: \"%s\" did not resolve: %d",
2635 httpAddrString(&(addr
->addr
), fqdn
, sizeof(fqdn
)),
2640 httpAddrFreeList(addrlist
);
2645 * Assemble the final device URI using the resolved hostname...
2648 httpAssembleURI(HTTP_URI_CODING_ALL
, uribuf
->buffer
, (int)uribuf
->bufsize
, scheme
,
2649 NULL
, hostTarget
, port
, resource
);
2650 DEBUG_printf(("5http_resolve_cb: Resolved URI is \"%s\".", uribuf
->buffer
));
2652 avahi_simple_poll_quit(uribuf
->poll
);
2654 #endif /* HAVE_DNSSD */