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 a short string describing a HTTP status
40 * _cups_hstrerror() - hstrerror() emulation function for Solaris and
42 * _httpDecodeURI() - Percent-decode a HTTP request URI.
43 * _httpEncodeURI() - Percent-encode a HTTP request URI.
44 * _httpResolveURI() - Resolve a DNS-SD URI.
45 * http_client_cb() - Client callback for resolving URI.
46 * http_copy_decode() - Copy and decode a URI.
47 * http_copy_encode() - Copy and encode a URI.
48 * http_poll_cb() - Wait for input on the specified file descriptors.
49 * http_resolve_cb() - Build a device URI for the given service name.
50 * http_resolve_cb() - Build a device URI for the given service name.
54 * Include necessary headers...
57 #include "cups-private.h"
62 # elif defined(HAVE_POLL)
65 # include <sys/select.h>
67 #elif defined(HAVE_AVAHI)
68 # include <avahi-client/client.h>
69 # include <avahi-client/lookup.h>
70 # include <avahi-common/simple-watch.h>
71 #endif /* HAVE_DNSSD */
78 typedef struct _http_uribuf_s
/* URI buffer */
81 AvahiSimplePoll
*poll
; /* Poll state */
82 #endif /* HAVE_AVAHI */
83 char *buffer
; /* Pointer to buffer */
84 size_t bufsize
; /* Size of buffer */
85 int options
; /* Options passed to _httpResolveURI */
86 const char *resource
; /* Resource from URI */
94 static const char * const http_days
[7] =
104 static const char * const http_months
[12] =
125 static const char *http_copy_decode(char *dst
, const char *src
,
126 int dstsize
, const char *term
,
128 static char *http_copy_encode(char *dst
, const char *src
,
129 char *dstend
, const char *reserved
,
130 const char *term
, int encode
);
132 static void DNSSD_API
http_resolve_cb(DNSServiceRef sdRef
,
133 DNSServiceFlags flags
,
134 uint32_t interfaceIndex
,
135 DNSServiceErrorType errorCode
,
136 const char *fullName
,
137 const char *hostTarget
,
138 uint16_t port
, uint16_t txtLen
,
139 const unsigned char *txtRecord
,
141 #endif /* HAVE_DNSSD */
144 static void http_client_cb(AvahiClient
*client
,
145 AvahiClientState state
, void *simple_poll
);
146 static int http_poll_cb(struct pollfd
*pollfds
, unsigned int num_pollfds
,
147 int timeout
, void *context
);
148 static void http_resolve_cb(AvahiServiceResolver
*resolver
,
149 AvahiIfIndex interface
,
150 AvahiProtocol protocol
,
151 AvahiResolverEvent event
,
152 const char *name
, const char *type
,
153 const char *domain
, const char *host_name
,
154 const AvahiAddress
*address
, uint16_t port
,
155 AvahiStringList
*txt
,
156 AvahiLookupResultFlags flags
, void *context
);
157 #endif /* HAVE_AVAHI */
161 * 'httpAssembleURI()' - Assemble a uniform resource identifier from its
164 * This function escapes reserved characters in the URI depending on the
165 * value of the "encoding" argument. You should use this function in
166 * place of traditional string functions whenever you need to create a
169 * @since CUPS 1.2/OS X 10.5@
172 http_uri_status_t
/* O - URI status */
174 http_uri_coding_t encoding
, /* I - Encoding flags */
175 char *uri
, /* I - URI buffer */
176 int urilen
, /* I - Size of URI buffer */
177 const char *scheme
, /* I - Scheme name */
178 const char *username
, /* I - Username */
179 const char *host
, /* I - Hostname or address */
180 int port
, /* I - Port number */
181 const char *resource
) /* I - Resource */
183 char *ptr
, /* Pointer into URI buffer */
184 *end
; /* End of URI buffer */
188 * Range check input...
191 if (!uri
|| urilen
< 1 || !scheme
|| port
< 0)
196 return (HTTP_URI_STATUS_BAD_ARGUMENTS
);
200 * Assemble the URI starting with the scheme...
203 end
= uri
+ urilen
- 1;
204 ptr
= http_copy_encode(uri
, scheme
, end
, NULL
, NULL
, 0);
207 goto assemble_overflow
;
209 if (!strcmp(scheme
, "mailto"))
212 * mailto: only has :, no //...
218 goto assemble_overflow
;
223 * Schemes other than mailto: all have //...
233 goto assemble_overflow
;
237 * Next the username and hostname, if any...
242 const char *hostptr
; /* Pointer into hostname */
243 int have_ipv6
; /* Do we have an IPv6 address? */
245 if (username
&& *username
)
248 * Add username@ first...
251 ptr
= http_copy_encode(ptr
, username
, end
, "/?#[]@", NULL
,
252 encoding
& HTTP_URI_CODING_USERNAME
);
255 goto assemble_overflow
;
260 goto assemble_overflow
;
264 * Then add the hostname. Since IPv6 is a particular pain to deal
265 * with, we have several special cases to deal with. If we get
266 * an IPv6 address with brackets around it, assume it is already in
267 * URI format. Since DNS-SD service names can sometimes look like
268 * raw IPv6 addresses, we specifically look for "._tcp" in the name,
273 have_ipv6
= strchr(host
, ':') && !strstr(host
, "._tcp");
274 *hostptr
&& have_ipv6
;
276 if (*hostptr
!= ':' && !isxdigit(*hostptr
& 255))
278 have_ipv6
= *hostptr
== '%';
285 * We have a raw IPv6 address...
288 if (strchr(host
, '%') && !(encoding
& HTTP_URI_CODING_RFC6874
))
291 * We have a link-local address, add "[v1." prefix...
302 goto assemble_overflow
;
307 * We have a normal (or RFC 6874 link-local) address, add "[" prefix...
313 goto assemble_overflow
;
317 * Copy the rest of the IPv6 address, and terminate with "]".
320 while (ptr
< end
&& *host
)
325 * Convert/encode zone separator
328 if (encoding
& HTTP_URI_CODING_RFC6874
)
330 if (ptr
>= (end
- 2))
331 goto assemble_overflow
;
347 goto assemble_overflow
;
352 goto assemble_overflow
;
357 * Otherwise, just copy the host string (the extra chars are not in the
358 * "reg-name" ABNF rule; anything <= SP or >= DEL plus % gets automatically
362 ptr
= http_copy_encode(ptr
, host
, end
, "\"#/:<>?@[\\]^`{|}", NULL
,
363 encoding
& HTTP_URI_CODING_HOSTNAME
);
366 goto assemble_overflow
;
370 * Finish things off with the port number...
375 snprintf(ptr
, end
- ptr
+ 1, ":%d", port
);
379 goto assemble_overflow
;
384 * Last but not least, add the resource string...
389 char *query
; /* Pointer to query string */
393 * Copy the resource string up to the query string if present...
396 query
= strchr(resource
, '?');
397 ptr
= http_copy_encode(ptr
, resource
, end
, NULL
, "?",
398 encoding
& HTTP_URI_CODING_RESOURCE
);
400 goto assemble_overflow
;
405 * Copy query string without encoding...
408 ptr
= http_copy_encode(ptr
, query
, end
, NULL
, NULL
,
409 encoding
& HTTP_URI_CODING_QUERY
);
411 goto assemble_overflow
;
417 goto assemble_overflow
;
420 * Nul-terminate the URI buffer and return with no errors...
425 return (HTTP_URI_STATUS_OK
);
428 * Clear the URI string and return an overflow error; I don't usually
429 * like goto's, but in this case it makes sense...
435 return (HTTP_URI_STATUS_OVERFLOW
);
440 * 'httpAssembleURIf()' - Assemble a uniform resource identifier from its
441 * components with a formatted resource.
443 * This function creates a formatted version of the resource string
444 * argument "resourcef" and escapes reserved characters in the URI
445 * depending on the value of the "encoding" argument. You should use
446 * this function in place of traditional string functions whenever
447 * you need to create a URI string.
449 * @since CUPS 1.2/OS X 10.5@
452 http_uri_status_t
/* O - URI status */
454 http_uri_coding_t encoding
, /* I - Encoding flags */
455 char *uri
, /* I - URI buffer */
456 int urilen
, /* I - Size of URI buffer */
457 const char *scheme
, /* I - Scheme name */
458 const char *username
, /* I - Username */
459 const char *host
, /* I - Hostname or address */
460 int port
, /* I - Port number */
461 const char *resourcef
, /* I - Printf-style resource */
462 ...) /* I - Additional arguments as needed */
464 va_list ap
; /* Pointer to additional arguments */
465 char resource
[1024]; /* Formatted resource string */
466 int bytes
; /* Bytes in formatted string */
470 * Range check input...
473 if (!uri
|| urilen
< 1 || !scheme
|| port
< 0 || !resourcef
)
478 return (HTTP_URI_STATUS_BAD_ARGUMENTS
);
482 * Format the resource string and assemble the URI...
485 va_start(ap
, resourcef
);
486 bytes
= vsnprintf(resource
, sizeof(resource
), resourcef
, ap
);
489 if (bytes
>= sizeof(resource
))
492 return (HTTP_URI_STATUS_OVERFLOW
);
495 return (httpAssembleURI(encoding
, uri
, urilen
, scheme
, username
, host
,
501 * 'httpAssembleUUID()' - Assemble a name-based UUID URN conforming to RFC 4122.
503 * This function creates a unique 128-bit identifying number using the server
504 * name, port number, random data, and optionally an object name and/or object
505 * number. The result is formatted as a UUID URN as defined in RFC 4122.
507 * The buffer needs to be at least 46 bytes in size.
509 * @since CUPS 1.7/OS X 10.9@
512 char * /* I - UUID string */
513 httpAssembleUUID(const char *server
, /* I - Server name */
514 int port
, /* I - Port number */
515 const char *name
, /* I - Object name or NULL */
516 int number
, /* I - Object number or 0 */
517 char *buffer
, /* I - String buffer */
518 size_t bufsize
) /* I - Size of buffer */
520 char data
[1024]; /* Source string for MD5 */
521 _cups_md5_state_t md5state
; /* MD5 state */
522 unsigned char md5sum
[16]; /* MD5 digest/sum */
526 * Build a version 3 UUID conforming to RFC 4122.
528 * Start with the MD5 sum of the server, port, object name and
529 * number, and some random data on the end.
532 snprintf(data
, sizeof(data
), "%s:%d:%s:%d:%04x:%04x", server
,
533 port
, name
? name
: server
, number
,
534 (unsigned)CUPS_RAND() & 0xffff, (unsigned)CUPS_RAND() & 0xffff);
536 _cupsMD5Init(&md5state
);
537 _cupsMD5Append(&md5state
, (unsigned char *)data
, strlen(data
));
538 _cupsMD5Finish(&md5state
, md5sum
);
541 * Generate the UUID from the MD5...
544 snprintf(buffer
, bufsize
,
545 "urn:uuid:%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-"
546 "%02x%02x%02x%02x%02x%02x",
547 md5sum
[0], md5sum
[1], md5sum
[2], md5sum
[3], md5sum
[4], md5sum
[5],
548 (md5sum
[6] & 15) | 0x30, md5sum
[7], (md5sum
[8] & 0x3f) | 0x40,
549 md5sum
[9], md5sum
[10], md5sum
[11], md5sum
[12], md5sum
[13],
550 md5sum
[14], md5sum
[15]);
555 /* For OS X 10.8 and earlier */
556 char *_httpAssembleUUID(const char *server
, int port
, const char *name
,
557 int number
, char *buffer
, size_t bufsize
)
559 return (httpAssembleUUID(server
, port
, name
, number
, buffer
, bufsize
));
564 * 'httpDecode64()' - Base64-decode a string.
566 * This function is deprecated. Use the httpDecode64_2() function instead
567 * which provides buffer length arguments.
572 char * /* O - Decoded string */
573 httpDecode64(char *out
, /* I - String to write to */
574 const char *in
) /* I - String to read from */
576 int outlen
; /* Output buffer length */
580 * Use the old maximum buffer size for binary compatibility...
585 return (httpDecode64_2(out
, &outlen
, in
));
590 * 'httpDecode64_2()' - Base64-decode a string.
592 * @since CUPS 1.1.21/OS X 10.4@
595 char * /* O - Decoded string */
596 httpDecode64_2(char *out
, /* I - String to write to */
597 int *outlen
, /* IO - Size of output string */
598 const char *in
) /* I - String to read from */
600 int pos
, /* Bit position */
601 base64
; /* Value of this character */
602 char *outptr
, /* Output pointer */
603 *outend
; /* End of output buffer */
607 * Range check input...
610 if (!out
|| !outlen
|| *outlen
< 1 || !in
)
622 * Convert from base-64 to bytes...
625 for (outptr
= out
, outend
= out
+ *outlen
- 1, pos
= 0; *in
!= '\0'; in
++)
628 * Decode this character into a number from 0 to 63...
631 if (*in
>= 'A' && *in
<= 'Z')
633 else if (*in
>= 'a' && *in
<= 'z')
634 base64
= *in
- 'a' + 26;
635 else if (*in
>= '0' && *in
<= '9')
636 base64
= *in
- '0' + 52;
647 * Store the result in the appropriate chars...
654 *outptr
= base64
<< 2;
659 *outptr
++ |= (base64
>> 4) & 3;
661 *outptr
= (base64
<< 4) & 255;
666 *outptr
++ |= (base64
>> 2) & 15;
668 *outptr
= (base64
<< 6) & 255;
682 * Return the decoded string and size...
685 *outlen
= (int)(outptr
- out
);
692 * 'httpEncode64()' - Base64-encode a string.
694 * This function is deprecated. Use the httpEncode64_2() function instead
695 * which provides buffer length arguments.
700 char * /* O - Encoded string */
701 httpEncode64(char *out
, /* I - String to write to */
702 const char *in
) /* I - String to read from */
704 return (httpEncode64_2(out
, 512, in
, (int)strlen(in
)));
709 * 'httpEncode64_2()' - Base64-encode a string.
711 * @since CUPS 1.1.21/OS X 10.4@
714 char * /* O - Encoded string */
715 httpEncode64_2(char *out
, /* I - String to write to */
716 int outlen
, /* I - Size of output string */
717 const char *in
, /* I - String to read from */
718 int inlen
) /* I - Size of input string */
720 char *outptr
, /* Output pointer */
721 *outend
; /* End of output buffer */
722 static const char base64
[] = /* Base64 characters... */
724 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
725 "abcdefghijklmnopqrstuvwxyz"
732 * Range check input...
735 if (!out
|| outlen
< 1 || !in
)
739 * Convert bytes to base-64...
742 for (outptr
= out
, outend
= out
+ outlen
- 1; inlen
> 0; in
++, inlen
--)
745 * Encode the up to 3 characters as 4 Base64 numbers...
749 *outptr
++ = base64
[(in
[0] & 255) >> 2];
754 *outptr
++ = base64
[(((in
[0] & 255) << 4) | ((in
[1] & 255) >> 4)) & 63];
756 *outptr
++ = base64
[((in
[0] & 255) << 4) & 63];
773 *outptr
++ = base64
[(((in
[0] & 255) << 2) | ((in
[1] & 255) >> 6)) & 63];
775 *outptr
++ = base64
[((in
[0] & 255) << 2) & 63];
788 *outptr
++ = base64
[in
[0] & 63];
794 * Return the encoded string...
802 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
807 const char * /* O - Date/time string */
808 httpGetDateString(time_t t
) /* I - UNIX time */
810 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
813 return (httpGetDateString2(t
, cg
->http_date
, sizeof(cg
->http_date
)));
818 * 'httpGetDateString2()' - Get a formatted date/time string from a time value.
820 * @since CUPS 1.2/OS X 10.5@
823 const char * /* O - Date/time string */
824 httpGetDateString2(time_t t
, /* I - UNIX time */
825 char *s
, /* I - String buffer */
826 int slen
) /* I - Size of string buffer */
828 struct tm
*tdate
; /* UNIX date/time data */
833 snprintf(s
, slen
, "%s, %02d %s %d %02d:%02d:%02d GMT",
834 http_days
[tdate
->tm_wday
], tdate
->tm_mday
,
835 http_months
[tdate
->tm_mon
], tdate
->tm_year
+ 1900,
836 tdate
->tm_hour
, tdate
->tm_min
, tdate
->tm_sec
);
845 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
848 time_t /* O - UNIX time */
849 httpGetDateTime(const char *s
) /* I - Date/time string */
851 int i
; /* Looping var */
852 char mon
[16]; /* Abbreviated month name */
853 int day
, year
; /* Day of month and year */
854 int hour
, min
, sec
; /* Time */
855 int days
; /* Number of days since 1970 */
856 static const int normal_days
[] = /* Days to a month, normal years */
857 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
858 static const int leap_days
[] = /* Days to a month, leap years */
859 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 };
862 DEBUG_printf(("2httpGetDateTime(s=\"%s\")", s
));
865 * Extract the date and time from the formatted string...
868 if (sscanf(s
, "%*s%d%15s%d%d:%d:%d", &day
, mon
, &year
, &hour
, &min
, &sec
) < 6)
871 DEBUG_printf(("4httpGetDateTime: day=%d, mon=\"%s\", year=%d, hour=%d, "
872 "min=%d, sec=%d", day
, mon
, year
, hour
, min
, sec
));
875 * Convert the month name to a number from 0 to 11.
878 for (i
= 0; i
< 12; i
++)
879 if (!_cups_strcasecmp(mon
, http_months
[i
]))
885 DEBUG_printf(("4httpGetDateTime: i=%d", i
));
888 * Now convert the date and time to a UNIX time value in seconds since
889 * 1970. We can't use mktime() since the timezone may not be UTC but
890 * the date/time string *is* UTC.
893 if ((year
& 3) == 0 && ((year
% 100) != 0 || (year
% 400) == 0))
894 days
= leap_days
[i
] + day
- 1;
896 days
= normal_days
[i
] + day
- 1;
898 DEBUG_printf(("4httpGetDateTime: days=%d", days
));
900 days
+= (year
- 1970) * 365 + /* 365 days per year (normally) */
901 ((year
- 1) / 4 - 492) - /* + leap days */
902 ((year
- 1) / 100 - 19) + /* - 100 year days */
903 ((year
- 1) / 400 - 4); /* + 400 year days */
905 DEBUG_printf(("4httpGetDateTime: days=%d\n", days
));
907 return (days
* 86400 + hour
* 3600 + min
* 60 + sec
);
912 * 'httpSeparate()' - Separate a Universal Resource Identifier into its
915 * This function is deprecated; use the httpSeparateURI() function instead.
921 httpSeparate(const char *uri
, /* I - Universal Resource Identifier */
922 char *scheme
, /* O - Scheme [32] (http, https, etc.) */
923 char *username
, /* O - Username [1024] */
924 char *host
, /* O - Hostname [1024] */
925 int *port
, /* O - Port number to use */
926 char *resource
) /* O - Resource/filename [1024] */
928 httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, 32, username
,
929 HTTP_MAX_URI
, host
, HTTP_MAX_URI
, port
, resource
,
935 * 'httpSeparate2()' - Separate a Universal Resource Identifier into its
938 * This function is deprecated; use the httpSeparateURI() function instead.
940 * @since CUPS 1.1.21/OS X 10.4@
945 httpSeparate2(const char *uri
, /* I - Universal Resource Identifier */
946 char *scheme
, /* O - Scheme (http, https, etc.) */
947 int schemelen
, /* I - Size of scheme buffer */
948 char *username
, /* O - Username */
949 int usernamelen
, /* I - Size of username buffer */
950 char *host
, /* O - Hostname */
951 int hostlen
, /* I - Size of hostname buffer */
952 int *port
, /* O - Port number to use */
953 char *resource
, /* O - Resource/filename */
954 int resourcelen
) /* I - Size of resource buffer */
956 httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, schemelen
, username
,
957 usernamelen
, host
, hostlen
, port
, resource
, resourcelen
);
962 * 'httpSeparateURI()' - Separate a Universal Resource Identifier into its
965 * @since CUPS 1.2/OS X 10.5@
968 http_uri_status_t
/* O - Result of separation */
970 http_uri_coding_t decoding
, /* I - Decoding flags */
971 const char *uri
, /* I - Universal Resource Identifier */
972 char *scheme
, /* O - Scheme (http, https, etc.) */
973 int schemelen
, /* I - Size of scheme buffer */
974 char *username
, /* O - Username */
975 int usernamelen
, /* I - Size of username buffer */
976 char *host
, /* O - Hostname */
977 int hostlen
, /* I - Size of hostname buffer */
978 int *port
, /* O - Port number to use */
979 char *resource
, /* O - Resource/filename */
980 int resourcelen
) /* I - Size of resource buffer */
982 char *ptr
, /* Pointer into string... */
983 *end
; /* End of string */
984 const char *sep
; /* Separator character */
985 http_uri_status_t status
; /* Result of separation */
989 * Initialize everything to blank...
992 if (scheme
&& schemelen
> 0)
995 if (username
&& usernamelen
> 0)
998 if (host
&& hostlen
> 0)
1004 if (resource
&& resourcelen
> 0)
1008 * Range check input...
1011 if (!uri
|| !port
|| !scheme
|| schemelen
<= 0 || !username
||
1012 usernamelen
<= 0 || !host
|| hostlen
<= 0 || !resource
||
1014 return (HTTP_URI_STATUS_BAD_ARGUMENTS
);
1017 return (HTTP_URI_STATUS_BAD_URI
);
1020 * Grab the scheme portion of the URI...
1023 status
= HTTP_URI_STATUS_OK
;
1025 if (!strncmp(uri
, "//", 2))
1028 * Workaround for HP IPP client bug...
1031 strlcpy(scheme
, "ipp", schemelen
);
1032 status
= HTTP_URI_STATUS_MISSING_SCHEME
;
1034 else if (*uri
== '/')
1040 strlcpy(scheme
, "file", schemelen
);
1041 status
= HTTP_URI_STATUS_MISSING_SCHEME
;
1046 * Standard URI with scheme...
1049 for (ptr
= scheme
, end
= scheme
+ schemelen
- 1;
1050 *uri
&& *uri
!= ':' && ptr
< end
;)
1051 if (strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1052 "abcdefghijklmnopqrstuvwxyz"
1053 "0123456789-+.", *uri
) != NULL
)
1063 return (HTTP_URI_STATUS_BAD_SCHEME
);
1070 * Set the default port number...
1073 if (!strcmp(scheme
, "http"))
1075 else if (!strcmp(scheme
, "https"))
1077 else if (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps"))
1079 else if (!_cups_strcasecmp(scheme
, "lpd"))
1081 else if (!strcmp(scheme
, "socket")) /* Not yet registered with IANA... */
1083 else if (strcmp(scheme
, "file") && strcmp(scheme
, "mailto"))
1084 status
= HTTP_URI_STATUS_UNKNOWN_SCHEME
;
1087 * Now see if we have a hostname...
1090 if (!strncmp(uri
, "//", 2))
1093 * Yes, extract it...
1099 * Grab the username, if any...
1102 if ((sep
= strpbrk(uri
, "@/")) != NULL
&& *sep
== '@')
1105 * Get a username:password combo...
1108 uri
= http_copy_decode(username
, uri
, usernamelen
, "@",
1109 decoding
& HTTP_URI_CODING_USERNAME
);
1114 return (HTTP_URI_STATUS_BAD_USERNAME
);
1121 * Then the hostname/IP address...
1127 * Grab IPv6 address...
1134 * Skip IPvFuture ("vXXXX.") prefix...
1139 while (isxdigit(*uri
& 255))
1145 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1151 uri
= http_copy_decode(host
, uri
, hostlen
, "]",
1152 decoding
& HTTP_URI_CODING_HOSTNAME
);
1157 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1167 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1172 for (ptr
= host
; *ptr
; ptr
++)
1176 * Convert zone separator to % and stop here...
1182 else if (*ptr
== '%')
1185 * Stop at zone separator (RFC 6874)
1190 else if (*ptr
!= ':' && *ptr
!= '.' && !isxdigit(*ptr
& 255))
1193 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1199 * Validate the hostname or IPv4 address first...
1202 for (ptr
= (char *)uri
; *ptr
; ptr
++)
1203 if (strchr(":?/", *ptr
))
1205 else if (!strchr("abcdefghijklmnopqrstuvwxyz" /* unreserved */
1206 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" /* unreserved */
1207 "0123456789" /* unreserved */
1208 "-._~" /* unreserved */
1209 "%" /* pct-encoded */
1210 "!$&'()*+,;=" /* sub-delims */
1211 "\\", *ptr
)) /* SMB domain */
1214 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1218 * Then copy the hostname or IPv4 address to the buffer...
1221 uri
= http_copy_decode(host
, uri
, hostlen
, ":?/",
1222 decoding
& HTTP_URI_CODING_HOSTNAME
);
1227 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1232 * Validate hostname for file scheme - only empty and localhost are
1236 if (!strcmp(scheme
, "file") && strcmp(host
, "localhost") && host
[0])
1239 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1243 * See if we have a port number...
1249 * Yes, collect the port number...
1252 if (!isdigit(uri
[1] & 255))
1255 return (HTTP_URI_STATUS_BAD_PORT
);
1258 *port
= strtol(uri
+ 1, (char **)&uri
, 10);
1260 if (*uri
!= '/' && *uri
)
1263 return (HTTP_URI_STATUS_BAD_PORT
);
1269 * The remaining portion is the resource string...
1272 if (*uri
== '?' || !*uri
)
1275 * Hostname but no path...
1278 status
= HTTP_URI_STATUS_MISSING_RESOURCE
;
1282 * Copy any query string...
1286 uri
= http_copy_decode(resource
+ 1, uri
, resourcelen
- 1, NULL
,
1287 decoding
& HTTP_URI_CODING_QUERY
);
1293 uri
= http_copy_decode(resource
, uri
, resourcelen
, "?",
1294 decoding
& HTTP_URI_CODING_RESOURCE
);
1296 if (uri
&& *uri
== '?')
1299 * Concatenate any query string...
1302 char *resptr
= resource
+ strlen(resource
);
1304 uri
= http_copy_decode(resptr
, uri
,
1305 resourcelen
- (int)(resptr
- resource
), NULL
,
1306 decoding
& HTTP_URI_CODING_QUERY
);
1313 return (HTTP_URI_STATUS_BAD_RESOURCE
);
1317 * Return the URI separation status...
1325 * 'httpStatus()' - Return a short string describing a HTTP status code.
1327 * The returned string is localized to the current POSIX locale and is based
1328 * on the status strings defined in RFC 2616.
1331 const char * /* O - Localized status string */
1332 httpStatus(http_status_t status
) /* I - HTTP status code */
1334 const char *s
; /* Status string */
1335 _cups_globals_t
*cg
= _cupsGlobals(); /* Global data */
1338 if (!cg
->lang_default
)
1339 cg
->lang_default
= cupsLangDefault();
1343 case HTTP_STATUS_ERROR
:
1344 s
= strerror(errno
);
1346 case HTTP_STATUS_CONTINUE
:
1349 case HTTP_STATUS_SWITCHING_PROTOCOLS
:
1350 s
= _("Switching Protocols");
1352 case HTTP_STATUS_OK
:
1355 case HTTP_STATUS_CREATED
:
1358 case HTTP_STATUS_ACCEPTED
:
1361 case HTTP_STATUS_NO_CONTENT
:
1362 s
= _("No Content");
1364 case HTTP_STATUS_MOVED_PERMANENTLY
:
1365 s
= _("Moved Permanently");
1367 case HTTP_STATUS_SEE_OTHER
:
1370 case HTTP_STATUS_NOT_MODIFIED
:
1371 s
= _("Not Modified");
1373 case HTTP_STATUS_BAD_REQUEST
:
1374 s
= _("Bad Request");
1376 case HTTP_STATUS_UNAUTHORIZED
:
1377 case HTTP_STATUS_CUPS_AUTHORIZATION_CANCELED
:
1378 s
= _("Unauthorized");
1380 case HTTP_STATUS_FORBIDDEN
:
1383 case HTTP_STATUS_NOT_FOUND
:
1386 case HTTP_STATUS_REQUEST_TOO_LARGE
:
1387 s
= _("Request Entity Too Large");
1389 case HTTP_STATUS_URI_TOO_LONG
:
1390 s
= _("URI Too Long");
1392 case HTTP_STATUS_UPGRADE_REQUIRED
:
1393 s
= _("Upgrade Required");
1395 case HTTP_STATUS_NOT_IMPLEMENTED
:
1396 s
= _("Not Implemented");
1398 case HTTP_STATUS_NOT_SUPPORTED
:
1399 s
= _("Not Supported");
1401 case HTTP_STATUS_EXPECTATION_FAILED
:
1402 s
= _("Expectation Failed");
1404 case HTTP_STATUS_SERVICE_UNAVAILABLE
:
1405 s
= _("Service Unavailable");
1407 case HTTP_STATUS_SERVER_ERROR
:
1408 s
= _("Internal Server Error");
1410 case HTTP_STATUS_CUPS_PKI_ERROR
:
1411 s
= _("SSL/TLS Negotiation Error");
1413 case HTTP_STATUS_CUPS_WEBIF_DISABLED
:
1414 s
= _("Web Interface is Disabled");
1422 return (_cupsLangString(cg
->lang_default
, s
));
1426 #ifndef HAVE_HSTRERROR
1428 * '_cups_hstrerror()' - hstrerror() emulation function for Solaris and others.
1431 const char * /* O - Error string */
1432 _cups_hstrerror(int error
) /* I - Error number */
1434 static const char * const errors
[] = /* Error strings */
1439 "Unrecoverable lookup error.",
1440 "No data associated with name."
1444 if (error
< 0 || error
> 4)
1445 return ("Unknown hostname lookup error.");
1447 return (errors
[error
]);
1449 #endif /* !HAVE_HSTRERROR */
1453 * '_httpDecodeURI()' - Percent-decode a HTTP request URI.
1456 char * /* O - Decoded URI or NULL on error */
1457 _httpDecodeURI(char *dst
, /* I - Destination buffer */
1458 const char *src
, /* I - Source URI */
1459 size_t dstsize
) /* I - Size of destination buffer */
1461 if (http_copy_decode(dst
, src
, (int)dstsize
, NULL
, 1))
1469 * '_httpEncodeURI()' - Percent-encode a HTTP request URI.
1472 char * /* O - Encoded URI */
1473 _httpEncodeURI(char *dst
, /* I - Destination buffer */
1474 const char *src
, /* I - Source URI */
1475 size_t dstsize
) /* I - Size of destination buffer */
1477 http_copy_encode(dst
, src
, dst
+ dstsize
- 1, NULL
, NULL
, 1);
1483 * '_httpResolveURI()' - Resolve a DNS-SD URI.
1486 const char * /* O - Resolved URI */
1488 const char *uri
, /* I - DNS-SD URI */
1489 char *resolved_uri
, /* I - Buffer for resolved URI */
1490 size_t resolved_size
, /* I - Size of URI buffer */
1491 int options
, /* I - Resolve options */
1492 int (*cb
)(void *context
), /* I - Continue callback function */
1493 void *context
) /* I - Context pointer for callback */
1495 char scheme
[32], /* URI components... */
1501 http_uri_status_t status
; /* URI decode status */
1505 DEBUG_printf(("4_httpResolveURI(uri=\"%s\", resolved_uri=%p, "
1506 "resolved_size=" CUPS_LLFMT
")", uri
, resolved_uri
,
1507 CUPS_LLCAST resolved_size
));
1510 * Get the device URI...
1514 if ((status
= httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
,
1515 sizeof(scheme
), userpass
, sizeof(userpass
),
1516 hostname
, sizeof(hostname
), &port
, resource
,
1517 sizeof(resource
))) < HTTP_URI_STATUS_OK
)
1519 if (httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
,
1520 sizeof(scheme
), userpass
, sizeof(userpass
),
1521 hostname
, sizeof(hostname
), &port
, resource
,
1522 sizeof(resource
)) < HTTP_URI_STATUS_OK
)
1525 if (options
& _HTTP_RESOLVE_STDERR
)
1526 _cupsLangPrintFilter(stderr
, "ERROR", _("Bad device-uri \"%s\"."), uri
);
1528 DEBUG_printf(("6_httpResolveURI: httpSeparateURI returned %d!", status
));
1529 DEBUG_puts("5_httpResolveURI: Returning NULL");
1534 * Resolve it as needed...
1537 if (strstr(hostname
, "._tcp"))
1539 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
1540 char *regtype
, /* Pointer to type in hostname */
1541 *domain
; /* Pointer to domain in hostname */
1542 _http_uribuf_t uribuf
; /* URI buffer */
1543 int offline
= 0; /* offline-report state set? */
1546 # pragma comment(lib, "dnssd.lib")
1548 DNSServiceRef ref
, /* DNS-SD master service reference */
1549 domainref
, /* DNS-SD service reference for domain */
1550 localref
; /* DNS-SD service reference for .local */
1551 int domainsent
= 0; /* Send the domain resolve? */
1553 struct pollfd polldata
; /* Polling data */
1554 # else /* select() */
1555 fd_set input_set
; /* Input set for select() */
1556 struct timeval stimeout
; /* Timeout value for select() */
1557 # endif /* HAVE_POLL */
1558 # elif defined(HAVE_AVAHI)
1559 AvahiClient
*client
; /* Client information */
1560 int error
; /* Status */
1561 # endif /* HAVE_DNSSD */
1563 if (options
& _HTTP_RESOLVE_STDERR
)
1564 fprintf(stderr
, "DEBUG: Resolving \"%s\"...\n", hostname
);
1567 * Separate the hostname into service name, registration type, and domain...
1570 for (regtype
= strstr(hostname
, "._tcp") - 2;
1573 if (regtype
[0] == '.' && regtype
[1] == '_')
1576 * Found ._servicetype in front of ._tcp...
1583 if (regtype
<= hostname
)
1585 DEBUG_puts("5_httpResolveURI: Bad hostname, returning NULL");
1589 for (domain
= strchr(regtype
, '.');
1591 domain
= strchr(domain
+ 1, '.'))
1592 if (domain
[1] != '_')
1598 uribuf
.buffer
= resolved_uri
;
1599 uribuf
.bufsize
= resolved_size
;
1600 uribuf
.options
= options
;
1601 uribuf
.resource
= resource
;
1603 resolved_uri
[0] = '\0';
1605 DEBUG_printf(("6_httpResolveURI: Resolving hostname=\"%s\", regtype=\"%s\", "
1606 "domain=\"%s\"\n", hostname
, regtype
, domain
));
1607 if (options
& _HTTP_RESOLVE_STDERR
)
1609 fputs("STATE: +connecting-to-device\n", stderr
);
1610 fprintf(stderr
, "DEBUG: Resolving \"%s\", regtype=\"%s\", "
1611 "domain=\"local.\"...\n", hostname
, regtype
);
1617 if (DNSServiceCreateConnection(&ref
) == kDNSServiceErr_NoError
)
1619 int myinterface
= kDNSServiceInterfaceIndexAny
;
1620 /* Lookup on any interface */
1622 if (!strcmp(scheme
, "ippusb"))
1623 myinterface
= kDNSServiceInterfaceIndexLocalOnly
;
1626 if (DNSServiceResolve(&localref
,
1627 kDNSServiceFlagsShareConnection
, myinterface
,
1628 hostname
, regtype
, "local.", http_resolve_cb
,
1629 &uribuf
) == kDNSServiceErr_NoError
)
1631 int fds
; /* Number of ready descriptors */
1632 time_t timeout
, /* Poll timeout */
1633 start_time
= time(NULL
),/* Start time */
1634 end_time
= start_time
+ 90;
1637 while (time(NULL
) < end_time
)
1639 if (options
& _HTTP_RESOLVE_STDERR
)
1640 _cupsLangPrintFilter(stderr
, "INFO", _("Looking for printer."));
1642 if (cb
&& !(*cb
)(context
))
1644 DEBUG_puts("5_httpResolveURI: callback returned 0 (stop)");
1649 * Wakeup every 2 seconds to emit a "looking for printer" message...
1652 if ((timeout
= end_time
- time(NULL
)) > 2)
1656 polldata
.fd
= DNSServiceRefSockFD(ref
);
1657 polldata
.events
= POLLIN
;
1659 fds
= poll(&polldata
, 1, 1000 * timeout
);
1661 # else /* select() */
1662 FD_ZERO(&input_set
);
1663 FD_SET(DNSServiceRefSockFD(ref
), &input_set
);
1666 stimeout
.tv_sec
= (long)timeout
;
1668 stimeout
.tv_sec
= timeout
;
1670 stimeout
.tv_usec
= 0;
1672 fds
= select(DNSServiceRefSockFD(ref
)+1, &input_set
, NULL
, NULL
,
1674 # endif /* HAVE_POLL */
1678 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1680 DEBUG_printf(("5_httpResolveURI: poll error: %s", strerror(errno
)));
1687 * Wait 2 seconds for a response to the local resolve; if nothing
1688 * comes in, do an additional domain resolution...
1691 if (domainsent
== 0 && domain
&& _cups_strcasecmp(domain
, "local."))
1693 if (options
& _HTTP_RESOLVE_STDERR
)
1695 "DEBUG: Resolving \"%s\", regtype=\"%s\", "
1696 "domain=\"%s\"...\n", hostname
, regtype
,
1697 domain
? domain
: "");
1700 if (DNSServiceResolve(&domainref
,
1701 kDNSServiceFlagsShareConnection
,
1702 myinterface
, hostname
, regtype
, domain
,
1704 &uribuf
) == kDNSServiceErr_NoError
)
1709 * If it hasn't resolved within 5 seconds set the offline-report
1710 * printer-state-reason...
1713 if ((options
& _HTTP_RESOLVE_STDERR
) && offline
== 0 &&
1714 time(NULL
) > (start_time
+ 5))
1716 fputs("STATE: +offline-report\n", stderr
);
1722 if (DNSServiceProcessResult(ref
) == kDNSServiceErr_NoError
)
1731 DNSServiceRefDeallocate(domainref
);
1733 DNSServiceRefDeallocate(localref
);
1736 DNSServiceRefDeallocate(ref
);
1738 # else /* HAVE_AVAHI */
1739 if ((uribuf
.poll
= avahi_simple_poll_new()) != NULL
)
1741 avahi_simple_poll_set_func(uribuf
.poll
, http_poll_cb
, NULL
);
1743 if ((client
= avahi_client_new(avahi_simple_poll_get(uribuf
.poll
),
1745 &uribuf
, &error
)) != NULL
)
1747 if (avahi_service_resolver_new(client
, AVAHI_IF_UNSPEC
,
1748 AVAHI_PROTO_UNSPEC
, hostname
,
1749 regtype
, "local.", AVAHI_PROTO_UNSPEC
, 0,
1750 http_resolve_cb
, &uribuf
) != NULL
)
1752 time_t start_time
= time(NULL
),
1754 end_time
= start_time
+ 90;
1756 int pstatus
; /* Poll status */
1758 pstatus
= avahi_simple_poll_iterate(uribuf
.poll
, 2000);
1760 if (pstatus
== 0 && !resolved_uri
[0] && domain
&&
1761 _cups_strcasecmp(domain
, "local."))
1764 * Resolve for .local hasn't returned anything, try the listed
1768 avahi_service_resolver_new(client
, AVAHI_IF_UNSPEC
,
1769 AVAHI_PROTO_UNSPEC
, hostname
,
1770 regtype
, domain
, AVAHI_PROTO_UNSPEC
, 0,
1771 http_resolve_cb
, &uribuf
);
1774 while (!pstatus
&& !resolved_uri
[0] && time(NULL
) < end_time
)
1776 if ((pstatus
= avahi_simple_poll_iterate(uribuf
.poll
, 2000)) != 0)
1780 * If it hasn't resolved within 5 seconds set the offline-report
1781 * printer-state-reason...
1784 if ((options
& _HTTP_RESOLVE_STDERR
) && offline
== 0 &&
1785 time(NULL
) > (start_time
+ 5))
1787 fputs("STATE: +offline-report\n", stderr
);
1793 * Collect the result (if we got one).
1796 if (resolved_uri
[0])
1800 avahi_client_free(client
);
1803 avahi_simple_poll_free(uribuf
.poll
);
1805 # endif /* HAVE_DNSSD */
1807 if (options
& _HTTP_RESOLVE_STDERR
)
1811 fprintf(stderr
, "DEBUG: Resolved as \"%s\"...\n", uri
);
1812 fputs("STATE: -connecting-to-device,offline-report\n", stderr
);
1816 fputs("DEBUG: Unable to resolve URI\n", stderr
);
1817 fputs("STATE: -connecting-to-device\n", stderr
);
1821 #else /* HAVE_DNSSD || HAVE_AVAHI */
1823 * No DNS-SD support...
1827 #endif /* HAVE_DNSSD || HAVE_AVAHI */
1829 if ((options
& _HTTP_RESOLVE_STDERR
) && !uri
)
1830 _cupsLangPrintFilter(stderr
, "INFO", _("Unable to find printer."));
1835 * Nothing more to do...
1838 strlcpy(resolved_uri
, uri
, resolved_size
);
1842 DEBUG_printf(("5_httpResolveURI: Returning \"%s\"", uri
));
1850 * 'http_client_cb()' - Client callback for resolving URI.
1855 AvahiClient
*client
, /* I - Client information */
1856 AvahiClientState state
, /* I - Current state */
1857 void *context
) /* I - Pointer to URI buffer */
1859 DEBUG_printf(("7http_client_cb(client=%p, state=%d, context=%p)", client
,
1863 * If the connection drops, quit.
1866 if (state
== AVAHI_CLIENT_FAILURE
)
1868 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
1871 avahi_simple_poll_quit(uribuf
->poll
);
1874 #endif /* HAVE_AVAHI */
1878 * 'http_copy_decode()' - Copy and decode a URI.
1881 static const char * /* O - New source pointer or NULL on error */
1882 http_copy_decode(char *dst
, /* O - Destination buffer */
1883 const char *src
, /* I - Source pointer */
1884 int dstsize
, /* I - Destination size */
1885 const char *term
, /* I - Terminating characters */
1886 int decode
) /* I - Decode %-encoded values */
1888 char *ptr
, /* Pointer into buffer */
1889 *end
; /* End of buffer */
1890 int quoted
; /* Quoted character */
1894 * Copy the src to the destination until we hit a terminating character
1895 * or the end of the string.
1898 for (ptr
= dst
, end
= dst
+ dstsize
- 1;
1899 *src
&& (!term
|| !strchr(term
, *src
));
1903 if (*src
== '%' && decode
)
1905 if (isxdigit(src
[1] & 255) && isxdigit(src
[2] & 255))
1908 * Grab a hex-encoded character...
1913 quoted
= (tolower(*src
) - 'a' + 10) << 4;
1915 quoted
= (*src
- '0') << 4;
1919 quoted
|= tolower(*src
) - 'a' + 10;
1921 quoted
|= *src
- '0';
1928 * Bad hex-encoded character...
1935 else if ((*src
& 255) <= 0x20 || (*src
& 255) >= 0x7f)
1951 * 'http_copy_encode()' - Copy and encode a URI.
1954 static char * /* O - End of current URI */
1955 http_copy_encode(char *dst
, /* O - Destination buffer */
1956 const char *src
, /* I - Source pointer */
1957 char *dstend
, /* I - End of destination buffer */
1958 const char *reserved
, /* I - Extra reserved characters */
1959 const char *term
, /* I - Terminating characters */
1960 int encode
) /* I - %-encode reserved chars? */
1962 static const char hex
[] = "0123456789ABCDEF";
1965 while (*src
&& dst
< dstend
)
1967 if (term
&& *src
== *term
)
1970 if (encode
&& (*src
== '%' || *src
<= ' ' || *src
& 128 ||
1971 (reserved
&& strchr(reserved
, *src
))))
1974 * Hex encode reserved characters...
1977 if ((dst
+ 2) >= dstend
)
1981 *dst
++ = hex
[(*src
>> 4) & 15];
1982 *dst
++ = hex
[*src
& 15];
2001 * 'http_resolve_cb()' - Build a device URI for the given service name.
2004 static void DNSSD_API
2006 DNSServiceRef sdRef
, /* I - Service reference */
2007 DNSServiceFlags flags
, /* I - Results flags */
2008 uint32_t interfaceIndex
, /* I - Interface number */
2009 DNSServiceErrorType errorCode
, /* I - Error, if any */
2010 const char *fullName
, /* I - Full service name */
2011 const char *hostTarget
, /* I - Hostname */
2012 uint16_t port
, /* I - Port number */
2013 uint16_t txtLen
, /* I - Length of TXT record */
2014 const unsigned char *txtRecord
, /* I - TXT record data */
2015 void *context
) /* I - Pointer to URI buffer */
2017 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
2019 const char *scheme
, /* URI scheme */
2020 *hostptr
, /* Pointer into hostTarget */
2021 *reskey
, /* "rp" or "rfo" */
2022 *resdefault
; /* Default path */
2023 char resource
[257], /* Remote path */
2024 fqdn
[256]; /* FQDN of the .local name */
2025 const void *value
; /* Value from TXT record */
2026 uint8_t valueLen
; /* Length of value */
2029 DEBUG_printf(("7http_resolve_cb(sdRef=%p, flags=%x, interfaceIndex=%u, "
2030 "errorCode=%d, fullName=\"%s\", hostTarget=\"%s\", port=%u, "
2031 "txtLen=%u, txtRecord=%p, context=%p)", sdRef
, flags
,
2032 interfaceIndex
, errorCode
, fullName
, hostTarget
, port
, txtLen
,
2033 txtRecord
, context
));
2036 * Figure out the scheme from the full name...
2039 if (strstr(fullName
, "._ipps") || strstr(fullName
, "._ipp-tls"))
2041 else if (strstr(fullName
, "._ipp") || strstr(fullName
, "._fax-ipp"))
2043 else if (strstr(fullName
, "._http."))
2045 else if (strstr(fullName
, "._https."))
2047 else if (strstr(fullName
, "._printer."))
2049 else if (strstr(fullName
, "._pdl-datastream."))
2052 scheme
= "riousbprint";
2055 * Extract the "remote printer" key from the TXT record...
2058 if ((uribuf
->options
& _HTTP_RESOLVE_FAXOUT
) &&
2059 (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")))
2062 resdefault
= "/ipp/faxout";
2070 if ((value
= TXTRecordGetValuePtr(txtLen
, txtRecord
, reskey
,
2071 &valueLen
)) != NULL
)
2073 if (((char *)value
)[0] == '/')
2076 * Value (incorrectly) has a leading slash already...
2079 memcpy(resource
, value
, valueLen
);
2080 resource
[valueLen
] = '\0';
2085 * Convert to resource by concatenating with a leading "/"...
2089 memcpy(resource
+ 1, value
, valueLen
);
2090 resource
[valueLen
+ 1] = '\0';
2096 * Use the default value...
2099 strlcpy(resource
, resdefault
, sizeof(resource
));
2103 * Lookup the FQDN if needed...
2106 if ((uribuf
->options
& _HTTP_RESOLVE_FQDN
) &&
2107 (hostptr
= hostTarget
+ strlen(hostTarget
) - 7) > hostTarget
&&
2108 !_cups_strcasecmp(hostptr
, ".local."))
2111 * OK, we got a .local name but the caller needs a real domain. Start by
2112 * getting the IP address of the .local name and then do reverse-lookups...
2115 http_addrlist_t
*addrlist
, /* List of addresses */
2116 *addr
; /* Current address */
2118 DEBUG_printf(("8http_resolve_cb: Looking up \"%s\".", hostTarget
));
2120 snprintf(fqdn
, sizeof(fqdn
), "%d", ntohs(port
));
2121 if ((addrlist
= httpAddrGetList(hostTarget
, AF_UNSPEC
, fqdn
)) != NULL
)
2123 for (addr
= addrlist
; addr
; addr
= addr
->next
)
2125 int error
= getnameinfo(&(addr
->addr
.addr
),
2126 httpAddrLength(&(addr
->addr
)),
2127 fqdn
, sizeof(fqdn
), NULL
, 0, NI_NAMEREQD
);
2131 DEBUG_printf(("8http_resolve_cb: Found \"%s\".", fqdn
));
2133 if ((hostptr
= fqdn
+ strlen(fqdn
) - 6) <= fqdn
||
2134 _cups_strcasecmp(hostptr
, ".local"))
2142 DEBUG_printf(("8http_resolve_cb: \"%s\" did not resolve: %d",
2143 httpAddrString(&(addr
->addr
), fqdn
, sizeof(fqdn
)),
2148 httpAddrFreeList(addrlist
);
2153 * Assemble the final device URI...
2156 if ((!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")) &&
2157 !strcmp(uribuf
->resource
, "/cups"))
2158 httpAssembleURIf(HTTP_URI_CODING_ALL
, uribuf
->buffer
, uribuf
->bufsize
,
2159 scheme
, NULL
, hostTarget
, ntohs(port
), "%s?snmp=false",
2162 httpAssembleURI(HTTP_URI_CODING_ALL
, uribuf
->buffer
, uribuf
->bufsize
,
2163 scheme
, NULL
, hostTarget
, ntohs(port
), resource
);
2165 DEBUG_printf(("8http_resolve_cb: Resolved URI is \"%s\"...", uribuf
->buffer
));
2168 #elif defined(HAVE_AVAHI)
2170 * 'http_poll_cb()' - Wait for input on the specified file descriptors.
2172 * Note: This function is needed because avahi_simple_poll_iterate is broken
2173 * and always uses a timeout of 0 (!) milliseconds.
2174 * (Avahi Ticket #364)
2177 static int /* O - Number of file descriptors matching */
2179 struct pollfd
*pollfds
, /* I - File descriptors */
2180 unsigned int num_pollfds
, /* I - Number of file descriptors */
2181 int timeout
, /* I - Timeout in milliseconds (used) */
2182 void *context
) /* I - User data (unused) */
2187 return (poll(pollfds
, num_pollfds
, 2000));
2192 * 'http_resolve_cb()' - Build a device URI for the given service name.
2197 AvahiServiceResolver
*resolver
, /* I - Resolver (unused) */
2198 AvahiIfIndex interface
, /* I - Interface index (unused) */
2199 AvahiProtocol protocol
, /* I - Network protocol (unused) */
2200 AvahiResolverEvent event
, /* I - Event (found, etc.) */
2201 const char *name
, /* I - Service name */
2202 const char *type
, /* I - Registration type */
2203 const char *domain
, /* I - Domain (unused) */
2204 const char *hostTarget
, /* I - Hostname */
2205 const AvahiAddress
*address
, /* I - Address (unused) */
2206 uint16_t port
, /* I - Port number */
2207 AvahiStringList
*txt
, /* I - TXT record */
2208 AvahiLookupResultFlags flags
, /* I - Lookup flags (unused) */
2209 void *context
) /* I - Pointer to URI buffer */
2211 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
2213 const char *scheme
, /* URI scheme */
2214 *hostptr
, /* Pointer into hostTarget */
2215 *reskey
, /* "rp" or "rfo" */
2216 *resdefault
; /* Default path */
2217 char resource
[257], /* Remote path */
2218 fqdn
[256]; /* FQDN of the .local name */
2219 AvahiStringList
*pair
; /* Current TXT record key/value pair */
2220 char *value
; /* Value for "rp" key */
2221 size_t valueLen
= 0; /* Length of "rp" key */
2224 DEBUG_printf(("7http_resolve_cb(resolver=%p, "
2225 "interface=%d, protocol=%d, event=%d, name=\"%s\", "
2226 "type=\"%s\", domain=\"%s\", hostTarget=\"%s\", address=%p, "
2227 "port=%d, txt=%p, flags=%d, context=%p)",
2228 resolver
, interface
, protocol
, event
, name
, type
, domain
,
2229 hostTarget
, address
, port
, txt
, flags
, context
));
2231 if (event
!= AVAHI_RESOLVER_FOUND
)
2233 avahi_service_resolver_free(resolver
);
2234 avahi_simple_poll_quit(uribuf
->poll
);
2239 * Figure out the scheme from the full name...
2242 if (strstr(type
, "_ipp."))
2244 else if (strstr(type
, "_printer."))
2246 else if (strstr(type
, "_pdl-datastream."))
2249 scheme
= "riousbprint";
2251 if (!strncmp(type
, "_ipps.", 6) || !strncmp(type
, "_ipp-tls.", 9))
2253 else if (!strncmp(type
, "_ipp.", 5) || !strncmp(type
, "_fax-ipp.", 9))
2255 else if (!strncmp(type
, "_http.", 6))
2257 else if (!strncmp(type
, "_https.", 7))
2259 else if (!strncmp(type
, "_printer.", 9))
2261 else if (!strncmp(type
, "_pdl-datastream.", 16))
2265 avahi_service_resolver_free(resolver
);
2266 avahi_simple_poll_quit(uribuf
->poll
);
2271 * Extract the remote resource key from the TXT record...
2274 if ((uribuf
->options
& _HTTP_RESOLVE_FAXOUT
) &&
2275 (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")))
2278 resdefault
= "/ipp/faxout";
2286 if ((pair
= avahi_string_list_find(txt
, reskey
)) != NULL
)
2288 avahi_string_list_get_pair(pair
, NULL
, &value
, &valueLen
);
2290 if (value
[0] == '/')
2293 * Value (incorrectly) has a leading slash already...
2296 memcpy(resource
, value
, valueLen
);
2297 resource
[valueLen
] = '\0';
2302 * Convert to resource by concatenating with a leading "/"...
2306 memcpy(resource
+ 1, value
, valueLen
);
2307 resource
[valueLen
+ 1] = '\0';
2313 * Use the default value...
2316 strlcpy(resource
, resdefault
, sizeof(resource
));
2320 * Lookup the FQDN if needed...
2323 if ((uribuf
->options
& _HTTP_RESOLVE_FQDN
) &&
2324 (hostptr
= hostTarget
+ strlen(hostTarget
) - 6) > hostTarget
&&
2325 !_cups_strcasecmp(hostptr
, ".local"))
2328 * OK, we got a .local name but the caller needs a real domain. Start by
2329 * getting the IP address of the .local name and then do reverse-lookups...
2332 http_addrlist_t
*addrlist
, /* List of addresses */
2333 *addr
; /* Current address */
2335 DEBUG_printf(("8http_resolve_cb: Looking up \"%s\".", hostTarget
));
2337 snprintf(fqdn
, sizeof(fqdn
), "%d", ntohs(port
));
2338 if ((addrlist
= httpAddrGetList(hostTarget
, AF_UNSPEC
, fqdn
)) != NULL
)
2340 for (addr
= addrlist
; addr
; addr
= addr
->next
)
2342 int error
= getnameinfo(&(addr
->addr
.addr
),
2343 httpAddrLength(&(addr
->addr
)),
2344 fqdn
, sizeof(fqdn
), NULL
, 0, NI_NAMEREQD
);
2348 DEBUG_printf(("8http_resolve_cb: Found \"%s\".", fqdn
));
2350 if ((hostptr
= fqdn
+ strlen(fqdn
) - 6) <= fqdn
||
2351 _cups_strcasecmp(hostptr
, ".local"))
2359 DEBUG_printf(("8http_resolve_cb: \"%s\" did not resolve: %d",
2360 httpAddrString(&(addr
->addr
), fqdn
, sizeof(fqdn
)),
2365 httpAddrFreeList(addrlist
);
2370 * Assemble the final device URI using the resolved hostname...
2373 httpAssembleURI(HTTP_URI_CODING_ALL
, uribuf
->buffer
, uribuf
->bufsize
, scheme
,
2374 NULL
, hostTarget
, port
, resource
);
2375 DEBUG_printf(("8http_resolve_cb: Resolved URI is \"%s\".", uribuf
->buffer
));
2377 avahi_simple_poll_quit(uribuf
->poll
);
2379 #endif /* HAVE_DNSSD */