2 * "$Id: http-support.c 7952 2008-09-17 00:56:20Z mike $"
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_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 if (username
&& *username
)
245 * Add username@ first...
248 ptr
= http_copy_encode(ptr
, username
, end
, "/?#[]@", NULL
,
249 encoding
& HTTP_URI_CODING_USERNAME
);
252 goto assemble_overflow
;
257 goto assemble_overflow
;
261 * Then add the hostname. Since IPv6 is a particular pain to deal
262 * with, we have several special cases to deal with. If we get
263 * an IPv6 address with brackets around it, assume it is already in
264 * URI format. Since DNS-SD service names can sometimes look like
265 * raw IPv6 addresses, we specifically look for "._tcp" in the name,
269 if (host
[0] != '[' && strchr(host
, ':') && !strstr(host
, "._tcp"))
272 * We have a raw IPv6 address...
275 if (strchr(host
, '%'))
278 * We have a link-local address, add "[v1." prefix...
289 goto assemble_overflow
;
294 * We have a normal address, add "[" prefix...
300 goto assemble_overflow
;
304 * Copy the rest of the IPv6 address, and terminate with "]".
307 while (ptr
< end
&& *host
)
311 *ptr
++ = '+'; /* Convert zone separator */
319 goto assemble_overflow
;
324 goto assemble_overflow
;
329 * Otherwise, just copy the host string...
331 ptr
= http_copy_encode(ptr
, host
, end
, "<>{}|^:/?#[]@\\\"", NULL
,
332 encoding
& HTTP_URI_CODING_HOSTNAME
);
335 goto assemble_overflow
;
339 * Finish things off with the port number...
344 snprintf(ptr
, end
- ptr
+ 1, ":%d", port
);
348 goto assemble_overflow
;
353 * Last but not least, add the resource string...
358 char *query
; /* Pointer to query string */
362 * Copy the resource string up to the query string if present...
365 query
= strchr(resource
, '?');
366 ptr
= http_copy_encode(ptr
, resource
, end
, NULL
, "?",
367 encoding
& HTTP_URI_CODING_RESOURCE
);
369 goto assemble_overflow
;
374 * Copy query string without encoding...
377 ptr
= http_copy_encode(ptr
, query
, end
, NULL
, NULL
,
378 encoding
& HTTP_URI_CODING_QUERY
);
380 goto assemble_overflow
;
386 goto assemble_overflow
;
389 * Nul-terminate the URI buffer and return with no errors...
394 return (HTTP_URI_OK
);
397 * Clear the URI string and return an overflow error; I don't usually
398 * like goto's, but in this case it makes sense...
404 return (HTTP_URI_OVERFLOW
);
409 * 'httpAssembleURIf()' - Assemble a uniform resource identifier from its
410 * components with a formatted resource.
412 * This function creates a formatted version of the resource string
413 * argument "resourcef" and escapes reserved characters in the URI
414 * depending on the value of the "encoding" argument. You should use
415 * this function in place of traditional string functions whenever
416 * you need to create a URI string.
418 * @since CUPS 1.2/OS X 10.5@
421 http_uri_status_t
/* O - URI status */
423 http_uri_coding_t encoding
, /* I - Encoding flags */
424 char *uri
, /* I - URI buffer */
425 int urilen
, /* I - Size of URI buffer */
426 const char *scheme
, /* I - Scheme name */
427 const char *username
, /* I - Username */
428 const char *host
, /* I - Hostname or address */
429 int port
, /* I - Port number */
430 const char *resourcef
, /* I - Printf-style resource */
431 ...) /* I - Additional arguments as needed */
433 va_list ap
; /* Pointer to additional arguments */
434 char resource
[1024]; /* Formatted resource string */
435 int bytes
; /* Bytes in formatted string */
439 * Range check input...
442 if (!uri
|| urilen
< 1 || !scheme
|| port
< 0 || !resourcef
)
447 return (HTTP_URI_BAD_ARGUMENTS
);
451 * Format the resource string and assemble the URI...
454 va_start(ap
, resourcef
);
455 bytes
= vsnprintf(resource
, sizeof(resource
), resourcef
, ap
);
458 if (bytes
>= sizeof(resource
))
461 return (HTTP_URI_OVERFLOW
);
464 return (httpAssembleURI(encoding
, uri
, urilen
, scheme
, username
, host
,
470 * 'httpAssembleUUID()' - Assemble a name-based UUID URN conforming to RFC 4122.
472 * This function creates a unique 128-bit identifying number using the server
473 * name, port number, random data, and optionally an object name and/or object
474 * number. The result is formatted as a UUID URN as defined in RFC 4122.
476 * The buffer needs to be at least 46 bytes in size.
479 char * /* I - UUID string */
480 httpAssembleUUID(const char *server
, /* I - Server name */
481 int port
, /* I - Port number */
482 const char *name
, /* I - Object name or NULL */
483 int number
, /* I - Object number or 0 */
484 char *buffer
, /* I - String buffer */
485 size_t bufsize
) /* I - Size of buffer */
487 char data
[1024]; /* Source string for MD5 */
488 _cups_md5_state_t md5state
; /* MD5 state */
489 unsigned char md5sum
[16]; /* MD5 digest/sum */
493 * Build a version 3 UUID conforming to RFC 4122.
495 * Start with the MD5 sum of the server, port, object name and
496 * number, and some random data on the end.
499 snprintf(data
, sizeof(data
), "%s:%d:%s:%d:%04x:%04x", server
,
500 port
, name
? name
: server
, number
,
501 (unsigned)CUPS_RAND() & 0xffff, (unsigned)CUPS_RAND() & 0xffff);
503 _cupsMD5Init(&md5state
);
504 _cupsMD5Append(&md5state
, (unsigned char *)data
, strlen(data
));
505 _cupsMD5Finish(&md5state
, md5sum
);
508 * Generate the UUID from the MD5...
511 snprintf(buffer
, bufsize
,
512 "urn:uuid:%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-"
513 "%02x%02x%02x%02x%02x%02x",
514 md5sum
[0], md5sum
[1], md5sum
[2], md5sum
[3], md5sum
[4], md5sum
[5],
515 (md5sum
[6] & 15) | 0x30, md5sum
[7], (md5sum
[8] & 0x3f) | 0x40,
516 md5sum
[9], md5sum
[10], md5sum
[11], md5sum
[12], md5sum
[13],
517 md5sum
[14], md5sum
[15]);
522 /* For OS X 10.8 and earlier */
523 char *_httpAssembleUUID(const char *server
, int port
, const char *name
,
524 int number
, char *buffer
, size_t bufsize
)
526 return (httpAssembleUUID(server
, port
, name
, number
, buffer
, bufsize
));
531 * 'httpDecode64()' - Base64-decode a string.
533 * This function is deprecated. Use the httpDecode64_2() function instead
534 * which provides buffer length arguments.
539 char * /* O - Decoded string */
540 httpDecode64(char *out
, /* I - String to write to */
541 const char *in
) /* I - String to read from */
543 int outlen
; /* Output buffer length */
547 * Use the old maximum buffer size for binary compatibility...
552 return (httpDecode64_2(out
, &outlen
, in
));
557 * 'httpDecode64_2()' - Base64-decode a string.
559 * @since CUPS 1.1.21/OS X 10.4@
562 char * /* O - Decoded string */
563 httpDecode64_2(char *out
, /* I - String to write to */
564 int *outlen
, /* IO - Size of output string */
565 const char *in
) /* I - String to read from */
567 int pos
, /* Bit position */
568 base64
; /* Value of this character */
569 char *outptr
, /* Output pointer */
570 *outend
; /* End of output buffer */
574 * Range check input...
577 if (!out
|| !outlen
|| *outlen
< 1 || !in
)
589 * Convert from base-64 to bytes...
592 for (outptr
= out
, outend
= out
+ *outlen
- 1, pos
= 0; *in
!= '\0'; in
++)
595 * Decode this character into a number from 0 to 63...
598 if (*in
>= 'A' && *in
<= 'Z')
600 else if (*in
>= 'a' && *in
<= 'z')
601 base64
= *in
- 'a' + 26;
602 else if (*in
>= '0' && *in
<= '9')
603 base64
= *in
- '0' + 52;
614 * Store the result in the appropriate chars...
621 *outptr
= base64
<< 2;
626 *outptr
++ |= (base64
>> 4) & 3;
628 *outptr
= (base64
<< 4) & 255;
633 *outptr
++ |= (base64
>> 2) & 15;
635 *outptr
= (base64
<< 6) & 255;
649 * Return the decoded string and size...
652 *outlen
= (int)(outptr
- out
);
659 * 'httpEncode64()' - Base64-encode a string.
661 * This function is deprecated. Use the httpEncode64_2() function instead
662 * which provides buffer length arguments.
667 char * /* O - Encoded string */
668 httpEncode64(char *out
, /* I - String to write to */
669 const char *in
) /* I - String to read from */
671 return (httpEncode64_2(out
, 512, in
, (int)strlen(in
)));
676 * 'httpEncode64_2()' - Base64-encode a string.
678 * @since CUPS 1.1.21/OS X 10.4@
681 char * /* O - Encoded string */
682 httpEncode64_2(char *out
, /* I - String to write to */
683 int outlen
, /* I - Size of output string */
684 const char *in
, /* I - String to read from */
685 int inlen
) /* I - Size of input string */
687 char *outptr
, /* Output pointer */
688 *outend
; /* End of output buffer */
689 static const char base64
[] = /* Base64 characters... */
691 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
692 "abcdefghijklmnopqrstuvwxyz"
699 * Range check input...
702 if (!out
|| outlen
< 1 || !in
)
706 * Convert bytes to base-64...
709 for (outptr
= out
, outend
= out
+ outlen
- 1; inlen
> 0; in
++, inlen
--)
712 * Encode the up to 3 characters as 4 Base64 numbers...
716 *outptr
++ = base64
[(in
[0] & 255) >> 2];
721 *outptr
++ = base64
[(((in
[0] & 255) << 4) | ((in
[1] & 255) >> 4)) & 63];
723 *outptr
++ = base64
[((in
[0] & 255) << 4) & 63];
740 *outptr
++ = base64
[(((in
[0] & 255) << 2) | ((in
[1] & 255) >> 6)) & 63];
742 *outptr
++ = base64
[((in
[0] & 255) << 2) & 63];
755 *outptr
++ = base64
[in
[0] & 63];
761 * Return the encoded string...
769 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
774 const char * /* O - Date/time string */
775 httpGetDateString(time_t t
) /* I - UNIX time */
777 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
780 return (httpGetDateString2(t
, cg
->http_date
, sizeof(cg
->http_date
)));
785 * 'httpGetDateString2()' - Get a formatted date/time string from a time value.
787 * @since CUPS 1.2/OS X 10.5@
790 const char * /* O - Date/time string */
791 httpGetDateString2(time_t t
, /* I - UNIX time */
792 char *s
, /* I - String buffer */
793 int slen
) /* I - Size of string buffer */
795 struct tm
*tdate
; /* UNIX date/time data */
800 snprintf(s
, slen
, "%s, %02d %s %d %02d:%02d:%02d GMT",
801 http_days
[tdate
->tm_wday
], tdate
->tm_mday
,
802 http_months
[tdate
->tm_mon
], tdate
->tm_year
+ 1900,
803 tdate
->tm_hour
, tdate
->tm_min
, tdate
->tm_sec
);
812 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
815 time_t /* O - UNIX time */
816 httpGetDateTime(const char *s
) /* I - Date/time string */
818 int i
; /* Looping var */
819 char mon
[16]; /* Abbreviated month name */
820 int day
, year
; /* Day of month and year */
821 int hour
, min
, sec
; /* Time */
822 int days
; /* Number of days since 1970 */
823 static const int normal_days
[] = /* Days to a month, normal years */
824 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
825 static const int leap_days
[] = /* Days to a month, leap years */
826 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 };
829 DEBUG_printf(("2httpGetDateTime(s=\"%s\")", s
));
832 * Extract the date and time from the formatted string...
835 if (sscanf(s
, "%*s%d%15s%d%d:%d:%d", &day
, mon
, &year
, &hour
, &min
, &sec
) < 6)
838 DEBUG_printf(("4httpGetDateTime: day=%d, mon=\"%s\", year=%d, hour=%d, "
839 "min=%d, sec=%d", day
, mon
, year
, hour
, min
, sec
));
842 * Convert the month name to a number from 0 to 11.
845 for (i
= 0; i
< 12; i
++)
846 if (!_cups_strcasecmp(mon
, http_months
[i
]))
852 DEBUG_printf(("4httpGetDateTime: i=%d", i
));
855 * Now convert the date and time to a UNIX time value in seconds since
856 * 1970. We can't use mktime() since the timezone may not be UTC but
857 * the date/time string *is* UTC.
860 if ((year
& 3) == 0 && ((year
% 100) != 0 || (year
% 400) == 0))
861 days
= leap_days
[i
] + day
- 1;
863 days
= normal_days
[i
] + day
- 1;
865 DEBUG_printf(("4httpGetDateTime: days=%d", days
));
867 days
+= (year
- 1970) * 365 + /* 365 days per year (normally) */
868 ((year
- 1) / 4 - 492) - /* + leap days */
869 ((year
- 1) / 100 - 19) + /* - 100 year days */
870 ((year
- 1) / 400 - 4); /* + 400 year days */
872 DEBUG_printf(("4httpGetDateTime: days=%d\n", days
));
874 return (days
* 86400 + hour
* 3600 + min
* 60 + sec
);
879 * 'httpSeparate()' - Separate a Universal Resource Identifier into its
882 * This function is deprecated; use the httpSeparateURI() function instead.
888 httpSeparate(const char *uri
, /* I - Universal Resource Identifier */
889 char *scheme
, /* O - Scheme [32] (http, https, etc.) */
890 char *username
, /* O - Username [1024] */
891 char *host
, /* O - Hostname [1024] */
892 int *port
, /* O - Port number to use */
893 char *resource
) /* O - Resource/filename [1024] */
895 httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, 32, username
,
896 HTTP_MAX_URI
, host
, HTTP_MAX_URI
, port
, resource
,
902 * 'httpSeparate2()' - Separate a Universal Resource Identifier into its
905 * This function is deprecated; use the httpSeparateURI() function instead.
907 * @since CUPS 1.1.21/OS X 10.4@
912 httpSeparate2(const char *uri
, /* I - Universal Resource Identifier */
913 char *scheme
, /* O - Scheme (http, https, etc.) */
914 int schemelen
, /* I - Size of scheme buffer */
915 char *username
, /* O - Username */
916 int usernamelen
, /* I - Size of username buffer */
917 char *host
, /* O - Hostname */
918 int hostlen
, /* I - Size of hostname buffer */
919 int *port
, /* O - Port number to use */
920 char *resource
, /* O - Resource/filename */
921 int resourcelen
) /* I - Size of resource buffer */
923 httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, schemelen
, username
,
924 usernamelen
, host
, hostlen
, port
, resource
, resourcelen
);
929 * 'httpSeparateURI()' - Separate a Universal Resource Identifier into its
932 * @since CUPS 1.2/OS X 10.5@
935 http_uri_status_t
/* O - Result of separation */
937 http_uri_coding_t decoding
, /* I - Decoding flags */
938 const char *uri
, /* I - Universal Resource Identifier */
939 char *scheme
, /* O - Scheme (http, https, etc.) */
940 int schemelen
, /* I - Size of scheme buffer */
941 char *username
, /* O - Username */
942 int usernamelen
, /* I - Size of username buffer */
943 char *host
, /* O - Hostname */
944 int hostlen
, /* I - Size of hostname buffer */
945 int *port
, /* O - Port number to use */
946 char *resource
, /* O - Resource/filename */
947 int resourcelen
) /* I - Size of resource buffer */
949 char *ptr
, /* Pointer into string... */
950 *end
; /* End of string */
951 const char *sep
; /* Separator character */
952 http_uri_status_t status
; /* Result of separation */
956 * Initialize everything to blank...
959 if (scheme
&& schemelen
> 0)
962 if (username
&& usernamelen
> 0)
965 if (host
&& hostlen
> 0)
971 if (resource
&& resourcelen
> 0)
975 * Range check input...
978 if (!uri
|| !port
|| !scheme
|| schemelen
<= 0 || !username
||
979 usernamelen
<= 0 || !host
|| hostlen
<= 0 || !resource
||
981 return (HTTP_URI_BAD_ARGUMENTS
);
984 return (HTTP_URI_BAD_URI
);
987 * Grab the scheme portion of the URI...
990 status
= HTTP_URI_OK
;
992 if (!strncmp(uri
, "//", 2))
995 * Workaround for HP IPP client bug...
998 strlcpy(scheme
, "ipp", schemelen
);
999 status
= HTTP_URI_MISSING_SCHEME
;
1001 else if (*uri
== '/')
1007 strlcpy(scheme
, "file", schemelen
);
1008 status
= HTTP_URI_MISSING_SCHEME
;
1013 * Standard URI with scheme...
1016 for (ptr
= scheme
, end
= scheme
+ schemelen
- 1;
1017 *uri
&& *uri
!= ':' && ptr
< end
;)
1018 if (strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1019 "abcdefghijklmnopqrstuvwxyz"
1020 "0123456789-+.", *uri
) != NULL
)
1030 return (HTTP_URI_BAD_SCHEME
);
1037 * Set the default port number...
1040 if (!strcmp(scheme
, "http"))
1042 else if (!strcmp(scheme
, "https"))
1044 else if (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps"))
1046 else if (!_cups_strcasecmp(scheme
, "lpd"))
1048 else if (!strcmp(scheme
, "socket")) /* Not yet registered with IANA... */
1050 else if (strcmp(scheme
, "file") && strcmp(scheme
, "mailto"))
1051 status
= HTTP_URI_UNKNOWN_SCHEME
;
1054 * Now see if we have a hostname...
1057 if (!strncmp(uri
, "//", 2))
1060 * Yes, extract it...
1066 * Grab the username, if any...
1069 if ((sep
= strpbrk(uri
, "@/")) != NULL
&& *sep
== '@')
1072 * Get a username:password combo...
1075 uri
= http_copy_decode(username
, uri
, usernamelen
, "@",
1076 decoding
& HTTP_URI_CODING_USERNAME
);
1081 return (HTTP_URI_BAD_USERNAME
);
1088 * Then the hostname/IP address...
1094 * Grab IPv6 address...
1098 if (!strncmp(uri
, "v1.", 3))
1099 uri
+= 3; /* Skip IPvN leader... */
1101 uri
= http_copy_decode(host
, uri
, hostlen
, "]",
1102 decoding
& HTTP_URI_CODING_HOSTNAME
);
1107 return (HTTP_URI_BAD_HOSTNAME
);
1117 return (HTTP_URI_BAD_HOSTNAME
);
1122 for (ptr
= host
; *ptr
; ptr
++)
1126 * Convert zone separator to % and stop here...
1132 else if (*ptr
!= ':' && *ptr
!= '.' && !isxdigit(*ptr
& 255))
1135 return (HTTP_URI_BAD_HOSTNAME
);
1141 * Validate the hostname or IPv4 address first...
1144 for (ptr
= (char *)uri
; *ptr
; ptr
++)
1145 if (strchr(":?/", *ptr
))
1147 else if (!strchr("abcdefghijklmnopqrstuvwxyz"
1148 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1152 "!$&'()*+,;=\\", *ptr
))
1155 return (HTTP_URI_BAD_HOSTNAME
);
1159 * Then copy the hostname or IPv4 address to the buffer...
1162 uri
= http_copy_decode(host
, uri
, hostlen
, ":?/",
1163 decoding
& HTTP_URI_CODING_HOSTNAME
);
1168 return (HTTP_URI_BAD_HOSTNAME
);
1173 * Validate hostname for file scheme - only empty and localhost are
1177 if (!strcmp(scheme
, "file") && strcmp(host
, "localhost") && host
[0])
1180 return (HTTP_URI_BAD_HOSTNAME
);
1184 * See if we have a port number...
1190 * Yes, collect the port number...
1193 if (!isdigit(uri
[1] & 255))
1196 return (HTTP_URI_BAD_PORT
);
1199 *port
= strtol(uri
+ 1, (char **)&uri
, 10);
1201 if (*uri
!= '/' && *uri
)
1204 return (HTTP_URI_BAD_PORT
);
1210 * The remaining portion is the resource string...
1213 if (*uri
== '?' || !*uri
)
1216 * Hostname but no path...
1219 status
= HTTP_URI_MISSING_RESOURCE
;
1223 * Copy any query string...
1227 uri
= http_copy_decode(resource
+ 1, uri
, resourcelen
- 1, NULL
,
1228 decoding
& HTTP_URI_CODING_QUERY
);
1234 uri
= http_copy_decode(resource
, uri
, resourcelen
, "?",
1235 decoding
& HTTP_URI_CODING_RESOURCE
);
1237 if (uri
&& *uri
== '?')
1240 * Concatenate any query string...
1243 char *resptr
= resource
+ strlen(resource
);
1245 uri
= http_copy_decode(resptr
, uri
, resourcelen
- (int)(resptr
- resource
),
1246 NULL
, decoding
& HTTP_URI_CODING_QUERY
);
1253 return (HTTP_URI_BAD_RESOURCE
);
1257 * Return the URI separation status...
1265 * 'httpStatus()' - Return a short string describing a HTTP status code.
1267 * The returned string is localized to the current POSIX locale and is based
1268 * on the status strings defined in RFC 2616.
1271 const char * /* O - Localized status string */
1272 httpStatus(http_status_t status
) /* I - HTTP status code */
1274 const char *s
; /* Status string */
1275 _cups_globals_t
*cg
= _cupsGlobals(); /* Global data */
1278 if (!cg
->lang_default
)
1279 cg
->lang_default
= cupsLangDefault();
1283 case HTTP_CONTINUE
:
1286 case HTTP_SWITCHING_PROTOCOLS
:
1287 s
= _("Switching Protocols");
1295 case HTTP_ACCEPTED
:
1298 case HTTP_NO_CONTENT
:
1299 s
= _("No Content");
1301 case HTTP_MOVED_PERMANENTLY
:
1302 s
= _("Moved Permanently");
1304 case HTTP_SEE_OTHER
:
1307 case HTTP_NOT_MODIFIED
:
1308 s
= _("Not Modified");
1310 case HTTP_BAD_REQUEST
:
1311 s
= _("Bad Request");
1313 case HTTP_UNAUTHORIZED
:
1314 case HTTP_AUTHORIZATION_CANCELED
:
1315 s
= _("Unauthorized");
1317 case HTTP_FORBIDDEN
:
1320 case HTTP_NOT_FOUND
:
1323 case HTTP_REQUEST_TOO_LARGE
:
1324 s
= _("Request Entity Too Large");
1326 case HTTP_URI_TOO_LONG
:
1327 s
= _("URI Too Long");
1329 case HTTP_UPGRADE_REQUIRED
:
1330 s
= _("Upgrade Required");
1332 case HTTP_NOT_IMPLEMENTED
:
1333 s
= _("Not Implemented");
1335 case HTTP_NOT_SUPPORTED
:
1336 s
= _("Not Supported");
1338 case HTTP_EXPECTATION_FAILED
:
1339 s
= _("Expectation Failed");
1341 case HTTP_SERVICE_UNAVAILABLE
:
1342 s
= _("Service Unavailable");
1344 case HTTP_SERVER_ERROR
:
1345 s
= _("Internal Server Error");
1347 case HTTP_PKI_ERROR
:
1348 s
= _("SSL/TLS Negotiation Error");
1350 case HTTP_WEBIF_DISABLED
:
1351 s
= _("Web Interface is Disabled");
1359 return (_cupsLangString(cg
->lang_default
, s
));
1363 #ifndef HAVE_HSTRERROR
1365 * '_cups_hstrerror()' - hstrerror() emulation function for Solaris and others.
1368 const char * /* O - Error string */
1369 _cups_hstrerror(int error
) /* I - Error number */
1371 static const char * const errors
[] = /* Error strings */
1376 "Unrecoverable lookup error.",
1377 "No data associated with name."
1381 if (error
< 0 || error
> 4)
1382 return ("Unknown hostname lookup error.");
1384 return (errors
[error
]);
1386 #endif /* !HAVE_HSTRERROR */
1390 * '_httpDecodeURI()' - Percent-decode a HTTP request URI.
1393 char * /* O - Decoded URI or NULL on error */
1394 _httpDecodeURI(char *dst
, /* I - Destination buffer */
1395 const char *src
, /* I - Source URI */
1396 size_t dstsize
) /* I - Size of destination buffer */
1398 if (http_copy_decode(dst
, src
, (int)dstsize
, NULL
, 1))
1406 * '_httpEncodeURI()' - Percent-encode a HTTP request URI.
1409 char * /* O - Encoded URI */
1410 _httpEncodeURI(char *dst
, /* I - Destination buffer */
1411 const char *src
, /* I - Source URI */
1412 size_t dstsize
) /* I - Size of destination buffer */
1414 http_copy_encode(dst
, src
, dst
+ dstsize
- 1, NULL
, NULL
, 1);
1420 * '_httpResolveURI()' - Resolve a DNS-SD URI.
1423 const char * /* O - Resolved URI */
1425 const char *uri
, /* I - DNS-SD URI */
1426 char *resolved_uri
, /* I - Buffer for resolved URI */
1427 size_t resolved_size
, /* I - Size of URI buffer */
1428 int options
, /* I - Resolve options */
1429 int (*cb
)(void *context
), /* I - Continue callback function */
1430 void *context
) /* I - Context pointer for callback */
1432 char scheme
[32], /* URI components... */
1438 http_uri_status_t status
; /* URI decode status */
1442 DEBUG_printf(("4_httpResolveURI(uri=\"%s\", resolved_uri=%p, "
1443 "resolved_size=" CUPS_LLFMT
")", uri
, resolved_uri
,
1444 CUPS_LLCAST resolved_size
));
1447 * Get the device URI...
1451 if ((status
= httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
,
1452 sizeof(scheme
), userpass
, sizeof(userpass
),
1453 hostname
, sizeof(hostname
), &port
, resource
,
1454 sizeof(resource
))) < HTTP_URI_OK
)
1456 if (httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
,
1457 sizeof(scheme
), userpass
, sizeof(userpass
),
1458 hostname
, sizeof(hostname
), &port
, resource
,
1459 sizeof(resource
)) < HTTP_URI_OK
)
1462 if (options
& _HTTP_RESOLVE_STDERR
)
1463 _cupsLangPrintFilter(stderr
, "ERROR", _("Bad device-uri \"%s\"."), uri
);
1465 DEBUG_printf(("6_httpResolveURI: httpSeparateURI returned %d!", status
));
1466 DEBUG_puts("5_httpResolveURI: Returning NULL");
1471 * Resolve it as needed...
1474 if (strstr(hostname
, "._tcp"))
1476 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
1477 char *regtype
, /* Pointer to type in hostname */
1478 *domain
; /* Pointer to domain in hostname */
1479 _http_uribuf_t uribuf
; /* URI buffer */
1480 int offline
= 0; /* offline-report state set? */
1483 # pragma comment(lib, "dnssd.lib")
1485 DNSServiceRef ref
, /* DNS-SD master service reference */
1486 domainref
, /* DNS-SD service reference for domain */
1487 localref
; /* DNS-SD service reference for .local */
1488 int domainsent
= 0; /* Send the domain resolve? */
1490 struct pollfd polldata
; /* Polling data */
1491 # else /* select() */
1492 fd_set input_set
; /* Input set for select() */
1493 struct timeval stimeout
; /* Timeout value for select() */
1494 # endif /* HAVE_POLL */
1495 # elif defined(HAVE_AVAHI)
1496 AvahiClient
*client
; /* Client information */
1497 int error
; /* Status */
1498 # endif /* HAVE_DNSSD */
1500 if (options
& _HTTP_RESOLVE_STDERR
)
1501 fprintf(stderr
, "DEBUG: Resolving \"%s\"...\n", hostname
);
1504 * Separate the hostname into service name, registration type, and domain...
1507 for (regtype
= strstr(hostname
, "._tcp") - 2;
1510 if (regtype
[0] == '.' && regtype
[1] == '_')
1513 * Found ._servicetype in front of ._tcp...
1520 if (regtype
<= hostname
)
1522 DEBUG_puts("5_httpResolveURI: Bad hostname, returning NULL");
1526 for (domain
= strchr(regtype
, '.');
1528 domain
= strchr(domain
+ 1, '.'))
1529 if (domain
[1] != '_')
1535 uribuf
.buffer
= resolved_uri
;
1536 uribuf
.bufsize
= resolved_size
;
1537 uribuf
.options
= options
;
1538 uribuf
.resource
= resource
;
1540 resolved_uri
[0] = '\0';
1542 DEBUG_printf(("6_httpResolveURI: Resolving hostname=\"%s\", regtype=\"%s\", "
1543 "domain=\"%s\"\n", hostname
, regtype
, domain
));
1544 if (options
& _HTTP_RESOLVE_STDERR
)
1546 fputs("STATE: +connecting-to-device\n", stderr
);
1547 fprintf(stderr
, "DEBUG: Resolving \"%s\", regtype=\"%s\", "
1548 "domain=\"local.\"...\n", hostname
, regtype
);
1554 if (DNSServiceCreateConnection(&ref
) == kDNSServiceErr_NoError
)
1556 int myinterface
= kDNSServiceInterfaceIndexAny
;
1557 /* Lookup on any interface */
1559 if (!strcmp(scheme
, "ippusb"))
1560 myinterface
= kDNSServiceInterfaceIndexLocalOnly
;
1563 if (DNSServiceResolve(&localref
,
1564 kDNSServiceFlagsShareConnection
, myinterface
,
1565 hostname
, regtype
, "local.", http_resolve_cb
,
1566 &uribuf
) == kDNSServiceErr_NoError
)
1568 int fds
; /* Number of ready descriptors */
1569 time_t timeout
, /* Poll timeout */
1570 start_time
= time(NULL
),/* Start time */
1571 end_time
= start_time
+ 90;
1574 while (time(NULL
) < end_time
)
1576 if (options
& _HTTP_RESOLVE_STDERR
)
1577 _cupsLangPrintFilter(stderr
, "INFO", _("Looking for printer."));
1579 if (cb
&& !(*cb
)(context
))
1581 DEBUG_puts("5_httpResolveURI: callback returned 0 (stop)");
1586 * Wakeup every 2 seconds to emit a "looking for printer" message...
1589 if ((timeout
= end_time
- time(NULL
)) > 2)
1593 polldata
.fd
= DNSServiceRefSockFD(ref
);
1594 polldata
.events
= POLLIN
;
1596 fds
= poll(&polldata
, 1, 1000 * timeout
);
1598 # else /* select() */
1599 FD_ZERO(&input_set
);
1600 FD_SET(DNSServiceRefSockFD(ref
), &input_set
);
1603 stimeout
.tv_sec
= (long)timeout
;
1605 stimeout
.tv_sec
= timeout
;
1607 stimeout
.tv_usec
= 0;
1609 fds
= select(DNSServiceRefSockFD(ref
)+1, &input_set
, NULL
, NULL
,
1611 # endif /* HAVE_POLL */
1615 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1617 DEBUG_printf(("5_httpResolveURI: poll error: %s", strerror(errno
)));
1624 * Wait 2 seconds for a response to the local resolve; if nothing
1625 * comes in, do an additional domain resolution...
1628 if (domainsent
== 0 && domain
&& _cups_strcasecmp(domain
, "local."))
1630 if (options
& _HTTP_RESOLVE_STDERR
)
1632 "DEBUG: Resolving \"%s\", regtype=\"%s\", "
1633 "domain=\"%s\"...\n", hostname
, regtype
,
1634 domain
? domain
: "");
1637 if (DNSServiceResolve(&domainref
,
1638 kDNSServiceFlagsShareConnection
,
1639 myinterface
, hostname
, regtype
, domain
,
1641 &uribuf
) == kDNSServiceErr_NoError
)
1646 * If it hasn't resolved within 5 seconds set the offline-report
1647 * printer-state-reason...
1650 if ((options
& _HTTP_RESOLVE_STDERR
) && offline
== 0 &&
1651 time(NULL
) > (start_time
+ 5))
1653 fputs("STATE: +offline-report\n", stderr
);
1659 if (DNSServiceProcessResult(ref
) == kDNSServiceErr_NoError
)
1668 DNSServiceRefDeallocate(domainref
);
1670 DNSServiceRefDeallocate(localref
);
1673 DNSServiceRefDeallocate(ref
);
1675 # else /* HAVE_AVAHI */
1676 if ((uribuf
.poll
= avahi_simple_poll_new()) != NULL
)
1678 avahi_simple_poll_set_func(uribuf
.poll
, http_poll_cb
, NULL
);
1680 if ((client
= avahi_client_new(avahi_simple_poll_get(uribuf
.poll
),
1682 &uribuf
, &error
)) != NULL
)
1684 if (avahi_service_resolver_new(client
, AVAHI_IF_UNSPEC
,
1685 AVAHI_PROTO_UNSPEC
, hostname
,
1686 regtype
, "local.", AVAHI_PROTO_UNSPEC
, 0,
1687 http_resolve_cb
, &uribuf
) != NULL
)
1689 time_t start_time
= time(NULL
),
1691 end_time
= start_time
+ 90;
1693 int pstatus
; /* Poll status */
1695 pstatus
= avahi_simple_poll_iterate(uribuf
.poll
, 2000);
1697 if (pstatus
== 0 && !resolved_uri
[0] && domain
&&
1698 _cups_strcasecmp(domain
, "local."))
1701 * Resolve for .local hasn't returned anything, try the listed
1705 avahi_service_resolver_new(client
, AVAHI_IF_UNSPEC
,
1706 AVAHI_PROTO_UNSPEC
, hostname
,
1707 regtype
, domain
, AVAHI_PROTO_UNSPEC
, 0,
1708 http_resolve_cb
, &uribuf
);
1711 while (!pstatus
&& !resolved_uri
[0] && time(NULL
) < end_time
)
1713 if ((pstatus
= avahi_simple_poll_iterate(uribuf
.poll
, 2000)) != 0)
1717 * If it hasn't resolved within 5 seconds set the offline-report
1718 * printer-state-reason...
1721 if ((options
& _HTTP_RESOLVE_STDERR
) && offline
== 0 &&
1722 time(NULL
) > (start_time
+ 5))
1724 fputs("STATE: +offline-report\n", stderr
);
1730 * Collect the result (if we got one).
1733 if (resolved_uri
[0])
1737 avahi_client_free(client
);
1740 avahi_simple_poll_free(uribuf
.poll
);
1742 # endif /* HAVE_DNSSD */
1744 if (options
& _HTTP_RESOLVE_STDERR
)
1748 fprintf(stderr
, "DEBUG: Resolved as \"%s\"...\n", uri
);
1749 fputs("STATE: -connecting-to-device,offline-report\n", stderr
);
1753 fputs("DEBUG: Unable to resolve URI\n", stderr
);
1754 fputs("STATE: -connecting-to-device\n", stderr
);
1758 #else /* HAVE_DNSSD || HAVE_AVAHI */
1760 * No DNS-SD support...
1764 #endif /* HAVE_DNSSD || HAVE_AVAHI */
1766 if ((options
& _HTTP_RESOLVE_STDERR
) && !uri
)
1767 _cupsLangPrintFilter(stderr
, "INFO", _("Unable to find printer."));
1772 * Nothing more to do...
1775 strlcpy(resolved_uri
, uri
, resolved_size
);
1779 DEBUG_printf(("5_httpResolveURI: Returning \"%s\"", uri
));
1787 * 'http_client_cb()' - Client callback for resolving URI.
1792 AvahiClient
*client
, /* I - Client information */
1793 AvahiClientState state
, /* I - Current state */
1794 void *context
) /* I - Pointer to URI buffer */
1796 DEBUG_printf(("7http_client_cb(client=%p, state=%d, context=%p)", client
,
1800 * If the connection drops, quit.
1803 if (state
== AVAHI_CLIENT_FAILURE
)
1805 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
1808 avahi_simple_poll_quit(uribuf
->poll
);
1811 #endif /* HAVE_AVAHI */
1815 * 'http_copy_decode()' - Copy and decode a URI.
1818 static const char * /* O - New source pointer or NULL on error */
1819 http_copy_decode(char *dst
, /* O - Destination buffer */
1820 const char *src
, /* I - Source pointer */
1821 int dstsize
, /* I - Destination size */
1822 const char *term
, /* I - Terminating characters */
1823 int decode
) /* I - Decode %-encoded values */
1825 char *ptr
, /* Pointer into buffer */
1826 *end
; /* End of buffer */
1827 int quoted
; /* Quoted character */
1831 * Copy the src to the destination until we hit a terminating character
1832 * or the end of the string.
1835 for (ptr
= dst
, end
= dst
+ dstsize
- 1;
1836 *src
&& (!term
|| !strchr(term
, *src
));
1840 if (*src
== '%' && decode
)
1842 if (isxdigit(src
[1] & 255) && isxdigit(src
[2] & 255))
1845 * Grab a hex-encoded character...
1850 quoted
= (tolower(*src
) - 'a' + 10) << 4;
1852 quoted
= (*src
- '0') << 4;
1856 quoted
|= tolower(*src
) - 'a' + 10;
1858 quoted
|= *src
- '0';
1865 * Bad hex-encoded character...
1883 * 'http_copy_encode()' - Copy and encode a URI.
1886 static char * /* O - End of current URI */
1887 http_copy_encode(char *dst
, /* O - Destination buffer */
1888 const char *src
, /* I - Source pointer */
1889 char *dstend
, /* I - End of destination buffer */
1890 const char *reserved
, /* I - Extra reserved characters */
1891 const char *term
, /* I - Terminating characters */
1892 int encode
) /* I - %-encode reserved chars? */
1894 static const char hex
[] = "0123456789ABCDEF";
1897 while (*src
&& dst
< dstend
)
1899 if (term
&& *src
== *term
)
1902 if (encode
&& (*src
== '%' || *src
<= ' ' || *src
& 128 ||
1903 (reserved
&& strchr(reserved
, *src
))))
1906 * Hex encode reserved characters...
1909 if ((dst
+ 2) >= dstend
)
1913 *dst
++ = hex
[(*src
>> 4) & 15];
1914 *dst
++ = hex
[*src
& 15];
1933 * 'http_resolve_cb()' - Build a device URI for the given service name.
1936 static void DNSSD_API
1938 DNSServiceRef sdRef
, /* I - Service reference */
1939 DNSServiceFlags flags
, /* I - Results flags */
1940 uint32_t interfaceIndex
, /* I - Interface number */
1941 DNSServiceErrorType errorCode
, /* I - Error, if any */
1942 const char *fullName
, /* I - Full service name */
1943 const char *hostTarget
, /* I - Hostname */
1944 uint16_t port
, /* I - Port number */
1945 uint16_t txtLen
, /* I - Length of TXT record */
1946 const unsigned char *txtRecord
, /* I - TXT record data */
1947 void *context
) /* I - Pointer to URI buffer */
1949 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
1951 const char *scheme
, /* URI scheme */
1952 *hostptr
, /* Pointer into hostTarget */
1953 *reskey
, /* "rp" or "rfo" */
1954 *resdefault
; /* Default path */
1955 char resource
[257], /* Remote path */
1956 fqdn
[256]; /* FQDN of the .local name */
1957 const void *value
; /* Value from TXT record */
1958 uint8_t valueLen
; /* Length of value */
1961 DEBUG_printf(("7http_resolve_cb(sdRef=%p, flags=%x, interfaceIndex=%u, "
1962 "errorCode=%d, fullName=\"%s\", hostTarget=\"%s\", port=%u, "
1963 "txtLen=%u, txtRecord=%p, context=%p)", sdRef
, flags
,
1964 interfaceIndex
, errorCode
, fullName
, hostTarget
, port
, txtLen
,
1965 txtRecord
, context
));
1968 * Figure out the scheme from the full name...
1971 if (strstr(fullName
, "._ipps") || strstr(fullName
, "._ipp-tls"))
1973 else if (strstr(fullName
, "._ipp") || strstr(fullName
, "._fax-ipp"))
1975 else if (strstr(fullName
, "._http."))
1977 else if (strstr(fullName
, "._https."))
1979 else if (strstr(fullName
, "._printer."))
1981 else if (strstr(fullName
, "._pdl-datastream."))
1984 scheme
= "riousbprint";
1987 * Extract the "remote printer" key from the TXT record...
1990 if ((uribuf
->options
& _HTTP_RESOLVE_FAXOUT
) &&
1991 (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")))
1994 resdefault
= "/ipp/faxout";
2002 if ((value
= TXTRecordGetValuePtr(txtLen
, txtRecord
, reskey
,
2003 &valueLen
)) != NULL
)
2005 if (((char *)value
)[0] == '/')
2008 * Value (incorrectly) has a leading slash already...
2011 memcpy(resource
, value
, valueLen
);
2012 resource
[valueLen
] = '\0';
2017 * Convert to resource by concatenating with a leading "/"...
2021 memcpy(resource
+ 1, value
, valueLen
);
2022 resource
[valueLen
+ 1] = '\0';
2028 * Use the default value...
2031 strlcpy(resource
, resdefault
, sizeof(resource
));
2035 * Lookup the FQDN if needed...
2038 if ((uribuf
->options
& _HTTP_RESOLVE_FQDN
) &&
2039 (hostptr
= hostTarget
+ strlen(hostTarget
) - 7) > hostTarget
&&
2040 !_cups_strcasecmp(hostptr
, ".local."))
2043 * OK, we got a .local name but the caller needs a real domain. Start by
2044 * getting the IP address of the .local name and then do reverse-lookups...
2047 http_addrlist_t
*addrlist
, /* List of addresses */
2048 *addr
; /* Current address */
2050 DEBUG_printf(("8http_resolve_cb: Looking up \"%s\".", hostTarget
));
2052 snprintf(fqdn
, sizeof(fqdn
), "%d", ntohs(port
));
2053 if ((addrlist
= httpAddrGetList(hostTarget
, AF_UNSPEC
, fqdn
)) != NULL
)
2055 for (addr
= addrlist
; addr
; addr
= addr
->next
)
2057 int error
= getnameinfo(&(addr
->addr
.addr
),
2058 httpAddrLength(&(addr
->addr
)),
2059 fqdn
, sizeof(fqdn
), NULL
, 0, NI_NAMEREQD
);
2063 DEBUG_printf(("8http_resolve_cb: Found \"%s\".", fqdn
));
2065 if ((hostptr
= fqdn
+ strlen(fqdn
) - 6) <= fqdn
||
2066 _cups_strcasecmp(hostptr
, ".local"))
2074 DEBUG_printf(("8http_resolve_cb: \"%s\" did not resolve: %d",
2075 httpAddrString(&(addr
->addr
), fqdn
, sizeof(fqdn
)),
2080 httpAddrFreeList(addrlist
);
2085 * Assemble the final device URI...
2088 if ((!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")) &&
2089 !strcmp(uribuf
->resource
, "/cups"))
2090 httpAssembleURIf(HTTP_URI_CODING_ALL
, uribuf
->buffer
, uribuf
->bufsize
,
2091 scheme
, NULL
, hostTarget
, ntohs(port
), "%s?snmp=false",
2094 httpAssembleURI(HTTP_URI_CODING_ALL
, uribuf
->buffer
, uribuf
->bufsize
,
2095 scheme
, NULL
, hostTarget
, ntohs(port
), resource
);
2097 DEBUG_printf(("8http_resolve_cb: Resolved URI is \"%s\"...", uribuf
->buffer
));
2100 #elif defined(HAVE_AVAHI)
2102 * 'http_poll_cb()' - Wait for input on the specified file descriptors.
2104 * Note: This function is needed because avahi_simple_poll_iterate is broken
2105 * and always uses a timeout of 0 (!) milliseconds.
2106 * (Avahi Ticket #364)
2109 static int /* O - Number of file descriptors matching */
2111 struct pollfd
*pollfds
, /* I - File descriptors */
2112 unsigned int num_pollfds
, /* I - Number of file descriptors */
2113 int timeout
, /* I - Timeout in milliseconds (used) */
2114 void *context
) /* I - User data (unused) */
2119 return (poll(pollfds
, num_pollfds
, 2000));
2124 * 'http_resolve_cb()' - Build a device URI for the given service name.
2129 AvahiServiceResolver
*resolver
, /* I - Resolver (unused) */
2130 AvahiIfIndex interface
, /* I - Interface index (unused) */
2131 AvahiProtocol protocol
, /* I - Network protocol (unused) */
2132 AvahiResolverEvent event
, /* I - Event (found, etc.) */
2133 const char *name
, /* I - Service name */
2134 const char *type
, /* I - Registration type */
2135 const char *domain
, /* I - Domain (unused) */
2136 const char *hostTarget
, /* I - Hostname */
2137 const AvahiAddress
*address
, /* I - Address (unused) */
2138 uint16_t port
, /* I - Port number */
2139 AvahiStringList
*txt
, /* I - TXT record */
2140 AvahiLookupResultFlags flags
, /* I - Lookup flags (unused) */
2141 void *context
) /* I - Pointer to URI buffer */
2143 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
2145 const char *scheme
, /* URI scheme */
2146 *hostptr
, /* Pointer into hostTarget */
2147 *reskey
, /* "rp" or "rfo" */
2148 *resdefault
; /* Default path */
2149 char resource
[257], /* Remote path */
2150 fqdn
[256]; /* FQDN of the .local name */
2151 AvahiStringList
*pair
; /* Current TXT record key/value pair */
2152 char *value
; /* Value for "rp" key */
2153 size_t valueLen
= 0; /* Length of "rp" key */
2156 DEBUG_printf(("7http_resolve_cb(resolver=%p, "
2157 "interface=%d, protocol=%d, event=%d, name=\"%s\", "
2158 "type=\"%s\", domain=\"%s\", hostTarget=\"%s\", address=%p, "
2159 "port=%d, txt=%p, flags=%d, context=%p)",
2160 resolver
, interface
, protocol
, event
, name
, type
, domain
,
2161 hostTarget
, address
, port
, txt
, flags
, context
));
2163 if (event
!= AVAHI_RESOLVER_FOUND
)
2165 avahi_service_resolver_free(resolver
);
2166 avahi_simple_poll_quit(uribuf
->poll
);
2171 * Figure out the scheme from the full name...
2174 if (strstr(type
, "_ipp."))
2176 else if (strstr(type
, "_printer."))
2178 else if (strstr(type
, "_pdl-datastream."))
2181 scheme
= "riousbprint";
2183 if (!strncmp(type
, "_ipps.", 6) || !strncmp(type
, "_ipp-tls.", 9))
2185 else if (!strncmp(type
, "_ipp.", 5) || !strncmp(type
, "_fax-ipp.", 9))
2187 else if (!strncmp(type
, "_http.", 6))
2189 else if (!strncmp(type
, "_https.", 7))
2191 else if (!strncmp(type
, "_printer.", 9))
2193 else if (!strncmp(type
, "_pdl-datastream.", 16))
2197 avahi_service_resolver_free(resolver
);
2198 avahi_simple_poll_quit(uribuf
->poll
);
2203 * Extract the remote resource key from the TXT record...
2206 if ((uribuf
->options
& _HTTP_RESOLVE_FAXOUT
) &&
2207 (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")))
2210 resdefault
= "/ipp/faxout";
2218 if ((pair
= avahi_string_list_find(txt
, reskey
)) != NULL
)
2220 avahi_string_list_get_pair(pair
, NULL
, &value
, &valueLen
);
2222 if (value
[0] == '/')
2225 * Value (incorrectly) has a leading slash already...
2228 memcpy(resource
, value
, valueLen
);
2229 resource
[valueLen
] = '\0';
2234 * Convert to resource by concatenating with a leading "/"...
2238 memcpy(resource
+ 1, value
, valueLen
);
2239 resource
[valueLen
+ 1] = '\0';
2245 * Use the default value...
2248 strlcpy(resource
, resdefault
, sizeof(resource
));
2252 * Lookup the FQDN if needed...
2255 if ((uribuf
->options
& _HTTP_RESOLVE_FQDN
) &&
2256 (hostptr
= hostTarget
+ strlen(hostTarget
) - 6) > hostTarget
&&
2257 !_cups_strcasecmp(hostptr
, ".local"))
2260 * OK, we got a .local name but the caller needs a real domain. Start by
2261 * getting the IP address of the .local name and then do reverse-lookups...
2264 http_addrlist_t
*addrlist
, /* List of addresses */
2265 *addr
; /* Current address */
2267 DEBUG_printf(("8http_resolve_cb: Looking up \"%s\".", hostTarget
));
2269 snprintf(fqdn
, sizeof(fqdn
), "%d", ntohs(port
));
2270 if ((addrlist
= httpAddrGetList(hostTarget
, AF_UNSPEC
, fqdn
)) != NULL
)
2272 for (addr
= addrlist
; addr
; addr
= addr
->next
)
2274 int error
= getnameinfo(&(addr
->addr
.addr
),
2275 httpAddrLength(&(addr
->addr
)),
2276 fqdn
, sizeof(fqdn
), NULL
, 0, NI_NAMEREQD
);
2280 DEBUG_printf(("8http_resolve_cb: Found \"%s\".", fqdn
));
2282 if ((hostptr
= fqdn
+ strlen(fqdn
) - 6) <= fqdn
||
2283 _cups_strcasecmp(hostptr
, ".local"))
2291 DEBUG_printf(("8http_resolve_cb: \"%s\" did not resolve: %d",
2292 httpAddrString(&(addr
->addr
), fqdn
, sizeof(fqdn
)),
2297 httpAddrFreeList(addrlist
);
2302 * Assemble the final device URI using the resolved hostname...
2305 httpAssembleURI(HTTP_URI_CODING_ALL
, uribuf
->buffer
, uribuf
->bufsize
, scheme
,
2306 NULL
, hostTarget
, port
, resource
);
2307 DEBUG_printf(("8http_resolve_cb: Resolved URI is \"%s\".", uribuf
->buffer
));
2309 avahi_simple_poll_quit(uribuf
->poll
);
2311 #endif /* HAVE_DNSSD */
2315 * End of "$Id: http-support.c 7952 2008-09-17 00:56:20Z mike $".