4 * HTTP support routines for CUPS.
6 * Copyright 2007-2015 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * These coded instructions, statements, and computer programs are the
10 * property of Apple Inc. and are protected by Federal copyright
11 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
12 * which should have been included with this file. If this file is
13 * file is missing or damaged, see the license at "http://www.cups.org/".
15 * This file is subject to the Apple OS-Developed Software exception.
19 * Include necessary headers...
22 #include "cups-private.h"
27 # elif defined(HAVE_POLL)
30 # include <sys/select.h>
32 #elif defined(HAVE_AVAHI)
33 # include <avahi-client/client.h>
34 # include <avahi-client/lookup.h>
35 # include <avahi-common/simple-watch.h>
36 #endif /* HAVE_DNSSD */
43 typedef struct _http_uribuf_s
/* URI buffer */
46 AvahiSimplePoll
*poll
; /* Poll state */
47 #endif /* HAVE_AVAHI */
48 char *buffer
; /* Pointer to buffer */
49 size_t bufsize
; /* Size of buffer */
50 int options
; /* Options passed to _httpResolveURI */
51 const char *resource
; /* Resource from URI */
52 const char *uuid
; /* UUID from URI */
60 static const char * const http_days
[7] =/* Days of the week */
70 static const char * const http_months
[12] =
71 { /* Months of the year */
85 static const char * const http_states
[] =
86 { /* HTTP state strings */
91 "HTTP_STATE_GET_SEND",
94 "HTTP_STATE_POST_RECV",
95 "HTTP_STATE_POST_SEND",
97 "HTTP_STATE_PUT_RECV",
100 "HTTP_STATE_CONNECT",
102 "HTTP_STATE_UNKNOWN_METHOD",
103 "HTTP_STATE_UNKNOWN_VERSION"
111 static const char *http_copy_decode(char *dst
, const char *src
,
112 int dstsize
, const char *term
,
114 static char *http_copy_encode(char *dst
, const char *src
,
115 char *dstend
, const char *reserved
,
116 const char *term
, int encode
);
118 static void DNSSD_API
http_resolve_cb(DNSServiceRef sdRef
,
119 DNSServiceFlags flags
,
120 uint32_t interfaceIndex
,
121 DNSServiceErrorType errorCode
,
122 const char *fullName
,
123 const char *hostTarget
,
124 uint16_t port
, uint16_t txtLen
,
125 const unsigned char *txtRecord
,
127 #endif /* HAVE_DNSSD */
130 static void http_client_cb(AvahiClient
*client
,
131 AvahiClientState state
, void *simple_poll
);
132 static int http_poll_cb(struct pollfd
*pollfds
, unsigned int num_pollfds
,
133 int timeout
, void *context
);
134 static void http_resolve_cb(AvahiServiceResolver
*resolver
,
135 AvahiIfIndex interface
,
136 AvahiProtocol protocol
,
137 AvahiResolverEvent event
,
138 const char *name
, const char *type
,
139 const char *domain
, const char *host_name
,
140 const AvahiAddress
*address
, uint16_t port
,
141 AvahiStringList
*txt
,
142 AvahiLookupResultFlags flags
, void *context
);
143 #endif /* HAVE_AVAHI */
147 * 'httpAssembleURI()' - Assemble a uniform resource identifier from its
150 * This function escapes reserved characters in the URI depending on the
151 * value of the "encoding" argument. You should use this function in
152 * place of traditional string functions whenever you need to create a
155 * @since CUPS 1.2/OS X 10.5@
158 http_uri_status_t
/* O - URI status */
160 http_uri_coding_t encoding
, /* I - Encoding flags */
161 char *uri
, /* I - URI buffer */
162 int urilen
, /* I - Size of URI buffer */
163 const char *scheme
, /* I - Scheme name */
164 const char *username
, /* I - Username */
165 const char *host
, /* I - Hostname or address */
166 int port
, /* I - Port number */
167 const char *resource
) /* I - Resource */
169 char *ptr
, /* Pointer into URI buffer */
170 *end
; /* End of URI buffer */
174 * Range check input...
177 if (!uri
|| urilen
< 1 || !scheme
|| port
< 0)
182 return (HTTP_URI_STATUS_BAD_ARGUMENTS
);
186 * Assemble the URI starting with the scheme...
189 end
= uri
+ urilen
- 1;
190 ptr
= http_copy_encode(uri
, scheme
, end
, NULL
, NULL
, 0);
193 goto assemble_overflow
;
195 if (!strcmp(scheme
, "geo") || !strcmp(scheme
, "mailto") || !strcmp(scheme
, "tel"))
198 * geo:, mailto:, and tel: only have :, no //...
204 goto assemble_overflow
;
209 * Schemes other than geo:, mailto:, and tel: typically have //...
219 goto assemble_overflow
;
223 * Next the username and hostname, if any...
228 const char *hostptr
; /* Pointer into hostname */
229 int have_ipv6
; /* Do we have an IPv6 address? */
231 if (username
&& *username
)
234 * Add username@ first...
237 ptr
= http_copy_encode(ptr
, username
, end
, "/?#[]@", NULL
,
238 encoding
& HTTP_URI_CODING_USERNAME
);
241 goto assemble_overflow
;
246 goto assemble_overflow
;
250 * Then add the hostname. Since IPv6 is a particular pain to deal
251 * with, we have several special cases to deal with. If we get
252 * an IPv6 address with brackets around it, assume it is already in
253 * URI format. Since DNS-SD service names can sometimes look like
254 * raw IPv6 addresses, we specifically look for "._tcp" in the name,
259 have_ipv6
= strchr(host
, ':') && !strstr(host
, "._tcp");
260 *hostptr
&& have_ipv6
;
262 if (*hostptr
!= ':' && !isxdigit(*hostptr
& 255))
264 have_ipv6
= *hostptr
== '%';
271 * We have a raw IPv6 address...
274 if (strchr(host
, '%') && !(encoding
& HTTP_URI_CODING_RFC6874
))
277 * We have a link-local address, add "[v1." prefix...
288 goto assemble_overflow
;
293 * We have a normal (or RFC 6874 link-local) address, add "[" prefix...
299 goto assemble_overflow
;
303 * Copy the rest of the IPv6 address, and terminate with "]".
306 while (ptr
< end
&& *host
)
311 * Convert/encode zone separator
314 if (encoding
& HTTP_URI_CODING_RFC6874
)
316 if (ptr
>= (end
- 2))
317 goto assemble_overflow
;
333 goto assemble_overflow
;
338 goto assemble_overflow
;
343 * Otherwise, just copy the host string (the extra chars are not in the
344 * "reg-name" ABNF rule; anything <= SP or >= DEL plus % gets automatically
348 ptr
= http_copy_encode(ptr
, host
, end
, "\"#/:<>?@[\\]^`{|}", NULL
,
349 encoding
& HTTP_URI_CODING_HOSTNAME
);
352 goto assemble_overflow
;
356 * Finish things off with the port number...
361 snprintf(ptr
, (size_t)(end
- ptr
+ 1), ":%d", port
);
365 goto assemble_overflow
;
370 * Last but not least, add the resource string...
375 char *query
; /* Pointer to query string */
379 * Copy the resource string up to the query string if present...
382 query
= strchr(resource
, '?');
383 ptr
= http_copy_encode(ptr
, resource
, end
, NULL
, "?",
384 encoding
& HTTP_URI_CODING_RESOURCE
);
386 goto assemble_overflow
;
391 * Copy query string without encoding...
394 ptr
= http_copy_encode(ptr
, query
, end
, NULL
, NULL
,
395 encoding
& HTTP_URI_CODING_QUERY
);
397 goto assemble_overflow
;
403 goto assemble_overflow
;
406 * Nul-terminate the URI buffer and return with no errors...
411 return (HTTP_URI_STATUS_OK
);
414 * Clear the URI string and return an overflow error; I don't usually
415 * like goto's, but in this case it makes sense...
421 return (HTTP_URI_STATUS_OVERFLOW
);
426 * 'httpAssembleURIf()' - Assemble a uniform resource identifier from its
427 * components with a formatted resource.
429 * This function creates a formatted version of the resource string
430 * argument "resourcef" and escapes reserved characters in the URI
431 * depending on the value of the "encoding" argument. You should use
432 * this function in place of traditional string functions whenever
433 * you need to create a URI string.
435 * @since CUPS 1.2/OS X 10.5@
438 http_uri_status_t
/* O - URI status */
440 http_uri_coding_t encoding
, /* I - Encoding flags */
441 char *uri
, /* I - URI buffer */
442 int urilen
, /* I - Size of URI buffer */
443 const char *scheme
, /* I - Scheme name */
444 const char *username
, /* I - Username */
445 const char *host
, /* I - Hostname or address */
446 int port
, /* I - Port number */
447 const char *resourcef
, /* I - Printf-style resource */
448 ...) /* I - Additional arguments as needed */
450 va_list ap
; /* Pointer to additional arguments */
451 char resource
[1024]; /* Formatted resource string */
452 int bytes
; /* Bytes in formatted string */
456 * Range check input...
459 if (!uri
|| urilen
< 1 || !scheme
|| port
< 0 || !resourcef
)
464 return (HTTP_URI_STATUS_BAD_ARGUMENTS
);
468 * Format the resource string and assemble the URI...
471 va_start(ap
, resourcef
);
472 bytes
= vsnprintf(resource
, sizeof(resource
), resourcef
, ap
);
475 if ((size_t)bytes
>= sizeof(resource
))
478 return (HTTP_URI_STATUS_OVERFLOW
);
481 return (httpAssembleURI(encoding
, uri
, urilen
, scheme
, username
, host
,
487 * 'httpAssembleUUID()' - Assemble a name-based UUID URN conforming to RFC 4122.
489 * This function creates a unique 128-bit identifying number using the server
490 * name, port number, random data, and optionally an object name and/or object
491 * number. The result is formatted as a UUID URN as defined in RFC 4122.
493 * The buffer needs to be at least 46 bytes in size.
495 * @since CUPS 1.7/OS X 10.9@
498 char * /* I - UUID string */
499 httpAssembleUUID(const char *server
, /* I - Server name */
500 int port
, /* I - Port number */
501 const char *name
, /* I - Object name or NULL */
502 int number
, /* I - Object number or 0 */
503 char *buffer
, /* I - String buffer */
504 size_t bufsize
) /* I - Size of buffer */
506 char data
[1024]; /* Source string for MD5 */
507 _cups_md5_state_t md5state
; /* MD5 state */
508 unsigned char md5sum
[16]; /* MD5 digest/sum */
512 * Build a version 3 UUID conforming to RFC 4122.
514 * Start with the MD5 sum of the server, port, object name and
515 * number, and some random data on the end.
518 snprintf(data
, sizeof(data
), "%s:%d:%s:%d:%04x:%04x", server
,
519 port
, name
? name
: server
, number
,
520 (unsigned)CUPS_RAND() & 0xffff, (unsigned)CUPS_RAND() & 0xffff);
522 _cupsMD5Init(&md5state
);
523 _cupsMD5Append(&md5state
, (unsigned char *)data
, (int)strlen(data
));
524 _cupsMD5Finish(&md5state
, md5sum
);
527 * Generate the UUID from the MD5...
530 snprintf(buffer
, bufsize
,
531 "urn:uuid:%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-"
532 "%02x%02x%02x%02x%02x%02x",
533 md5sum
[0], md5sum
[1], md5sum
[2], md5sum
[3], md5sum
[4], md5sum
[5],
534 (md5sum
[6] & 15) | 0x30, md5sum
[7], (md5sum
[8] & 0x3f) | 0x40,
535 md5sum
[9], md5sum
[10], md5sum
[11], md5sum
[12], md5sum
[13],
536 md5sum
[14], md5sum
[15]);
543 * 'httpDecode64()' - Base64-decode a string.
545 * This function is deprecated. Use the httpDecode64_2() function instead
546 * which provides buffer length arguments.
551 char * /* O - Decoded string */
552 httpDecode64(char *out
, /* I - String to write to */
553 const char *in
) /* I - String to read from */
555 int outlen
; /* Output buffer length */
559 * Use the old maximum buffer size for binary compatibility...
564 return (httpDecode64_2(out
, &outlen
, in
));
569 * 'httpDecode64_2()' - Base64-decode a string.
571 * @since CUPS 1.1.21/OS X 10.4@
574 char * /* O - Decoded string */
575 httpDecode64_2(char *out
, /* I - String to write to */
576 int *outlen
, /* IO - Size of output string */
577 const char *in
) /* I - String to read from */
579 int pos
; /* Bit position */
580 unsigned base64
; /* Value of this character */
581 char *outptr
, /* Output pointer */
582 *outend
; /* End of output buffer */
586 * Range check input...
589 if (!out
|| !outlen
|| *outlen
< 1 || !in
)
601 * Convert from base-64 to bytes...
604 for (outptr
= out
, outend
= out
+ *outlen
- 1, pos
= 0; *in
!= '\0'; in
++)
607 * Decode this character into a number from 0 to 63...
610 if (*in
>= 'A' && *in
<= 'Z')
611 base64
= (unsigned)(*in
- 'A');
612 else if (*in
>= 'a' && *in
<= 'z')
613 base64
= (unsigned)(*in
- 'a' + 26);
614 else if (*in
>= '0' && *in
<= '9')
615 base64
= (unsigned)(*in
- '0' + 52);
626 * Store the result in the appropriate chars...
633 *outptr
= (char)(base64
<< 2);
638 *outptr
++ |= (char)((base64
>> 4) & 3);
640 *outptr
= (char)((base64
<< 4) & 255);
645 *outptr
++ |= (char)((base64
>> 2) & 15);
647 *outptr
= (char)((base64
<< 6) & 255);
652 *outptr
++ |= (char)base64
;
661 * Return the decoded string and size...
664 *outlen
= (int)(outptr
- out
);
671 * 'httpEncode64()' - Base64-encode a string.
673 * This function is deprecated. Use the httpEncode64_2() function instead
674 * which provides buffer length arguments.
679 char * /* O - Encoded string */
680 httpEncode64(char *out
, /* I - String to write to */
681 const char *in
) /* I - String to read from */
683 return (httpEncode64_2(out
, 512, in
, (int)strlen(in
)));
688 * 'httpEncode64_2()' - Base64-encode a string.
690 * @since CUPS 1.1.21/OS X 10.4@
693 char * /* O - Encoded string */
694 httpEncode64_2(char *out
, /* I - String to write to */
695 int outlen
, /* I - Size of output string */
696 const char *in
, /* I - String to read from */
697 int inlen
) /* I - Size of input string */
699 char *outptr
, /* Output pointer */
700 *outend
; /* End of output buffer */
701 static const char base64
[] = /* Base64 characters... */
703 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
704 "abcdefghijklmnopqrstuvwxyz"
711 * Range check input...
714 if (!out
|| outlen
< 1 || !in
)
718 * Convert bytes to base-64...
721 for (outptr
= out
, outend
= out
+ outlen
- 1; inlen
> 0; in
++, inlen
--)
724 * Encode the up to 3 characters as 4 Base64 numbers...
728 *outptr
++ = base64
[(in
[0] & 255) >> 2];
733 *outptr
++ = base64
[(((in
[0] & 255) << 4) | ((in
[1] & 255) >> 4)) & 63];
735 *outptr
++ = base64
[((in
[0] & 255) << 4) & 63];
752 *outptr
++ = base64
[(((in
[0] & 255) << 2) | ((in
[1] & 255) >> 6)) & 63];
754 *outptr
++ = base64
[((in
[0] & 255) << 2) & 63];
767 *outptr
++ = base64
[in
[0] & 63];
773 * Return the encoded string...
781 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
786 const char * /* O - Date/time string */
787 httpGetDateString(time_t t
) /* I - UNIX time */
789 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
792 return (httpGetDateString2(t
, cg
->http_date
, sizeof(cg
->http_date
)));
797 * 'httpGetDateString2()' - Get a formatted date/time string from a time value.
799 * @since CUPS 1.2/OS X 10.5@
802 const char * /* O - Date/time string */
803 httpGetDateString2(time_t t
, /* I - UNIX time */
804 char *s
, /* I - String buffer */
805 int slen
) /* I - Size of string buffer */
807 struct tm
*tdate
; /* UNIX date/time data */
812 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
);
821 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
824 time_t /* O - UNIX time */
825 httpGetDateTime(const char *s
) /* I - Date/time string */
827 int i
; /* Looping var */
828 char mon
[16]; /* Abbreviated month name */
829 int day
, year
; /* Day of month and year */
830 int hour
, min
, sec
; /* Time */
831 int days
; /* Number of days since 1970 */
832 static const int normal_days
[] = /* Days to a month, normal years */
833 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
834 static const int leap_days
[] = /* Days to a month, leap years */
835 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 };
838 DEBUG_printf(("2httpGetDateTime(s=\"%s\")", s
));
841 * Extract the date and time from the formatted string...
844 if (sscanf(s
, "%*s%d%15s%d%d:%d:%d", &day
, mon
, &year
, &hour
, &min
, &sec
) < 6)
847 DEBUG_printf(("4httpGetDateTime: day=%d, mon=\"%s\", year=%d, hour=%d, "
848 "min=%d, sec=%d", day
, mon
, year
, hour
, min
, sec
));
851 * Convert the month name to a number from 0 to 11.
854 for (i
= 0; i
< 12; i
++)
855 if (!_cups_strcasecmp(mon
, http_months
[i
]))
861 DEBUG_printf(("4httpGetDateTime: i=%d", i
));
864 * Now convert the date and time to a UNIX time value in seconds since
865 * 1970. We can't use mktime() since the timezone may not be UTC but
866 * the date/time string *is* UTC.
869 if ((year
& 3) == 0 && ((year
% 100) != 0 || (year
% 400) == 0))
870 days
= leap_days
[i
] + day
- 1;
872 days
= normal_days
[i
] + day
- 1;
874 DEBUG_printf(("4httpGetDateTime: days=%d", days
));
876 days
+= (year
- 1970) * 365 + /* 365 days per year (normally) */
877 ((year
- 1) / 4 - 492) - /* + leap days */
878 ((year
- 1) / 100 - 19) + /* - 100 year days */
879 ((year
- 1) / 400 - 4); /* + 400 year days */
881 DEBUG_printf(("4httpGetDateTime: days=%d\n", days
));
883 return (days
* 86400 + hour
* 3600 + min
* 60 + sec
);
888 * 'httpSeparate()' - Separate a Universal Resource Identifier into its
891 * This function is deprecated; use the httpSeparateURI() function instead.
897 httpSeparate(const char *uri
, /* I - Universal Resource Identifier */
898 char *scheme
, /* O - Scheme [32] (http, https, etc.) */
899 char *username
, /* O - Username [1024] */
900 char *host
, /* O - Hostname [1024] */
901 int *port
, /* O - Port number to use */
902 char *resource
) /* O - Resource/filename [1024] */
904 httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, 32, username
,
905 HTTP_MAX_URI
, host
, HTTP_MAX_URI
, port
, resource
,
911 * 'httpSeparate2()' - Separate a Universal Resource Identifier into its
914 * This function is deprecated; use the httpSeparateURI() function instead.
916 * @since CUPS 1.1.21/OS X 10.4@
921 httpSeparate2(const char *uri
, /* I - Universal Resource Identifier */
922 char *scheme
, /* O - Scheme (http, https, etc.) */
923 int schemelen
, /* I - Size of scheme buffer */
924 char *username
, /* O - Username */
925 int usernamelen
, /* I - Size of username buffer */
926 char *host
, /* O - Hostname */
927 int hostlen
, /* I - Size of hostname buffer */
928 int *port
, /* O - Port number to use */
929 char *resource
, /* O - Resource/filename */
930 int resourcelen
) /* I - Size of resource buffer */
932 httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, schemelen
, username
,
933 usernamelen
, host
, hostlen
, port
, resource
, resourcelen
);
938 * 'httpSeparateURI()' - Separate a Universal Resource Identifier into its
941 * @since CUPS 1.2/OS X 10.5@
944 http_uri_status_t
/* O - Result of separation */
946 http_uri_coding_t decoding
, /* I - Decoding flags */
947 const char *uri
, /* I - Universal Resource Identifier */
948 char *scheme
, /* O - Scheme (http, https, etc.) */
949 int schemelen
, /* I - Size of scheme buffer */
950 char *username
, /* O - Username */
951 int usernamelen
, /* I - Size of username buffer */
952 char *host
, /* O - Hostname */
953 int hostlen
, /* I - Size of hostname buffer */
954 int *port
, /* O - Port number to use */
955 char *resource
, /* O - Resource/filename */
956 int resourcelen
) /* I - Size of resource buffer */
958 char *ptr
, /* Pointer into string... */
959 *end
; /* End of string */
960 const char *sep
; /* Separator character */
961 http_uri_status_t status
; /* Result of separation */
965 * Initialize everything to blank...
968 if (scheme
&& schemelen
> 0)
971 if (username
&& usernamelen
> 0)
974 if (host
&& hostlen
> 0)
980 if (resource
&& resourcelen
> 0)
984 * Range check input...
987 if (!uri
|| !port
|| !scheme
|| schemelen
<= 0 || !username
||
988 usernamelen
<= 0 || !host
|| hostlen
<= 0 || !resource
||
990 return (HTTP_URI_STATUS_BAD_ARGUMENTS
);
993 return (HTTP_URI_STATUS_BAD_URI
);
996 * Grab the scheme portion of the URI...
999 status
= HTTP_URI_STATUS_OK
;
1001 if (!strncmp(uri
, "//", 2))
1004 * Workaround for HP IPP client bug...
1007 strlcpy(scheme
, "ipp", (size_t)schemelen
);
1008 status
= HTTP_URI_STATUS_MISSING_SCHEME
;
1010 else if (*uri
== '/')
1016 strlcpy(scheme
, "file", (size_t)schemelen
);
1017 status
= HTTP_URI_STATUS_MISSING_SCHEME
;
1022 * Standard URI with scheme...
1025 for (ptr
= scheme
, end
= scheme
+ schemelen
- 1;
1026 *uri
&& *uri
!= ':' && ptr
< end
;)
1027 if (strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1028 "abcdefghijklmnopqrstuvwxyz"
1029 "0123456789-+.", *uri
) != NULL
)
1039 return (HTTP_URI_STATUS_BAD_SCHEME
);
1046 * Set the default port number...
1049 if (!strcmp(scheme
, "http"))
1051 else if (!strcmp(scheme
, "https"))
1053 else if (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps"))
1055 else if (!_cups_strcasecmp(scheme
, "lpd"))
1057 else if (!strcmp(scheme
, "socket")) /* Not yet registered with IANA... */
1059 else if (strcmp(scheme
, "file") && strcmp(scheme
, "mailto") && strcmp(scheme
, "tel"))
1060 status
= HTTP_URI_STATUS_UNKNOWN_SCHEME
;
1063 * Now see if we have a hostname...
1066 if (!strncmp(uri
, "//", 2))
1069 * Yes, extract it...
1075 * Grab the username, if any...
1078 if ((sep
= strpbrk(uri
, "@/")) != NULL
&& *sep
== '@')
1081 * Get a username:password combo...
1084 uri
= http_copy_decode(username
, uri
, usernamelen
, "@",
1085 decoding
& HTTP_URI_CODING_USERNAME
);
1090 return (HTTP_URI_STATUS_BAD_USERNAME
);
1097 * Then the hostname/IP address...
1103 * Grab IPv6 address...
1110 * Skip IPvFuture ("vXXXX.") prefix...
1115 while (isxdigit(*uri
& 255))
1121 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1127 uri
= http_copy_decode(host
, uri
, hostlen
, "]",
1128 decoding
& HTTP_URI_CODING_HOSTNAME
);
1133 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1143 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1148 for (ptr
= host
; *ptr
; ptr
++)
1152 * Convert zone separator to % and stop here...
1158 else if (*ptr
== '%')
1161 * Stop at zone separator (RFC 6874)
1166 else if (*ptr
!= ':' && *ptr
!= '.' && !isxdigit(*ptr
& 255))
1169 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1175 * Validate the hostname or IPv4 address first...
1178 for (ptr
= (char *)uri
; *ptr
; ptr
++)
1179 if (strchr(":?/", *ptr
))
1181 else if (!strchr("abcdefghijklmnopqrstuvwxyz" /* unreserved */
1182 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" /* unreserved */
1183 "0123456789" /* unreserved */
1184 "-._~" /* unreserved */
1185 "%" /* pct-encoded */
1186 "!$&'()*+,;=" /* sub-delims */
1187 "\\", *ptr
)) /* SMB domain */
1190 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1194 * Then copy the hostname or IPv4 address to the buffer...
1197 uri
= http_copy_decode(host
, uri
, hostlen
, ":?/",
1198 decoding
& HTTP_URI_CODING_HOSTNAME
);
1203 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1208 * Validate hostname for file scheme - only empty and localhost are
1212 if (!strcmp(scheme
, "file") && strcmp(host
, "localhost") && host
[0])
1215 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1219 * See if we have a port number...
1225 * Yes, collect the port number...
1228 if (!isdigit(uri
[1] & 255))
1231 return (HTTP_URI_STATUS_BAD_PORT
);
1234 *port
= (int)strtol(uri
+ 1, (char **)&uri
, 10);
1236 if (*port
<= 0 || *port
> 65535)
1239 return (HTTP_URI_STATUS_BAD_PORT
);
1242 if (*uri
!= '/' && *uri
)
1245 return (HTTP_URI_STATUS_BAD_PORT
);
1251 * The remaining portion is the resource string...
1254 if (*uri
== '?' || !*uri
)
1257 * Hostname but no path...
1260 status
= HTTP_URI_STATUS_MISSING_RESOURCE
;
1264 * Copy any query string...
1268 uri
= http_copy_decode(resource
+ 1, uri
, resourcelen
- 1, NULL
,
1269 decoding
& HTTP_URI_CODING_QUERY
);
1275 uri
= http_copy_decode(resource
, uri
, resourcelen
, "?",
1276 decoding
& HTTP_URI_CODING_RESOURCE
);
1278 if (uri
&& *uri
== '?')
1281 * Concatenate any query string...
1284 char *resptr
= resource
+ strlen(resource
);
1286 uri
= http_copy_decode(resptr
, uri
,
1287 resourcelen
- (int)(resptr
- resource
), NULL
,
1288 decoding
& HTTP_URI_CODING_QUERY
);
1295 return (HTTP_URI_STATUS_BAD_RESOURCE
);
1299 * Return the URI separation status...
1307 * 'httpStateString()' - Return the string describing a HTTP state value.
1309 * @since CUPS 2.0/OS 10.10@
1312 const char * /* O - State string */
1313 httpStateString(http_state_t state
) /* I - HTTP state value */
1315 if (state
< HTTP_STATE_ERROR
|| state
> HTTP_STATE_UNKNOWN_VERSION
)
1316 return ("HTTP_STATE_???");
1318 return (http_states
[state
- HTTP_STATE_ERROR
]);
1323 * '_httpStatus()' - Return the localized string describing a HTTP status code.
1325 * The returned string is localized using the passed message catalog.
1328 const char * /* O - Localized status string */
1329 _httpStatus(cups_lang_t
*lang
, /* I - Language */
1330 http_status_t status
) /* I - HTTP status code */
1332 const char *s
; /* Status string */
1337 case HTTP_STATUS_ERROR
:
1338 s
= strerror(errno
);
1340 case HTTP_STATUS_CONTINUE
:
1343 case HTTP_STATUS_SWITCHING_PROTOCOLS
:
1344 s
= _("Switching Protocols");
1346 case HTTP_STATUS_OK
:
1349 case HTTP_STATUS_CREATED
:
1352 case HTTP_STATUS_ACCEPTED
:
1355 case HTTP_STATUS_NO_CONTENT
:
1356 s
= _("No Content");
1358 case HTTP_STATUS_MOVED_PERMANENTLY
:
1359 s
= _("Moved Permanently");
1361 case HTTP_STATUS_SEE_OTHER
:
1364 case HTTP_STATUS_NOT_MODIFIED
:
1365 s
= _("Not Modified");
1367 case HTTP_STATUS_BAD_REQUEST
:
1368 s
= _("Bad Request");
1370 case HTTP_STATUS_UNAUTHORIZED
:
1371 case HTTP_STATUS_CUPS_AUTHORIZATION_CANCELED
:
1372 s
= _("Unauthorized");
1374 case HTTP_STATUS_FORBIDDEN
:
1377 case HTTP_STATUS_NOT_FOUND
:
1380 case HTTP_STATUS_REQUEST_TOO_LARGE
:
1381 s
= _("Request Entity Too Large");
1383 case HTTP_STATUS_URI_TOO_LONG
:
1384 s
= _("URI Too Long");
1386 case HTTP_STATUS_UPGRADE_REQUIRED
:
1387 s
= _("Upgrade Required");
1389 case HTTP_STATUS_NOT_IMPLEMENTED
:
1390 s
= _("Not Implemented");
1392 case HTTP_STATUS_NOT_SUPPORTED
:
1393 s
= _("Not Supported");
1395 case HTTP_STATUS_EXPECTATION_FAILED
:
1396 s
= _("Expectation Failed");
1398 case HTTP_STATUS_SERVICE_UNAVAILABLE
:
1399 s
= _("Service Unavailable");
1401 case HTTP_STATUS_SERVER_ERROR
:
1402 s
= _("Internal Server Error");
1404 case HTTP_STATUS_CUPS_PKI_ERROR
:
1405 s
= _("SSL/TLS Negotiation Error");
1407 case HTTP_STATUS_CUPS_WEBIF_DISABLED
:
1408 s
= _("Web Interface is Disabled");
1416 return (_cupsLangString(lang
, s
));
1421 * 'httpStatus()' - Return a short string describing a HTTP status code.
1423 * The returned string is localized to the current POSIX locale and is based
1424 * on the status strings defined in RFC 2616.
1427 const char * /* O - Localized status string */
1428 httpStatus(http_status_t status
) /* I - HTTP status code */
1430 _cups_globals_t
*cg
= _cupsGlobals(); /* Global data */
1433 if (!cg
->lang_default
)
1434 cg
->lang_default
= cupsLangDefault();
1436 return (_httpStatus(cg
->lang_default
, status
));
1440 * 'httpURIStatusString()' - Return a string describing a URI status code.
1442 * @since CUPS 2.0/OS 10.10@
1445 const char * /* O - Localized status string */
1446 httpURIStatusString(
1447 http_uri_status_t status
) /* I - URI status code */
1449 const char *s
; /* Status string */
1450 _cups_globals_t
*cg
= _cupsGlobals(); /* Global data */
1453 if (!cg
->lang_default
)
1454 cg
->lang_default
= cupsLangDefault();
1458 case HTTP_URI_STATUS_OVERFLOW
:
1459 s
= _("URI too large");
1461 case HTTP_URI_STATUS_BAD_ARGUMENTS
:
1462 s
= _("Bad arguments to function");
1464 case HTTP_URI_STATUS_BAD_RESOURCE
:
1465 s
= _("Bad resource in URI");
1467 case HTTP_URI_STATUS_BAD_PORT
:
1468 s
= _("Bad port number in URI");
1470 case HTTP_URI_STATUS_BAD_HOSTNAME
:
1471 s
= _("Bad hostname/address in URI");
1473 case HTTP_URI_STATUS_BAD_USERNAME
:
1474 s
= _("Bad username in URI");
1476 case HTTP_URI_STATUS_BAD_SCHEME
:
1477 s
= _("Bad scheme in URI");
1479 case HTTP_URI_STATUS_BAD_URI
:
1480 s
= _("Bad/empty URI");
1482 case HTTP_URI_STATUS_OK
:
1485 case HTTP_URI_STATUS_MISSING_SCHEME
:
1486 s
= _("Missing scheme in URI");
1488 case HTTP_URI_STATUS_UNKNOWN_SCHEME
:
1489 s
= _("Unknown scheme in URI");
1491 case HTTP_URI_STATUS_MISSING_RESOURCE
:
1492 s
= _("Missing resource in URI");
1500 return (_cupsLangString(cg
->lang_default
, s
));
1504 #ifndef HAVE_HSTRERROR
1506 * '_cups_hstrerror()' - hstrerror() emulation function for Solaris and others.
1509 const char * /* O - Error string */
1510 _cups_hstrerror(int error
) /* I - Error number */
1512 static const char * const errors
[] = /* Error strings */
1517 "Unrecoverable lookup error.",
1518 "No data associated with name."
1522 if (error
< 0 || error
> 4)
1523 return ("Unknown hostname lookup error.");
1525 return (errors
[error
]);
1527 #endif /* !HAVE_HSTRERROR */
1531 * '_httpDecodeURI()' - Percent-decode a HTTP request URI.
1534 char * /* O - Decoded URI or NULL on error */
1535 _httpDecodeURI(char *dst
, /* I - Destination buffer */
1536 const char *src
, /* I - Source URI */
1537 size_t dstsize
) /* I - Size of destination buffer */
1539 if (http_copy_decode(dst
, src
, (int)dstsize
, NULL
, 1))
1547 * '_httpEncodeURI()' - Percent-encode a HTTP request URI.
1550 char * /* O - Encoded URI */
1551 _httpEncodeURI(char *dst
, /* I - Destination buffer */
1552 const char *src
, /* I - Source URI */
1553 size_t dstsize
) /* I - Size of destination buffer */
1555 http_copy_encode(dst
, src
, dst
+ dstsize
- 1, NULL
, NULL
, 1);
1561 * '_httpResolveURI()' - Resolve a DNS-SD URI.
1564 const char * /* O - Resolved URI */
1566 const char *uri
, /* I - DNS-SD URI */
1567 char *resolved_uri
, /* I - Buffer for resolved URI */
1568 size_t resolved_size
, /* I - Size of URI buffer */
1569 int options
, /* I - Resolve options */
1570 int (*cb
)(void *context
), /* I - Continue callback function */
1571 void *context
) /* I - Context pointer for callback */
1573 char scheme
[32], /* URI components... */
1579 http_uri_status_t status
; /* URI decode status */
1583 DEBUG_printf(("4_httpResolveURI(uri=\"%s\", resolved_uri=%p, "
1584 "resolved_size=" CUPS_LLFMT
")", uri
, resolved_uri
,
1585 CUPS_LLCAST resolved_size
));
1588 * Get the device URI...
1592 if ((status
= httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
,
1593 sizeof(scheme
), userpass
, sizeof(userpass
),
1594 hostname
, sizeof(hostname
), &port
, resource
,
1595 sizeof(resource
))) < HTTP_URI_STATUS_OK
)
1597 if (httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
,
1598 sizeof(scheme
), userpass
, sizeof(userpass
),
1599 hostname
, sizeof(hostname
), &port
, resource
,
1600 sizeof(resource
)) < HTTP_URI_STATUS_OK
)
1603 if (options
& _HTTP_RESOLVE_STDERR
)
1604 _cupsLangPrintFilter(stderr
, "ERROR", _("Bad device-uri \"%s\"."), uri
);
1606 DEBUG_printf(("6_httpResolveURI: httpSeparateURI returned %d!", status
));
1607 DEBUG_puts("5_httpResolveURI: Returning NULL");
1612 * Resolve it as needed...
1615 if (strstr(hostname
, "._tcp"))
1617 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
1618 char *regtype
, /* Pointer to type in hostname */
1619 *domain
, /* Pointer to domain in hostname */
1620 *uuid
, /* Pointer to UUID in URI */
1621 *uuidend
; /* Pointer to end of UUID in URI */
1622 _http_uribuf_t uribuf
; /* URI buffer */
1623 int offline
= 0; /* offline-report state set? */
1626 # pragma comment(lib, "dnssd.lib")
1628 DNSServiceRef ref
, /* DNS-SD master service reference */
1629 domainref
= NULL
,/* DNS-SD service reference for domain */
1630 ippref
= NULL
, /* DNS-SD service reference for network IPP */
1631 ippsref
= NULL
, /* DNS-SD service reference for network IPPS */
1632 localref
; /* DNS-SD service reference for .local */
1633 int extrasent
= 0; /* Send the domain/IPP/IPPS resolves? */
1635 struct pollfd polldata
; /* Polling data */
1636 # else /* select() */
1637 fd_set input_set
; /* Input set for select() */
1638 struct timeval stimeout
; /* Timeout value for select() */
1639 # endif /* HAVE_POLL */
1640 # elif defined(HAVE_AVAHI)
1641 AvahiClient
*client
; /* Client information */
1642 int error
; /* Status */
1643 # endif /* HAVE_DNSSD */
1645 if (options
& _HTTP_RESOLVE_STDERR
)
1646 fprintf(stderr
, "DEBUG: Resolving \"%s\"...\n", hostname
);
1649 * Separate the hostname into service name, registration type, and domain...
1652 for (regtype
= strstr(hostname
, "._tcp") - 2;
1655 if (regtype
[0] == '.' && regtype
[1] == '_')
1658 * Found ._servicetype in front of ._tcp...
1665 if (regtype
<= hostname
)
1667 DEBUG_puts("5_httpResolveURI: Bad hostname, returning NULL");
1671 for (domain
= strchr(regtype
, '.');
1673 domain
= strchr(domain
+ 1, '.'))
1674 if (domain
[1] != '_')
1680 if ((uuid
= strstr(resource
, "?uuid=")) != NULL
)
1684 if ((uuidend
= strchr(uuid
, '&')) != NULL
)
1688 resolved_uri
[0] = '\0';
1690 uribuf
.buffer
= resolved_uri
;
1691 uribuf
.bufsize
= resolved_size
;
1692 uribuf
.options
= options
;
1693 uribuf
.resource
= resource
;
1696 DEBUG_printf(("6_httpResolveURI: Resolving hostname=\"%s\", regtype=\"%s\", "
1697 "domain=\"%s\"\n", hostname
, regtype
, domain
));
1698 if (options
& _HTTP_RESOLVE_STDERR
)
1700 fputs("STATE: +connecting-to-device\n", stderr
);
1701 fprintf(stderr
, "DEBUG: Resolving \"%s\", regtype=\"%s\", "
1702 "domain=\"local.\"...\n", hostname
, regtype
);
1708 if (DNSServiceCreateConnection(&ref
) == kDNSServiceErr_NoError
)
1710 uint32_t myinterface
= kDNSServiceInterfaceIndexAny
;
1711 /* Lookup on any interface */
1713 if (!strcmp(scheme
, "ippusb"))
1714 myinterface
= kDNSServiceInterfaceIndexLocalOnly
;
1717 if (DNSServiceResolve(&localref
,
1718 kDNSServiceFlagsShareConnection
, myinterface
,
1719 hostname
, regtype
, "local.", http_resolve_cb
,
1720 &uribuf
) == kDNSServiceErr_NoError
)
1722 int fds
; /* Number of ready descriptors */
1723 time_t timeout
, /* Poll timeout */
1724 start_time
= time(NULL
),/* Start time */
1725 end_time
= start_time
+ 90;
1728 while (time(NULL
) < end_time
)
1730 if (options
& _HTTP_RESOLVE_STDERR
)
1731 _cupsLangPrintFilter(stderr
, "INFO", _("Looking for printer..."));
1733 if (cb
&& !(*cb
)(context
))
1735 DEBUG_puts("5_httpResolveURI: callback returned 0 (stop)");
1740 * Wakeup every 2 seconds to emit a "looking for printer" message...
1743 if ((timeout
= end_time
- time(NULL
)) > 2)
1747 polldata
.fd
= DNSServiceRefSockFD(ref
);
1748 polldata
.events
= POLLIN
;
1750 fds
= poll(&polldata
, 1, (int)(1000 * timeout
));
1752 # else /* select() */
1753 FD_ZERO(&input_set
);
1754 FD_SET(DNSServiceRefSockFD(ref
), &input_set
);
1757 stimeout
.tv_sec
= (long)timeout
;
1759 stimeout
.tv_sec
= timeout
;
1761 stimeout
.tv_usec
= 0;
1763 fds
= select(DNSServiceRefSockFD(ref
)+1, &input_set
, NULL
, NULL
,
1765 # endif /* HAVE_POLL */
1769 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1771 DEBUG_printf(("5_httpResolveURI: poll error: %s", strerror(errno
)));
1778 * Wait 2 seconds for a response to the local resolve; if nothing
1779 * comes in, do an additional domain resolution...
1782 if (extrasent
== 0 && domain
&& _cups_strcasecmp(domain
, "local."))
1784 if (options
& _HTTP_RESOLVE_STDERR
)
1786 "DEBUG: Resolving \"%s\", regtype=\"%s\", "
1787 "domain=\"%s\"...\n", hostname
, regtype
,
1788 domain
? domain
: "");
1791 if (DNSServiceResolve(&domainref
,
1792 kDNSServiceFlagsShareConnection
,
1793 myinterface
, hostname
, regtype
, domain
,
1795 &uribuf
) == kDNSServiceErr_NoError
)
1798 else if (extrasent
== 0 && !strcmp(scheme
, "ippusb"))
1800 if (options
& _HTTP_RESOLVE_STDERR
)
1801 fprintf(stderr
, "DEBUG: Resolving \"%s\", regtype=\"_ipps._tcp\", domain=\"local.\"...\n", hostname
);
1804 if (DNSServiceResolve(&ippsref
,
1805 kDNSServiceFlagsShareConnection
,
1806 kDNSServiceInterfaceIndexAny
, hostname
,
1807 "_ipps._tcp", domain
, http_resolve_cb
,
1808 &uribuf
) == kDNSServiceErr_NoError
)
1811 else if (extrasent
== 1 && !strcmp(scheme
, "ippusb"))
1813 if (options
& _HTTP_RESOLVE_STDERR
)
1814 fprintf(stderr
, "DEBUG: Resolving \"%s\", regtype=\"_ipp._tcp\", domain=\"local.\"...\n", hostname
);
1817 if (DNSServiceResolve(&ippref
,
1818 kDNSServiceFlagsShareConnection
,
1819 kDNSServiceInterfaceIndexAny
, hostname
,
1820 "_ipp._tcp", domain
, http_resolve_cb
,
1821 &uribuf
) == kDNSServiceErr_NoError
)
1826 * If it hasn't resolved within 5 seconds set the offline-report
1827 * printer-state-reason...
1830 if ((options
& _HTTP_RESOLVE_STDERR
) && offline
== 0 &&
1831 time(NULL
) > (start_time
+ 5))
1833 fputs("STATE: +offline-report\n", stderr
);
1839 if (DNSServiceProcessResult(ref
) == kDNSServiceErr_NoError
&&
1851 DNSServiceRefDeallocate(domainref
);
1853 DNSServiceRefDeallocate(ippref
);
1855 DNSServiceRefDeallocate(ippsref
);
1858 DNSServiceRefDeallocate(localref
);
1861 DNSServiceRefDeallocate(ref
);
1863 # else /* HAVE_AVAHI */
1864 if ((uribuf
.poll
= avahi_simple_poll_new()) != NULL
)
1866 avahi_simple_poll_set_func(uribuf
.poll
, http_poll_cb
, NULL
);
1868 if ((client
= avahi_client_new(avahi_simple_poll_get(uribuf
.poll
),
1870 &uribuf
, &error
)) != NULL
)
1872 if (avahi_service_resolver_new(client
, AVAHI_IF_UNSPEC
,
1873 AVAHI_PROTO_UNSPEC
, hostname
,
1874 regtype
, "local.", AVAHI_PROTO_UNSPEC
, 0,
1875 http_resolve_cb
, &uribuf
) != NULL
)
1877 time_t start_time
= time(NULL
),
1879 end_time
= start_time
+ 90;
1881 int pstatus
; /* Poll status */
1883 pstatus
= avahi_simple_poll_iterate(uribuf
.poll
, 2000);
1885 if (pstatus
== 0 && !resolved_uri
[0] && domain
&&
1886 _cups_strcasecmp(domain
, "local."))
1889 * Resolve for .local hasn't returned anything, try the listed
1893 avahi_service_resolver_new(client
, AVAHI_IF_UNSPEC
,
1894 AVAHI_PROTO_UNSPEC
, hostname
,
1895 regtype
, domain
, AVAHI_PROTO_UNSPEC
, 0,
1896 http_resolve_cb
, &uribuf
);
1899 while (!pstatus
&& !resolved_uri
[0] && time(NULL
) < end_time
)
1901 if ((pstatus
= avahi_simple_poll_iterate(uribuf
.poll
, 2000)) != 0)
1905 * If it hasn't resolved within 5 seconds set the offline-report
1906 * printer-state-reason...
1909 if ((options
& _HTTP_RESOLVE_STDERR
) && offline
== 0 &&
1910 time(NULL
) > (start_time
+ 5))
1912 fputs("STATE: +offline-report\n", stderr
);
1918 * Collect the result (if we got one).
1921 if (resolved_uri
[0])
1925 avahi_client_free(client
);
1928 avahi_simple_poll_free(uribuf
.poll
);
1930 # endif /* HAVE_DNSSD */
1932 if (options
& _HTTP_RESOLVE_STDERR
)
1936 fprintf(stderr
, "DEBUG: Resolved as \"%s\"...\n", uri
);
1937 fputs("STATE: -connecting-to-device,offline-report\n", stderr
);
1941 fputs("DEBUG: Unable to resolve URI\n", stderr
);
1942 fputs("STATE: -connecting-to-device\n", stderr
);
1946 #else /* HAVE_DNSSD || HAVE_AVAHI */
1948 * No DNS-SD support...
1952 #endif /* HAVE_DNSSD || HAVE_AVAHI */
1954 if ((options
& _HTTP_RESOLVE_STDERR
) && !uri
)
1955 _cupsLangPrintFilter(stderr
, "INFO", _("Unable to find printer."));
1960 * Nothing more to do...
1963 strlcpy(resolved_uri
, uri
, resolved_size
);
1967 DEBUG_printf(("5_httpResolveURI: Returning \"%s\"", uri
));
1975 * 'http_client_cb()' - Client callback for resolving URI.
1980 AvahiClient
*client
, /* I - Client information */
1981 AvahiClientState state
, /* I - Current state */
1982 void *context
) /* I - Pointer to URI buffer */
1984 DEBUG_printf(("7http_client_cb(client=%p, state=%d, context=%p)", client
,
1988 * If the connection drops, quit.
1991 if (state
== AVAHI_CLIENT_FAILURE
)
1993 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
1996 avahi_simple_poll_quit(uribuf
->poll
);
1999 #endif /* HAVE_AVAHI */
2003 * 'http_copy_decode()' - Copy and decode a URI.
2006 static const char * /* O - New source pointer or NULL on error */
2007 http_copy_decode(char *dst
, /* O - Destination buffer */
2008 const char *src
, /* I - Source pointer */
2009 int dstsize
, /* I - Destination size */
2010 const char *term
, /* I - Terminating characters */
2011 int decode
) /* I - Decode %-encoded values */
2013 char *ptr
, /* Pointer into buffer */
2014 *end
; /* End of buffer */
2015 int quoted
; /* Quoted character */
2019 * Copy the src to the destination until we hit a terminating character
2020 * or the end of the string.
2023 for (ptr
= dst
, end
= dst
+ dstsize
- 1;
2024 *src
&& (!term
|| !strchr(term
, *src
));
2028 if (*src
== '%' && decode
)
2030 if (isxdigit(src
[1] & 255) && isxdigit(src
[2] & 255))
2033 * Grab a hex-encoded character...
2038 quoted
= (tolower(*src
) - 'a' + 10) << 4;
2040 quoted
= (*src
- '0') << 4;
2044 quoted
|= tolower(*src
) - 'a' + 10;
2046 quoted
|= *src
- '0';
2048 *ptr
++ = (char)quoted
;
2053 * Bad hex-encoded character...
2060 else if ((*src
& 255) <= 0x20 || (*src
& 255) >= 0x7f)
2076 * 'http_copy_encode()' - Copy and encode a URI.
2079 static char * /* O - End of current URI */
2080 http_copy_encode(char *dst
, /* O - Destination buffer */
2081 const char *src
, /* I - Source pointer */
2082 char *dstend
, /* I - End of destination buffer */
2083 const char *reserved
, /* I - Extra reserved characters */
2084 const char *term
, /* I - Terminating characters */
2085 int encode
) /* I - %-encode reserved chars? */
2087 static const char hex
[] = "0123456789ABCDEF";
2090 while (*src
&& dst
< dstend
)
2092 if (term
&& *src
== *term
)
2095 if (encode
&& (*src
== '%' || *src
<= ' ' || *src
& 128 ||
2096 (reserved
&& strchr(reserved
, *src
))))
2099 * Hex encode reserved characters...
2102 if ((dst
+ 2) >= dstend
)
2106 *dst
++ = hex
[(*src
>> 4) & 15];
2107 *dst
++ = hex
[*src
& 15];
2126 * 'http_resolve_cb()' - Build a device URI for the given service name.
2129 static void DNSSD_API
2131 DNSServiceRef sdRef
, /* I - Service reference */
2132 DNSServiceFlags flags
, /* I - Results flags */
2133 uint32_t interfaceIndex
, /* I - Interface number */
2134 DNSServiceErrorType errorCode
, /* I - Error, if any */
2135 const char *fullName
, /* I - Full service name */
2136 const char *hostTarget
, /* I - Hostname */
2137 uint16_t port
, /* I - Port number */
2138 uint16_t txtLen
, /* I - Length of TXT record */
2139 const unsigned char *txtRecord
, /* I - TXT record data */
2140 void *context
) /* I - Pointer to URI buffer */
2142 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
2144 const char *scheme
, /* URI scheme */
2145 *hostptr
, /* Pointer into hostTarget */
2146 *reskey
, /* "rp" or "rfo" */
2147 *resdefault
; /* Default path */
2148 char resource
[257], /* Remote path */
2149 fqdn
[256]; /* FQDN of the .local name */
2150 const void *value
; /* Value from TXT record */
2151 uint8_t valueLen
; /* Length of value */
2154 DEBUG_printf(("7http_resolve_cb(sdRef=%p, flags=%x, interfaceIndex=%u, "
2155 "errorCode=%d, fullName=\"%s\", hostTarget=\"%s\", port=%u, "
2156 "txtLen=%u, txtRecord=%p, context=%p)", sdRef
, flags
,
2157 interfaceIndex
, errorCode
, fullName
, hostTarget
, port
, txtLen
,
2158 txtRecord
, context
));
2161 * If we have a UUID, compare it...
2165 (value
= TXTRecordGetValuePtr(txtLen
, txtRecord
, "UUID",
2166 &valueLen
)) != NULL
)
2168 char uuid
[256]; /* UUID value */
2170 memcpy(uuid
, value
, valueLen
);
2171 uuid
[valueLen
] = '\0';
2173 if (_cups_strcasecmp(uuid
, uribuf
->uuid
))
2175 if (uribuf
->options
& _HTTP_RESOLVE_STDERR
)
2176 fprintf(stderr
, "DEBUG: Found UUID %s, looking for %s.", uuid
,
2179 DEBUG_printf(("7http_resolve_cb: Found UUID %s, looking for %s.", uuid
,
2186 * Figure out the scheme from the full name...
2189 if (strstr(fullName
, "._ipps") || strstr(fullName
, "._ipp-tls"))
2191 else if (strstr(fullName
, "._ipp") || strstr(fullName
, "._fax-ipp"))
2193 else if (strstr(fullName
, "._http."))
2195 else if (strstr(fullName
, "._https."))
2197 else if (strstr(fullName
, "._printer."))
2199 else if (strstr(fullName
, "._pdl-datastream."))
2202 scheme
= "riousbprint";
2205 * Extract the "remote printer" key from the TXT record...
2208 if ((uribuf
->options
& _HTTP_RESOLVE_FAXOUT
) &&
2209 (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")) &&
2210 !TXTRecordGetValuePtr(txtLen
, txtRecord
, "printer-type", &valueLen
))
2213 resdefault
= "/ipp/faxout";
2221 if ((value
= TXTRecordGetValuePtr(txtLen
, txtRecord
, reskey
,
2222 &valueLen
)) != NULL
)
2224 if (((char *)value
)[0] == '/')
2227 * Value (incorrectly) has a leading slash already...
2230 memcpy(resource
, value
, valueLen
);
2231 resource
[valueLen
] = '\0';
2236 * Convert to resource by concatenating with a leading "/"...
2240 memcpy(resource
+ 1, value
, valueLen
);
2241 resource
[valueLen
+ 1] = '\0';
2247 * Use the default value...
2250 strlcpy(resource
, resdefault
, sizeof(resource
));
2254 * Lookup the FQDN if needed...
2257 if ((uribuf
->options
& _HTTP_RESOLVE_FQDN
) &&
2258 (hostptr
= hostTarget
+ strlen(hostTarget
) - 7) > hostTarget
&&
2259 !_cups_strcasecmp(hostptr
, ".local."))
2262 * OK, we got a .local name but the caller needs a real domain. Start by
2263 * getting the IP address of the .local name and then do reverse-lookups...
2266 http_addrlist_t
*addrlist
, /* List of addresses */
2267 *addr
; /* Current address */
2269 DEBUG_printf(("8http_resolve_cb: Looking up \"%s\".", hostTarget
));
2271 snprintf(fqdn
, sizeof(fqdn
), "%d", ntohs(port
));
2272 if ((addrlist
= httpAddrGetList(hostTarget
, AF_UNSPEC
, fqdn
)) != NULL
)
2274 for (addr
= addrlist
; addr
; addr
= addr
->next
)
2276 int error
= getnameinfo(&(addr
->addr
.addr
), (socklen_t
)httpAddrLength(&(addr
->addr
)), fqdn
, sizeof(fqdn
), NULL
, 0, NI_NAMEREQD
);
2280 DEBUG_printf(("8http_resolve_cb: Found \"%s\".", fqdn
));
2282 if ((hostptr
= fqdn
+ strlen(fqdn
) - 6) <= fqdn
||
2283 _cups_strcasecmp(hostptr
, ".local"))
2291 DEBUG_printf(("8http_resolve_cb: \"%s\" did not resolve: %d",
2292 httpAddrString(&(addr
->addr
), fqdn
, sizeof(fqdn
)),
2297 httpAddrFreeList(addrlist
);
2302 * Assemble the final device URI...
2305 if ((!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")) &&
2306 !strcmp(uribuf
->resource
, "/cups"))
2307 httpAssembleURIf(HTTP_URI_CODING_ALL
, uribuf
->buffer
, (int)uribuf
->bufsize
, scheme
, NULL
, hostTarget
, ntohs(port
), "%s?snmp=false", resource
);
2309 httpAssembleURI(HTTP_URI_CODING_ALL
, uribuf
->buffer
, (int)uribuf
->bufsize
, scheme
, NULL
, hostTarget
, ntohs(port
), resource
);
2311 DEBUG_printf(("8http_resolve_cb: Resolved URI is \"%s\"...", uribuf
->buffer
));
2314 #elif defined(HAVE_AVAHI)
2316 * 'http_poll_cb()' - Wait for input on the specified file descriptors.
2318 * Note: This function is needed because avahi_simple_poll_iterate is broken
2319 * and always uses a timeout of 0 (!) milliseconds.
2320 * (Avahi Ticket #364)
2323 static int /* O - Number of file descriptors matching */
2325 struct pollfd
*pollfds
, /* I - File descriptors */
2326 unsigned int num_pollfds
, /* I - Number of file descriptors */
2327 int timeout
, /* I - Timeout in milliseconds (used) */
2328 void *context
) /* I - User data (unused) */
2333 return (poll(pollfds
, num_pollfds
, 2000));
2338 * 'http_resolve_cb()' - Build a device URI for the given service name.
2343 AvahiServiceResolver
*resolver
, /* I - Resolver (unused) */
2344 AvahiIfIndex interface
, /* I - Interface index (unused) */
2345 AvahiProtocol protocol
, /* I - Network protocol (unused) */
2346 AvahiResolverEvent event
, /* I - Event (found, etc.) */
2347 const char *name
, /* I - Service name */
2348 const char *type
, /* I - Registration type */
2349 const char *domain
, /* I - Domain (unused) */
2350 const char *hostTarget
, /* I - Hostname */
2351 const AvahiAddress
*address
, /* I - Address (unused) */
2352 uint16_t port
, /* I - Port number */
2353 AvahiStringList
*txt
, /* I - TXT record */
2354 AvahiLookupResultFlags flags
, /* I - Lookup flags (unused) */
2355 void *context
) /* I - Pointer to URI buffer */
2357 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
2359 const char *scheme
, /* URI scheme */
2360 *hostptr
, /* Pointer into hostTarget */
2361 *reskey
, /* "rp" or "rfo" */
2362 *resdefault
; /* Default path */
2363 char resource
[257], /* Remote path */
2364 fqdn
[256]; /* FQDN of the .local name */
2365 AvahiStringList
*pair
; /* Current TXT record key/value pair */
2366 char *value
; /* Value for "rp" key */
2367 size_t valueLen
= 0; /* Length of "rp" key */
2370 DEBUG_printf(("7http_resolve_cb(resolver=%p, "
2371 "interface=%d, protocol=%d, event=%d, name=\"%s\", "
2372 "type=\"%s\", domain=\"%s\", hostTarget=\"%s\", address=%p, "
2373 "port=%d, txt=%p, flags=%d, context=%p)",
2374 resolver
, interface
, protocol
, event
, name
, type
, domain
,
2375 hostTarget
, address
, port
, txt
, flags
, context
));
2377 if (event
!= AVAHI_RESOLVER_FOUND
)
2379 avahi_service_resolver_free(resolver
);
2380 avahi_simple_poll_quit(uribuf
->poll
);
2385 * If we have a UUID, compare it...
2388 if (uribuf
->uuid
&& (pair
= avahi_string_list_find(txt
, "UUID")) != NULL
)
2390 char uuid
[256]; /* UUID value */
2392 avahi_string_list_get_pair(pair
, NULL
, &value
, &valueLen
);
2394 memcpy(uuid
, value
, valueLen
);
2395 uuid
[valueLen
] = '\0';
2397 if (_cups_strcasecmp(uuid
, uribuf
->uuid
))
2399 if (uribuf
->options
& _HTTP_RESOLVE_STDERR
)
2400 fprintf(stderr
, "DEBUG: Found UUID %s, looking for %s.", uuid
,
2403 DEBUG_printf(("7http_resolve_cb: Found UUID %s, looking for %s.", uuid
,
2410 * Figure out the scheme from the full name...
2413 if (strstr(type
, "_ipp."))
2415 else if (strstr(type
, "_printer."))
2417 else if (strstr(type
, "_pdl-datastream."))
2420 scheme
= "riousbprint";
2422 if (!strncmp(type
, "_ipps.", 6) || !strncmp(type
, "_ipp-tls.", 9))
2424 else if (!strncmp(type
, "_ipp.", 5) || !strncmp(type
, "_fax-ipp.", 9))
2426 else if (!strncmp(type
, "_http.", 6))
2428 else if (!strncmp(type
, "_https.", 7))
2430 else if (!strncmp(type
, "_printer.", 9))
2432 else if (!strncmp(type
, "_pdl-datastream.", 16))
2436 avahi_service_resolver_free(resolver
);
2437 avahi_simple_poll_quit(uribuf
->poll
);
2442 * Extract the remote resource key from the TXT record...
2445 if ((uribuf
->options
& _HTTP_RESOLVE_FAXOUT
) &&
2446 (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")) &&
2447 !avahi_string_list_find(txt
, "printer-type"))
2450 resdefault
= "/ipp/faxout";
2458 if ((pair
= avahi_string_list_find(txt
, reskey
)) != NULL
)
2460 avahi_string_list_get_pair(pair
, NULL
, &value
, &valueLen
);
2462 if (value
[0] == '/')
2465 * Value (incorrectly) has a leading slash already...
2468 memcpy(resource
, value
, valueLen
);
2469 resource
[valueLen
] = '\0';
2474 * Convert to resource by concatenating with a leading "/"...
2478 memcpy(resource
+ 1, value
, valueLen
);
2479 resource
[valueLen
+ 1] = '\0';
2485 * Use the default value...
2488 strlcpy(resource
, resdefault
, sizeof(resource
));
2492 * Lookup the FQDN if needed...
2495 if ((uribuf
->options
& _HTTP_RESOLVE_FQDN
) &&
2496 (hostptr
= hostTarget
+ strlen(hostTarget
) - 6) > hostTarget
&&
2497 !_cups_strcasecmp(hostptr
, ".local"))
2500 * OK, we got a .local name but the caller needs a real domain. Start by
2501 * getting the IP address of the .local name and then do reverse-lookups...
2504 http_addrlist_t
*addrlist
, /* List of addresses */
2505 *addr
; /* Current address */
2507 DEBUG_printf(("8http_resolve_cb: Looking up \"%s\".", hostTarget
));
2509 snprintf(fqdn
, sizeof(fqdn
), "%d", ntohs(port
));
2510 if ((addrlist
= httpAddrGetList(hostTarget
, AF_UNSPEC
, fqdn
)) != NULL
)
2512 for (addr
= addrlist
; addr
; addr
= addr
->next
)
2514 int error
= getnameinfo(&(addr
->addr
.addr
), (socklen_t
)httpAddrLength(&(addr
->addr
)), fqdn
, sizeof(fqdn
), NULL
, 0, NI_NAMEREQD
);
2518 DEBUG_printf(("8http_resolve_cb: Found \"%s\".", fqdn
));
2520 if ((hostptr
= fqdn
+ strlen(fqdn
) - 6) <= fqdn
||
2521 _cups_strcasecmp(hostptr
, ".local"))
2529 DEBUG_printf(("8http_resolve_cb: \"%s\" did not resolve: %d",
2530 httpAddrString(&(addr
->addr
), fqdn
, sizeof(fqdn
)),
2535 httpAddrFreeList(addrlist
);
2540 * Assemble the final device URI using the resolved hostname...
2543 httpAssembleURI(HTTP_URI_CODING_ALL
, uribuf
->buffer
, uribuf
->bufsize
, scheme
,
2544 NULL
, hostTarget
, port
, resource
);
2545 DEBUG_printf(("8http_resolve_cb: Resolved URI is \"%s\".", uribuf
->buffer
));
2547 avahi_simple_poll_quit(uribuf
->poll
);
2549 #endif /* HAVE_DNSSD */