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 */
89 const char *uuid
; /* UUID from URI */
97 static const char * const http_days
[7] =
107 static const char * const http_months
[12] =
128 static const char *http_copy_decode(char *dst
, const char *src
,
129 int dstsize
, const char *term
,
131 static char *http_copy_encode(char *dst
, const char *src
,
132 char *dstend
, const char *reserved
,
133 const char *term
, int encode
);
135 static void DNSSD_API
http_resolve_cb(DNSServiceRef sdRef
,
136 DNSServiceFlags flags
,
137 uint32_t interfaceIndex
,
138 DNSServiceErrorType errorCode
,
139 const char *fullName
,
140 const char *hostTarget
,
141 uint16_t port
, uint16_t txtLen
,
142 const unsigned char *txtRecord
,
144 #endif /* HAVE_DNSSD */
147 static void http_client_cb(AvahiClient
*client
,
148 AvahiClientState state
, void *simple_poll
);
149 static int http_poll_cb(struct pollfd
*pollfds
, unsigned int num_pollfds
,
150 int timeout
, void *context
);
151 static void http_resolve_cb(AvahiServiceResolver
*resolver
,
152 AvahiIfIndex interface
,
153 AvahiProtocol protocol
,
154 AvahiResolverEvent event
,
155 const char *name
, const char *type
,
156 const char *domain
, const char *host_name
,
157 const AvahiAddress
*address
, uint16_t port
,
158 AvahiStringList
*txt
,
159 AvahiLookupResultFlags flags
, void *context
);
160 #endif /* HAVE_AVAHI */
164 * 'httpAssembleURI()' - Assemble a uniform resource identifier from its
167 * This function escapes reserved characters in the URI depending on the
168 * value of the "encoding" argument. You should use this function in
169 * place of traditional string functions whenever you need to create a
172 * @since CUPS 1.2/OS X 10.5@
175 http_uri_status_t
/* O - URI status */
177 http_uri_coding_t encoding
, /* I - Encoding flags */
178 char *uri
, /* I - URI buffer */
179 int urilen
, /* I - Size of URI buffer */
180 const char *scheme
, /* I - Scheme name */
181 const char *username
, /* I - Username */
182 const char *host
, /* I - Hostname or address */
183 int port
, /* I - Port number */
184 const char *resource
) /* I - Resource */
186 char *ptr
, /* Pointer into URI buffer */
187 *end
; /* End of URI buffer */
191 * Range check input...
194 if (!uri
|| urilen
< 1 || !scheme
|| port
< 0)
199 return (HTTP_URI_STATUS_BAD_ARGUMENTS
);
203 * Assemble the URI starting with the scheme...
206 end
= uri
+ urilen
- 1;
207 ptr
= http_copy_encode(uri
, scheme
, end
, NULL
, NULL
, 0);
210 goto assemble_overflow
;
212 if (!strcmp(scheme
, "mailto"))
215 * mailto: only has :, no //...
221 goto assemble_overflow
;
226 * Schemes other than mailto: all have //...
236 goto assemble_overflow
;
240 * Next the username and hostname, if any...
245 const char *hostptr
; /* Pointer into hostname */
246 int have_ipv6
; /* Do we have an IPv6 address? */
248 if (username
&& *username
)
251 * Add username@ first...
254 ptr
= http_copy_encode(ptr
, username
, end
, "/?#[]@", NULL
,
255 encoding
& HTTP_URI_CODING_USERNAME
);
258 goto assemble_overflow
;
263 goto assemble_overflow
;
267 * Then add the hostname. Since IPv6 is a particular pain to deal
268 * with, we have several special cases to deal with. If we get
269 * an IPv6 address with brackets around it, assume it is already in
270 * URI format. Since DNS-SD service names can sometimes look like
271 * raw IPv6 addresses, we specifically look for "._tcp" in the name,
276 have_ipv6
= strchr(host
, ':') && !strstr(host
, "._tcp");
277 *hostptr
&& have_ipv6
;
279 if (*hostptr
!= ':' && !isxdigit(*hostptr
& 255))
281 have_ipv6
= *hostptr
== '%';
288 * We have a raw IPv6 address...
291 if (strchr(host
, '%') && !(encoding
& HTTP_URI_CODING_RFC6874
))
294 * We have a link-local address, add "[v1." prefix...
305 goto assemble_overflow
;
310 * We have a normal (or RFC 6874 link-local) address, add "[" prefix...
316 goto assemble_overflow
;
320 * Copy the rest of the IPv6 address, and terminate with "]".
323 while (ptr
< end
&& *host
)
328 * Convert/encode zone separator
331 if (encoding
& HTTP_URI_CODING_RFC6874
)
333 if (ptr
>= (end
- 2))
334 goto assemble_overflow
;
350 goto assemble_overflow
;
355 goto assemble_overflow
;
360 * Otherwise, just copy the host string (the extra chars are not in the
361 * "reg-name" ABNF rule; anything <= SP or >= DEL plus % gets automatically
365 ptr
= http_copy_encode(ptr
, host
, end
, "\"#/:<>?@[\\]^`{|}", NULL
,
366 encoding
& HTTP_URI_CODING_HOSTNAME
);
369 goto assemble_overflow
;
373 * Finish things off with the port number...
378 snprintf(ptr
, end
- ptr
+ 1, ":%d", port
);
382 goto assemble_overflow
;
387 * Last but not least, add the resource string...
392 char *query
; /* Pointer to query string */
396 * Copy the resource string up to the query string if present...
399 query
= strchr(resource
, '?');
400 ptr
= http_copy_encode(ptr
, resource
, end
, NULL
, "?",
401 encoding
& HTTP_URI_CODING_RESOURCE
);
403 goto assemble_overflow
;
408 * Copy query string without encoding...
411 ptr
= http_copy_encode(ptr
, query
, end
, NULL
, NULL
,
412 encoding
& HTTP_URI_CODING_QUERY
);
414 goto assemble_overflow
;
420 goto assemble_overflow
;
423 * Nul-terminate the URI buffer and return with no errors...
428 return (HTTP_URI_STATUS_OK
);
431 * Clear the URI string and return an overflow error; I don't usually
432 * like goto's, but in this case it makes sense...
438 return (HTTP_URI_STATUS_OVERFLOW
);
443 * 'httpAssembleURIf()' - Assemble a uniform resource identifier from its
444 * components with a formatted resource.
446 * This function creates a formatted version of the resource string
447 * argument "resourcef" and escapes reserved characters in the URI
448 * depending on the value of the "encoding" argument. You should use
449 * this function in place of traditional string functions whenever
450 * you need to create a URI string.
452 * @since CUPS 1.2/OS X 10.5@
455 http_uri_status_t
/* O - URI status */
457 http_uri_coding_t encoding
, /* I - Encoding flags */
458 char *uri
, /* I - URI buffer */
459 int urilen
, /* I - Size of URI buffer */
460 const char *scheme
, /* I - Scheme name */
461 const char *username
, /* I - Username */
462 const char *host
, /* I - Hostname or address */
463 int port
, /* I - Port number */
464 const char *resourcef
, /* I - Printf-style resource */
465 ...) /* I - Additional arguments as needed */
467 va_list ap
; /* Pointer to additional arguments */
468 char resource
[1024]; /* Formatted resource string */
469 int bytes
; /* Bytes in formatted string */
473 * Range check input...
476 if (!uri
|| urilen
< 1 || !scheme
|| port
< 0 || !resourcef
)
481 return (HTTP_URI_STATUS_BAD_ARGUMENTS
);
485 * Format the resource string and assemble the URI...
488 va_start(ap
, resourcef
);
489 bytes
= vsnprintf(resource
, sizeof(resource
), resourcef
, ap
);
492 if (bytes
>= sizeof(resource
))
495 return (HTTP_URI_STATUS_OVERFLOW
);
498 return (httpAssembleURI(encoding
, uri
, urilen
, scheme
, username
, host
,
504 * 'httpAssembleUUID()' - Assemble a name-based UUID URN conforming to RFC 4122.
506 * This function creates a unique 128-bit identifying number using the server
507 * name, port number, random data, and optionally an object name and/or object
508 * number. The result is formatted as a UUID URN as defined in RFC 4122.
510 * The buffer needs to be at least 46 bytes in size.
512 * @since CUPS 1.7/OS X 10.9@
515 char * /* I - UUID string */
516 httpAssembleUUID(const char *server
, /* I - Server name */
517 int port
, /* I - Port number */
518 const char *name
, /* I - Object name or NULL */
519 int number
, /* I - Object number or 0 */
520 char *buffer
, /* I - String buffer */
521 size_t bufsize
) /* I - Size of buffer */
523 char data
[1024]; /* Source string for MD5 */
524 _cups_md5_state_t md5state
; /* MD5 state */
525 unsigned char md5sum
[16]; /* MD5 digest/sum */
529 * Build a version 3 UUID conforming to RFC 4122.
531 * Start with the MD5 sum of the server, port, object name and
532 * number, and some random data on the end.
535 snprintf(data
, sizeof(data
), "%s:%d:%s:%d:%04x:%04x", server
,
536 port
, name
? name
: server
, number
,
537 (unsigned)CUPS_RAND() & 0xffff, (unsigned)CUPS_RAND() & 0xffff);
539 _cupsMD5Init(&md5state
);
540 _cupsMD5Append(&md5state
, (unsigned char *)data
, strlen(data
));
541 _cupsMD5Finish(&md5state
, md5sum
);
544 * Generate the UUID from the MD5...
547 snprintf(buffer
, bufsize
,
548 "urn:uuid:%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-"
549 "%02x%02x%02x%02x%02x%02x",
550 md5sum
[0], md5sum
[1], md5sum
[2], md5sum
[3], md5sum
[4], md5sum
[5],
551 (md5sum
[6] & 15) | 0x30, md5sum
[7], (md5sum
[8] & 0x3f) | 0x40,
552 md5sum
[9], md5sum
[10], md5sum
[11], md5sum
[12], md5sum
[13],
553 md5sum
[14], md5sum
[15]);
558 /* For OS X 10.8 and earlier */
559 char *_httpAssembleUUID(const char *server
, int port
, const char *name
,
560 int number
, char *buffer
, size_t bufsize
)
562 return (httpAssembleUUID(server
, port
, name
, number
, buffer
, bufsize
));
567 * 'httpDecode64()' - Base64-decode a string.
569 * This function is deprecated. Use the httpDecode64_2() function instead
570 * which provides buffer length arguments.
575 char * /* O - Decoded string */
576 httpDecode64(char *out
, /* I - String to write to */
577 const char *in
) /* I - String to read from */
579 int outlen
; /* Output buffer length */
583 * Use the old maximum buffer size for binary compatibility...
588 return (httpDecode64_2(out
, &outlen
, in
));
593 * 'httpDecode64_2()' - Base64-decode a string.
595 * @since CUPS 1.1.21/OS X 10.4@
598 char * /* O - Decoded string */
599 httpDecode64_2(char *out
, /* I - String to write to */
600 int *outlen
, /* IO - Size of output string */
601 const char *in
) /* I - String to read from */
603 int pos
, /* Bit position */
604 base64
; /* Value of this character */
605 char *outptr
, /* Output pointer */
606 *outend
; /* End of output buffer */
610 * Range check input...
613 if (!out
|| !outlen
|| *outlen
< 1 || !in
)
625 * Convert from base-64 to bytes...
628 for (outptr
= out
, outend
= out
+ *outlen
- 1, pos
= 0; *in
!= '\0'; in
++)
631 * Decode this character into a number from 0 to 63...
634 if (*in
>= 'A' && *in
<= 'Z')
636 else if (*in
>= 'a' && *in
<= 'z')
637 base64
= *in
- 'a' + 26;
638 else if (*in
>= '0' && *in
<= '9')
639 base64
= *in
- '0' + 52;
650 * Store the result in the appropriate chars...
657 *outptr
= base64
<< 2;
662 *outptr
++ |= (base64
>> 4) & 3;
664 *outptr
= (base64
<< 4) & 255;
669 *outptr
++ |= (base64
>> 2) & 15;
671 *outptr
= (base64
<< 6) & 255;
685 * Return the decoded string and size...
688 *outlen
= (int)(outptr
- out
);
695 * 'httpEncode64()' - Base64-encode a string.
697 * This function is deprecated. Use the httpEncode64_2() function instead
698 * which provides buffer length arguments.
703 char * /* O - Encoded string */
704 httpEncode64(char *out
, /* I - String to write to */
705 const char *in
) /* I - String to read from */
707 return (httpEncode64_2(out
, 512, in
, (int)strlen(in
)));
712 * 'httpEncode64_2()' - Base64-encode a string.
714 * @since CUPS 1.1.21/OS X 10.4@
717 char * /* O - Encoded string */
718 httpEncode64_2(char *out
, /* I - String to write to */
719 int outlen
, /* I - Size of output string */
720 const char *in
, /* I - String to read from */
721 int inlen
) /* I - Size of input string */
723 char *outptr
, /* Output pointer */
724 *outend
; /* End of output buffer */
725 static const char base64
[] = /* Base64 characters... */
727 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
728 "abcdefghijklmnopqrstuvwxyz"
735 * Range check input...
738 if (!out
|| outlen
< 1 || !in
)
742 * Convert bytes to base-64...
745 for (outptr
= out
, outend
= out
+ outlen
- 1; inlen
> 0; in
++, inlen
--)
748 * Encode the up to 3 characters as 4 Base64 numbers...
752 *outptr
++ = base64
[(in
[0] & 255) >> 2];
757 *outptr
++ = base64
[(((in
[0] & 255) << 4) | ((in
[1] & 255) >> 4)) & 63];
759 *outptr
++ = base64
[((in
[0] & 255) << 4) & 63];
776 *outptr
++ = base64
[(((in
[0] & 255) << 2) | ((in
[1] & 255) >> 6)) & 63];
778 *outptr
++ = base64
[((in
[0] & 255) << 2) & 63];
791 *outptr
++ = base64
[in
[0] & 63];
797 * Return the encoded string...
805 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
810 const char * /* O - Date/time string */
811 httpGetDateString(time_t t
) /* I - UNIX time */
813 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
816 return (httpGetDateString2(t
, cg
->http_date
, sizeof(cg
->http_date
)));
821 * 'httpGetDateString2()' - Get a formatted date/time string from a time value.
823 * @since CUPS 1.2/OS X 10.5@
826 const char * /* O - Date/time string */
827 httpGetDateString2(time_t t
, /* I - UNIX time */
828 char *s
, /* I - String buffer */
829 int slen
) /* I - Size of string buffer */
831 struct tm
*tdate
; /* UNIX date/time data */
836 snprintf(s
, slen
, "%s, %02d %s %d %02d:%02d:%02d GMT",
837 http_days
[tdate
->tm_wday
], tdate
->tm_mday
,
838 http_months
[tdate
->tm_mon
], tdate
->tm_year
+ 1900,
839 tdate
->tm_hour
, tdate
->tm_min
, tdate
->tm_sec
);
848 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
851 time_t /* O - UNIX time */
852 httpGetDateTime(const char *s
) /* I - Date/time string */
854 int i
; /* Looping var */
855 char mon
[16]; /* Abbreviated month name */
856 int day
, year
; /* Day of month and year */
857 int hour
, min
, sec
; /* Time */
858 int days
; /* Number of days since 1970 */
859 static const int normal_days
[] = /* Days to a month, normal years */
860 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
861 static const int leap_days
[] = /* Days to a month, leap years */
862 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 };
865 DEBUG_printf(("2httpGetDateTime(s=\"%s\")", s
));
868 * Extract the date and time from the formatted string...
871 if (sscanf(s
, "%*s%d%15s%d%d:%d:%d", &day
, mon
, &year
, &hour
, &min
, &sec
) < 6)
874 DEBUG_printf(("4httpGetDateTime: day=%d, mon=\"%s\", year=%d, hour=%d, "
875 "min=%d, sec=%d", day
, mon
, year
, hour
, min
, sec
));
878 * Convert the month name to a number from 0 to 11.
881 for (i
= 0; i
< 12; i
++)
882 if (!_cups_strcasecmp(mon
, http_months
[i
]))
888 DEBUG_printf(("4httpGetDateTime: i=%d", i
));
891 * Now convert the date and time to a UNIX time value in seconds since
892 * 1970. We can't use mktime() since the timezone may not be UTC but
893 * the date/time string *is* UTC.
896 if ((year
& 3) == 0 && ((year
% 100) != 0 || (year
% 400) == 0))
897 days
= leap_days
[i
] + day
- 1;
899 days
= normal_days
[i
] + day
- 1;
901 DEBUG_printf(("4httpGetDateTime: days=%d", days
));
903 days
+= (year
- 1970) * 365 + /* 365 days per year (normally) */
904 ((year
- 1) / 4 - 492) - /* + leap days */
905 ((year
- 1) / 100 - 19) + /* - 100 year days */
906 ((year
- 1) / 400 - 4); /* + 400 year days */
908 DEBUG_printf(("4httpGetDateTime: days=%d\n", days
));
910 return (days
* 86400 + hour
* 3600 + min
* 60 + sec
);
915 * 'httpSeparate()' - Separate a Universal Resource Identifier into its
918 * This function is deprecated; use the httpSeparateURI() function instead.
924 httpSeparate(const char *uri
, /* I - Universal Resource Identifier */
925 char *scheme
, /* O - Scheme [32] (http, https, etc.) */
926 char *username
, /* O - Username [1024] */
927 char *host
, /* O - Hostname [1024] */
928 int *port
, /* O - Port number to use */
929 char *resource
) /* O - Resource/filename [1024] */
931 httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, 32, username
,
932 HTTP_MAX_URI
, host
, HTTP_MAX_URI
, port
, resource
,
938 * 'httpSeparate2()' - Separate a Universal Resource Identifier into its
941 * This function is deprecated; use the httpSeparateURI() function instead.
943 * @since CUPS 1.1.21/OS X 10.4@
948 httpSeparate2(const char *uri
, /* I - Universal Resource Identifier */
949 char *scheme
, /* O - Scheme (http, https, etc.) */
950 int schemelen
, /* I - Size of scheme buffer */
951 char *username
, /* O - Username */
952 int usernamelen
, /* I - Size of username buffer */
953 char *host
, /* O - Hostname */
954 int hostlen
, /* I - Size of hostname buffer */
955 int *port
, /* O - Port number to use */
956 char *resource
, /* O - Resource/filename */
957 int resourcelen
) /* I - Size of resource buffer */
959 httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, schemelen
, username
,
960 usernamelen
, host
, hostlen
, port
, resource
, resourcelen
);
965 * 'httpSeparateURI()' - Separate a Universal Resource Identifier into its
968 * @since CUPS 1.2/OS X 10.5@
971 http_uri_status_t
/* O - Result of separation */
973 http_uri_coding_t decoding
, /* I - Decoding flags */
974 const char *uri
, /* I - Universal Resource Identifier */
975 char *scheme
, /* O - Scheme (http, https, etc.) */
976 int schemelen
, /* I - Size of scheme buffer */
977 char *username
, /* O - Username */
978 int usernamelen
, /* I - Size of username buffer */
979 char *host
, /* O - Hostname */
980 int hostlen
, /* I - Size of hostname buffer */
981 int *port
, /* O - Port number to use */
982 char *resource
, /* O - Resource/filename */
983 int resourcelen
) /* I - Size of resource buffer */
985 char *ptr
, /* Pointer into string... */
986 *end
; /* End of string */
987 const char *sep
; /* Separator character */
988 http_uri_status_t status
; /* Result of separation */
992 * Initialize everything to blank...
995 if (scheme
&& schemelen
> 0)
998 if (username
&& usernamelen
> 0)
1001 if (host
&& hostlen
> 0)
1007 if (resource
&& resourcelen
> 0)
1011 * Range check input...
1014 if (!uri
|| !port
|| !scheme
|| schemelen
<= 0 || !username
||
1015 usernamelen
<= 0 || !host
|| hostlen
<= 0 || !resource
||
1017 return (HTTP_URI_STATUS_BAD_ARGUMENTS
);
1020 return (HTTP_URI_STATUS_BAD_URI
);
1023 * Grab the scheme portion of the URI...
1026 status
= HTTP_URI_STATUS_OK
;
1028 if (!strncmp(uri
, "//", 2))
1031 * Workaround for HP IPP client bug...
1034 strlcpy(scheme
, "ipp", schemelen
);
1035 status
= HTTP_URI_STATUS_MISSING_SCHEME
;
1037 else if (*uri
== '/')
1043 strlcpy(scheme
, "file", schemelen
);
1044 status
= HTTP_URI_STATUS_MISSING_SCHEME
;
1049 * Standard URI with scheme...
1052 for (ptr
= scheme
, end
= scheme
+ schemelen
- 1;
1053 *uri
&& *uri
!= ':' && ptr
< end
;)
1054 if (strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1055 "abcdefghijklmnopqrstuvwxyz"
1056 "0123456789-+.", *uri
) != NULL
)
1066 return (HTTP_URI_STATUS_BAD_SCHEME
);
1073 * Set the default port number...
1076 if (!strcmp(scheme
, "http"))
1078 else if (!strcmp(scheme
, "https"))
1080 else if (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps"))
1082 else if (!_cups_strcasecmp(scheme
, "lpd"))
1084 else if (!strcmp(scheme
, "socket")) /* Not yet registered with IANA... */
1086 else if (strcmp(scheme
, "file") && strcmp(scheme
, "mailto"))
1087 status
= HTTP_URI_STATUS_UNKNOWN_SCHEME
;
1090 * Now see if we have a hostname...
1093 if (!strncmp(uri
, "//", 2))
1096 * Yes, extract it...
1102 * Grab the username, if any...
1105 if ((sep
= strpbrk(uri
, "@/")) != NULL
&& *sep
== '@')
1108 * Get a username:password combo...
1111 uri
= http_copy_decode(username
, uri
, usernamelen
, "@",
1112 decoding
& HTTP_URI_CODING_USERNAME
);
1117 return (HTTP_URI_STATUS_BAD_USERNAME
);
1124 * Then the hostname/IP address...
1130 * Grab IPv6 address...
1137 * Skip IPvFuture ("vXXXX.") prefix...
1142 while (isxdigit(*uri
& 255))
1148 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1154 uri
= http_copy_decode(host
, uri
, hostlen
, "]",
1155 decoding
& HTTP_URI_CODING_HOSTNAME
);
1160 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1170 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1175 for (ptr
= host
; *ptr
; ptr
++)
1179 * Convert zone separator to % and stop here...
1185 else if (*ptr
== '%')
1188 * Stop at zone separator (RFC 6874)
1193 else if (*ptr
!= ':' && *ptr
!= '.' && !isxdigit(*ptr
& 255))
1196 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1202 * Validate the hostname or IPv4 address first...
1205 for (ptr
= (char *)uri
; *ptr
; ptr
++)
1206 if (strchr(":?/", *ptr
))
1208 else if (!strchr("abcdefghijklmnopqrstuvwxyz" /* unreserved */
1209 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" /* unreserved */
1210 "0123456789" /* unreserved */
1211 "-._~" /* unreserved */
1212 "%" /* pct-encoded */
1213 "!$&'()*+,;=" /* sub-delims */
1214 "\\", *ptr
)) /* SMB domain */
1217 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1221 * Then copy the hostname or IPv4 address to the buffer...
1224 uri
= http_copy_decode(host
, uri
, hostlen
, ":?/",
1225 decoding
& HTTP_URI_CODING_HOSTNAME
);
1230 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1235 * Validate hostname for file scheme - only empty and localhost are
1239 if (!strcmp(scheme
, "file") && strcmp(host
, "localhost") && host
[0])
1242 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1246 * See if we have a port number...
1252 * Yes, collect the port number...
1255 if (!isdigit(uri
[1] & 255))
1258 return (HTTP_URI_STATUS_BAD_PORT
);
1261 *port
= strtol(uri
+ 1, (char **)&uri
, 10);
1263 if (*uri
!= '/' && *uri
)
1266 return (HTTP_URI_STATUS_BAD_PORT
);
1272 * The remaining portion is the resource string...
1275 if (*uri
== '?' || !*uri
)
1278 * Hostname but no path...
1281 status
= HTTP_URI_STATUS_MISSING_RESOURCE
;
1285 * Copy any query string...
1289 uri
= http_copy_decode(resource
+ 1, uri
, resourcelen
- 1, NULL
,
1290 decoding
& HTTP_URI_CODING_QUERY
);
1296 uri
= http_copy_decode(resource
, uri
, resourcelen
, "?",
1297 decoding
& HTTP_URI_CODING_RESOURCE
);
1299 if (uri
&& *uri
== '?')
1302 * Concatenate any query string...
1305 char *resptr
= resource
+ strlen(resource
);
1307 uri
= http_copy_decode(resptr
, uri
,
1308 resourcelen
- (int)(resptr
- resource
), NULL
,
1309 decoding
& HTTP_URI_CODING_QUERY
);
1316 return (HTTP_URI_STATUS_BAD_RESOURCE
);
1320 * Return the URI separation status...
1328 * '_httpStatus()' - Return the localized string describing a HTTP status code.
1330 * The returned string is localized using the passed message catalog.
1333 const char * /* O - Localized status string */
1334 _httpStatus(cups_lang_t
*lang
, /* I - Language */
1335 http_status_t status
) /* I - HTTP status code */
1337 const char *s
; /* Status string */
1342 case HTTP_STATUS_ERROR
:
1343 s
= strerror(errno
);
1345 case HTTP_STATUS_CONTINUE
:
1348 case HTTP_STATUS_SWITCHING_PROTOCOLS
:
1349 s
= _("Switching Protocols");
1351 case HTTP_STATUS_OK
:
1354 case HTTP_STATUS_CREATED
:
1357 case HTTP_STATUS_ACCEPTED
:
1360 case HTTP_STATUS_NO_CONTENT
:
1361 s
= _("No Content");
1363 case HTTP_STATUS_MOVED_PERMANENTLY
:
1364 s
= _("Moved Permanently");
1366 case HTTP_STATUS_SEE_OTHER
:
1369 case HTTP_STATUS_NOT_MODIFIED
:
1370 s
= _("Not Modified");
1372 case HTTP_STATUS_BAD_REQUEST
:
1373 s
= _("Bad Request");
1375 case HTTP_STATUS_UNAUTHORIZED
:
1376 case HTTP_STATUS_CUPS_AUTHORIZATION_CANCELED
:
1377 s
= _("Unauthorized");
1379 case HTTP_STATUS_FORBIDDEN
:
1382 case HTTP_STATUS_NOT_FOUND
:
1385 case HTTP_STATUS_REQUEST_TOO_LARGE
:
1386 s
= _("Request Entity Too Large");
1388 case HTTP_STATUS_URI_TOO_LONG
:
1389 s
= _("URI Too Long");
1391 case HTTP_STATUS_UPGRADE_REQUIRED
:
1392 s
= _("Upgrade Required");
1394 case HTTP_STATUS_NOT_IMPLEMENTED
:
1395 s
= _("Not Implemented");
1397 case HTTP_STATUS_NOT_SUPPORTED
:
1398 s
= _("Not Supported");
1400 case HTTP_STATUS_EXPECTATION_FAILED
:
1401 s
= _("Expectation Failed");
1403 case HTTP_STATUS_SERVICE_UNAVAILABLE
:
1404 s
= _("Service Unavailable");
1406 case HTTP_STATUS_SERVER_ERROR
:
1407 s
= _("Internal Server Error");
1409 case HTTP_STATUS_CUPS_PKI_ERROR
:
1410 s
= _("SSL/TLS Negotiation Error");
1412 case HTTP_STATUS_CUPS_WEBIF_DISABLED
:
1413 s
= _("Web Interface is Disabled");
1421 return (_cupsLangString(lang
, s
));
1426 * 'httpStatus()' - Return a short string describing a HTTP status code.
1428 * The returned string is localized to the current POSIX locale and is based
1429 * on the status strings defined in RFC 2616.
1432 const char * /* O - Localized status string */
1433 httpStatus(http_status_t status
) /* I - HTTP status code */
1435 _cups_globals_t
*cg
= _cupsGlobals(); /* Global data */
1438 if (!cg
->lang_default
)
1439 cg
->lang_default
= cupsLangDefault();
1441 return (_httpStatus(cg
->lang_default
, status
));
1445 #ifndef HAVE_HSTRERROR
1447 * '_cups_hstrerror()' - hstrerror() emulation function for Solaris and others.
1450 const char * /* O - Error string */
1451 _cups_hstrerror(int error
) /* I - Error number */
1453 static const char * const errors
[] = /* Error strings */
1458 "Unrecoverable lookup error.",
1459 "No data associated with name."
1463 if (error
< 0 || error
> 4)
1464 return ("Unknown hostname lookup error.");
1466 return (errors
[error
]);
1468 #endif /* !HAVE_HSTRERROR */
1472 * '_httpDecodeURI()' - Percent-decode a HTTP request URI.
1475 char * /* O - Decoded URI or NULL on error */
1476 _httpDecodeURI(char *dst
, /* I - Destination buffer */
1477 const char *src
, /* I - Source URI */
1478 size_t dstsize
) /* I - Size of destination buffer */
1480 if (http_copy_decode(dst
, src
, (int)dstsize
, NULL
, 1))
1488 * '_httpEncodeURI()' - Percent-encode a HTTP request URI.
1491 char * /* O - Encoded URI */
1492 _httpEncodeURI(char *dst
, /* I - Destination buffer */
1493 const char *src
, /* I - Source URI */
1494 size_t dstsize
) /* I - Size of destination buffer */
1496 http_copy_encode(dst
, src
, dst
+ dstsize
- 1, NULL
, NULL
, 1);
1502 * '_httpResolveURI()' - Resolve a DNS-SD URI.
1505 const char * /* O - Resolved URI */
1507 const char *uri
, /* I - DNS-SD URI */
1508 char *resolved_uri
, /* I - Buffer for resolved URI */
1509 size_t resolved_size
, /* I - Size of URI buffer */
1510 int options
, /* I - Resolve options */
1511 int (*cb
)(void *context
), /* I - Continue callback function */
1512 void *context
) /* I - Context pointer for callback */
1514 char scheme
[32], /* URI components... */
1520 http_uri_status_t status
; /* URI decode status */
1524 DEBUG_printf(("4_httpResolveURI(uri=\"%s\", resolved_uri=%p, "
1525 "resolved_size=" CUPS_LLFMT
")", uri
, resolved_uri
,
1526 CUPS_LLCAST resolved_size
));
1529 * Get the device URI...
1533 if ((status
= httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
,
1534 sizeof(scheme
), userpass
, sizeof(userpass
),
1535 hostname
, sizeof(hostname
), &port
, resource
,
1536 sizeof(resource
))) < HTTP_URI_STATUS_OK
)
1538 if (httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
,
1539 sizeof(scheme
), userpass
, sizeof(userpass
),
1540 hostname
, sizeof(hostname
), &port
, resource
,
1541 sizeof(resource
)) < HTTP_URI_STATUS_OK
)
1544 if (options
& _HTTP_RESOLVE_STDERR
)
1545 _cupsLangPrintFilter(stderr
, "ERROR", _("Bad device-uri \"%s\"."), uri
);
1547 DEBUG_printf(("6_httpResolveURI: httpSeparateURI returned %d!", status
));
1548 DEBUG_puts("5_httpResolveURI: Returning NULL");
1553 * Resolve it as needed...
1556 if (strstr(hostname
, "._tcp"))
1558 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
1559 char *regtype
, /* Pointer to type in hostname */
1560 *domain
, /* Pointer to domain in hostname */
1561 *uuid
, /* Pointer to UUID in URI */
1562 *uuidend
; /* Pointer to end of UUID in URI */
1563 _http_uribuf_t uribuf
; /* URI buffer */
1564 int offline
= 0; /* offline-report state set? */
1567 # pragma comment(lib, "dnssd.lib")
1569 DNSServiceRef ref
, /* DNS-SD master service reference */
1570 domainref
, /* DNS-SD service reference for domain */
1571 localref
; /* DNS-SD service reference for .local */
1572 int domainsent
= 0; /* Send the domain resolve? */
1574 struct pollfd polldata
; /* Polling data */
1575 # else /* select() */
1576 fd_set input_set
; /* Input set for select() */
1577 struct timeval stimeout
; /* Timeout value for select() */
1578 # endif /* HAVE_POLL */
1579 # elif defined(HAVE_AVAHI)
1580 AvahiClient
*client
; /* Client information */
1581 int error
; /* Status */
1582 # endif /* HAVE_DNSSD */
1584 if (options
& _HTTP_RESOLVE_STDERR
)
1585 fprintf(stderr
, "DEBUG: Resolving \"%s\"...\n", hostname
);
1588 * Separate the hostname into service name, registration type, and domain...
1591 for (regtype
= strstr(hostname
, "._tcp") - 2;
1594 if (regtype
[0] == '.' && regtype
[1] == '_')
1597 * Found ._servicetype in front of ._tcp...
1604 if (regtype
<= hostname
)
1606 DEBUG_puts("5_httpResolveURI: Bad hostname, returning NULL");
1610 for (domain
= strchr(regtype
, '.');
1612 domain
= strchr(domain
+ 1, '.'))
1613 if (domain
[1] != '_')
1619 if ((uuid
= strstr(resource
, "?uuid=")) != NULL
)
1623 if ((uuidend
= strchr(uuid
, '&')) != NULL
)
1627 resolved_uri
[0] = '\0';
1629 uribuf
.buffer
= resolved_uri
;
1630 uribuf
.bufsize
= resolved_size
;
1631 uribuf
.options
= options
;
1632 uribuf
.resource
= resource
;
1635 DEBUG_printf(("6_httpResolveURI: Resolving hostname=\"%s\", regtype=\"%s\", "
1636 "domain=\"%s\"\n", hostname
, regtype
, domain
));
1637 if (options
& _HTTP_RESOLVE_STDERR
)
1639 fputs("STATE: +connecting-to-device\n", stderr
);
1640 fprintf(stderr
, "DEBUG: Resolving \"%s\", regtype=\"%s\", "
1641 "domain=\"local.\"...\n", hostname
, regtype
);
1647 if (DNSServiceCreateConnection(&ref
) == kDNSServiceErr_NoError
)
1649 int myinterface
= kDNSServiceInterfaceIndexAny
;
1650 /* Lookup on any interface */
1652 if (!strcmp(scheme
, "ippusb"))
1653 myinterface
= kDNSServiceInterfaceIndexLocalOnly
;
1656 if (DNSServiceResolve(&localref
,
1657 kDNSServiceFlagsShareConnection
, myinterface
,
1658 hostname
, regtype
, "local.", http_resolve_cb
,
1659 &uribuf
) == kDNSServiceErr_NoError
)
1661 int fds
; /* Number of ready descriptors */
1662 time_t timeout
, /* Poll timeout */
1663 start_time
= time(NULL
),/* Start time */
1664 end_time
= start_time
+ 90;
1667 while (time(NULL
) < end_time
)
1669 if (options
& _HTTP_RESOLVE_STDERR
)
1670 _cupsLangPrintFilter(stderr
, "INFO", _("Looking for printer."));
1672 if (cb
&& !(*cb
)(context
))
1674 DEBUG_puts("5_httpResolveURI: callback returned 0 (stop)");
1679 * Wakeup every 2 seconds to emit a "looking for printer" message...
1682 if ((timeout
= end_time
- time(NULL
)) > 2)
1686 polldata
.fd
= DNSServiceRefSockFD(ref
);
1687 polldata
.events
= POLLIN
;
1689 fds
= poll(&polldata
, 1, 1000 * timeout
);
1691 # else /* select() */
1692 FD_ZERO(&input_set
);
1693 FD_SET(DNSServiceRefSockFD(ref
), &input_set
);
1696 stimeout
.tv_sec
= (long)timeout
;
1698 stimeout
.tv_sec
= timeout
;
1700 stimeout
.tv_usec
= 0;
1702 fds
= select(DNSServiceRefSockFD(ref
)+1, &input_set
, NULL
, NULL
,
1704 # endif /* HAVE_POLL */
1708 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1710 DEBUG_printf(("5_httpResolveURI: poll error: %s", strerror(errno
)));
1717 * Wait 2 seconds for a response to the local resolve; if nothing
1718 * comes in, do an additional domain resolution...
1721 if (domainsent
== 0 && domain
&& _cups_strcasecmp(domain
, "local."))
1723 if (options
& _HTTP_RESOLVE_STDERR
)
1725 "DEBUG: Resolving \"%s\", regtype=\"%s\", "
1726 "domain=\"%s\"...\n", hostname
, regtype
,
1727 domain
? domain
: "");
1730 if (DNSServiceResolve(&domainref
,
1731 kDNSServiceFlagsShareConnection
,
1732 myinterface
, hostname
, regtype
, domain
,
1734 &uribuf
) == kDNSServiceErr_NoError
)
1739 * If it hasn't resolved within 5 seconds set the offline-report
1740 * printer-state-reason...
1743 if ((options
& _HTTP_RESOLVE_STDERR
) && offline
== 0 &&
1744 time(NULL
) > (start_time
+ 5))
1746 fputs("STATE: +offline-report\n", stderr
);
1752 if (DNSServiceProcessResult(ref
) == kDNSServiceErr_NoError
&&
1762 DNSServiceRefDeallocate(domainref
);
1764 DNSServiceRefDeallocate(localref
);
1767 DNSServiceRefDeallocate(ref
);
1769 # else /* HAVE_AVAHI */
1770 if ((uribuf
.poll
= avahi_simple_poll_new()) != NULL
)
1772 avahi_simple_poll_set_func(uribuf
.poll
, http_poll_cb
, NULL
);
1774 if ((client
= avahi_client_new(avahi_simple_poll_get(uribuf
.poll
),
1776 &uribuf
, &error
)) != NULL
)
1778 if (avahi_service_resolver_new(client
, AVAHI_IF_UNSPEC
,
1779 AVAHI_PROTO_UNSPEC
, hostname
,
1780 regtype
, "local.", AVAHI_PROTO_UNSPEC
, 0,
1781 http_resolve_cb
, &uribuf
) != NULL
)
1783 time_t start_time
= time(NULL
),
1785 end_time
= start_time
+ 90;
1787 int pstatus
; /* Poll status */
1789 pstatus
= avahi_simple_poll_iterate(uribuf
.poll
, 2000);
1791 if (pstatus
== 0 && !resolved_uri
[0] && domain
&&
1792 _cups_strcasecmp(domain
, "local."))
1795 * Resolve for .local hasn't returned anything, try the listed
1799 avahi_service_resolver_new(client
, AVAHI_IF_UNSPEC
,
1800 AVAHI_PROTO_UNSPEC
, hostname
,
1801 regtype
, domain
, AVAHI_PROTO_UNSPEC
, 0,
1802 http_resolve_cb
, &uribuf
);
1805 while (!pstatus
&& !resolved_uri
[0] && time(NULL
) < end_time
)
1807 if ((pstatus
= avahi_simple_poll_iterate(uribuf
.poll
, 2000)) != 0)
1811 * If it hasn't resolved within 5 seconds set the offline-report
1812 * printer-state-reason...
1815 if ((options
& _HTTP_RESOLVE_STDERR
) && offline
== 0 &&
1816 time(NULL
) > (start_time
+ 5))
1818 fputs("STATE: +offline-report\n", stderr
);
1824 * Collect the result (if we got one).
1827 if (resolved_uri
[0])
1831 avahi_client_free(client
);
1834 avahi_simple_poll_free(uribuf
.poll
);
1836 # endif /* HAVE_DNSSD */
1838 if (options
& _HTTP_RESOLVE_STDERR
)
1842 fprintf(stderr
, "DEBUG: Resolved as \"%s\"...\n", uri
);
1843 fputs("STATE: -connecting-to-device,offline-report\n", stderr
);
1847 fputs("DEBUG: Unable to resolve URI\n", stderr
);
1848 fputs("STATE: -connecting-to-device\n", stderr
);
1852 #else /* HAVE_DNSSD || HAVE_AVAHI */
1854 * No DNS-SD support...
1858 #endif /* HAVE_DNSSD || HAVE_AVAHI */
1860 if ((options
& _HTTP_RESOLVE_STDERR
) && !uri
)
1861 _cupsLangPrintFilter(stderr
, "INFO", _("Unable to find printer."));
1866 * Nothing more to do...
1869 strlcpy(resolved_uri
, uri
, resolved_size
);
1873 DEBUG_printf(("5_httpResolveURI: Returning \"%s\"", uri
));
1881 * 'http_client_cb()' - Client callback for resolving URI.
1886 AvahiClient
*client
, /* I - Client information */
1887 AvahiClientState state
, /* I - Current state */
1888 void *context
) /* I - Pointer to URI buffer */
1890 DEBUG_printf(("7http_client_cb(client=%p, state=%d, context=%p)", client
,
1894 * If the connection drops, quit.
1897 if (state
== AVAHI_CLIENT_FAILURE
)
1899 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
1902 avahi_simple_poll_quit(uribuf
->poll
);
1905 #endif /* HAVE_AVAHI */
1909 * 'http_copy_decode()' - Copy and decode a URI.
1912 static const char * /* O - New source pointer or NULL on error */
1913 http_copy_decode(char *dst
, /* O - Destination buffer */
1914 const char *src
, /* I - Source pointer */
1915 int dstsize
, /* I - Destination size */
1916 const char *term
, /* I - Terminating characters */
1917 int decode
) /* I - Decode %-encoded values */
1919 char *ptr
, /* Pointer into buffer */
1920 *end
; /* End of buffer */
1921 int quoted
; /* Quoted character */
1925 * Copy the src to the destination until we hit a terminating character
1926 * or the end of the string.
1929 for (ptr
= dst
, end
= dst
+ dstsize
- 1;
1930 *src
&& (!term
|| !strchr(term
, *src
));
1934 if (*src
== '%' && decode
)
1936 if (isxdigit(src
[1] & 255) && isxdigit(src
[2] & 255))
1939 * Grab a hex-encoded character...
1944 quoted
= (tolower(*src
) - 'a' + 10) << 4;
1946 quoted
= (*src
- '0') << 4;
1950 quoted
|= tolower(*src
) - 'a' + 10;
1952 quoted
|= *src
- '0';
1959 * Bad hex-encoded character...
1966 else if ((*src
& 255) <= 0x20 || (*src
& 255) >= 0x7f)
1982 * 'http_copy_encode()' - Copy and encode a URI.
1985 static char * /* O - End of current URI */
1986 http_copy_encode(char *dst
, /* O - Destination buffer */
1987 const char *src
, /* I - Source pointer */
1988 char *dstend
, /* I - End of destination buffer */
1989 const char *reserved
, /* I - Extra reserved characters */
1990 const char *term
, /* I - Terminating characters */
1991 int encode
) /* I - %-encode reserved chars? */
1993 static const char hex
[] = "0123456789ABCDEF";
1996 while (*src
&& dst
< dstend
)
1998 if (term
&& *src
== *term
)
2001 if (encode
&& (*src
== '%' || *src
<= ' ' || *src
& 128 ||
2002 (reserved
&& strchr(reserved
, *src
))))
2005 * Hex encode reserved characters...
2008 if ((dst
+ 2) >= dstend
)
2012 *dst
++ = hex
[(*src
>> 4) & 15];
2013 *dst
++ = hex
[*src
& 15];
2032 * 'http_resolve_cb()' - Build a device URI for the given service name.
2035 static void DNSSD_API
2037 DNSServiceRef sdRef
, /* I - Service reference */
2038 DNSServiceFlags flags
, /* I - Results flags */
2039 uint32_t interfaceIndex
, /* I - Interface number */
2040 DNSServiceErrorType errorCode
, /* I - Error, if any */
2041 const char *fullName
, /* I - Full service name */
2042 const char *hostTarget
, /* I - Hostname */
2043 uint16_t port
, /* I - Port number */
2044 uint16_t txtLen
, /* I - Length of TXT record */
2045 const unsigned char *txtRecord
, /* I - TXT record data */
2046 void *context
) /* I - Pointer to URI buffer */
2048 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
2050 const char *scheme
, /* URI scheme */
2051 *hostptr
, /* Pointer into hostTarget */
2052 *reskey
, /* "rp" or "rfo" */
2053 *resdefault
; /* Default path */
2054 char resource
[257], /* Remote path */
2055 fqdn
[256]; /* FQDN of the .local name */
2056 const void *value
; /* Value from TXT record */
2057 uint8_t valueLen
; /* Length of value */
2060 DEBUG_printf(("7http_resolve_cb(sdRef=%p, flags=%x, interfaceIndex=%u, "
2061 "errorCode=%d, fullName=\"%s\", hostTarget=\"%s\", port=%u, "
2062 "txtLen=%u, txtRecord=%p, context=%p)", sdRef
, flags
,
2063 interfaceIndex
, errorCode
, fullName
, hostTarget
, port
, txtLen
,
2064 txtRecord
, context
));
2067 * If we have a UUID, compare it...
2071 (value
= TXTRecordGetValuePtr(txtLen
, txtRecord
, "UUID",
2072 &valueLen
)) != NULL
)
2074 char uuid
[256]; /* UUID value */
2076 memcpy(uuid
, value
, valueLen
);
2077 uuid
[valueLen
] = '\0';
2079 if (_cups_strcasecmp(uuid
, uribuf
->uuid
))
2081 if (uribuf
->options
& _HTTP_RESOLVE_STDERR
)
2083 _cupsLangPrintFilter(stderr
, "INFO", _("Still looking for printer."));
2084 fprintf(stderr
, "DEBUG: Found UUID %s, looking for %s.", uuid
,
2088 DEBUG_printf(("7http_resolve_cb: Found UUID %s, looking for %s.", uuid
,
2095 * Figure out the scheme from the full name...
2098 if (strstr(fullName
, "._ipps") || strstr(fullName
, "._ipp-tls"))
2100 else if (strstr(fullName
, "._ipp") || strstr(fullName
, "._fax-ipp"))
2102 else if (strstr(fullName
, "._http."))
2104 else if (strstr(fullName
, "._https."))
2106 else if (strstr(fullName
, "._printer."))
2108 else if (strstr(fullName
, "._pdl-datastream."))
2111 scheme
= "riousbprint";
2114 * Extract the "remote printer" key from the TXT record...
2117 if ((uribuf
->options
& _HTTP_RESOLVE_FAXOUT
) &&
2118 (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")) &&
2119 !TXTRecordGetValuePtr(txtLen
, txtRecord
, "printer-type", &valueLen
))
2122 resdefault
= "/ipp/faxout";
2130 if ((value
= TXTRecordGetValuePtr(txtLen
, txtRecord
, reskey
,
2131 &valueLen
)) != NULL
)
2133 if (((char *)value
)[0] == '/')
2136 * Value (incorrectly) has a leading slash already...
2139 memcpy(resource
, value
, valueLen
);
2140 resource
[valueLen
] = '\0';
2145 * Convert to resource by concatenating with a leading "/"...
2149 memcpy(resource
+ 1, value
, valueLen
);
2150 resource
[valueLen
+ 1] = '\0';
2156 * Use the default value...
2159 strlcpy(resource
, resdefault
, sizeof(resource
));
2163 * Lookup the FQDN if needed...
2166 if ((uribuf
->options
& _HTTP_RESOLVE_FQDN
) &&
2167 (hostptr
= hostTarget
+ strlen(hostTarget
) - 7) > hostTarget
&&
2168 !_cups_strcasecmp(hostptr
, ".local."))
2171 * OK, we got a .local name but the caller needs a real domain. Start by
2172 * getting the IP address of the .local name and then do reverse-lookups...
2175 http_addrlist_t
*addrlist
, /* List of addresses */
2176 *addr
; /* Current address */
2178 DEBUG_printf(("8http_resolve_cb: Looking up \"%s\".", hostTarget
));
2180 snprintf(fqdn
, sizeof(fqdn
), "%d", ntohs(port
));
2181 if ((addrlist
= httpAddrGetList(hostTarget
, AF_UNSPEC
, fqdn
)) != NULL
)
2183 for (addr
= addrlist
; addr
; addr
= addr
->next
)
2185 int error
= getnameinfo(&(addr
->addr
.addr
),
2186 httpAddrLength(&(addr
->addr
)),
2187 fqdn
, sizeof(fqdn
), NULL
, 0, NI_NAMEREQD
);
2191 DEBUG_printf(("8http_resolve_cb: Found \"%s\".", fqdn
));
2193 if ((hostptr
= fqdn
+ strlen(fqdn
) - 6) <= fqdn
||
2194 _cups_strcasecmp(hostptr
, ".local"))
2202 DEBUG_printf(("8http_resolve_cb: \"%s\" did not resolve: %d",
2203 httpAddrString(&(addr
->addr
), fqdn
, sizeof(fqdn
)),
2208 httpAddrFreeList(addrlist
);
2213 * Assemble the final device URI...
2216 if ((!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")) &&
2217 !strcmp(uribuf
->resource
, "/cups"))
2218 httpAssembleURIf(HTTP_URI_CODING_ALL
, uribuf
->buffer
, uribuf
->bufsize
,
2219 scheme
, NULL
, hostTarget
, ntohs(port
), "%s?snmp=false",
2222 httpAssembleURI(HTTP_URI_CODING_ALL
, uribuf
->buffer
, uribuf
->bufsize
,
2223 scheme
, NULL
, hostTarget
, ntohs(port
), resource
);
2225 DEBUG_printf(("8http_resolve_cb: Resolved URI is \"%s\"...", uribuf
->buffer
));
2228 #elif defined(HAVE_AVAHI)
2230 * 'http_poll_cb()' - Wait for input on the specified file descriptors.
2232 * Note: This function is needed because avahi_simple_poll_iterate is broken
2233 * and always uses a timeout of 0 (!) milliseconds.
2234 * (Avahi Ticket #364)
2237 static int /* O - Number of file descriptors matching */
2239 struct pollfd
*pollfds
, /* I - File descriptors */
2240 unsigned int num_pollfds
, /* I - Number of file descriptors */
2241 int timeout
, /* I - Timeout in milliseconds (used) */
2242 void *context
) /* I - User data (unused) */
2247 return (poll(pollfds
, num_pollfds
, 2000));
2252 * 'http_resolve_cb()' - Build a device URI for the given service name.
2257 AvahiServiceResolver
*resolver
, /* I - Resolver (unused) */
2258 AvahiIfIndex interface
, /* I - Interface index (unused) */
2259 AvahiProtocol protocol
, /* I - Network protocol (unused) */
2260 AvahiResolverEvent event
, /* I - Event (found, etc.) */
2261 const char *name
, /* I - Service name */
2262 const char *type
, /* I - Registration type */
2263 const char *domain
, /* I - Domain (unused) */
2264 const char *hostTarget
, /* I - Hostname */
2265 const AvahiAddress
*address
, /* I - Address (unused) */
2266 uint16_t port
, /* I - Port number */
2267 AvahiStringList
*txt
, /* I - TXT record */
2268 AvahiLookupResultFlags flags
, /* I - Lookup flags (unused) */
2269 void *context
) /* I - Pointer to URI buffer */
2271 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
2273 const char *scheme
, /* URI scheme */
2274 *hostptr
, /* Pointer into hostTarget */
2275 *reskey
, /* "rp" or "rfo" */
2276 *resdefault
; /* Default path */
2277 char resource
[257], /* Remote path */
2278 fqdn
[256]; /* FQDN of the .local name */
2279 AvahiStringList
*pair
; /* Current TXT record key/value pair */
2280 char *value
; /* Value for "rp" key */
2281 size_t valueLen
= 0; /* Length of "rp" key */
2284 DEBUG_printf(("7http_resolve_cb(resolver=%p, "
2285 "interface=%d, protocol=%d, event=%d, name=\"%s\", "
2286 "type=\"%s\", domain=\"%s\", hostTarget=\"%s\", address=%p, "
2287 "port=%d, txt=%p, flags=%d, context=%p)",
2288 resolver
, interface
, protocol
, event
, name
, type
, domain
,
2289 hostTarget
, address
, port
, txt
, flags
, context
));
2291 if (event
!= AVAHI_RESOLVER_FOUND
)
2293 avahi_service_resolver_free(resolver
);
2294 avahi_simple_poll_quit(uribuf
->poll
);
2299 * If we have a UUID, compare it...
2302 if (uribuf
->uuid
&& (pair
= avahi_string_list_find(txt
, "UUID")) != NULL
)
2304 char uuid
[256]; /* UUID value */
2306 avahi_string_list_get_pair(pair
, NULL
, &value
, &valueLen
);
2308 memcpy(uuid
, value
, valueLen
);
2309 uuid
[valueLen
] = '\0';
2311 if (_cups_strcasecmp(uuid
, uribuf
->uuid
))
2313 if (uribuf
->options
& _HTTP_RESOLVE_STDERR
)
2315 _cupsLangPrintFilter(stderr
, "INFO", _("Still looking for printer."));
2316 fprintf(stderr
, "DEBUG: Found UUID %s, looking for %s.", uuid
,
2320 DEBUG_printf(("7http_resolve_cb: Found UUID %s, looking for %s.", uuid
,
2327 * Figure out the scheme from the full name...
2330 if (strstr(type
, "_ipp."))
2332 else if (strstr(type
, "_printer."))
2334 else if (strstr(type
, "_pdl-datastream."))
2337 scheme
= "riousbprint";
2339 if (!strncmp(type
, "_ipps.", 6) || !strncmp(type
, "_ipp-tls.", 9))
2341 else if (!strncmp(type
, "_ipp.", 5) || !strncmp(type
, "_fax-ipp.", 9))
2343 else if (!strncmp(type
, "_http.", 6))
2345 else if (!strncmp(type
, "_https.", 7))
2347 else if (!strncmp(type
, "_printer.", 9))
2349 else if (!strncmp(type
, "_pdl-datastream.", 16))
2353 avahi_service_resolver_free(resolver
);
2354 avahi_simple_poll_quit(uribuf
->poll
);
2359 * Extract the remote resource key from the TXT record...
2362 if ((uribuf
->options
& _HTTP_RESOLVE_FAXOUT
) &&
2363 (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")) &&
2364 !avahi_string_list_find(txt
, "printer-type"))
2367 resdefault
= "/ipp/faxout";
2375 if ((pair
= avahi_string_list_find(txt
, reskey
)) != NULL
)
2377 avahi_string_list_get_pair(pair
, NULL
, &value
, &valueLen
);
2379 if (value
[0] == '/')
2382 * Value (incorrectly) has a leading slash already...
2385 memcpy(resource
, value
, valueLen
);
2386 resource
[valueLen
] = '\0';
2391 * Convert to resource by concatenating with a leading "/"...
2395 memcpy(resource
+ 1, value
, valueLen
);
2396 resource
[valueLen
+ 1] = '\0';
2402 * Use the default value...
2405 strlcpy(resource
, resdefault
, sizeof(resource
));
2409 * Lookup the FQDN if needed...
2412 if ((uribuf
->options
& _HTTP_RESOLVE_FQDN
) &&
2413 (hostptr
= hostTarget
+ strlen(hostTarget
) - 6) > hostTarget
&&
2414 !_cups_strcasecmp(hostptr
, ".local"))
2417 * OK, we got a .local name but the caller needs a real domain. Start by
2418 * getting the IP address of the .local name and then do reverse-lookups...
2421 http_addrlist_t
*addrlist
, /* List of addresses */
2422 *addr
; /* Current address */
2424 DEBUG_printf(("8http_resolve_cb: Looking up \"%s\".", hostTarget
));
2426 snprintf(fqdn
, sizeof(fqdn
), "%d", ntohs(port
));
2427 if ((addrlist
= httpAddrGetList(hostTarget
, AF_UNSPEC
, fqdn
)) != NULL
)
2429 for (addr
= addrlist
; addr
; addr
= addr
->next
)
2431 int error
= getnameinfo(&(addr
->addr
.addr
),
2432 httpAddrLength(&(addr
->addr
)),
2433 fqdn
, sizeof(fqdn
), NULL
, 0, NI_NAMEREQD
);
2437 DEBUG_printf(("8http_resolve_cb: Found \"%s\".", fqdn
));
2439 if ((hostptr
= fqdn
+ strlen(fqdn
) - 6) <= fqdn
||
2440 _cups_strcasecmp(hostptr
, ".local"))
2448 DEBUG_printf(("8http_resolve_cb: \"%s\" did not resolve: %d",
2449 httpAddrString(&(addr
->addr
), fqdn
, sizeof(fqdn
)),
2454 httpAddrFreeList(addrlist
);
2459 * Assemble the final device URI using the resolved hostname...
2462 httpAssembleURI(HTTP_URI_CODING_ALL
, uribuf
->buffer
, uribuf
->bufsize
, scheme
,
2463 NULL
, hostTarget
, port
, resource
);
2464 DEBUG_printf(("8http_resolve_cb: Resolved URI is \"%s\".", uribuf
->buffer
));
2466 avahi_simple_poll_quit(uribuf
->poll
);
2468 #endif /* HAVE_DNSSD */