4 * HTTP support routines for CUPS.
6 * Copyright 2007-2013 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 * httpAssembleURI() - Assemble a uniform resource identifier from its
21 * httpAssembleURIf() - Assemble a uniform resource identifier from its
22 * components with a formatted resource.
23 * httpAssembleUUID() - Assemble a name-based UUID URN conforming to RFC
25 * httpDecode64() - Base64-decode a string.
26 * httpDecode64_2() - Base64-decode a string.
27 * httpEncode64() - Base64-encode a string.
28 * httpEncode64_2() - Base64-encode a string.
29 * httpGetDateString() - Get a formatted date/time string from a time value.
30 * httpGetDateString2() - Get a formatted date/time string from a time value.
31 * httpGetDateTime() - Get a time value from a formatted date/time string.
32 * httpSeparate() - Separate a Universal Resource Identifier into its
34 * httpSeparate2() - Separate a Universal Resource Identifier into its
36 * httpSeparateURI() - Separate a Universal Resource Identifier into its
38 * _httpStatus() - Return the localized string describing a HTTP
40 * httpStatus() - Return a short string describing a HTTP status
42 * _cups_hstrerror() - hstrerror() emulation function for Solaris and
44 * _httpDecodeURI() - Percent-decode a HTTP request URI.
45 * _httpEncodeURI() - Percent-encode a HTTP request URI.
46 * _httpResolveURI() - Resolve a DNS-SD URI.
47 * http_client_cb() - Client callback for resolving URI.
48 * http_copy_decode() - Copy and decode a URI.
49 * http_copy_encode() - Copy and encode a URI.
50 * http_poll_cb() - Wait for input on the specified file descriptors.
51 * http_resolve_cb() - Build a device URI for the given service name.
52 * http_resolve_cb() - Build a device URI for the given service name.
56 * Include necessary headers...
59 #include "cups-private.h"
64 # elif defined(HAVE_POLL)
67 # include <sys/select.h>
69 #elif defined(HAVE_AVAHI)
70 # include <avahi-client/client.h>
71 # include <avahi-client/lookup.h>
72 # include <avahi-common/simple-watch.h>
73 #endif /* HAVE_DNSSD */
80 typedef struct _http_uribuf_s
/* URI buffer */
83 AvahiSimplePoll
*poll
; /* Poll state */
84 #endif /* HAVE_AVAHI */
85 char *buffer
; /* Pointer to buffer */
86 size_t bufsize
; /* Size of buffer */
87 int options
; /* Options passed to _httpResolveURI */
88 const char *resource
; /* Resource from URI */
96 static const char * const http_days
[7] =
106 static const char * const http_months
[12] =
127 static const char *http_copy_decode(char *dst
, const char *src
,
128 int dstsize
, const char *term
,
130 static char *http_copy_encode(char *dst
, const char *src
,
131 char *dstend
, const char *reserved
,
132 const char *term
, int encode
);
134 static void DNSSD_API
http_resolve_cb(DNSServiceRef sdRef
,
135 DNSServiceFlags flags
,
136 uint32_t interfaceIndex
,
137 DNSServiceErrorType errorCode
,
138 const char *fullName
,
139 const char *hostTarget
,
140 uint16_t port
, uint16_t txtLen
,
141 const unsigned char *txtRecord
,
143 #endif /* HAVE_DNSSD */
146 static void http_client_cb(AvahiClient
*client
,
147 AvahiClientState state
, void *simple_poll
);
148 static int http_poll_cb(struct pollfd
*pollfds
, unsigned int num_pollfds
,
149 int timeout
, void *context
);
150 static void http_resolve_cb(AvahiServiceResolver
*resolver
,
151 AvahiIfIndex interface
,
152 AvahiProtocol protocol
,
153 AvahiResolverEvent event
,
154 const char *name
, const char *type
,
155 const char *domain
, const char *host_name
,
156 const AvahiAddress
*address
, uint16_t port
,
157 AvahiStringList
*txt
,
158 AvahiLookupResultFlags flags
, void *context
);
159 #endif /* HAVE_AVAHI */
163 * 'httpAssembleURI()' - Assemble a uniform resource identifier from its
166 * This function escapes reserved characters in the URI depending on the
167 * value of the "encoding" argument. You should use this function in
168 * place of traditional string functions whenever you need to create a
171 * @since CUPS 1.2/OS X 10.5@
174 http_uri_status_t
/* O - URI status */
176 http_uri_coding_t encoding
, /* I - Encoding flags */
177 char *uri
, /* I - URI buffer */
178 int urilen
, /* I - Size of URI buffer */
179 const char *scheme
, /* I - Scheme name */
180 const char *username
, /* I - Username */
181 const char *host
, /* I - Hostname or address */
182 int port
, /* I - Port number */
183 const char *resource
) /* I - Resource */
185 char *ptr
, /* Pointer into URI buffer */
186 *end
; /* End of URI buffer */
190 * Range check input...
193 if (!uri
|| urilen
< 1 || !scheme
|| port
< 0)
198 return (HTTP_URI_STATUS_BAD_ARGUMENTS
);
202 * Assemble the URI starting with the scheme...
205 end
= uri
+ urilen
- 1;
206 ptr
= http_copy_encode(uri
, scheme
, end
, NULL
, NULL
, 0);
209 goto assemble_overflow
;
211 if (!strcmp(scheme
, "mailto"))
214 * mailto: only has :, no //...
220 goto assemble_overflow
;
225 * Schemes other than mailto: all have //...
235 goto assemble_overflow
;
239 * Next the username and hostname, if any...
244 const char *hostptr
; /* Pointer into hostname */
245 int have_ipv6
; /* Do we have an IPv6 address? */
247 if (username
&& *username
)
250 * Add username@ first...
253 ptr
= http_copy_encode(ptr
, username
, end
, "/?#[]@", NULL
,
254 encoding
& HTTP_URI_CODING_USERNAME
);
257 goto assemble_overflow
;
262 goto assemble_overflow
;
266 * Then add the hostname. Since IPv6 is a particular pain to deal
267 * with, we have several special cases to deal with. If we get
268 * an IPv6 address with brackets around it, assume it is already in
269 * URI format. Since DNS-SD service names can sometimes look like
270 * raw IPv6 addresses, we specifically look for "._tcp" in the name,
275 have_ipv6
= strchr(host
, ':') && !strstr(host
, "._tcp");
276 *hostptr
&& have_ipv6
;
278 if (*hostptr
!= ':' && !isxdigit(*hostptr
& 255))
280 have_ipv6
= *hostptr
== '%';
287 * We have a raw IPv6 address...
290 if (strchr(host
, '%') && !(encoding
& HTTP_URI_CODING_RFC6874
))
293 * We have a link-local address, add "[v1." prefix...
304 goto assemble_overflow
;
309 * We have a normal (or RFC 6874 link-local) address, add "[" prefix...
315 goto assemble_overflow
;
319 * Copy the rest of the IPv6 address, and terminate with "]".
322 while (ptr
< end
&& *host
)
327 * Convert/encode zone separator
330 if (encoding
& HTTP_URI_CODING_RFC6874
)
332 if (ptr
>= (end
- 2))
333 goto assemble_overflow
;
349 goto assemble_overflow
;
354 goto assemble_overflow
;
359 * Otherwise, just copy the host string (the extra chars are not in the
360 * "reg-name" ABNF rule; anything <= SP or >= DEL plus % gets automatically
364 ptr
= http_copy_encode(ptr
, host
, end
, "\"#/:<>?@[\\]^`{|}", NULL
,
365 encoding
& HTTP_URI_CODING_HOSTNAME
);
368 goto assemble_overflow
;
372 * Finish things off with the port number...
377 snprintf(ptr
, end
- ptr
+ 1, ":%d", port
);
381 goto assemble_overflow
;
386 * Last but not least, add the resource string...
391 char *query
; /* Pointer to query string */
395 * Copy the resource string up to the query string if present...
398 query
= strchr(resource
, '?');
399 ptr
= http_copy_encode(ptr
, resource
, end
, NULL
, "?",
400 encoding
& HTTP_URI_CODING_RESOURCE
);
402 goto assemble_overflow
;
407 * Copy query string without encoding...
410 ptr
= http_copy_encode(ptr
, query
, end
, NULL
, NULL
,
411 encoding
& HTTP_URI_CODING_QUERY
);
413 goto assemble_overflow
;
419 goto assemble_overflow
;
422 * Nul-terminate the URI buffer and return with no errors...
427 return (HTTP_URI_STATUS_OK
);
430 * Clear the URI string and return an overflow error; I don't usually
431 * like goto's, but in this case it makes sense...
437 return (HTTP_URI_STATUS_OVERFLOW
);
442 * 'httpAssembleURIf()' - Assemble a uniform resource identifier from its
443 * components with a formatted resource.
445 * This function creates a formatted version of the resource string
446 * argument "resourcef" and escapes reserved characters in the URI
447 * depending on the value of the "encoding" argument. You should use
448 * this function in place of traditional string functions whenever
449 * you need to create a URI string.
451 * @since CUPS 1.2/OS X 10.5@
454 http_uri_status_t
/* O - URI status */
456 http_uri_coding_t encoding
, /* I - Encoding flags */
457 char *uri
, /* I - URI buffer */
458 int urilen
, /* I - Size of URI buffer */
459 const char *scheme
, /* I - Scheme name */
460 const char *username
, /* I - Username */
461 const char *host
, /* I - Hostname or address */
462 int port
, /* I - Port number */
463 const char *resourcef
, /* I - Printf-style resource */
464 ...) /* I - Additional arguments as needed */
466 va_list ap
; /* Pointer to additional arguments */
467 char resource
[1024]; /* Formatted resource string */
468 int bytes
; /* Bytes in formatted string */
472 * Range check input...
475 if (!uri
|| urilen
< 1 || !scheme
|| port
< 0 || !resourcef
)
480 return (HTTP_URI_STATUS_BAD_ARGUMENTS
);
484 * Format the resource string and assemble the URI...
487 va_start(ap
, resourcef
);
488 bytes
= vsnprintf(resource
, sizeof(resource
), resourcef
, ap
);
491 if (bytes
>= sizeof(resource
))
494 return (HTTP_URI_STATUS_OVERFLOW
);
497 return (httpAssembleURI(encoding
, uri
, urilen
, scheme
, username
, host
,
503 * 'httpAssembleUUID()' - Assemble a name-based UUID URN conforming to RFC 4122.
505 * This function creates a unique 128-bit identifying number using the server
506 * name, port number, random data, and optionally an object name and/or object
507 * number. The result is formatted as a UUID URN as defined in RFC 4122.
509 * The buffer needs to be at least 46 bytes in size.
511 * @since CUPS 1.7/OS X 10.9@
514 char * /* I - UUID string */
515 httpAssembleUUID(const char *server
, /* I - Server name */
516 int port
, /* I - Port number */
517 const char *name
, /* I - Object name or NULL */
518 int number
, /* I - Object number or 0 */
519 char *buffer
, /* I - String buffer */
520 size_t bufsize
) /* I - Size of buffer */
522 char data
[1024]; /* Source string for MD5 */
523 _cups_md5_state_t md5state
; /* MD5 state */
524 unsigned char md5sum
[16]; /* MD5 digest/sum */
528 * Build a version 3 UUID conforming to RFC 4122.
530 * Start with the MD5 sum of the server, port, object name and
531 * number, and some random data on the end.
534 snprintf(data
, sizeof(data
), "%s:%d:%s:%d:%04x:%04x", server
,
535 port
, name
? name
: server
, number
,
536 (unsigned)CUPS_RAND() & 0xffff, (unsigned)CUPS_RAND() & 0xffff);
538 _cupsMD5Init(&md5state
);
539 _cupsMD5Append(&md5state
, (unsigned char *)data
, strlen(data
));
540 _cupsMD5Finish(&md5state
, md5sum
);
543 * Generate the UUID from the MD5...
546 snprintf(buffer
, bufsize
,
547 "urn:uuid:%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-"
548 "%02x%02x%02x%02x%02x%02x",
549 md5sum
[0], md5sum
[1], md5sum
[2], md5sum
[3], md5sum
[4], md5sum
[5],
550 (md5sum
[6] & 15) | 0x30, md5sum
[7], (md5sum
[8] & 0x3f) | 0x40,
551 md5sum
[9], md5sum
[10], md5sum
[11], md5sum
[12], md5sum
[13],
552 md5sum
[14], md5sum
[15]);
557 /* For OS X 10.8 and earlier */
558 char *_httpAssembleUUID(const char *server
, int port
, const char *name
,
559 int number
, char *buffer
, size_t bufsize
)
561 return (httpAssembleUUID(server
, port
, name
, number
, buffer
, bufsize
));
566 * 'httpDecode64()' - Base64-decode a string.
568 * This function is deprecated. Use the httpDecode64_2() function instead
569 * which provides buffer length arguments.
574 char * /* O - Decoded string */
575 httpDecode64(char *out
, /* I - String to write to */
576 const char *in
) /* I - String to read from */
578 int outlen
; /* Output buffer length */
582 * Use the old maximum buffer size for binary compatibility...
587 return (httpDecode64_2(out
, &outlen
, in
));
592 * 'httpDecode64_2()' - Base64-decode a string.
594 * @since CUPS 1.1.21/OS X 10.4@
597 char * /* O - Decoded string */
598 httpDecode64_2(char *out
, /* I - String to write to */
599 int *outlen
, /* IO - Size of output string */
600 const char *in
) /* I - String to read from */
602 int pos
, /* Bit position */
603 base64
; /* Value of this character */
604 char *outptr
, /* Output pointer */
605 *outend
; /* End of output buffer */
609 * Range check input...
612 if (!out
|| !outlen
|| *outlen
< 1 || !in
)
624 * Convert from base-64 to bytes...
627 for (outptr
= out
, outend
= out
+ *outlen
- 1, pos
= 0; *in
!= '\0'; in
++)
630 * Decode this character into a number from 0 to 63...
633 if (*in
>= 'A' && *in
<= 'Z')
635 else if (*in
>= 'a' && *in
<= 'z')
636 base64
= *in
- 'a' + 26;
637 else if (*in
>= '0' && *in
<= '9')
638 base64
= *in
- '0' + 52;
649 * Store the result in the appropriate chars...
656 *outptr
= base64
<< 2;
661 *outptr
++ |= (base64
>> 4) & 3;
663 *outptr
= (base64
<< 4) & 255;
668 *outptr
++ |= (base64
>> 2) & 15;
670 *outptr
= (base64
<< 6) & 255;
684 * Return the decoded string and size...
687 *outlen
= (int)(outptr
- out
);
694 * 'httpEncode64()' - Base64-encode a string.
696 * This function is deprecated. Use the httpEncode64_2() function instead
697 * which provides buffer length arguments.
702 char * /* O - Encoded string */
703 httpEncode64(char *out
, /* I - String to write to */
704 const char *in
) /* I - String to read from */
706 return (httpEncode64_2(out
, 512, in
, (int)strlen(in
)));
711 * 'httpEncode64_2()' - Base64-encode a string.
713 * @since CUPS 1.1.21/OS X 10.4@
716 char * /* O - Encoded string */
717 httpEncode64_2(char *out
, /* I - String to write to */
718 int outlen
, /* I - Size of output string */
719 const char *in
, /* I - String to read from */
720 int inlen
) /* I - Size of input string */
722 char *outptr
, /* Output pointer */
723 *outend
; /* End of output buffer */
724 static const char base64
[] = /* Base64 characters... */
726 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
727 "abcdefghijklmnopqrstuvwxyz"
734 * Range check input...
737 if (!out
|| outlen
< 1 || !in
)
741 * Convert bytes to base-64...
744 for (outptr
= out
, outend
= out
+ outlen
- 1; inlen
> 0; in
++, inlen
--)
747 * Encode the up to 3 characters as 4 Base64 numbers...
751 *outptr
++ = base64
[(in
[0] & 255) >> 2];
756 *outptr
++ = base64
[(((in
[0] & 255) << 4) | ((in
[1] & 255) >> 4)) & 63];
758 *outptr
++ = base64
[((in
[0] & 255) << 4) & 63];
775 *outptr
++ = base64
[(((in
[0] & 255) << 2) | ((in
[1] & 255) >> 6)) & 63];
777 *outptr
++ = base64
[((in
[0] & 255) << 2) & 63];
790 *outptr
++ = base64
[in
[0] & 63];
796 * Return the encoded string...
804 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
809 const char * /* O - Date/time string */
810 httpGetDateString(time_t t
) /* I - UNIX time */
812 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
815 return (httpGetDateString2(t
, cg
->http_date
, sizeof(cg
->http_date
)));
820 * 'httpGetDateString2()' - Get a formatted date/time string from a time value.
822 * @since CUPS 1.2/OS X 10.5@
825 const char * /* O - Date/time string */
826 httpGetDateString2(time_t t
, /* I - UNIX time */
827 char *s
, /* I - String buffer */
828 int slen
) /* I - Size of string buffer */
830 struct tm
*tdate
; /* UNIX date/time data */
835 snprintf(s
, slen
, "%s, %02d %s %d %02d:%02d:%02d GMT",
836 http_days
[tdate
->tm_wday
], tdate
->tm_mday
,
837 http_months
[tdate
->tm_mon
], tdate
->tm_year
+ 1900,
838 tdate
->tm_hour
, tdate
->tm_min
, tdate
->tm_sec
);
847 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
850 time_t /* O - UNIX time */
851 httpGetDateTime(const char *s
) /* I - Date/time string */
853 int i
; /* Looping var */
854 char mon
[16]; /* Abbreviated month name */
855 int day
, year
; /* Day of month and year */
856 int hour
, min
, sec
; /* Time */
857 int days
; /* Number of days since 1970 */
858 static const int normal_days
[] = /* Days to a month, normal years */
859 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
860 static const int leap_days
[] = /* Days to a month, leap years */
861 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 };
864 DEBUG_printf(("2httpGetDateTime(s=\"%s\")", s
));
867 * Extract the date and time from the formatted string...
870 if (sscanf(s
, "%*s%d%15s%d%d:%d:%d", &day
, mon
, &year
, &hour
, &min
, &sec
) < 6)
873 DEBUG_printf(("4httpGetDateTime: day=%d, mon=\"%s\", year=%d, hour=%d, "
874 "min=%d, sec=%d", day
, mon
, year
, hour
, min
, sec
));
877 * Convert the month name to a number from 0 to 11.
880 for (i
= 0; i
< 12; i
++)
881 if (!_cups_strcasecmp(mon
, http_months
[i
]))
887 DEBUG_printf(("4httpGetDateTime: i=%d", i
));
890 * Now convert the date and time to a UNIX time value in seconds since
891 * 1970. We can't use mktime() since the timezone may not be UTC but
892 * the date/time string *is* UTC.
895 if ((year
& 3) == 0 && ((year
% 100) != 0 || (year
% 400) == 0))
896 days
= leap_days
[i
] + day
- 1;
898 days
= normal_days
[i
] + day
- 1;
900 DEBUG_printf(("4httpGetDateTime: days=%d", days
));
902 days
+= (year
- 1970) * 365 + /* 365 days per year (normally) */
903 ((year
- 1) / 4 - 492) - /* + leap days */
904 ((year
- 1) / 100 - 19) + /* - 100 year days */
905 ((year
- 1) / 400 - 4); /* + 400 year days */
907 DEBUG_printf(("4httpGetDateTime: days=%d\n", days
));
909 return (days
* 86400 + hour
* 3600 + min
* 60 + sec
);
914 * 'httpSeparate()' - Separate a Universal Resource Identifier into its
917 * This function is deprecated; use the httpSeparateURI() function instead.
923 httpSeparate(const char *uri
, /* I - Universal Resource Identifier */
924 char *scheme
, /* O - Scheme [32] (http, https, etc.) */
925 char *username
, /* O - Username [1024] */
926 char *host
, /* O - Hostname [1024] */
927 int *port
, /* O - Port number to use */
928 char *resource
) /* O - Resource/filename [1024] */
930 httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, 32, username
,
931 HTTP_MAX_URI
, host
, HTTP_MAX_URI
, port
, resource
,
937 * 'httpSeparate2()' - Separate a Universal Resource Identifier into its
940 * This function is deprecated; use the httpSeparateURI() function instead.
942 * @since CUPS 1.1.21/OS X 10.4@
947 httpSeparate2(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 httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, schemelen
, username
,
959 usernamelen
, host
, hostlen
, port
, resource
, resourcelen
);
964 * 'httpSeparateURI()' - Separate a Universal Resource Identifier into its
967 * @since CUPS 1.2/OS X 10.5@
970 http_uri_status_t
/* O - Result of separation */
972 http_uri_coding_t decoding
, /* I - Decoding flags */
973 const char *uri
, /* I - Universal Resource Identifier */
974 char *scheme
, /* O - Scheme (http, https, etc.) */
975 int schemelen
, /* I - Size of scheme buffer */
976 char *username
, /* O - Username */
977 int usernamelen
, /* I - Size of username buffer */
978 char *host
, /* O - Hostname */
979 int hostlen
, /* I - Size of hostname buffer */
980 int *port
, /* O - Port number to use */
981 char *resource
, /* O - Resource/filename */
982 int resourcelen
) /* I - Size of resource buffer */
984 char *ptr
, /* Pointer into string... */
985 *end
; /* End of string */
986 const char *sep
; /* Separator character */
987 http_uri_status_t status
; /* Result of separation */
991 * Initialize everything to blank...
994 if (scheme
&& schemelen
> 0)
997 if (username
&& usernamelen
> 0)
1000 if (host
&& hostlen
> 0)
1006 if (resource
&& resourcelen
> 0)
1010 * Range check input...
1013 if (!uri
|| !port
|| !scheme
|| schemelen
<= 0 || !username
||
1014 usernamelen
<= 0 || !host
|| hostlen
<= 0 || !resource
||
1016 return (HTTP_URI_STATUS_BAD_ARGUMENTS
);
1019 return (HTTP_URI_STATUS_BAD_URI
);
1022 * Grab the scheme portion of the URI...
1025 status
= HTTP_URI_STATUS_OK
;
1027 if (!strncmp(uri
, "//", 2))
1030 * Workaround for HP IPP client bug...
1033 strlcpy(scheme
, "ipp", schemelen
);
1034 status
= HTTP_URI_STATUS_MISSING_SCHEME
;
1036 else if (*uri
== '/')
1042 strlcpy(scheme
, "file", schemelen
);
1043 status
= HTTP_URI_STATUS_MISSING_SCHEME
;
1048 * Standard URI with scheme...
1051 for (ptr
= scheme
, end
= scheme
+ schemelen
- 1;
1052 *uri
&& *uri
!= ':' && ptr
< end
;)
1053 if (strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1054 "abcdefghijklmnopqrstuvwxyz"
1055 "0123456789-+.", *uri
) != NULL
)
1065 return (HTTP_URI_STATUS_BAD_SCHEME
);
1072 * Set the default port number...
1075 if (!strcmp(scheme
, "http"))
1077 else if (!strcmp(scheme
, "https"))
1079 else if (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps"))
1081 else if (!_cups_strcasecmp(scheme
, "lpd"))
1083 else if (!strcmp(scheme
, "socket")) /* Not yet registered with IANA... */
1085 else if (strcmp(scheme
, "file") && strcmp(scheme
, "mailto"))
1086 status
= HTTP_URI_STATUS_UNKNOWN_SCHEME
;
1089 * Now see if we have a hostname...
1092 if (!strncmp(uri
, "//", 2))
1095 * Yes, extract it...
1101 * Grab the username, if any...
1104 if ((sep
= strpbrk(uri
, "@/")) != NULL
&& *sep
== '@')
1107 * Get a username:password combo...
1110 uri
= http_copy_decode(username
, uri
, usernamelen
, "@",
1111 decoding
& HTTP_URI_CODING_USERNAME
);
1116 return (HTTP_URI_STATUS_BAD_USERNAME
);
1123 * Then the hostname/IP address...
1129 * Grab IPv6 address...
1136 * Skip IPvFuture ("vXXXX.") prefix...
1141 while (isxdigit(*uri
& 255))
1147 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1153 uri
= http_copy_decode(host
, uri
, hostlen
, "]",
1154 decoding
& HTTP_URI_CODING_HOSTNAME
);
1159 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1169 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1174 for (ptr
= host
; *ptr
; ptr
++)
1178 * Convert zone separator to % and stop here...
1184 else if (*ptr
== '%')
1187 * Stop at zone separator (RFC 6874)
1192 else if (*ptr
!= ':' && *ptr
!= '.' && !isxdigit(*ptr
& 255))
1195 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1201 * Validate the hostname or IPv4 address first...
1204 for (ptr
= (char *)uri
; *ptr
; ptr
++)
1205 if (strchr(":?/", *ptr
))
1207 else if (!strchr("abcdefghijklmnopqrstuvwxyz" /* unreserved */
1208 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" /* unreserved */
1209 "0123456789" /* unreserved */
1210 "-._~" /* unreserved */
1211 "%" /* pct-encoded */
1212 "!$&'()*+,;=" /* sub-delims */
1213 "\\", *ptr
)) /* SMB domain */
1216 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1220 * Then copy the hostname or IPv4 address to the buffer...
1223 uri
= http_copy_decode(host
, uri
, hostlen
, ":?/",
1224 decoding
& HTTP_URI_CODING_HOSTNAME
);
1229 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1234 * Validate hostname for file scheme - only empty and localhost are
1238 if (!strcmp(scheme
, "file") && strcmp(host
, "localhost") && host
[0])
1241 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1245 * See if we have a port number...
1251 * Yes, collect the port number...
1254 if (!isdigit(uri
[1] & 255))
1257 return (HTTP_URI_STATUS_BAD_PORT
);
1260 *port
= strtol(uri
+ 1, (char **)&uri
, 10);
1262 if (*uri
!= '/' && *uri
)
1265 return (HTTP_URI_STATUS_BAD_PORT
);
1271 * The remaining portion is the resource string...
1274 if (*uri
== '?' || !*uri
)
1277 * Hostname but no path...
1280 status
= HTTP_URI_STATUS_MISSING_RESOURCE
;
1284 * Copy any query string...
1288 uri
= http_copy_decode(resource
+ 1, uri
, resourcelen
- 1, NULL
,
1289 decoding
& HTTP_URI_CODING_QUERY
);
1295 uri
= http_copy_decode(resource
, uri
, resourcelen
, "?",
1296 decoding
& HTTP_URI_CODING_RESOURCE
);
1298 if (uri
&& *uri
== '?')
1301 * Concatenate any query string...
1304 char *resptr
= resource
+ strlen(resource
);
1306 uri
= http_copy_decode(resptr
, uri
,
1307 resourcelen
- (int)(resptr
- resource
), NULL
,
1308 decoding
& HTTP_URI_CODING_QUERY
);
1315 return (HTTP_URI_STATUS_BAD_RESOURCE
);
1319 * Return the URI separation status...
1327 * '_httpStatus()' - Return the localized string describing a HTTP status code.
1329 * The returned string is localized using the passed message catalog.
1332 const char * /* O - Localized status string */
1333 _httpStatus(cups_lang_t
*lang
, /* I - Language */
1334 http_status_t status
) /* I - HTTP status code */
1336 const char *s
; /* Status string */
1341 case HTTP_STATUS_ERROR
:
1342 s
= strerror(errno
);
1344 case HTTP_STATUS_CONTINUE
:
1347 case HTTP_STATUS_SWITCHING_PROTOCOLS
:
1348 s
= _("Switching Protocols");
1350 case HTTP_STATUS_OK
:
1353 case HTTP_STATUS_CREATED
:
1356 case HTTP_STATUS_ACCEPTED
:
1359 case HTTP_STATUS_NO_CONTENT
:
1360 s
= _("No Content");
1362 case HTTP_STATUS_MOVED_PERMANENTLY
:
1363 s
= _("Moved Permanently");
1365 case HTTP_STATUS_SEE_OTHER
:
1368 case HTTP_STATUS_NOT_MODIFIED
:
1369 s
= _("Not Modified");
1371 case HTTP_STATUS_BAD_REQUEST
:
1372 s
= _("Bad Request");
1374 case HTTP_STATUS_UNAUTHORIZED
:
1375 case HTTP_STATUS_CUPS_AUTHORIZATION_CANCELED
:
1376 s
= _("Unauthorized");
1378 case HTTP_STATUS_FORBIDDEN
:
1381 case HTTP_STATUS_NOT_FOUND
:
1384 case HTTP_STATUS_REQUEST_TOO_LARGE
:
1385 s
= _("Request Entity Too Large");
1387 case HTTP_STATUS_URI_TOO_LONG
:
1388 s
= _("URI Too Long");
1390 case HTTP_STATUS_UPGRADE_REQUIRED
:
1391 s
= _("Upgrade Required");
1393 case HTTP_STATUS_NOT_IMPLEMENTED
:
1394 s
= _("Not Implemented");
1396 case HTTP_STATUS_NOT_SUPPORTED
:
1397 s
= _("Not Supported");
1399 case HTTP_STATUS_EXPECTATION_FAILED
:
1400 s
= _("Expectation Failed");
1402 case HTTP_STATUS_SERVICE_UNAVAILABLE
:
1403 s
= _("Service Unavailable");
1405 case HTTP_STATUS_SERVER_ERROR
:
1406 s
= _("Internal Server Error");
1408 case HTTP_STATUS_CUPS_PKI_ERROR
:
1409 s
= _("SSL/TLS Negotiation Error");
1411 case HTTP_STATUS_CUPS_WEBIF_DISABLED
:
1412 s
= _("Web Interface is Disabled");
1420 return (_cupsLangString(lang
, s
));
1425 * 'httpStatus()' - Return a short string describing a HTTP status code.
1427 * The returned string is localized to the current POSIX locale and is based
1428 * on the status strings defined in RFC 2616.
1431 const char * /* O - Localized status string */
1432 httpStatus(http_status_t status
) /* I - HTTP status code */
1434 _cups_globals_t
*cg
= _cupsGlobals(); /* Global data */
1437 if (!cg
->lang_default
)
1438 cg
->lang_default
= cupsLangDefault();
1440 return (_httpStatus(cg
->lang_default
, status
));
1444 #ifndef HAVE_HSTRERROR
1446 * '_cups_hstrerror()' - hstrerror() emulation function for Solaris and others.
1449 const char * /* O - Error string */
1450 _cups_hstrerror(int error
) /* I - Error number */
1452 static const char * const errors
[] = /* Error strings */
1457 "Unrecoverable lookup error.",
1458 "No data associated with name."
1462 if (error
< 0 || error
> 4)
1463 return ("Unknown hostname lookup error.");
1465 return (errors
[error
]);
1467 #endif /* !HAVE_HSTRERROR */
1471 * '_httpDecodeURI()' - Percent-decode a HTTP request URI.
1474 char * /* O - Decoded URI or NULL on error */
1475 _httpDecodeURI(char *dst
, /* I - Destination buffer */
1476 const char *src
, /* I - Source URI */
1477 size_t dstsize
) /* I - Size of destination buffer */
1479 if (http_copy_decode(dst
, src
, (int)dstsize
, NULL
, 1))
1487 * '_httpEncodeURI()' - Percent-encode a HTTP request URI.
1490 char * /* O - Encoded URI */
1491 _httpEncodeURI(char *dst
, /* I - Destination buffer */
1492 const char *src
, /* I - Source URI */
1493 size_t dstsize
) /* I - Size of destination buffer */
1495 http_copy_encode(dst
, src
, dst
+ dstsize
- 1, NULL
, NULL
, 1);
1501 * '_httpResolveURI()' - Resolve a DNS-SD URI.
1504 const char * /* O - Resolved URI */
1506 const char *uri
, /* I - DNS-SD URI */
1507 char *resolved_uri
, /* I - Buffer for resolved URI */
1508 size_t resolved_size
, /* I - Size of URI buffer */
1509 int options
, /* I - Resolve options */
1510 int (*cb
)(void *context
), /* I - Continue callback function */
1511 void *context
) /* I - Context pointer for callback */
1513 char scheme
[32], /* URI components... */
1519 http_uri_status_t status
; /* URI decode status */
1523 DEBUG_printf(("4_httpResolveURI(uri=\"%s\", resolved_uri=%p, "
1524 "resolved_size=" CUPS_LLFMT
")", uri
, resolved_uri
,
1525 CUPS_LLCAST resolved_size
));
1528 * Get the device URI...
1532 if ((status
= httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
,
1533 sizeof(scheme
), userpass
, sizeof(userpass
),
1534 hostname
, sizeof(hostname
), &port
, resource
,
1535 sizeof(resource
))) < HTTP_URI_STATUS_OK
)
1537 if (httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
,
1538 sizeof(scheme
), userpass
, sizeof(userpass
),
1539 hostname
, sizeof(hostname
), &port
, resource
,
1540 sizeof(resource
)) < HTTP_URI_STATUS_OK
)
1543 if (options
& _HTTP_RESOLVE_STDERR
)
1544 _cupsLangPrintFilter(stderr
, "ERROR", _("Bad device-uri \"%s\"."), uri
);
1546 DEBUG_printf(("6_httpResolveURI: httpSeparateURI returned %d!", status
));
1547 DEBUG_puts("5_httpResolveURI: Returning NULL");
1552 * Resolve it as needed...
1555 if (strstr(hostname
, "._tcp"))
1557 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
1558 char *regtype
, /* Pointer to type in hostname */
1559 *domain
; /* Pointer to domain in hostname */
1560 _http_uribuf_t uribuf
; /* URI buffer */
1561 int offline
= 0; /* offline-report state set? */
1564 # pragma comment(lib, "dnssd.lib")
1566 DNSServiceRef ref
, /* DNS-SD master service reference */
1567 domainref
, /* DNS-SD service reference for domain */
1568 localref
; /* DNS-SD service reference for .local */
1569 int domainsent
= 0; /* Send the domain resolve? */
1571 struct pollfd polldata
; /* Polling data */
1572 # else /* select() */
1573 fd_set input_set
; /* Input set for select() */
1574 struct timeval stimeout
; /* Timeout value for select() */
1575 # endif /* HAVE_POLL */
1576 # elif defined(HAVE_AVAHI)
1577 AvahiClient
*client
; /* Client information */
1578 int error
; /* Status */
1579 # endif /* HAVE_DNSSD */
1581 if (options
& _HTTP_RESOLVE_STDERR
)
1582 fprintf(stderr
, "DEBUG: Resolving \"%s\"...\n", hostname
);
1585 * Separate the hostname into service name, registration type, and domain...
1588 for (regtype
= strstr(hostname
, "._tcp") - 2;
1591 if (regtype
[0] == '.' && regtype
[1] == '_')
1594 * Found ._servicetype in front of ._tcp...
1601 if (regtype
<= hostname
)
1603 DEBUG_puts("5_httpResolveURI: Bad hostname, returning NULL");
1607 for (domain
= strchr(regtype
, '.');
1609 domain
= strchr(domain
+ 1, '.'))
1610 if (domain
[1] != '_')
1616 uribuf
.buffer
= resolved_uri
;
1617 uribuf
.bufsize
= resolved_size
;
1618 uribuf
.options
= options
;
1619 uribuf
.resource
= resource
;
1621 resolved_uri
[0] = '\0';
1623 DEBUG_printf(("6_httpResolveURI: Resolving hostname=\"%s\", regtype=\"%s\", "
1624 "domain=\"%s\"\n", hostname
, regtype
, domain
));
1625 if (options
& _HTTP_RESOLVE_STDERR
)
1627 fputs("STATE: +connecting-to-device\n", stderr
);
1628 fprintf(stderr
, "DEBUG: Resolving \"%s\", regtype=\"%s\", "
1629 "domain=\"local.\"...\n", hostname
, regtype
);
1635 if (DNSServiceCreateConnection(&ref
) == kDNSServiceErr_NoError
)
1637 int myinterface
= kDNSServiceInterfaceIndexAny
;
1638 /* Lookup on any interface */
1640 if (!strcmp(scheme
, "ippusb"))
1641 myinterface
= kDNSServiceInterfaceIndexLocalOnly
;
1644 if (DNSServiceResolve(&localref
,
1645 kDNSServiceFlagsShareConnection
, myinterface
,
1646 hostname
, regtype
, "local.", http_resolve_cb
,
1647 &uribuf
) == kDNSServiceErr_NoError
)
1649 int fds
; /* Number of ready descriptors */
1650 time_t timeout
, /* Poll timeout */
1651 start_time
= time(NULL
),/* Start time */
1652 end_time
= start_time
+ 90;
1655 while (time(NULL
) < end_time
)
1657 if (options
& _HTTP_RESOLVE_STDERR
)
1658 _cupsLangPrintFilter(stderr
, "INFO", _("Looking for printer."));
1660 if (cb
&& !(*cb
)(context
))
1662 DEBUG_puts("5_httpResolveURI: callback returned 0 (stop)");
1667 * Wakeup every 2 seconds to emit a "looking for printer" message...
1670 if ((timeout
= end_time
- time(NULL
)) > 2)
1674 polldata
.fd
= DNSServiceRefSockFD(ref
);
1675 polldata
.events
= POLLIN
;
1677 fds
= poll(&polldata
, 1, 1000 * timeout
);
1679 # else /* select() */
1680 FD_ZERO(&input_set
);
1681 FD_SET(DNSServiceRefSockFD(ref
), &input_set
);
1684 stimeout
.tv_sec
= (long)timeout
;
1686 stimeout
.tv_sec
= timeout
;
1688 stimeout
.tv_usec
= 0;
1690 fds
= select(DNSServiceRefSockFD(ref
)+1, &input_set
, NULL
, NULL
,
1692 # endif /* HAVE_POLL */
1696 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1698 DEBUG_printf(("5_httpResolveURI: poll error: %s", strerror(errno
)));
1705 * Wait 2 seconds for a response to the local resolve; if nothing
1706 * comes in, do an additional domain resolution...
1709 if (domainsent
== 0 && domain
&& _cups_strcasecmp(domain
, "local."))
1711 if (options
& _HTTP_RESOLVE_STDERR
)
1713 "DEBUG: Resolving \"%s\", regtype=\"%s\", "
1714 "domain=\"%s\"...\n", hostname
, regtype
,
1715 domain
? domain
: "");
1718 if (DNSServiceResolve(&domainref
,
1719 kDNSServiceFlagsShareConnection
,
1720 myinterface
, hostname
, regtype
, domain
,
1722 &uribuf
) == kDNSServiceErr_NoError
)
1727 * If it hasn't resolved within 5 seconds set the offline-report
1728 * printer-state-reason...
1731 if ((options
& _HTTP_RESOLVE_STDERR
) && offline
== 0 &&
1732 time(NULL
) > (start_time
+ 5))
1734 fputs("STATE: +offline-report\n", stderr
);
1740 if (DNSServiceProcessResult(ref
) == kDNSServiceErr_NoError
)
1749 DNSServiceRefDeallocate(domainref
);
1751 DNSServiceRefDeallocate(localref
);
1754 DNSServiceRefDeallocate(ref
);
1756 # else /* HAVE_AVAHI */
1757 if ((uribuf
.poll
= avahi_simple_poll_new()) != NULL
)
1759 avahi_simple_poll_set_func(uribuf
.poll
, http_poll_cb
, NULL
);
1761 if ((client
= avahi_client_new(avahi_simple_poll_get(uribuf
.poll
),
1763 &uribuf
, &error
)) != NULL
)
1765 if (avahi_service_resolver_new(client
, AVAHI_IF_UNSPEC
,
1766 AVAHI_PROTO_UNSPEC
, hostname
,
1767 regtype
, "local.", AVAHI_PROTO_UNSPEC
, 0,
1768 http_resolve_cb
, &uribuf
) != NULL
)
1770 time_t start_time
= time(NULL
),
1772 end_time
= start_time
+ 90;
1774 int pstatus
; /* Poll status */
1776 pstatus
= avahi_simple_poll_iterate(uribuf
.poll
, 2000);
1778 if (pstatus
== 0 && !resolved_uri
[0] && domain
&&
1779 _cups_strcasecmp(domain
, "local."))
1782 * Resolve for .local hasn't returned anything, try the listed
1786 avahi_service_resolver_new(client
, AVAHI_IF_UNSPEC
,
1787 AVAHI_PROTO_UNSPEC
, hostname
,
1788 regtype
, domain
, AVAHI_PROTO_UNSPEC
, 0,
1789 http_resolve_cb
, &uribuf
);
1792 while (!pstatus
&& !resolved_uri
[0] && time(NULL
) < end_time
)
1794 if ((pstatus
= avahi_simple_poll_iterate(uribuf
.poll
, 2000)) != 0)
1798 * If it hasn't resolved within 5 seconds set the offline-report
1799 * printer-state-reason...
1802 if ((options
& _HTTP_RESOLVE_STDERR
) && offline
== 0 &&
1803 time(NULL
) > (start_time
+ 5))
1805 fputs("STATE: +offline-report\n", stderr
);
1811 * Collect the result (if we got one).
1814 if (resolved_uri
[0])
1818 avahi_client_free(client
);
1821 avahi_simple_poll_free(uribuf
.poll
);
1823 # endif /* HAVE_DNSSD */
1825 if (options
& _HTTP_RESOLVE_STDERR
)
1829 fprintf(stderr
, "DEBUG: Resolved as \"%s\"...\n", uri
);
1830 fputs("STATE: -connecting-to-device,offline-report\n", stderr
);
1834 fputs("DEBUG: Unable to resolve URI\n", stderr
);
1835 fputs("STATE: -connecting-to-device\n", stderr
);
1839 #else /* HAVE_DNSSD || HAVE_AVAHI */
1841 * No DNS-SD support...
1845 #endif /* HAVE_DNSSD || HAVE_AVAHI */
1847 if ((options
& _HTTP_RESOLVE_STDERR
) && !uri
)
1848 _cupsLangPrintFilter(stderr
, "INFO", _("Unable to find printer."));
1853 * Nothing more to do...
1856 strlcpy(resolved_uri
, uri
, resolved_size
);
1860 DEBUG_printf(("5_httpResolveURI: Returning \"%s\"", uri
));
1868 * 'http_client_cb()' - Client callback for resolving URI.
1873 AvahiClient
*client
, /* I - Client information */
1874 AvahiClientState state
, /* I - Current state */
1875 void *context
) /* I - Pointer to URI buffer */
1877 DEBUG_printf(("7http_client_cb(client=%p, state=%d, context=%p)", client
,
1881 * If the connection drops, quit.
1884 if (state
== AVAHI_CLIENT_FAILURE
)
1886 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
1889 avahi_simple_poll_quit(uribuf
->poll
);
1892 #endif /* HAVE_AVAHI */
1896 * 'http_copy_decode()' - Copy and decode a URI.
1899 static const char * /* O - New source pointer or NULL on error */
1900 http_copy_decode(char *dst
, /* O - Destination buffer */
1901 const char *src
, /* I - Source pointer */
1902 int dstsize
, /* I - Destination size */
1903 const char *term
, /* I - Terminating characters */
1904 int decode
) /* I - Decode %-encoded values */
1906 char *ptr
, /* Pointer into buffer */
1907 *end
; /* End of buffer */
1908 int quoted
; /* Quoted character */
1912 * Copy the src to the destination until we hit a terminating character
1913 * or the end of the string.
1916 for (ptr
= dst
, end
= dst
+ dstsize
- 1;
1917 *src
&& (!term
|| !strchr(term
, *src
));
1921 if (*src
== '%' && decode
)
1923 if (isxdigit(src
[1] & 255) && isxdigit(src
[2] & 255))
1926 * Grab a hex-encoded character...
1931 quoted
= (tolower(*src
) - 'a' + 10) << 4;
1933 quoted
= (*src
- '0') << 4;
1937 quoted
|= tolower(*src
) - 'a' + 10;
1939 quoted
|= *src
- '0';
1946 * Bad hex-encoded character...
1953 else if ((*src
& 255) <= 0x20 || (*src
& 255) >= 0x7f)
1969 * 'http_copy_encode()' - Copy and encode a URI.
1972 static char * /* O - End of current URI */
1973 http_copy_encode(char *dst
, /* O - Destination buffer */
1974 const char *src
, /* I - Source pointer */
1975 char *dstend
, /* I - End of destination buffer */
1976 const char *reserved
, /* I - Extra reserved characters */
1977 const char *term
, /* I - Terminating characters */
1978 int encode
) /* I - %-encode reserved chars? */
1980 static const char hex
[] = "0123456789ABCDEF";
1983 while (*src
&& dst
< dstend
)
1985 if (term
&& *src
== *term
)
1988 if (encode
&& (*src
== '%' || *src
<= ' ' || *src
& 128 ||
1989 (reserved
&& strchr(reserved
, *src
))))
1992 * Hex encode reserved characters...
1995 if ((dst
+ 2) >= dstend
)
1999 *dst
++ = hex
[(*src
>> 4) & 15];
2000 *dst
++ = hex
[*src
& 15];
2019 * 'http_resolve_cb()' - Build a device URI for the given service name.
2022 static void DNSSD_API
2024 DNSServiceRef sdRef
, /* I - Service reference */
2025 DNSServiceFlags flags
, /* I - Results flags */
2026 uint32_t interfaceIndex
, /* I - Interface number */
2027 DNSServiceErrorType errorCode
, /* I - Error, if any */
2028 const char *fullName
, /* I - Full service name */
2029 const char *hostTarget
, /* I - Hostname */
2030 uint16_t port
, /* I - Port number */
2031 uint16_t txtLen
, /* I - Length of TXT record */
2032 const unsigned char *txtRecord
, /* I - TXT record data */
2033 void *context
) /* I - Pointer to URI buffer */
2035 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
2037 const char *scheme
, /* URI scheme */
2038 *hostptr
, /* Pointer into hostTarget */
2039 *reskey
, /* "rp" or "rfo" */
2040 *resdefault
; /* Default path */
2041 char resource
[257], /* Remote path */
2042 fqdn
[256]; /* FQDN of the .local name */
2043 const void *value
; /* Value from TXT record */
2044 uint8_t valueLen
; /* Length of value */
2047 DEBUG_printf(("7http_resolve_cb(sdRef=%p, flags=%x, interfaceIndex=%u, "
2048 "errorCode=%d, fullName=\"%s\", hostTarget=\"%s\", port=%u, "
2049 "txtLen=%u, txtRecord=%p, context=%p)", sdRef
, flags
,
2050 interfaceIndex
, errorCode
, fullName
, hostTarget
, port
, txtLen
,
2051 txtRecord
, context
));
2054 * Figure out the scheme from the full name...
2057 if (strstr(fullName
, "._ipps") || strstr(fullName
, "._ipp-tls"))
2059 else if (strstr(fullName
, "._ipp") || strstr(fullName
, "._fax-ipp"))
2061 else if (strstr(fullName
, "._http."))
2063 else if (strstr(fullName
, "._https."))
2065 else if (strstr(fullName
, "._printer."))
2067 else if (strstr(fullName
, "._pdl-datastream."))
2070 scheme
= "riousbprint";
2073 * Extract the "remote printer" key from the TXT record...
2076 if ((uribuf
->options
& _HTTP_RESOLVE_FAXOUT
) &&
2077 (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")) &&
2078 !TXTRecordGetValuePtr(txtLen
, txtRecord
, "printer-type", &valueLen
))
2081 resdefault
= "/ipp/faxout";
2089 if ((value
= TXTRecordGetValuePtr(txtLen
, txtRecord
, reskey
,
2090 &valueLen
)) != NULL
)
2092 if (((char *)value
)[0] == '/')
2095 * Value (incorrectly) has a leading slash already...
2098 memcpy(resource
, value
, valueLen
);
2099 resource
[valueLen
] = '\0';
2104 * Convert to resource by concatenating with a leading "/"...
2108 memcpy(resource
+ 1, value
, valueLen
);
2109 resource
[valueLen
+ 1] = '\0';
2115 * Use the default value...
2118 strlcpy(resource
, resdefault
, sizeof(resource
));
2122 * Lookup the FQDN if needed...
2125 if ((uribuf
->options
& _HTTP_RESOLVE_FQDN
) &&
2126 (hostptr
= hostTarget
+ strlen(hostTarget
) - 7) > hostTarget
&&
2127 !_cups_strcasecmp(hostptr
, ".local."))
2130 * OK, we got a .local name but the caller needs a real domain. Start by
2131 * getting the IP address of the .local name and then do reverse-lookups...
2134 http_addrlist_t
*addrlist
, /* List of addresses */
2135 *addr
; /* Current address */
2137 DEBUG_printf(("8http_resolve_cb: Looking up \"%s\".", hostTarget
));
2139 snprintf(fqdn
, sizeof(fqdn
), "%d", ntohs(port
));
2140 if ((addrlist
= httpAddrGetList(hostTarget
, AF_UNSPEC
, fqdn
)) != NULL
)
2142 for (addr
= addrlist
; addr
; addr
= addr
->next
)
2144 int error
= getnameinfo(&(addr
->addr
.addr
),
2145 httpAddrLength(&(addr
->addr
)),
2146 fqdn
, sizeof(fqdn
), NULL
, 0, NI_NAMEREQD
);
2150 DEBUG_printf(("8http_resolve_cb: Found \"%s\".", fqdn
));
2152 if ((hostptr
= fqdn
+ strlen(fqdn
) - 6) <= fqdn
||
2153 _cups_strcasecmp(hostptr
, ".local"))
2161 DEBUG_printf(("8http_resolve_cb: \"%s\" did not resolve: %d",
2162 httpAddrString(&(addr
->addr
), fqdn
, sizeof(fqdn
)),
2167 httpAddrFreeList(addrlist
);
2172 * Assemble the final device URI...
2175 if ((!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")) &&
2176 !strcmp(uribuf
->resource
, "/cups"))
2177 httpAssembleURIf(HTTP_URI_CODING_ALL
, uribuf
->buffer
, uribuf
->bufsize
,
2178 scheme
, NULL
, hostTarget
, ntohs(port
), "%s?snmp=false",
2181 httpAssembleURI(HTTP_URI_CODING_ALL
, uribuf
->buffer
, uribuf
->bufsize
,
2182 scheme
, NULL
, hostTarget
, ntohs(port
), resource
);
2184 DEBUG_printf(("8http_resolve_cb: Resolved URI is \"%s\"...", uribuf
->buffer
));
2187 #elif defined(HAVE_AVAHI)
2189 * 'http_poll_cb()' - Wait for input on the specified file descriptors.
2191 * Note: This function is needed because avahi_simple_poll_iterate is broken
2192 * and always uses a timeout of 0 (!) milliseconds.
2193 * (Avahi Ticket #364)
2196 static int /* O - Number of file descriptors matching */
2198 struct pollfd
*pollfds
, /* I - File descriptors */
2199 unsigned int num_pollfds
, /* I - Number of file descriptors */
2200 int timeout
, /* I - Timeout in milliseconds (used) */
2201 void *context
) /* I - User data (unused) */
2206 return (poll(pollfds
, num_pollfds
, 2000));
2211 * 'http_resolve_cb()' - Build a device URI for the given service name.
2216 AvahiServiceResolver
*resolver
, /* I - Resolver (unused) */
2217 AvahiIfIndex interface
, /* I - Interface index (unused) */
2218 AvahiProtocol protocol
, /* I - Network protocol (unused) */
2219 AvahiResolverEvent event
, /* I - Event (found, etc.) */
2220 const char *name
, /* I - Service name */
2221 const char *type
, /* I - Registration type */
2222 const char *domain
, /* I - Domain (unused) */
2223 const char *hostTarget
, /* I - Hostname */
2224 const AvahiAddress
*address
, /* I - Address (unused) */
2225 uint16_t port
, /* I - Port number */
2226 AvahiStringList
*txt
, /* I - TXT record */
2227 AvahiLookupResultFlags flags
, /* I - Lookup flags (unused) */
2228 void *context
) /* I - Pointer to URI buffer */
2230 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
2232 const char *scheme
, /* URI scheme */
2233 *hostptr
, /* Pointer into hostTarget */
2234 *reskey
, /* "rp" or "rfo" */
2235 *resdefault
; /* Default path */
2236 char resource
[257], /* Remote path */
2237 fqdn
[256]; /* FQDN of the .local name */
2238 AvahiStringList
*pair
; /* Current TXT record key/value pair */
2239 char *value
; /* Value for "rp" key */
2240 size_t valueLen
= 0; /* Length of "rp" key */
2243 DEBUG_printf(("7http_resolve_cb(resolver=%p, "
2244 "interface=%d, protocol=%d, event=%d, name=\"%s\", "
2245 "type=\"%s\", domain=\"%s\", hostTarget=\"%s\", address=%p, "
2246 "port=%d, txt=%p, flags=%d, context=%p)",
2247 resolver
, interface
, protocol
, event
, name
, type
, domain
,
2248 hostTarget
, address
, port
, txt
, flags
, context
));
2250 if (event
!= AVAHI_RESOLVER_FOUND
)
2252 avahi_service_resolver_free(resolver
);
2253 avahi_simple_poll_quit(uribuf
->poll
);
2258 * Figure out the scheme from the full name...
2261 if (strstr(type
, "_ipp."))
2263 else if (strstr(type
, "_printer."))
2265 else if (strstr(type
, "_pdl-datastream."))
2268 scheme
= "riousbprint";
2270 if (!strncmp(type
, "_ipps.", 6) || !strncmp(type
, "_ipp-tls.", 9))
2272 else if (!strncmp(type
, "_ipp.", 5) || !strncmp(type
, "_fax-ipp.", 9))
2274 else if (!strncmp(type
, "_http.", 6))
2276 else if (!strncmp(type
, "_https.", 7))
2278 else if (!strncmp(type
, "_printer.", 9))
2280 else if (!strncmp(type
, "_pdl-datastream.", 16))
2284 avahi_service_resolver_free(resolver
);
2285 avahi_simple_poll_quit(uribuf
->poll
);
2290 * Extract the remote resource key from the TXT record...
2293 if ((uribuf
->options
& _HTTP_RESOLVE_FAXOUT
) &&
2294 (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")))
2297 resdefault
= "/ipp/faxout";
2305 if ((pair
= avahi_string_list_find(txt
, reskey
)) != NULL
)
2307 avahi_string_list_get_pair(pair
, NULL
, &value
, &valueLen
);
2309 if (value
[0] == '/')
2312 * Value (incorrectly) has a leading slash already...
2315 memcpy(resource
, value
, valueLen
);
2316 resource
[valueLen
] = '\0';
2321 * Convert to resource by concatenating with a leading "/"...
2325 memcpy(resource
+ 1, value
, valueLen
);
2326 resource
[valueLen
+ 1] = '\0';
2332 * Use the default value...
2335 strlcpy(resource
, resdefault
, sizeof(resource
));
2339 * Lookup the FQDN if needed...
2342 if ((uribuf
->options
& _HTTP_RESOLVE_FQDN
) &&
2343 (hostptr
= hostTarget
+ strlen(hostTarget
) - 6) > hostTarget
&&
2344 !_cups_strcasecmp(hostptr
, ".local"))
2347 * OK, we got a .local name but the caller needs a real domain. Start by
2348 * getting the IP address of the .local name and then do reverse-lookups...
2351 http_addrlist_t
*addrlist
, /* List of addresses */
2352 *addr
; /* Current address */
2354 DEBUG_printf(("8http_resolve_cb: Looking up \"%s\".", hostTarget
));
2356 snprintf(fqdn
, sizeof(fqdn
), "%d", ntohs(port
));
2357 if ((addrlist
= httpAddrGetList(hostTarget
, AF_UNSPEC
, fqdn
)) != NULL
)
2359 for (addr
= addrlist
; addr
; addr
= addr
->next
)
2361 int error
= getnameinfo(&(addr
->addr
.addr
),
2362 httpAddrLength(&(addr
->addr
)),
2363 fqdn
, sizeof(fqdn
), NULL
, 0, NI_NAMEREQD
);
2367 DEBUG_printf(("8http_resolve_cb: Found \"%s\".", fqdn
));
2369 if ((hostptr
= fqdn
+ strlen(fqdn
) - 6) <= fqdn
||
2370 _cups_strcasecmp(hostptr
, ".local"))
2378 DEBUG_printf(("8http_resolve_cb: \"%s\" did not resolve: %d",
2379 httpAddrString(&(addr
->addr
), fqdn
, sizeof(fqdn
)),
2384 httpAddrFreeList(addrlist
);
2389 * Assemble the final device URI using the resolved hostname...
2392 httpAssembleURI(HTTP_URI_CODING_ALL
, uribuf
->buffer
, uribuf
->bufsize
, scheme
,
2393 NULL
, hostTarget
, port
, resource
);
2394 DEBUG_printf(("8http_resolve_cb: Resolved URI is \"%s\".", uribuf
->buffer
));
2396 avahi_simple_poll_quit(uribuf
->poll
);
2398 #endif /* HAVE_DNSSD */