2 * "$Id: http-support.c 7952 2008-09-17 00:56:20Z mike $"
4 * HTTP support routines for CUPS.
6 * Copyright 2007-2012 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() - Make a UUID URI conforming to RFC 4122.
24 * httpDecode64() - Base64-decode a string.
25 * httpDecode64_2() - Base64-decode a string.
26 * httpEncode64() - Base64-encode a string.
27 * httpEncode64_2() - Base64-encode a string.
28 * httpGetDateString() - Get a formatted date/time string from a time value.
29 * httpGetDateString2() - Get a formatted date/time string from a time value.
30 * httpGetDateTime() - Get a time value from a formatted date/time string.
31 * httpSeparate() - Separate a Universal Resource Identifier into its
33 * httpSeparate2() - Separate a Universal Resource Identifier into its
35 * httpSeparateURI() - Separate a Universal Resource Identifier into its
37 * httpStatus() - Return a short string describing a HTTP status
39 * _cups_hstrerror() - hstrerror() emulation function for Solaris and
41 * _httpDecodeURI() - Percent-decode a HTTP request URI.
42 * _httpEncodeURI() - Percent-encode a HTTP request URI.
43 * _httpResolveURI() - Resolve a DNS-SD URI.
44 * http_client_cb() - Client callback for resolving URI.
45 * http_copy_decode() - Copy and decode a URI.
46 * http_copy_encode() - Copy and encode a URI.
47 * http_poll_cb() - Wait for input on the specified file descriptors.
48 * http_resolve_cb() - Build a device URI for the given service name.
49 * http_resolve_cb() - Build a device URI for the given service name.
53 * Include necessary headers...
56 #include "cups-private.h"
61 # elif defined(HAVE_POLL)
64 # include <sys/select.h>
66 #elif defined(HAVE_AVAHI)
67 # include <avahi-client/client.h>
68 # include <avahi-client/lookup.h>
69 # include <avahi-common/simple-watch.h>
70 #endif /* HAVE_DNSSD */
77 typedef struct _http_uribuf_s
/* URI buffer */
80 AvahiSimplePoll
*poll
; /* Poll state */
81 #endif /* HAVE_AVAHI */
82 char *buffer
; /* Pointer to buffer */
83 size_t bufsize
; /* Size of buffer */
84 int options
; /* Options passed to _httpResolveURI */
85 const char *resource
; /* Resource from URI */
93 static const char * const http_days
[7] =
103 static const char * const http_months
[12] =
124 static const char *http_copy_decode(char *dst
, const char *src
,
125 int dstsize
, const char *term
,
127 static char *http_copy_encode(char *dst
, const char *src
,
128 char *dstend
, const char *reserved
,
129 const char *term
, int encode
);
131 static void DNSSD_API
http_resolve_cb(DNSServiceRef sdRef
,
132 DNSServiceFlags flags
,
133 uint32_t interfaceIndex
,
134 DNSServiceErrorType errorCode
,
135 const char *fullName
,
136 const char *hostTarget
,
137 uint16_t port
, uint16_t txtLen
,
138 const unsigned char *txtRecord
,
140 #endif /* HAVE_DNSSD */
143 static void http_client_cb(AvahiClient
*client
,
144 AvahiClientState state
, void *simple_poll
);
145 static int http_poll_cb(struct pollfd
*pollfds
, unsigned int num_pollfds
,
146 int timeout
, void *context
);
147 static void http_resolve_cb(AvahiServiceResolver
*resolver
,
148 AvahiIfIndex interface
,
149 AvahiProtocol protocol
,
150 AvahiResolverEvent event
,
151 const char *name
, const char *type
,
152 const char *domain
, const char *host_name
,
153 const AvahiAddress
*address
, uint16_t port
,
154 AvahiStringList
*txt
,
155 AvahiLookupResultFlags flags
, void *context
);
156 #endif /* HAVE_AVAHI */
160 * 'httpAssembleURI()' - Assemble a uniform resource identifier from its
163 * This function escapes reserved characters in the URI depending on the
164 * value of the "encoding" argument. You should use this function in
165 * place of traditional string functions whenever you need to create a
168 * @since CUPS 1.2/OS X 10.5@
171 http_uri_status_t
/* O - URI status */
173 http_uri_coding_t encoding
, /* I - Encoding flags */
174 char *uri
, /* I - URI buffer */
175 int urilen
, /* I - Size of URI buffer */
176 const char *scheme
, /* I - Scheme name */
177 const char *username
, /* I - Username */
178 const char *host
, /* I - Hostname or address */
179 int port
, /* I - Port number */
180 const char *resource
) /* I - Resource */
182 char *ptr
, /* Pointer into URI buffer */
183 *end
; /* End of URI buffer */
187 * Range check input...
190 if (!uri
|| urilen
< 1 || !scheme
|| port
< 0)
195 return (HTTP_URI_BAD_ARGUMENTS
);
199 * Assemble the URI starting with the scheme...
202 end
= uri
+ urilen
- 1;
203 ptr
= http_copy_encode(uri
, scheme
, end
, NULL
, NULL
, 0);
206 goto assemble_overflow
;
208 if (!strcmp(scheme
, "mailto"))
211 * mailto: only has :, no //...
217 goto assemble_overflow
;
222 * Schemes other than mailto: all have //...
232 goto assemble_overflow
;
236 * Next the username and hostname, if any...
241 if (username
&& *username
)
244 * Add username@ first...
247 ptr
= http_copy_encode(ptr
, username
, end
, "/?#[]@", NULL
,
248 encoding
& HTTP_URI_CODING_USERNAME
);
251 goto assemble_overflow
;
256 goto assemble_overflow
;
260 * Then add the hostname. Since IPv6 is a particular pain to deal
261 * with, we have several special cases to deal with. If we get
262 * an IPv6 address with brackets around it, assume it is already in
263 * URI format. Since DNS-SD service names can sometimes look like
264 * raw IPv6 addresses, we specifically look for "._tcp" in the name,
268 if (host
[0] != '[' && strchr(host
, ':') && !strstr(host
, "._tcp"))
271 * We have a raw IPv6 address...
274 if (strchr(host
, '%'))
277 * We have a link-local address, add "[v1." prefix...
288 goto assemble_overflow
;
293 * We have a normal address, add "[" prefix...
299 goto assemble_overflow
;
303 * Copy the rest of the IPv6 address, and terminate with "]".
306 while (ptr
< end
&& *host
)
310 *ptr
++ = '+'; /* Convert zone separator */
318 goto assemble_overflow
;
323 goto assemble_overflow
;
328 * 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()' - Make a UUID URI conforming to RFC 4122.
472 * The buffer needs to be at least 46 bytes in size.
475 char * /* I - UUID string */
476 _httpAssembleUUID(const char *server
, /* I - Server name */
477 int port
, /* I - Port number */
478 const char *name
, /* I - Object name or NULL */
479 int number
, /* I - Object number or 0 */
480 char *buffer
, /* I - String buffer */
481 size_t bufsize
) /* I - Size of buffer */
483 char data
[1024]; /* Source string for MD5 */
484 _cups_md5_state_t md5state
; /* MD5 state */
485 unsigned char md5sum
[16]; /* MD5 digest/sum */
489 * Build a version 3 UUID conforming to RFC 4122.
491 * Start with the MD5 sum of the server, port, object name and
492 * number, and some random data on the end.
495 snprintf(data
, sizeof(data
), "%s:%d:%s:%d:%04x:%04x", server
,
496 port
, name
? name
: server
, number
,
497 (unsigned)CUPS_RAND() & 0xffff, (unsigned)CUPS_RAND() & 0xffff);
499 _cupsMD5Init(&md5state
);
500 _cupsMD5Append(&md5state
, (unsigned char *)data
, strlen(data
));
501 _cupsMD5Finish(&md5state
, md5sum
);
504 * Generate the UUID from the MD5...
507 snprintf(buffer
, bufsize
,
508 "urn:uuid:%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-"
509 "%02x%02x%02x%02x%02x%02x",
510 md5sum
[0], md5sum
[1], md5sum
[2], md5sum
[3], md5sum
[4], md5sum
[5],
511 (md5sum
[6] & 15) | 0x30, md5sum
[7], (md5sum
[8] & 0x3f) | 0x40,
512 md5sum
[9], md5sum
[10], md5sum
[11], md5sum
[12], md5sum
[13],
513 md5sum
[14], md5sum
[15]);
520 * 'httpDecode64()' - Base64-decode a string.
522 * This function is deprecated. Use the httpDecode64_2() function instead
523 * which provides buffer length arguments.
528 char * /* O - Decoded string */
529 httpDecode64(char *out
, /* I - String to write to */
530 const char *in
) /* I - String to read from */
532 int outlen
; /* Output buffer length */
536 * Use the old maximum buffer size for binary compatibility...
541 return (httpDecode64_2(out
, &outlen
, in
));
546 * 'httpDecode64_2()' - Base64-decode a string.
548 * @since CUPS 1.1.21/OS X 10.4@
551 char * /* O - Decoded string */
552 httpDecode64_2(char *out
, /* I - String to write to */
553 int *outlen
, /* IO - Size of output string */
554 const char *in
) /* I - String to read from */
556 int pos
, /* Bit position */
557 base64
; /* Value of this character */
558 char *outptr
, /* Output pointer */
559 *outend
; /* End of output buffer */
563 * Range check input...
566 if (!out
|| !outlen
|| *outlen
< 1 || !in
)
578 * Convert from base-64 to bytes...
581 for (outptr
= out
, outend
= out
+ *outlen
- 1, pos
= 0; *in
!= '\0'; in
++)
584 * Decode this character into a number from 0 to 63...
587 if (*in
>= 'A' && *in
<= 'Z')
589 else if (*in
>= 'a' && *in
<= 'z')
590 base64
= *in
- 'a' + 26;
591 else if (*in
>= '0' && *in
<= '9')
592 base64
= *in
- '0' + 52;
603 * Store the result in the appropriate chars...
610 *outptr
= base64
<< 2;
615 *outptr
++ |= (base64
>> 4) & 3;
617 *outptr
= (base64
<< 4) & 255;
622 *outptr
++ |= (base64
>> 2) & 15;
624 *outptr
= (base64
<< 6) & 255;
638 * Return the decoded string and size...
641 *outlen
= (int)(outptr
- out
);
648 * 'httpEncode64()' - Base64-encode a string.
650 * This function is deprecated. Use the httpEncode64_2() function instead
651 * which provides buffer length arguments.
656 char * /* O - Encoded string */
657 httpEncode64(char *out
, /* I - String to write to */
658 const char *in
) /* I - String to read from */
660 return (httpEncode64_2(out
, 512, in
, (int)strlen(in
)));
665 * 'httpEncode64_2()' - Base64-encode a string.
667 * @since CUPS 1.1.21/OS X 10.4@
670 char * /* O - Encoded string */
671 httpEncode64_2(char *out
, /* I - String to write to */
672 int outlen
, /* I - Size of output string */
673 const char *in
, /* I - String to read from */
674 int inlen
) /* I - Size of input string */
676 char *outptr
, /* Output pointer */
677 *outend
; /* End of output buffer */
678 static const char base64
[] = /* Base64 characters... */
680 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
681 "abcdefghijklmnopqrstuvwxyz"
688 * Range check input...
691 if (!out
|| outlen
< 1 || !in
)
695 * Convert bytes to base-64...
698 for (outptr
= out
, outend
= out
+ outlen
- 1; inlen
> 0; in
++, inlen
--)
701 * Encode the up to 3 characters as 4 Base64 numbers...
705 *outptr
++ = base64
[(in
[0] & 255) >> 2];
710 *outptr
++ = base64
[(((in
[0] & 255) << 4) | ((in
[1] & 255) >> 4)) & 63];
712 *outptr
++ = base64
[((in
[0] & 255) << 4) & 63];
729 *outptr
++ = base64
[(((in
[0] & 255) << 2) | ((in
[1] & 255) >> 6)) & 63];
731 *outptr
++ = base64
[((in
[0] & 255) << 2) & 63];
744 *outptr
++ = base64
[in
[0] & 63];
750 * Return the encoded string...
758 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
763 const char * /* O - Date/time string */
764 httpGetDateString(time_t t
) /* I - UNIX time */
766 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
769 return (httpGetDateString2(t
, cg
->http_date
, sizeof(cg
->http_date
)));
774 * 'httpGetDateString2()' - Get a formatted date/time string from a time value.
776 * @since CUPS 1.2/OS X 10.5@
779 const char * /* O - Date/time string */
780 httpGetDateString2(time_t t
, /* I - UNIX time */
781 char *s
, /* I - String buffer */
782 int slen
) /* I - Size of string buffer */
784 struct tm
*tdate
; /* UNIX date/time data */
789 snprintf(s
, slen
, "%s, %02d %s %d %02d:%02d:%02d GMT",
790 http_days
[tdate
->tm_wday
], tdate
->tm_mday
,
791 http_months
[tdate
->tm_mon
], tdate
->tm_year
+ 1900,
792 tdate
->tm_hour
, tdate
->tm_min
, tdate
->tm_sec
);
801 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
804 time_t /* O - UNIX time */
805 httpGetDateTime(const char *s
) /* I - Date/time string */
807 int i
; /* Looping var */
808 char mon
[16]; /* Abbreviated month name */
809 int day
, year
; /* Day of month and year */
810 int hour
, min
, sec
; /* Time */
811 int days
; /* Number of days since 1970 */
812 static const int normal_days
[] = /* Days to a month, normal years */
813 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
814 static const int leap_days
[] = /* Days to a month, leap years */
815 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 };
818 DEBUG_printf(("2httpGetDateTime(s=\"%s\")", s
));
821 * Extract the date and time from the formatted string...
824 if (sscanf(s
, "%*s%d%15s%d%d:%d:%d", &day
, mon
, &year
, &hour
, &min
, &sec
) < 6)
827 DEBUG_printf(("4httpGetDateTime: day=%d, mon=\"%s\", year=%d, hour=%d, "
828 "min=%d, sec=%d", day
, mon
, year
, hour
, min
, sec
));
831 * Convert the month name to a number from 0 to 11.
834 for (i
= 0; i
< 12; i
++)
835 if (!_cups_strcasecmp(mon
, http_months
[i
]))
841 DEBUG_printf(("4httpGetDateTime: i=%d", i
));
844 * Now convert the date and time to a UNIX time value in seconds since
845 * 1970. We can't use mktime() since the timezone may not be UTC but
846 * the date/time string *is* UTC.
849 if ((year
& 3) == 0 && ((year
% 100) != 0 || (year
% 400) == 0))
850 days
= leap_days
[i
] + day
- 1;
852 days
= normal_days
[i
] + day
- 1;
854 DEBUG_printf(("4httpGetDateTime: days=%d", days
));
856 days
+= (year
- 1970) * 365 + /* 365 days per year (normally) */
857 ((year
- 1) / 4 - 492) - /* + leap days */
858 ((year
- 1) / 100 - 19) + /* - 100 year days */
859 ((year
- 1) / 400 - 4); /* + 400 year days */
861 DEBUG_printf(("4httpGetDateTime: days=%d\n", days
));
863 return (days
* 86400 + hour
* 3600 + min
* 60 + sec
);
868 * 'httpSeparate()' - Separate a Universal Resource Identifier into its
871 * This function is deprecated; use the httpSeparateURI() function instead.
877 httpSeparate(const char *uri
, /* I - Universal Resource Identifier */
878 char *scheme
, /* O - Scheme [32] (http, https, etc.) */
879 char *username
, /* O - Username [1024] */
880 char *host
, /* O - Hostname [1024] */
881 int *port
, /* O - Port number to use */
882 char *resource
) /* O - Resource/filename [1024] */
884 httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, 32, username
,
885 HTTP_MAX_URI
, host
, HTTP_MAX_URI
, port
, resource
,
891 * 'httpSeparate2()' - Separate a Universal Resource Identifier into its
894 * This function is deprecated; use the httpSeparateURI() function instead.
896 * @since CUPS 1.1.21/OS X 10.4@
901 httpSeparate2(const char *uri
, /* I - Universal Resource Identifier */
902 char *scheme
, /* O - Scheme (http, https, etc.) */
903 int schemelen
, /* I - Size of scheme buffer */
904 char *username
, /* O - Username */
905 int usernamelen
, /* I - Size of username buffer */
906 char *host
, /* O - Hostname */
907 int hostlen
, /* I - Size of hostname buffer */
908 int *port
, /* O - Port number to use */
909 char *resource
, /* O - Resource/filename */
910 int resourcelen
) /* I - Size of resource buffer */
912 httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, schemelen
, username
,
913 usernamelen
, host
, hostlen
, port
, resource
, resourcelen
);
918 * 'httpSeparateURI()' - Separate a Universal Resource Identifier into its
921 * @since CUPS 1.2/OS X 10.5@
924 http_uri_status_t
/* O - Result of separation */
926 http_uri_coding_t decoding
, /* I - Decoding flags */
927 const char *uri
, /* I - Universal Resource Identifier */
928 char *scheme
, /* O - Scheme (http, https, etc.) */
929 int schemelen
, /* I - Size of scheme buffer */
930 char *username
, /* O - Username */
931 int usernamelen
, /* I - Size of username buffer */
932 char *host
, /* O - Hostname */
933 int hostlen
, /* I - Size of hostname buffer */
934 int *port
, /* O - Port number to use */
935 char *resource
, /* O - Resource/filename */
936 int resourcelen
) /* I - Size of resource buffer */
938 char *ptr
, /* Pointer into string... */
939 *end
; /* End of string */
940 const char *sep
; /* Separator character */
941 http_uri_status_t status
; /* Result of separation */
945 * Initialize everything to blank...
948 if (scheme
&& schemelen
> 0)
951 if (username
&& usernamelen
> 0)
954 if (host
&& hostlen
> 0)
960 if (resource
&& resourcelen
> 0)
964 * Range check input...
967 if (!uri
|| !port
|| !scheme
|| schemelen
<= 0 || !username
||
968 usernamelen
<= 0 || !host
|| hostlen
<= 0 || !resource
||
970 return (HTTP_URI_BAD_ARGUMENTS
);
973 return (HTTP_URI_BAD_URI
);
976 * Grab the scheme portion of the URI...
979 status
= HTTP_URI_OK
;
981 if (!strncmp(uri
, "//", 2))
984 * Workaround for HP IPP client bug...
987 strlcpy(scheme
, "ipp", schemelen
);
988 status
= HTTP_URI_MISSING_SCHEME
;
990 else if (*uri
== '/')
996 strlcpy(scheme
, "file", schemelen
);
997 status
= HTTP_URI_MISSING_SCHEME
;
1002 * Standard URI with scheme...
1005 for (ptr
= scheme
, end
= scheme
+ schemelen
- 1;
1006 *uri
&& *uri
!= ':' && ptr
< end
;)
1007 if (strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1008 "abcdefghijklmnopqrstuvwxyz"
1009 "0123456789-+.", *uri
) != NULL
)
1019 return (HTTP_URI_BAD_SCHEME
);
1026 * Set the default port number...
1029 if (!strcmp(scheme
, "http"))
1031 else if (!strcmp(scheme
, "https"))
1033 else if (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps"))
1035 else if (!_cups_strcasecmp(scheme
, "lpd"))
1037 else if (!strcmp(scheme
, "socket")) /* Not yet registered with IANA... */
1039 else if (strcmp(scheme
, "file") && strcmp(scheme
, "mailto"))
1040 status
= HTTP_URI_UNKNOWN_SCHEME
;
1043 * Now see if we have a hostname...
1046 if (!strncmp(uri
, "//", 2))
1049 * Yes, extract it...
1055 * Grab the username, if any...
1058 if ((sep
= strpbrk(uri
, "@/")) != NULL
&& *sep
== '@')
1061 * Get a username:password combo...
1064 uri
= http_copy_decode(username
, uri
, usernamelen
, "@",
1065 decoding
& HTTP_URI_CODING_USERNAME
);
1070 return (HTTP_URI_BAD_USERNAME
);
1077 * Then the hostname/IP address...
1083 * Grab IPv6 address...
1087 if (!strncmp(uri
, "v1.", 3))
1088 uri
+= 3; /* Skip IPvN leader... */
1090 uri
= http_copy_decode(host
, uri
, hostlen
, "]",
1091 decoding
& HTTP_URI_CODING_HOSTNAME
);
1096 return (HTTP_URI_BAD_HOSTNAME
);
1106 return (HTTP_URI_BAD_HOSTNAME
);
1111 for (ptr
= host
; *ptr
; ptr
++)
1115 * Convert zone separator to % and stop here...
1121 else if (*ptr
!= ':' && *ptr
!= '.' && !isxdigit(*ptr
& 255))
1124 return (HTTP_URI_BAD_HOSTNAME
);
1130 * Validate the hostname or IPv4 address first...
1133 for (ptr
= (char *)uri
; *ptr
; ptr
++)
1134 if (strchr(":?/", *ptr
))
1136 else if (!strchr("abcdefghijklmnopqrstuvwxyz"
1137 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1141 "!$&'()*+,;=\\", *ptr
))
1144 return (HTTP_URI_BAD_HOSTNAME
);
1148 * Then copy the hostname or IPv4 address to the buffer...
1151 uri
= http_copy_decode(host
, uri
, hostlen
, ":?/",
1152 decoding
& HTTP_URI_CODING_HOSTNAME
);
1157 return (HTTP_URI_BAD_HOSTNAME
);
1162 * Validate hostname for file scheme - only empty and localhost are
1166 if (!strcmp(scheme
, "file") && strcmp(host
, "localhost") && host
[0])
1169 return (HTTP_URI_BAD_HOSTNAME
);
1173 * See if we have a port number...
1179 * Yes, collect the port number...
1182 if (!isdigit(uri
[1] & 255))
1185 return (HTTP_URI_BAD_PORT
);
1188 *port
= strtol(uri
+ 1, (char **)&uri
, 10);
1190 if (*uri
!= '/' && *uri
)
1193 return (HTTP_URI_BAD_PORT
);
1199 * The remaining portion is the resource string...
1202 if (*uri
== '?' || !*uri
)
1205 * Hostname but no path...
1208 status
= HTTP_URI_MISSING_RESOURCE
;
1212 * Copy any query string...
1216 uri
= http_copy_decode(resource
+ 1, uri
, resourcelen
- 1, NULL
,
1217 decoding
& HTTP_URI_CODING_QUERY
);
1223 uri
= http_copy_decode(resource
, uri
, resourcelen
, "?",
1224 decoding
& HTTP_URI_CODING_RESOURCE
);
1226 if (uri
&& *uri
== '?')
1229 * Concatenate any query string...
1232 char *resptr
= resource
+ strlen(resource
);
1234 uri
= http_copy_decode(resptr
, uri
, resourcelen
- (int)(resptr
- resource
),
1235 NULL
, decoding
& HTTP_URI_CODING_QUERY
);
1242 return (HTTP_URI_BAD_RESOURCE
);
1246 * Return the URI separation status...
1254 * 'httpStatus()' - Return a short string describing a HTTP status code.
1256 * The returned string is localized to the current POSIX locale and is based
1257 * on the status strings defined in RFC 2616.
1260 const char * /* O - Localized status string */
1261 httpStatus(http_status_t status
) /* I - HTTP status code */
1263 const char *s
; /* Status string */
1264 _cups_globals_t
*cg
= _cupsGlobals(); /* Global data */
1267 if (!cg
->lang_default
)
1268 cg
->lang_default
= cupsLangDefault();
1272 case HTTP_CONTINUE
:
1275 case HTTP_SWITCHING_PROTOCOLS
:
1276 s
= _("Switching Protocols");
1284 case HTTP_ACCEPTED
:
1287 case HTTP_NO_CONTENT
:
1288 s
= _("No Content");
1290 case HTTP_MOVED_PERMANENTLY
:
1291 s
= _("Moved Permanently");
1293 case HTTP_SEE_OTHER
:
1296 case HTTP_NOT_MODIFIED
:
1297 s
= _("Not Modified");
1299 case HTTP_BAD_REQUEST
:
1300 s
= _("Bad Request");
1302 case HTTP_UNAUTHORIZED
:
1303 case HTTP_AUTHORIZATION_CANCELED
:
1304 s
= _("Unauthorized");
1306 case HTTP_FORBIDDEN
:
1309 case HTTP_NOT_FOUND
:
1312 case HTTP_REQUEST_TOO_LARGE
:
1313 s
= _("Request Entity Too Large");
1315 case HTTP_URI_TOO_LONG
:
1316 s
= _("URI Too Long");
1318 case HTTP_UPGRADE_REQUIRED
:
1319 s
= _("Upgrade Required");
1321 case HTTP_NOT_IMPLEMENTED
:
1322 s
= _("Not Implemented");
1324 case HTTP_NOT_SUPPORTED
:
1325 s
= _("Not Supported");
1327 case HTTP_EXPECTATION_FAILED
:
1328 s
= _("Expectation Failed");
1330 case HTTP_SERVICE_UNAVAILABLE
:
1331 s
= _("Service Unavailable");
1333 case HTTP_SERVER_ERROR
:
1334 s
= _("Internal Server Error");
1336 case HTTP_PKI_ERROR
:
1337 s
= _("SSL/TLS Negotiation Error");
1339 case HTTP_WEBIF_DISABLED
:
1340 s
= _("Web Interface is Disabled");
1348 return (_cupsLangString(cg
->lang_default
, s
));
1352 #ifndef HAVE_HSTRERROR
1354 * '_cups_hstrerror()' - hstrerror() emulation function for Solaris and others.
1357 const char * /* O - Error string */
1358 _cups_hstrerror(int error
) /* I - Error number */
1360 static const char * const errors
[] = /* Error strings */
1365 "Unrecoverable lookup error.",
1366 "No data associated with name."
1370 if (error
< 0 || error
> 4)
1371 return ("Unknown hostname lookup error.");
1373 return (errors
[error
]);
1375 #endif /* !HAVE_HSTRERROR */
1379 * '_httpDecodeURI()' - Percent-decode a HTTP request URI.
1382 char * /* O - Decoded URI or NULL on error */
1383 _httpDecodeURI(char *dst
, /* I - Destination buffer */
1384 const char *src
, /* I - Source URI */
1385 size_t dstsize
) /* I - Size of destination buffer */
1387 if (http_copy_decode(dst
, src
, (int)dstsize
, NULL
, 1))
1395 * '_httpEncodeURI()' - Percent-encode a HTTP request URI.
1398 char * /* O - Encoded URI */
1399 _httpEncodeURI(char *dst
, /* I - Destination buffer */
1400 const char *src
, /* I - Source URI */
1401 size_t dstsize
) /* I - Size of destination buffer */
1403 http_copy_encode(dst
, src
, dst
+ dstsize
- 1, NULL
, NULL
, 1);
1409 * '_httpResolveURI()' - Resolve a DNS-SD URI.
1412 const char * /* O - Resolved URI */
1414 const char *uri
, /* I - DNS-SD URI */
1415 char *resolved_uri
, /* I - Buffer for resolved URI */
1416 size_t resolved_size
, /* I - Size of URI buffer */
1417 int options
, /* I - Resolve options */
1418 int (*cb
)(void *context
), /* I - Continue callback function */
1419 void *context
) /* I - Context pointer for callback */
1421 char scheme
[32], /* URI components... */
1427 http_uri_status_t status
; /* URI decode status */
1431 DEBUG_printf(("4_httpResolveURI(uri=\"%s\", resolved_uri=%p, "
1432 "resolved_size=" CUPS_LLFMT
")", uri
, resolved_uri
,
1433 CUPS_LLCAST resolved_size
));
1436 * Get the device URI...
1440 if ((status
= httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
,
1441 sizeof(scheme
), userpass
, sizeof(userpass
),
1442 hostname
, sizeof(hostname
), &port
, resource
,
1443 sizeof(resource
))) < HTTP_URI_OK
)
1445 if (httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
,
1446 sizeof(scheme
), userpass
, sizeof(userpass
),
1447 hostname
, sizeof(hostname
), &port
, resource
,
1448 sizeof(resource
)) < HTTP_URI_OK
)
1451 if (options
& _HTTP_RESOLVE_STDERR
)
1452 _cupsLangPrintFilter(stderr
, "ERROR", _("Bad device-uri \"%s\"."), uri
);
1454 DEBUG_printf(("6_httpResolveURI: httpSeparateURI returned %d!", status
));
1455 DEBUG_puts("5_httpResolveURI: Returning NULL");
1460 * Resolve it as needed...
1463 if (strstr(hostname
, "._tcp"))
1465 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
1466 char *regtype
, /* Pointer to type in hostname */
1467 *domain
; /* Pointer to domain in hostname */
1468 _http_uribuf_t uribuf
; /* URI buffer */
1469 int offline
= 0; /* offline-report state set? */
1472 # pragma comment(lib, "dnssd.lib")
1474 DNSServiceRef ref
, /* DNS-SD master service reference */
1475 domainref
, /* DNS-SD service reference for domain */
1476 localref
; /* DNS-SD service reference for .local */
1477 int domainsent
= 0; /* Send the domain resolve? */
1479 struct pollfd polldata
; /* Polling data */
1480 # else /* select() */
1481 fd_set input_set
; /* Input set for select() */
1482 struct timeval stimeout
; /* Timeout value for select() */
1483 # endif /* HAVE_POLL */
1484 # elif defined(HAVE_AVAHI)
1485 AvahiClient
*client
; /* Client information */
1486 int error
; /* Status */
1487 # endif /* HAVE_DNSSD */
1489 if (options
& _HTTP_RESOLVE_STDERR
)
1490 fprintf(stderr
, "DEBUG: Resolving \"%s\"...\n", hostname
);
1493 * Separate the hostname into service name, registration type, and domain...
1496 for (regtype
= strstr(hostname
, "._tcp") - 2;
1499 if (regtype
[0] == '.' && regtype
[1] == '_')
1502 * Found ._servicetype in front of ._tcp...
1509 if (regtype
<= hostname
)
1511 DEBUG_puts("5_httpResolveURI: Bad hostname, returning NULL");
1515 for (domain
= strchr(regtype
, '.');
1517 domain
= strchr(domain
+ 1, '.'))
1518 if (domain
[1] != '_')
1524 uribuf
.buffer
= resolved_uri
;
1525 uribuf
.bufsize
= resolved_size
;
1526 uribuf
.options
= options
;
1527 uribuf
.resource
= resource
;
1529 resolved_uri
[0] = '\0';
1531 DEBUG_printf(("6_httpResolveURI: Resolving hostname=\"%s\", regtype=\"%s\", "
1532 "domain=\"%s\"\n", hostname
, regtype
, domain
));
1533 if (options
& _HTTP_RESOLVE_STDERR
)
1535 fputs("STATE: +connecting-to-device\n", stderr
);
1536 fprintf(stderr
, "DEBUG: Resolving \"%s\", regtype=\"%s\", "
1537 "domain=\"local.\"...\n", hostname
, regtype
);
1543 if (DNSServiceCreateConnection(&ref
) == kDNSServiceErr_NoError
)
1546 if (DNSServiceResolve(&localref
,
1547 kDNSServiceFlagsShareConnection
, 0, hostname
, regtype
,
1548 "local.", http_resolve_cb
,
1549 &uribuf
) == kDNSServiceErr_NoError
)
1551 int fds
; /* Number of ready descriptors */
1552 time_t timeout
, /* Poll timeout */
1553 start_time
= time(NULL
),/* Start time */
1554 end_time
= start_time
+ 90;
1557 while (time(NULL
) < end_time
)
1559 if (options
& _HTTP_RESOLVE_STDERR
)
1560 _cupsLangPrintFilter(stderr
, "INFO", _("Looking for printer."));
1562 if (cb
&& !(*cb
)(context
))
1564 DEBUG_puts("5_httpResolveURI: callback returned 0 (stop)");
1569 * Wakeup every 2 seconds to emit a "looking for printer" message...
1572 if ((timeout
= end_time
- time(NULL
)) > 2)
1576 polldata
.fd
= DNSServiceRefSockFD(ref
);
1577 polldata
.events
= POLLIN
;
1579 fds
= poll(&polldata
, 1, 1000 * timeout
);
1581 # else /* select() */
1582 FD_ZERO(&input_set
);
1583 FD_SET(DNSServiceRefSockFD(ref
), &input_set
);
1586 stimeout
.tv_sec
= (long)timeout
;
1588 stimeout
.tv_sec
= timeout
;
1590 stimeout
.tv_usec
= 0;
1592 fds
= select(DNSServiceRefSockFD(ref
)+1, &input_set
, NULL
, NULL
,
1594 # endif /* HAVE_POLL */
1598 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1600 DEBUG_printf(("5_httpResolveURI: poll error: %s", strerror(errno
)));
1607 * Wait 2 seconds for a response to the local resolve; if nothing
1608 * comes in, do an additional domain resolution...
1611 if (domainsent
== 0 && domain
&& _cups_strcasecmp(domain
, "local."))
1613 if (options
& _HTTP_RESOLVE_STDERR
)
1615 "DEBUG: Resolving \"%s\", regtype=\"%s\", "
1616 "domain=\"%s\"...\n", hostname
, regtype
,
1617 domain
? domain
: "");
1620 if (DNSServiceResolve(&domainref
,
1621 kDNSServiceFlagsShareConnection
,
1622 0, hostname
, regtype
, domain
,
1624 &uribuf
) == kDNSServiceErr_NoError
)
1629 * If it hasn't resolved within 5 seconds set the offline-report
1630 * printer-state-reason...
1633 if ((options
& _HTTP_RESOLVE_STDERR
) && offline
== 0 &&
1634 time(NULL
) > (start_time
+ 5))
1636 fputs("STATE: +offline-report\n", stderr
);
1642 if (DNSServiceProcessResult(ref
) == kDNSServiceErr_NoError
)
1651 DNSServiceRefDeallocate(domainref
);
1653 DNSServiceRefDeallocate(localref
);
1656 DNSServiceRefDeallocate(ref
);
1658 # else /* HAVE_AVAHI */
1659 if ((uribuf
.poll
= avahi_simple_poll_new()) != NULL
)
1661 avahi_simple_poll_set_func(uribuf
.poll
, http_poll_cb
, NULL
);
1663 if ((client
= avahi_client_new(avahi_simple_poll_get(uribuf
.poll
),
1665 &uribuf
, &error
)) != NULL
)
1667 if (avahi_service_resolver_new(client
, AVAHI_IF_UNSPEC
,
1668 AVAHI_PROTO_UNSPEC
, hostname
,
1669 regtype
, "local.", AVAHI_PROTO_UNSPEC
, 0,
1670 http_resolve_cb
, &uribuf
) != NULL
)
1672 time_t start_time
= time(NULL
),
1674 end_time
= start_time
+ 90;
1676 int pstatus
; /* Poll status */
1678 pstatus
= avahi_simple_poll_iterate(uribuf
.poll
, 2000);
1680 if (pstatus
== 0 && !resolved_uri
[0] && domain
&&
1681 _cups_strcasecmp(domain
, "local."))
1684 * Resolve for .local hasn't returned anything, try the listed
1688 avahi_service_resolver_new(client
, AVAHI_IF_UNSPEC
,
1689 AVAHI_PROTO_UNSPEC
, hostname
,
1690 regtype
, domain
, AVAHI_PROTO_UNSPEC
, 0,
1691 http_resolve_cb
, &uribuf
);
1694 while (!pstatus
&& !resolved_uri
[0] && time(NULL
) < end_time
)
1696 if ((pstatus
= avahi_simple_poll_iterate(uribuf
.poll
, 2000)) != 0)
1700 * If it hasn't resolved within 5 seconds set the offline-report
1701 * printer-state-reason...
1704 if ((options
& _HTTP_RESOLVE_STDERR
) && offline
== 0 &&
1705 time(NULL
) > (start_time
+ 5))
1707 fputs("STATE: +offline-report\n", stderr
);
1713 * Collect the result (if we got one).
1716 if (resolved_uri
[0])
1720 avahi_client_free(client
);
1723 avahi_simple_poll_free(uribuf
.poll
);
1725 # endif /* HAVE_DNSSD */
1727 if (options
& _HTTP_RESOLVE_STDERR
)
1731 fprintf(stderr
, "DEBUG: Resolved as \"%s\"...\n", uri
);
1732 fputs("STATE: -connecting-to-device,offline-report\n", stderr
);
1736 fputs("DEBUG: Unable to resolve URI\n", stderr
);
1737 fputs("STATE: -connecting-to-device\n", stderr
);
1741 #else /* HAVE_DNSSD || HAVE_AVAHI */
1743 * No DNS-SD support...
1747 #endif /* HAVE_DNSSD || HAVE_AVAHI */
1749 if ((options
& _HTTP_RESOLVE_STDERR
) && !uri
)
1750 _cupsLangPrintFilter(stderr
, "ERROR", _("Unable to find printer."));
1755 * Nothing more to do...
1758 strlcpy(resolved_uri
, uri
, resolved_size
);
1762 DEBUG_printf(("5_httpResolveURI: Returning \"%s\"", uri
));
1770 * 'http_client_cb()' - Client callback for resolving URI.
1775 AvahiClient
*client
, /* I - Client information */
1776 AvahiClientState state
, /* I - Current state */
1777 void *context
) /* I - Pointer to URI buffer */
1779 DEBUG_printf(("7http_client_cb(client=%p, state=%d, context=%p)", client
,
1783 * If the connection drops, quit.
1786 if (state
== AVAHI_CLIENT_FAILURE
)
1788 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
1791 avahi_simple_poll_quit(uribuf
->poll
);
1794 #endif /* HAVE_AVAHI */
1798 * 'http_copy_decode()' - Copy and decode a URI.
1801 static const char * /* O - New source pointer or NULL on error */
1802 http_copy_decode(char *dst
, /* O - Destination buffer */
1803 const char *src
, /* I - Source pointer */
1804 int dstsize
, /* I - Destination size */
1805 const char *term
, /* I - Terminating characters */
1806 int decode
) /* I - Decode %-encoded values */
1808 char *ptr
, /* Pointer into buffer */
1809 *end
; /* End of buffer */
1810 int quoted
; /* Quoted character */
1814 * Copy the src to the destination until we hit a terminating character
1815 * or the end of the string.
1818 for (ptr
= dst
, end
= dst
+ dstsize
- 1;
1819 *src
&& (!term
|| !strchr(term
, *src
));
1823 if (*src
== '%' && decode
)
1825 if (isxdigit(src
[1] & 255) && isxdigit(src
[2] & 255))
1828 * Grab a hex-encoded character...
1833 quoted
= (tolower(*src
) - 'a' + 10) << 4;
1835 quoted
= (*src
- '0') << 4;
1839 quoted
|= tolower(*src
) - 'a' + 10;
1841 quoted
|= *src
- '0';
1848 * Bad hex-encoded character...
1866 * 'http_copy_encode()' - Copy and encode a URI.
1869 static char * /* O - End of current URI */
1870 http_copy_encode(char *dst
, /* O - Destination buffer */
1871 const char *src
, /* I - Source pointer */
1872 char *dstend
, /* I - End of destination buffer */
1873 const char *reserved
, /* I - Extra reserved characters */
1874 const char *term
, /* I - Terminating characters */
1875 int encode
) /* I - %-encode reserved chars? */
1877 static const char hex
[] = "0123456789ABCDEF";
1880 while (*src
&& dst
< dstend
)
1882 if (term
&& *src
== *term
)
1885 if (encode
&& (*src
== '%' || *src
<= ' ' || *src
& 128 ||
1886 (reserved
&& strchr(reserved
, *src
))))
1889 * Hex encode reserved characters...
1892 if ((dst
+ 2) >= dstend
)
1896 *dst
++ = hex
[(*src
>> 4) & 15];
1897 *dst
++ = hex
[*src
& 15];
1916 * 'http_resolve_cb()' - Build a device URI for the given service name.
1919 static void DNSSD_API
1921 DNSServiceRef sdRef
, /* I - Service reference */
1922 DNSServiceFlags flags
, /* I - Results flags */
1923 uint32_t interfaceIndex
, /* I - Interface number */
1924 DNSServiceErrorType errorCode
, /* I - Error, if any */
1925 const char *fullName
, /* I - Full service name */
1926 const char *hostTarget
, /* I - Hostname */
1927 uint16_t port
, /* I - Port number */
1928 uint16_t txtLen
, /* I - Length of TXT record */
1929 const unsigned char *txtRecord
, /* I - TXT record data */
1930 void *context
) /* I - Pointer to URI buffer */
1932 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
1934 const char *scheme
, /* URI scheme */
1935 *hostptr
, /* Pointer into hostTarget */
1936 *reskey
, /* "rp" or "rfo" */
1937 *resdefault
; /* Default path */
1938 char resource
[257], /* Remote path */
1939 fqdn
[256]; /* FQDN of the .local name */
1940 const void *value
; /* Value from TXT record */
1941 uint8_t valueLen
; /* Length of value */
1944 DEBUG_printf(("7http_resolve_cb(sdRef=%p, flags=%x, interfaceIndex=%u, "
1945 "errorCode=%d, fullName=\"%s\", hostTarget=\"%s\", port=%u, "
1946 "txtLen=%u, txtRecord=%p, context=%p)", sdRef
, flags
,
1947 interfaceIndex
, errorCode
, fullName
, hostTarget
, port
, txtLen
,
1948 txtRecord
, context
));
1951 * Figure out the scheme from the full name...
1954 if (strstr(fullName
, "._ipps") || strstr(fullName
, "._ipp-tls"))
1956 else if (strstr(fullName
, "._ipp") || strstr(fullName
, "._fax-ipp"))
1958 else if (strstr(fullName
, "._http."))
1960 else if (strstr(fullName
, "._https."))
1962 else if (strstr(fullName
, "._printer."))
1964 else if (strstr(fullName
, "._pdl-datastream."))
1967 scheme
= "riousbprint";
1970 * Extract the "remote printer" key from the TXT record...
1973 if ((uribuf
->options
& _HTTP_RESOLVE_FAXOUT
) &&
1974 (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")))
1977 resdefault
= "/ipp/faxout";
1985 if ((value
= TXTRecordGetValuePtr(txtLen
, txtRecord
, reskey
,
1986 &valueLen
)) != NULL
)
1988 if (((char *)value
)[0] == '/')
1991 * Value (incorrectly) has a leading slash already...
1994 memcpy(resource
, value
, valueLen
);
1995 resource
[valueLen
] = '\0';
2000 * Convert to resource by concatenating with a leading "/"...
2004 memcpy(resource
+ 1, value
, valueLen
);
2005 resource
[valueLen
+ 1] = '\0';
2011 * Use the default value...
2014 strlcpy(resource
, resdefault
, sizeof(resource
));
2018 * Lookup the FQDN if needed...
2021 if ((uribuf
->options
& _HTTP_RESOLVE_FQDN
) &&
2022 (hostptr
= hostTarget
+ strlen(hostTarget
) - 7) > hostTarget
&&
2023 !_cups_strcasecmp(hostptr
, ".local."))
2026 * OK, we got a .local name but the caller needs a real domain. Start by
2027 * getting the IP address of the .local name and then do reverse-lookups...
2030 http_addrlist_t
*addrlist
, /* List of addresses */
2031 *addr
; /* Current address */
2033 DEBUG_printf(("8http_resolve_cb: Looking up \"%s\".", hostTarget
));
2035 snprintf(fqdn
, sizeof(fqdn
), "%d", ntohs(port
));
2036 if ((addrlist
= httpAddrGetList(hostTarget
, AF_UNSPEC
, fqdn
)) != NULL
)
2038 for (addr
= addrlist
; addr
; addr
= addr
->next
)
2040 int error
= getnameinfo(&(addr
->addr
.addr
),
2041 httpAddrLength(&(addr
->addr
)),
2042 fqdn
, sizeof(fqdn
), NULL
, 0, NI_NAMEREQD
);
2046 DEBUG_printf(("8http_resolve_cb: Found \"%s\".", fqdn
));
2048 if ((hostptr
= fqdn
+ strlen(fqdn
) - 6) <= fqdn
||
2049 _cups_strcasecmp(hostptr
, ".local"))
2057 DEBUG_printf(("8http_resolve_cb: \"%s\" did not resolve: %d",
2058 httpAddrString(&(addr
->addr
), fqdn
, sizeof(fqdn
)),
2066 * Assemble the final device URI...
2069 if ((!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")) &&
2070 !strcmp(uribuf
->resource
, "/cups"))
2071 httpAssembleURIf(HTTP_URI_CODING_ALL
, uribuf
->buffer
, uribuf
->bufsize
,
2072 scheme
, NULL
, hostTarget
, ntohs(port
), "%s?snmp=false",
2075 httpAssembleURI(HTTP_URI_CODING_ALL
, uribuf
->buffer
, uribuf
->bufsize
,
2076 scheme
, NULL
, hostTarget
, ntohs(port
), resource
);
2078 DEBUG_printf(("8http_resolve_cb: Resolved URI is \"%s\"...", uribuf
->buffer
));
2081 #elif defined(HAVE_AVAHI)
2083 * 'http_poll_cb()' - Wait for input on the specified file descriptors.
2085 * Note: This function is needed because avahi_simple_poll_iterate is broken
2086 * and always uses a timeout of 0 (!) milliseconds.
2087 * (Avahi Ticket #364)
2090 static int /* O - Number of file descriptors matching */
2092 struct pollfd
*pollfds
, /* I - File descriptors */
2093 unsigned int num_pollfds
, /* I - Number of file descriptors */
2094 int timeout
, /* I - Timeout in milliseconds (used) */
2095 void *context
) /* I - User data (unused) */
2100 return (poll(pollfds
, num_pollfds
, 2000));
2105 * 'http_resolve_cb()' - Build a device URI for the given service name.
2110 AvahiServiceResolver
*resolver
, /* I - Resolver (unused) */
2111 AvahiIfIndex interface
, /* I - Interface index (unused) */
2112 AvahiProtocol protocol
, /* I - Network protocol (unused) */
2113 AvahiResolverEvent event
, /* I - Event (found, etc.) */
2114 const char *name
, /* I - Service name */
2115 const char *type
, /* I - Registration type */
2116 const char *domain
, /* I - Domain (unused) */
2117 const char *hostTarget
, /* I - Hostname */
2118 const AvahiAddress
*address
, /* I - Address (unused) */
2119 uint16_t port
, /* I - Port number */
2120 AvahiStringList
*txt
, /* I - TXT record */
2121 AvahiLookupResultFlags flags
, /* I - Lookup flags (unused) */
2122 void *context
) /* I - Pointer to URI buffer */
2124 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
2126 const char *scheme
, /* URI scheme */
2127 *hostptr
, /* Pointer into hostTarget */
2128 *reskey
, /* "rp" or "rfo" */
2129 *resdefault
; /* Default path */
2130 char resource
[257], /* Remote path */
2131 fqdn
[256]; /* FQDN of the .local name */
2132 AvahiStringList
*pair
; /* Current TXT record key/value pair */
2133 char *value
; /* Value for "rp" key */
2134 size_t valueLen
= 0; /* Length of "rp" key */
2137 DEBUG_printf(("7http_resolve_cb(resolver=%p, "
2138 "interface=%d, protocol=%d, event=%d, name=\"%s\", "
2139 "type=\"%s\", domain=\"%s\", hostTarget=\"%s\", address=%p, "
2140 "port=%d, txt=%p, flags=%d, context=%p)",
2141 resolver
, interface
, protocol
, event
, name
, type
, domain
,
2142 hostTarget
, address
, port
, txt
, flags
, context
));
2144 if (event
!= AVAHI_RESOLVER_FOUND
)
2146 avahi_service_resolver_free(resolver
);
2147 avahi_simple_poll_quit(uribuf
->poll
);
2152 * Figure out the scheme from the full name...
2155 if (strstr(type
, "_ipp."))
2157 else if (strstr(type
, "_printer."))
2159 else if (strstr(type
, "_pdl-datastream."))
2162 scheme
= "riousbprint";
2164 if (!strncmp(type
, "_ipps.", 6) || !strncmp(type
, "_ipp-tls.", 9))
2166 else if (!strncmp(type
, "_ipp.", 5) || !strncmp(type
, "_fax-ipp.", 9))
2168 else if (!strncmp(type
, "_http.", 6))
2170 else if (!strncmp(type
, "_https.", 7))
2172 else if (!strncmp(type
, "_printer.", 9))
2174 else if (!strncmp(type
, "_pdl-datastream.", 16))
2178 avahi_service_resolver_free(resolver
);
2179 avahi_simple_poll_quit(uribuf
->poll
);
2184 * Extract the remote resource key from the TXT record...
2187 if ((uribuf
->options
& _HTTP_RESOLVE_FAXOUT
) &&
2188 (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")))
2191 resdefault
= "/ipp/faxout";
2199 if ((pair
= avahi_string_list_find(txt
, reskey
)) != NULL
)
2201 avahi_string_list_get_pair(pair
, NULL
, &value
, &valueLen
);
2203 if (value
[0] == '/')
2206 * Value (incorrectly) has a leading slash already...
2209 memcpy(resource
, value
, valueLen
);
2210 resource
[valueLen
] = '\0';
2215 * Convert to resource by concatenating with a leading "/"...
2219 memcpy(resource
+ 1, value
, valueLen
);
2220 resource
[valueLen
+ 1] = '\0';
2226 * Use the default value...
2229 strlcpy(resource
, resdefault
, sizeof(resource
));
2233 * Lookup the FQDN if needed...
2236 if ((uribuf
->options
& _HTTP_RESOLVE_FQDN
) &&
2237 (hostptr
= hostTarget
+ strlen(hostTarget
) - 6) > hostTarget
&&
2238 !_cups_strcasecmp(hostptr
, ".local"))
2241 * OK, we got a .local name but the caller needs a real domain. Start by
2242 * getting the IP address of the .local name and then do reverse-lookups...
2245 http_addrlist_t
*addrlist
, /* List of addresses */
2246 *addr
; /* Current address */
2248 DEBUG_printf(("8http_resolve_cb: Looking up \"%s\".", hostTarget
));
2250 snprintf(fqdn
, sizeof(fqdn
), "%d", ntohs(port
));
2251 if ((addrlist
= httpAddrGetList(hostTarget
, AF_UNSPEC
, fqdn
)) != NULL
)
2253 for (addr
= addrlist
; addr
; addr
= addr
->next
)
2255 int error
= getnameinfo(&(addr
->addr
.addr
),
2256 httpAddrLength(&(addr
->addr
)),
2257 fqdn
, sizeof(fqdn
), NULL
, 0, NI_NAMEREQD
);
2261 DEBUG_printf(("8http_resolve_cb: Found \"%s\".", fqdn
));
2263 if ((hostptr
= fqdn
+ strlen(fqdn
) - 6) <= fqdn
||
2264 _cups_strcasecmp(hostptr
, ".local"))
2272 DEBUG_printf(("8http_resolve_cb: \"%s\" did not resolve: %d",
2273 httpAddrString(&(addr
->addr
), fqdn
, sizeof(fqdn
)),
2281 * Assemble the final device URI using the resolved hostname...
2284 httpAssembleURI(HTTP_URI_CODING_ALL
, uribuf
->buffer
, uribuf
->bufsize
, scheme
,
2285 NULL
, hostTarget
, port
, resource
);
2286 DEBUG_printf(("8http_resolve_cb: Resolved URI is \"%s\".", uribuf
->buffer
));
2288 avahi_simple_poll_quit(uribuf
->poll
);
2290 #endif /* HAVE_DNSSD */
2294 * End of "$Id: http-support.c 7952 2008-09-17 00:56:20Z mike $".