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 */
92 static const char * const http_days
[7] =
102 static const char * const http_months
[12] =
123 static const char *http_copy_decode(char *dst
, const char *src
,
124 int dstsize
, const char *term
,
126 static char *http_copy_encode(char *dst
, const char *src
,
127 char *dstend
, const char *reserved
,
128 const char *term
, int encode
);
130 static void DNSSD_API
http_resolve_cb(DNSServiceRef sdRef
,
131 DNSServiceFlags flags
,
132 uint32_t interfaceIndex
,
133 DNSServiceErrorType errorCode
,
134 const char *fullName
,
135 const char *hostTarget
,
136 uint16_t port
, uint16_t txtLen
,
137 const unsigned char *txtRecord
,
139 #endif /* HAVE_DNSSD */
142 static void http_client_cb(AvahiClient
*client
,
143 AvahiClientState state
, void *simple_poll
);
144 static int http_poll_cb(struct pollfd
*pollfds
, unsigned int num_pollfds
,
145 int timeout
, void *context
);
146 static void http_resolve_cb(AvahiServiceResolver
*resolver
,
147 AvahiIfIndex interface
,
148 AvahiProtocol protocol
,
149 AvahiResolverEvent event
,
150 const char *name
, const char *type
,
151 const char *domain
, const char *host_name
,
152 const AvahiAddress
*address
, uint16_t port
,
153 AvahiStringList
*txt
,
154 AvahiLookupResultFlags flags
, void *context
);
155 #endif /* HAVE_AVAHI */
159 * 'httpAssembleURI()' - Assemble a uniform resource identifier from its
162 * This function escapes reserved characters in the URI depending on the
163 * value of the "encoding" argument. You should use this function in
164 * place of traditional string functions whenever you need to create a
167 * @since CUPS 1.2/OS X 10.5@
170 http_uri_status_t
/* O - URI status */
172 http_uri_coding_t encoding
, /* I - Encoding flags */
173 char *uri
, /* I - URI buffer */
174 int urilen
, /* I - Size of URI buffer */
175 const char *scheme
, /* I - Scheme name */
176 const char *username
, /* I - Username */
177 const char *host
, /* I - Hostname or address */
178 int port
, /* I - Port number */
179 const char *resource
) /* I - Resource */
181 char *ptr
, /* Pointer into URI buffer */
182 *end
; /* End of URI buffer */
186 * Range check input...
189 if (!uri
|| urilen
< 1 || !scheme
|| port
< 0)
194 return (HTTP_URI_BAD_ARGUMENTS
);
198 * Assemble the URI starting with the scheme...
201 end
= uri
+ urilen
- 1;
202 ptr
= http_copy_encode(uri
, scheme
, end
, NULL
, NULL
, 0);
205 goto assemble_overflow
;
207 if (!strcmp(scheme
, "mailto"))
210 * mailto: only has :, no //...
216 goto assemble_overflow
;
221 * Schemes other than mailto: all have //...
231 goto assemble_overflow
;
235 * Next the username and hostname, if any...
240 if (username
&& *username
)
243 * Add username@ first...
246 ptr
= http_copy_encode(ptr
, username
, end
, "/?#[]@", NULL
,
247 encoding
& HTTP_URI_CODING_USERNAME
);
250 goto assemble_overflow
;
255 goto assemble_overflow
;
259 * Then add the hostname. Since IPv6 is a particular pain to deal
260 * with, we have several special cases to deal with. If we get
261 * an IPv6 address with brackets around it, assume it is already in
262 * URI format. Since DNS-SD service names can sometimes look like
263 * raw IPv6 addresses, we specifically look for "._tcp" in the name,
267 if (host
[0] != '[' && strchr(host
, ':') && !strstr(host
, "._tcp"))
270 * We have a raw IPv6 address...
273 if (strchr(host
, '%'))
276 * We have a link-local address, add "[v1." prefix...
287 goto assemble_overflow
;
292 * We have a normal address, add "[" prefix...
298 goto assemble_overflow
;
302 * Copy the rest of the IPv6 address, and terminate with "]".
305 while (ptr
< end
&& *host
)
309 *ptr
++ = '+'; /* Convert zone separator */
317 goto assemble_overflow
;
322 goto assemble_overflow
;
327 * Otherwise, just copy the host string...
330 ptr
= http_copy_encode(ptr
, host
, end
, ":/?#[]@\\\"", NULL
,
331 encoding
& HTTP_URI_CODING_HOSTNAME
);
334 goto assemble_overflow
;
338 * Finish things off with the port number...
343 snprintf(ptr
, end
- ptr
+ 1, ":%d", port
);
347 goto assemble_overflow
;
352 * Last but not least, add the resource string...
357 char *query
; /* Pointer to query string */
361 * Copy the resource string up to the query string if present...
364 query
= strchr(resource
, '?');
365 ptr
= http_copy_encode(ptr
, resource
, end
, NULL
, "?",
366 encoding
& HTTP_URI_CODING_RESOURCE
);
368 goto assemble_overflow
;
373 * Copy query string without encoding...
376 ptr
= http_copy_encode(ptr
, query
, end
, NULL
, NULL
,
377 encoding
& HTTP_URI_CODING_QUERY
);
379 goto assemble_overflow
;
385 goto assemble_overflow
;
388 * Nul-terminate the URI buffer and return with no errors...
393 return (HTTP_URI_OK
);
396 * Clear the URI string and return an overflow error; I don't usually
397 * like goto's, but in this case it makes sense...
403 return (HTTP_URI_OVERFLOW
);
408 * 'httpAssembleURIf()' - Assemble a uniform resource identifier from its
409 * components with a formatted resource.
411 * This function creates a formatted version of the resource string
412 * argument "resourcef" and escapes reserved characters in the URI
413 * depending on the value of the "encoding" argument. You should use
414 * this function in place of traditional string functions whenever
415 * you need to create a URI string.
417 * @since CUPS 1.2/OS X 10.5@
420 http_uri_status_t
/* O - URI status */
422 http_uri_coding_t encoding
, /* I - Encoding flags */
423 char *uri
, /* I - URI buffer */
424 int urilen
, /* I - Size of URI buffer */
425 const char *scheme
, /* I - Scheme name */
426 const char *username
, /* I - Username */
427 const char *host
, /* I - Hostname or address */
428 int port
, /* I - Port number */
429 const char *resourcef
, /* I - Printf-style resource */
430 ...) /* I - Additional arguments as needed */
432 va_list ap
; /* Pointer to additional arguments */
433 char resource
[1024]; /* Formatted resource string */
434 int bytes
; /* Bytes in formatted string */
438 * Range check input...
441 if (!uri
|| urilen
< 1 || !scheme
|| port
< 0 || !resourcef
)
446 return (HTTP_URI_BAD_ARGUMENTS
);
450 * Format the resource string and assemble the URI...
453 va_start(ap
, resourcef
);
454 bytes
= vsnprintf(resource
, sizeof(resource
), resourcef
, ap
);
457 if (bytes
>= sizeof(resource
))
460 return (HTTP_URI_OVERFLOW
);
463 return (httpAssembleURI(encoding
, uri
, urilen
, scheme
, username
, host
,
469 * '_httpAssembleUUID()' - Make a UUID URI conforming to RFC 4122.
471 * The buffer needs to be at least 46 bytes in size.
474 char * /* I - UUID string */
475 _httpAssembleUUID(const char *server
, /* I - Server name */
476 int port
, /* I - Port number */
477 const char *name
, /* I - Object name or NULL */
478 int number
, /* I - Object number or 0 */
479 char *buffer
, /* I - String buffer */
480 size_t bufsize
) /* I - Size of buffer */
482 char data
[1024]; /* Source string for MD5 */
483 _cups_md5_state_t md5state
; /* MD5 state */
484 unsigned char md5sum
[16]; /* MD5 digest/sum */
488 * Build a version 3 UUID conforming to RFC 4122.
490 * Start with the MD5 sum of the server, port, object name and
491 * number, and some random data on the end.
494 snprintf(data
, sizeof(data
), "%s:%d:%s:%d:%04x:%04x", server
,
495 port
, name
? name
: server
, number
,
496 (unsigned)CUPS_RAND() & 0xffff, (unsigned)CUPS_RAND() & 0xffff);
498 _cupsMD5Init(&md5state
);
499 _cupsMD5Append(&md5state
, (unsigned char *)data
, strlen(data
));
500 _cupsMD5Finish(&md5state
, md5sum
);
503 * Generate the UUID from the MD5...
506 snprintf(buffer
, bufsize
,
507 "urn:uuid:%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-"
508 "%02x%02x%02x%02x%02x%02x",
509 md5sum
[0], md5sum
[1], md5sum
[2], md5sum
[3], md5sum
[4], md5sum
[5],
510 (md5sum
[6] & 15) | 0x30, md5sum
[7], (md5sum
[8] & 0x3f) | 0x40,
511 md5sum
[9], md5sum
[10], md5sum
[11], md5sum
[12], md5sum
[13],
512 md5sum
[14], md5sum
[15]);
519 * 'httpDecode64()' - Base64-decode a string.
521 * This function is deprecated. Use the httpDecode64_2() function instead
522 * which provides buffer length arguments.
527 char * /* O - Decoded string */
528 httpDecode64(char *out
, /* I - String to write to */
529 const char *in
) /* I - String to read from */
531 int outlen
; /* Output buffer length */
535 * Use the old maximum buffer size for binary compatibility...
540 return (httpDecode64_2(out
, &outlen
, in
));
545 * 'httpDecode64_2()' - Base64-decode a string.
547 * @since CUPS 1.1.21/OS X 10.4@
550 char * /* O - Decoded string */
551 httpDecode64_2(char *out
, /* I - String to write to */
552 int *outlen
, /* IO - Size of output string */
553 const char *in
) /* I - String to read from */
555 int pos
, /* Bit position */
556 base64
; /* Value of this character */
557 char *outptr
, /* Output pointer */
558 *outend
; /* End of output buffer */
562 * Range check input...
565 if (!out
|| !outlen
|| *outlen
< 1 || !in
)
577 * Convert from base-64 to bytes...
580 for (outptr
= out
, outend
= out
+ *outlen
- 1, pos
= 0; *in
!= '\0'; in
++)
583 * Decode this character into a number from 0 to 63...
586 if (*in
>= 'A' && *in
<= 'Z')
588 else if (*in
>= 'a' && *in
<= 'z')
589 base64
= *in
- 'a' + 26;
590 else if (*in
>= '0' && *in
<= '9')
591 base64
= *in
- '0' + 52;
602 * Store the result in the appropriate chars...
609 *outptr
= base64
<< 2;
614 *outptr
++ |= (base64
>> 4) & 3;
616 *outptr
= (base64
<< 4) & 255;
621 *outptr
++ |= (base64
>> 2) & 15;
623 *outptr
= (base64
<< 6) & 255;
637 * Return the decoded string and size...
640 *outlen
= (int)(outptr
- out
);
647 * 'httpEncode64()' - Base64-encode a string.
649 * This function is deprecated. Use the httpEncode64_2() function instead
650 * which provides buffer length arguments.
655 char * /* O - Encoded string */
656 httpEncode64(char *out
, /* I - String to write to */
657 const char *in
) /* I - String to read from */
659 return (httpEncode64_2(out
, 512, in
, (int)strlen(in
)));
664 * 'httpEncode64_2()' - Base64-encode a string.
666 * @since CUPS 1.1.21/OS X 10.4@
669 char * /* O - Encoded string */
670 httpEncode64_2(char *out
, /* I - String to write to */
671 int outlen
, /* I - Size of output string */
672 const char *in
, /* I - String to read from */
673 int inlen
) /* I - Size of input string */
675 char *outptr
, /* Output pointer */
676 *outend
; /* End of output buffer */
677 static const char base64
[] = /* Base64 characters... */
679 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
680 "abcdefghijklmnopqrstuvwxyz"
687 * Range check input...
690 if (!out
|| outlen
< 1 || !in
)
694 * Convert bytes to base-64...
697 for (outptr
= out
, outend
= out
+ outlen
- 1; inlen
> 0; in
++, inlen
--)
700 * Encode the up to 3 characters as 4 Base64 numbers...
704 *outptr
++ = base64
[(in
[0] & 255) >> 2];
709 *outptr
++ = base64
[(((in
[0] & 255) << 4) | ((in
[1] & 255) >> 4)) & 63];
711 *outptr
++ = base64
[((in
[0] & 255) << 4) & 63];
728 *outptr
++ = base64
[(((in
[0] & 255) << 2) | ((in
[1] & 255) >> 6)) & 63];
730 *outptr
++ = base64
[((in
[0] & 255) << 2) & 63];
743 *outptr
++ = base64
[in
[0] & 63];
749 * Return the encoded string...
757 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
762 const char * /* O - Date/time string */
763 httpGetDateString(time_t t
) /* I - UNIX time */
765 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
768 return (httpGetDateString2(t
, cg
->http_date
, sizeof(cg
->http_date
)));
773 * 'httpGetDateString2()' - Get a formatted date/time string from a time value.
775 * @since CUPS 1.2/OS X 10.5@
778 const char * /* O - Date/time string */
779 httpGetDateString2(time_t t
, /* I - UNIX time */
780 char *s
, /* I - String buffer */
781 int slen
) /* I - Size of string buffer */
783 struct tm
*tdate
; /* UNIX date/time data */
788 snprintf(s
, slen
, "%s, %02d %s %d %02d:%02d:%02d GMT",
789 http_days
[tdate
->tm_wday
], tdate
->tm_mday
,
790 http_months
[tdate
->tm_mon
], tdate
->tm_year
+ 1900,
791 tdate
->tm_hour
, tdate
->tm_min
, tdate
->tm_sec
);
800 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
803 time_t /* O - UNIX time */
804 httpGetDateTime(const char *s
) /* I - Date/time string */
806 int i
; /* Looping var */
807 char mon
[16]; /* Abbreviated month name */
808 int day
, year
; /* Day of month and year */
809 int hour
, min
, sec
; /* Time */
810 int days
; /* Number of days since 1970 */
811 static const int normal_days
[] = /* Days to a month, normal years */
812 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
813 static const int leap_days
[] = /* Days to a month, leap years */
814 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 };
817 DEBUG_printf(("2httpGetDateTime(s=\"%s\")", s
));
820 * Extract the date and time from the formatted string...
823 if (sscanf(s
, "%*s%d%15s%d%d:%d:%d", &day
, mon
, &year
, &hour
, &min
, &sec
) < 6)
826 DEBUG_printf(("4httpGetDateTime: day=%d, mon=\"%s\", year=%d, hour=%d, "
827 "min=%d, sec=%d", day
, mon
, year
, hour
, min
, sec
));
830 * Convert the month name to a number from 0 to 11.
833 for (i
= 0; i
< 12; i
++)
834 if (!_cups_strcasecmp(mon
, http_months
[i
]))
840 DEBUG_printf(("4httpGetDateTime: i=%d", i
));
843 * Now convert the date and time to a UNIX time value in seconds since
844 * 1970. We can't use mktime() since the timezone may not be UTC but
845 * the date/time string *is* UTC.
848 if ((year
& 3) == 0 && ((year
% 100) != 0 || (year
% 400) == 0))
849 days
= leap_days
[i
] + day
- 1;
851 days
= normal_days
[i
] + day
- 1;
853 DEBUG_printf(("4httpGetDateTime: days=%d", days
));
855 days
+= (year
- 1970) * 365 + /* 365 days per year (normally) */
856 ((year
- 1) / 4 - 492) - /* + leap days */
857 ((year
- 1) / 100 - 19) + /* - 100 year days */
858 ((year
- 1) / 400 - 4); /* + 400 year days */
860 DEBUG_printf(("4httpGetDateTime: days=%d\n", days
));
862 return (days
* 86400 + hour
* 3600 + min
* 60 + sec
);
867 * 'httpSeparate()' - Separate a Universal Resource Identifier into its
870 * This function is deprecated; use the httpSeparateURI() function instead.
876 httpSeparate(const char *uri
, /* I - Universal Resource Identifier */
877 char *scheme
, /* O - Scheme [32] (http, https, etc.) */
878 char *username
, /* O - Username [1024] */
879 char *host
, /* O - Hostname [1024] */
880 int *port
, /* O - Port number to use */
881 char *resource
) /* O - Resource/filename [1024] */
883 httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, 32, username
,
884 HTTP_MAX_URI
, host
, HTTP_MAX_URI
, port
, resource
,
890 * 'httpSeparate2()' - Separate a Universal Resource Identifier into its
893 * This function is deprecated; use the httpSeparateURI() function instead.
895 * @since CUPS 1.1.21/OS X 10.4@
900 httpSeparate2(const char *uri
, /* I - Universal Resource Identifier */
901 char *scheme
, /* O - Scheme (http, https, etc.) */
902 int schemelen
, /* I - Size of scheme buffer */
903 char *username
, /* O - Username */
904 int usernamelen
, /* I - Size of username buffer */
905 char *host
, /* O - Hostname */
906 int hostlen
, /* I - Size of hostname buffer */
907 int *port
, /* O - Port number to use */
908 char *resource
, /* O - Resource/filename */
909 int resourcelen
) /* I - Size of resource buffer */
911 httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, schemelen
, username
,
912 usernamelen
, host
, hostlen
, port
, resource
, resourcelen
);
917 * 'httpSeparateURI()' - Separate a Universal Resource Identifier into its
920 * @since CUPS 1.2/OS X 10.5@
923 http_uri_status_t
/* O - Result of separation */
925 http_uri_coding_t decoding
, /* I - Decoding flags */
926 const char *uri
, /* I - Universal Resource Identifier */
927 char *scheme
, /* O - Scheme (http, https, etc.) */
928 int schemelen
, /* I - Size of scheme buffer */
929 char *username
, /* O - Username */
930 int usernamelen
, /* I - Size of username buffer */
931 char *host
, /* O - Hostname */
932 int hostlen
, /* I - Size of hostname buffer */
933 int *port
, /* O - Port number to use */
934 char *resource
, /* O - Resource/filename */
935 int resourcelen
) /* I - Size of resource buffer */
937 char *ptr
, /* Pointer into string... */
938 *end
; /* End of string */
939 const char *sep
; /* Separator character */
940 http_uri_status_t status
; /* Result of separation */
944 * Initialize everything to blank...
947 if (scheme
&& schemelen
> 0)
950 if (username
&& usernamelen
> 0)
953 if (host
&& hostlen
> 0)
959 if (resource
&& resourcelen
> 0)
963 * Range check input...
966 if (!uri
|| !port
|| !scheme
|| schemelen
<= 0 || !username
||
967 usernamelen
<= 0 || !host
|| hostlen
<= 0 || !resource
||
969 return (HTTP_URI_BAD_ARGUMENTS
);
972 return (HTTP_URI_BAD_URI
);
975 * Grab the scheme portion of the URI...
978 status
= HTTP_URI_OK
;
980 if (!strncmp(uri
, "//", 2))
983 * Workaround for HP IPP client bug...
986 strlcpy(scheme
, "ipp", schemelen
);
987 status
= HTTP_URI_MISSING_SCHEME
;
989 else if (*uri
== '/')
995 strlcpy(scheme
, "file", schemelen
);
996 status
= HTTP_URI_MISSING_SCHEME
;
1001 * Standard URI with scheme...
1004 for (ptr
= scheme
, end
= scheme
+ schemelen
- 1;
1005 *uri
&& *uri
!= ':' && ptr
< end
;)
1006 if (strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1007 "abcdefghijklmnopqrstuvwxyz"
1008 "0123456789-+.", *uri
) != NULL
)
1018 return (HTTP_URI_BAD_SCHEME
);
1025 * Set the default port number...
1028 if (!strcmp(scheme
, "http"))
1030 else if (!strcmp(scheme
, "https"))
1032 else if (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps"))
1034 else if (!_cups_strcasecmp(scheme
, "lpd"))
1036 else if (!strcmp(scheme
, "socket")) /* Not yet registered with IANA... */
1038 else if (strcmp(scheme
, "file") && strcmp(scheme
, "mailto"))
1039 status
= HTTP_URI_UNKNOWN_SCHEME
;
1042 * Now see if we have a hostname...
1045 if (!strncmp(uri
, "//", 2))
1048 * Yes, extract it...
1054 * Grab the username, if any...
1057 if ((sep
= strpbrk(uri
, "@/")) != NULL
&& *sep
== '@')
1060 * Get a username:password combo...
1063 uri
= http_copy_decode(username
, uri
, usernamelen
, "@",
1064 decoding
& HTTP_URI_CODING_USERNAME
);
1069 return (HTTP_URI_BAD_USERNAME
);
1076 * Then the hostname/IP address...
1082 * Grab IPv6 address...
1086 if (!strncmp(uri
, "v1.", 3))
1087 uri
+= 3; /* Skip IPvN leader... */
1089 uri
= http_copy_decode(host
, uri
, hostlen
, "]",
1090 decoding
& HTTP_URI_CODING_HOSTNAME
);
1095 return (HTTP_URI_BAD_HOSTNAME
);
1105 return (HTTP_URI_BAD_HOSTNAME
);
1110 for (ptr
= host
; *ptr
; ptr
++)
1114 * Convert zone separator to % and stop here...
1120 else if (*ptr
!= ':' && *ptr
!= '.' && !isxdigit(*ptr
& 255))
1123 return (HTTP_URI_BAD_HOSTNAME
);
1129 * Validate the hostname or IPv4 address first...
1132 for (ptr
= (char *)uri
; *ptr
; ptr
++)
1133 if (strchr(":?/", *ptr
))
1135 else if (!strchr("abcdefghijklmnopqrstuvwxyz"
1136 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1140 "!$&'()*+,;=\\", *ptr
))
1143 return (HTTP_URI_BAD_HOSTNAME
);
1147 * Then copy the hostname or IPv4 address to the buffer...
1150 uri
= http_copy_decode(host
, uri
, hostlen
, ":?/",
1151 decoding
& HTTP_URI_CODING_HOSTNAME
);
1156 return (HTTP_URI_BAD_HOSTNAME
);
1161 * Validate hostname for file scheme - only empty and localhost are
1165 if (!strcmp(scheme
, "file") && strcmp(host
, "localhost") && host
[0])
1168 return (HTTP_URI_BAD_HOSTNAME
);
1172 * See if we have a port number...
1178 * Yes, collect the port number...
1181 if (!isdigit(uri
[1] & 255))
1184 return (HTTP_URI_BAD_PORT
);
1187 *port
= strtol(uri
+ 1, (char **)&uri
, 10);
1189 if (*uri
!= '/' && *uri
)
1192 return (HTTP_URI_BAD_PORT
);
1198 * The remaining portion is the resource string...
1201 if (*uri
== '?' || !*uri
)
1204 * Hostname but no path...
1207 status
= HTTP_URI_MISSING_RESOURCE
;
1211 * Copy any query string...
1215 uri
= http_copy_decode(resource
+ 1, uri
, resourcelen
- 1, NULL
,
1216 decoding
& HTTP_URI_CODING_QUERY
);
1222 uri
= http_copy_decode(resource
, uri
, resourcelen
, "?",
1223 decoding
& HTTP_URI_CODING_RESOURCE
);
1225 if (uri
&& *uri
== '?')
1228 * Concatenate any query string...
1231 char *resptr
= resource
+ strlen(resource
);
1233 uri
= http_copy_decode(resptr
, uri
, resourcelen
- (int)(resptr
- resource
),
1234 NULL
, decoding
& HTTP_URI_CODING_QUERY
);
1241 return (HTTP_URI_BAD_RESOURCE
);
1245 * Return the URI separation status...
1253 * 'httpStatus()' - Return a short string describing a HTTP status code.
1255 * The returned string is localized to the current POSIX locale and is based
1256 * on the status strings defined in RFC 2616.
1259 const char * /* O - Localized status string */
1260 httpStatus(http_status_t status
) /* I - HTTP status code */
1262 const char *s
; /* Status string */
1263 _cups_globals_t
*cg
= _cupsGlobals(); /* Global data */
1266 if (!cg
->lang_default
)
1267 cg
->lang_default
= cupsLangDefault();
1271 case HTTP_CONTINUE
:
1274 case HTTP_SWITCHING_PROTOCOLS
:
1275 s
= _("Switching Protocols");
1283 case HTTP_ACCEPTED
:
1286 case HTTP_NO_CONTENT
:
1287 s
= _("No Content");
1289 case HTTP_MOVED_PERMANENTLY
:
1290 s
= _("Moved Permanently");
1292 case HTTP_SEE_OTHER
:
1295 case HTTP_NOT_MODIFIED
:
1296 s
= _("Not Modified");
1298 case HTTP_BAD_REQUEST
:
1299 s
= _("Bad Request");
1301 case HTTP_UNAUTHORIZED
:
1302 case HTTP_AUTHORIZATION_CANCELED
:
1303 s
= _("Unauthorized");
1305 case HTTP_FORBIDDEN
:
1308 case HTTP_NOT_FOUND
:
1311 case HTTP_REQUEST_TOO_LARGE
:
1312 s
= _("Request Entity Too Large");
1314 case HTTP_URI_TOO_LONG
:
1315 s
= _("URI Too Long");
1317 case HTTP_UPGRADE_REQUIRED
:
1318 s
= _("Upgrade Required");
1320 case HTTP_NOT_IMPLEMENTED
:
1321 s
= _("Not Implemented");
1323 case HTTP_NOT_SUPPORTED
:
1324 s
= _("Not Supported");
1326 case HTTP_EXPECTATION_FAILED
:
1327 s
= _("Expectation Failed");
1329 case HTTP_SERVICE_UNAVAILABLE
:
1330 s
= _("Service Unavailable");
1332 case HTTP_SERVER_ERROR
:
1333 s
= _("Internal Server Error");
1335 case HTTP_PKI_ERROR
:
1336 s
= _("SSL/TLS Negotiation Error");
1338 case HTTP_WEBIF_DISABLED
:
1339 s
= _("Web Interface is Disabled");
1347 return (_cupsLangString(cg
->lang_default
, s
));
1351 #ifndef HAVE_HSTRERROR
1353 * '_cups_hstrerror()' - hstrerror() emulation function for Solaris and others.
1356 const char * /* O - Error string */
1357 _cups_hstrerror(int error
) /* I - Error number */
1359 static const char * const errors
[] = /* Error strings */
1364 "Unrecoverable lookup error.",
1365 "No data associated with name."
1369 if (error
< 0 || error
> 4)
1370 return ("Unknown hostname lookup error.");
1372 return (errors
[error
]);
1374 #endif /* !HAVE_HSTRERROR */
1378 * '_httpDecodeURI()' - Percent-decode a HTTP request URI.
1381 char * /* O - Decoded URI or NULL on error */
1382 _httpDecodeURI(char *dst
, /* I - Destination buffer */
1383 const char *src
, /* I - Source URI */
1384 size_t dstsize
) /* I - Size of destination buffer */
1386 if (http_copy_decode(dst
, src
, (int)dstsize
, NULL
, 1))
1394 * '_httpEncodeURI()' - Percent-encode a HTTP request URI.
1397 char * /* O - Encoded URI */
1398 _httpEncodeURI(char *dst
, /* I - Destination buffer */
1399 const char *src
, /* I - Source URI */
1400 size_t dstsize
) /* I - Size of destination buffer */
1402 http_copy_encode(dst
, src
, dst
+ dstsize
- 1, NULL
, NULL
, 1);
1408 * '_httpResolveURI()' - Resolve a DNS-SD URI.
1411 const char * /* O - Resolved URI */
1413 const char *uri
, /* I - DNS-SD URI */
1414 char *resolved_uri
, /* I - Buffer for resolved URI */
1415 size_t resolved_size
, /* I - Size of URI buffer */
1416 int options
, /* I - Resolve options */
1417 int (*cb
)(void *context
), /* I - Continue callback function */
1418 void *context
) /* I - Context pointer for callback */
1420 char scheme
[32], /* URI components... */
1426 http_uri_status_t status
; /* URI decode status */
1430 DEBUG_printf(("4_httpResolveURI(uri=\"%s\", resolved_uri=%p, "
1431 "resolved_size=" CUPS_LLFMT
")", uri
, resolved_uri
,
1432 CUPS_LLCAST resolved_size
));
1435 * Get the device URI...
1439 if ((status
= httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
,
1440 sizeof(scheme
), userpass
, sizeof(userpass
),
1441 hostname
, sizeof(hostname
), &port
, resource
,
1442 sizeof(resource
))) < HTTP_URI_OK
)
1444 if (httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
,
1445 sizeof(scheme
), userpass
, sizeof(userpass
),
1446 hostname
, sizeof(hostname
), &port
, resource
,
1447 sizeof(resource
)) < HTTP_URI_OK
)
1450 if (options
& _HTTP_RESOLVE_STDERR
)
1451 _cupsLangPrintFilter(stderr
, "ERROR", _("Bad device-uri \"%s\"."), uri
);
1453 DEBUG_printf(("6_httpResolveURI: httpSeparateURI returned %d!", status
));
1454 DEBUG_puts("5_httpResolveURI: Returning NULL");
1459 * Resolve it as needed...
1462 if (strstr(hostname
, "._tcp"))
1464 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
1465 char *regtype
, /* Pointer to type in hostname */
1466 *domain
; /* Pointer to domain in hostname */
1467 _http_uribuf_t uribuf
; /* URI buffer */
1468 int offline
= 0; /* offline-report state set? */
1471 # pragma comment(lib, "dnssd.lib")
1473 DNSServiceRef ref
, /* DNS-SD master service reference */
1474 domainref
, /* DNS-SD service reference for domain */
1475 localref
; /* DNS-SD service reference for .local */
1476 int domainsent
= 0; /* Send the domain resolve? */
1478 struct pollfd polldata
; /* Polling data */
1479 # else /* select() */
1480 fd_set input_set
; /* Input set for select() */
1481 struct timeval stimeout
; /* Timeout value for select() */
1482 # endif /* HAVE_POLL */
1483 # elif defined(HAVE_AVAHI)
1484 AvahiClient
*client
; /* Client information */
1485 int error
; /* Status */
1486 # endif /* HAVE_DNSSD */
1488 if (options
& _HTTP_RESOLVE_STDERR
)
1489 fprintf(stderr
, "DEBUG: Resolving \"%s\"...\n", hostname
);
1492 * Separate the hostname into service name, registration type, and domain...
1495 for (regtype
= strstr(hostname
, "._tcp") - 2;
1498 if (regtype
[0] == '.' && regtype
[1] == '_')
1501 * Found ._servicetype in front of ._tcp...
1508 if (regtype
<= hostname
)
1510 DEBUG_puts("5_httpResolveURI: Bad hostname, returning NULL");
1514 for (domain
= strchr(regtype
, '.');
1516 domain
= strchr(domain
+ 1, '.'))
1517 if (domain
[1] != '_')
1523 uribuf
.buffer
= resolved_uri
;
1524 uribuf
.bufsize
= resolved_size
;
1525 uribuf
.options
= options
;
1527 resolved_uri
[0] = '\0';
1529 DEBUG_printf(("6_httpResolveURI: Resolving hostname=\"%s\", regtype=\"%s\", "
1530 "domain=\"%s\"\n", hostname
, regtype
, domain
));
1531 if (options
& _HTTP_RESOLVE_STDERR
)
1533 fputs("STATE: +connecting-to-device\n", stderr
);
1534 fprintf(stderr
, "DEBUG: Resolving \"%s\", regtype=\"%s\", "
1535 "domain=\"local.\"...\n", hostname
, regtype
);
1541 if (DNSServiceCreateConnection(&ref
) == kDNSServiceErr_NoError
)
1544 if (DNSServiceResolve(&localref
,
1545 kDNSServiceFlagsShareConnection
, 0, hostname
, regtype
,
1546 "local.", http_resolve_cb
,
1547 &uribuf
) == kDNSServiceErr_NoError
)
1549 int fds
; /* Number of ready descriptors */
1550 time_t timeout
, /* Poll timeout */
1551 start_time
= time(NULL
),/* Start time */
1552 end_time
= start_time
+ 90;
1555 while (time(NULL
) < end_time
)
1557 if (options
& _HTTP_RESOLVE_STDERR
)
1558 _cupsLangPrintFilter(stderr
, "INFO", _("Looking for printer."));
1560 if (cb
&& !(*cb
)(context
))
1562 DEBUG_puts("5_httpResolveURI: callback returned 0 (stop)");
1567 * Wakeup every 2 seconds to emit a "looking for printer" message...
1570 if ((timeout
= end_time
- time(NULL
)) > 2)
1574 polldata
.fd
= DNSServiceRefSockFD(ref
);
1575 polldata
.events
= POLLIN
;
1577 fds
= poll(&polldata
, 1, 1000 * timeout
);
1579 # else /* select() */
1580 FD_ZERO(&input_set
);
1581 FD_SET(DNSServiceRefSockFD(ref
), &input_set
);
1584 stimeout
.tv_sec
= (long)timeout
;
1586 stimeout
.tv_sec
= timeout
;
1588 stimeout
.tv_usec
= 0;
1590 fds
= select(DNSServiceRefSockFD(ref
)+1, &input_set
, NULL
, NULL
,
1592 # endif /* HAVE_POLL */
1596 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1598 DEBUG_printf(("5_httpResolveURI: poll error: %s", strerror(errno
)));
1605 * Wait 2 seconds for a response to the local resolve; if nothing
1606 * comes in, do an additional domain resolution...
1609 if (domainsent
== 0 && domain
&& _cups_strcasecmp(domain
, "local."))
1611 if (options
& _HTTP_RESOLVE_STDERR
)
1613 "DEBUG: Resolving \"%s\", regtype=\"%s\", "
1614 "domain=\"%s\"...\n", hostname
, regtype
,
1615 domain
? domain
: "");
1618 if (DNSServiceResolve(&domainref
,
1619 kDNSServiceFlagsShareConnection
,
1620 0, hostname
, regtype
, domain
,
1622 &uribuf
) == kDNSServiceErr_NoError
)
1627 * If it hasn't resolved within 5 seconds set the offline-report
1628 * printer-state-reason...
1631 if ((options
& _HTTP_RESOLVE_STDERR
) && offline
== 0 &&
1632 time(NULL
) > (start_time
+ 5))
1634 fputs("STATE: +offline-report\n", stderr
);
1640 if (DNSServiceProcessResult(ref
) == kDNSServiceErr_NoError
)
1649 DNSServiceRefDeallocate(domainref
);
1651 DNSServiceRefDeallocate(localref
);
1654 DNSServiceRefDeallocate(ref
);
1656 # else /* HAVE_AVAHI */
1657 if ((uribuf
.poll
= avahi_simple_poll_new()) != NULL
)
1659 avahi_simple_poll_set_func(uribuf
.poll
, http_poll_cb
, NULL
);
1661 if ((client
= avahi_client_new(avahi_simple_poll_get(uribuf
.poll
),
1663 &uribuf
, &error
)) != NULL
)
1665 if (avahi_service_resolver_new(client
, AVAHI_IF_UNSPEC
,
1666 AVAHI_PROTO_UNSPEC
, hostname
,
1667 regtype
, "local.", AVAHI_PROTO_UNSPEC
, 0,
1668 http_resolve_cb
, &uribuf
) != NULL
)
1670 time_t start_time
= time(NULL
),
1672 end_time
= start_time
+ 90;
1674 int pstatus
; /* Poll status */
1676 pstatus
= avahi_simple_poll_iterate(uribuf
.poll
, 2000);
1678 if (pstatus
== 0 && !resolved_uri
[0] && domain
&&
1679 _cups_strcasecmp(domain
, "local."))
1682 * Resolve for .local hasn't returned anything, try the listed
1686 avahi_service_resolver_new(client
, AVAHI_IF_UNSPEC
,
1687 AVAHI_PROTO_UNSPEC
, hostname
,
1688 regtype
, domain
, AVAHI_PROTO_UNSPEC
, 0,
1689 http_resolve_cb
, &uribuf
);
1692 while (!pstatus
&& !resolved_uri
[0] && time(NULL
) < end_time
)
1694 if ((pstatus
= avahi_simple_poll_iterate(uribuf
.poll
, 2000)) != 0)
1698 * If it hasn't resolved within 5 seconds set the offline-report
1699 * printer-state-reason...
1702 if ((options
& _HTTP_RESOLVE_STDERR
) && offline
== 0 &&
1703 time(NULL
) > (start_time
+ 5))
1705 fputs("STATE: +offline-report\n", stderr
);
1711 * Collect the result (if we got one).
1714 if (resolved_uri
[0])
1718 avahi_client_free(client
);
1721 avahi_simple_poll_free(uribuf
.poll
);
1723 # endif /* HAVE_DNSSD */
1725 if (options
& _HTTP_RESOLVE_STDERR
)
1729 fprintf(stderr
, "DEBUG: Resolved as \"%s\"...\n", uri
);
1730 fputs("STATE: -connecting-to-device,offline-report\n", stderr
);
1734 fputs("DEBUG: Unable to resolve URI\n", stderr
);
1735 fputs("STATE: -connecting-to-device\n", stderr
);
1739 #else /* HAVE_DNSSD || HAVE_AVAHI */
1741 * No DNS-SD support...
1745 #endif /* HAVE_DNSSD || HAVE_AVAHI */
1747 if ((options
& _HTTP_RESOLVE_STDERR
) && !uri
)
1748 _cupsLangPrintFilter(stderr
, "ERROR", _("Unable to find printer."));
1753 * Nothing more to do...
1756 strlcpy(resolved_uri
, uri
, resolved_size
);
1760 DEBUG_printf(("5_httpResolveURI: Returning \"%s\"", uri
));
1768 * 'http_client_cb()' - Client callback for resolving URI.
1773 AvahiClient
*client
, /* I - Client information */
1774 AvahiClientState state
, /* I - Current state */
1775 void *context
) /* I - Pointer to URI buffer */
1777 DEBUG_printf(("7http_client_cb(client=%p, state=%d, context=%p)", client
,
1781 * If the connection drops, quit.
1784 if (state
== AVAHI_CLIENT_FAILURE
)
1786 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
1789 avahi_simple_poll_quit(uribuf
->poll
);
1792 #endif /* HAVE_AVAHI */
1796 * 'http_copy_decode()' - Copy and decode a URI.
1799 static const char * /* O - New source pointer or NULL on error */
1800 http_copy_decode(char *dst
, /* O - Destination buffer */
1801 const char *src
, /* I - Source pointer */
1802 int dstsize
, /* I - Destination size */
1803 const char *term
, /* I - Terminating characters */
1804 int decode
) /* I - Decode %-encoded values */
1806 char *ptr
, /* Pointer into buffer */
1807 *end
; /* End of buffer */
1808 int quoted
; /* Quoted character */
1812 * Copy the src to the destination until we hit a terminating character
1813 * or the end of the string.
1816 for (ptr
= dst
, end
= dst
+ dstsize
- 1;
1817 *src
&& (!term
|| !strchr(term
, *src
));
1821 if (*src
== '%' && decode
)
1823 if (isxdigit(src
[1] & 255) && isxdigit(src
[2] & 255))
1826 * Grab a hex-encoded character...
1831 quoted
= (tolower(*src
) - 'a' + 10) << 4;
1833 quoted
= (*src
- '0') << 4;
1837 quoted
|= tolower(*src
) - 'a' + 10;
1839 quoted
|= *src
- '0';
1846 * Bad hex-encoded character...
1864 * 'http_copy_encode()' - Copy and encode a URI.
1867 static char * /* O - End of current URI */
1868 http_copy_encode(char *dst
, /* O - Destination buffer */
1869 const char *src
, /* I - Source pointer */
1870 char *dstend
, /* I - End of destination buffer */
1871 const char *reserved
, /* I - Extra reserved characters */
1872 const char *term
, /* I - Terminating characters */
1873 int encode
) /* I - %-encode reserved chars? */
1875 static const char hex
[] = "0123456789ABCDEF";
1878 while (*src
&& dst
< dstend
)
1880 if (term
&& *src
== *term
)
1883 if (encode
&& (*src
== '%' || *src
<= ' ' || *src
& 128 ||
1884 (reserved
&& strchr(reserved
, *src
))))
1887 * Hex encode reserved characters...
1890 if ((dst
+ 2) >= dstend
)
1894 *dst
++ = hex
[(*src
>> 4) & 15];
1895 *dst
++ = hex
[*src
& 15];
1914 * 'http_resolve_cb()' - Build a device URI for the given service name.
1917 static void DNSSD_API
1919 DNSServiceRef sdRef
, /* I - Service reference */
1920 DNSServiceFlags flags
, /* I - Results flags */
1921 uint32_t interfaceIndex
, /* I - Interface number */
1922 DNSServiceErrorType errorCode
, /* I - Error, if any */
1923 const char *fullName
, /* I - Full service name */
1924 const char *hostTarget
, /* I - Hostname */
1925 uint16_t port
, /* I - Port number */
1926 uint16_t txtLen
, /* I - Length of TXT record */
1927 const unsigned char *txtRecord
, /* I - TXT record data */
1928 void *context
) /* I - Pointer to URI buffer */
1930 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
1932 const char *scheme
, /* URI scheme */
1933 *hostptr
, /* Pointer into hostTarget */
1934 *reskey
, /* "rp" or "rfo" */
1935 *resdefault
; /* Default path */
1936 char resource
[257], /* Remote path */
1937 fqdn
[256]; /* FQDN of the .local name */
1938 const void *value
; /* Value from TXT record */
1939 uint8_t valueLen
; /* Length of value */
1942 DEBUG_printf(("7http_resolve_cb(sdRef=%p, flags=%x, interfaceIndex=%u, "
1943 "errorCode=%d, fullName=\"%s\", hostTarget=\"%s\", port=%u, "
1944 "txtLen=%u, txtRecord=%p, context=%p)", sdRef
, flags
,
1945 interfaceIndex
, errorCode
, fullName
, hostTarget
, port
, txtLen
,
1946 txtRecord
, context
));
1949 * Figure out the scheme from the full name...
1952 if (strstr(fullName
, "._ipps") || strstr(fullName
, "._ipp-tls"))
1954 else if (strstr(fullName
, "._ipp") || strstr(fullName
, "._fax-ipp"))
1956 else if (strstr(fullName
, "._http."))
1958 else if (strstr(fullName
, "._https."))
1960 else if (strstr(fullName
, "._printer."))
1962 else if (strstr(fullName
, "._pdl-datastream."))
1965 scheme
= "riousbprint";
1968 * Extract the "remote printer" key from the TXT record...
1971 if ((uribuf
->options
& _HTTP_RESOLVE_FAXOUT
) &&
1972 (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")))
1975 resdefault
= "/ipp/faxout";
1983 if ((value
= TXTRecordGetValuePtr(txtLen
, txtRecord
, reskey
,
1984 &valueLen
)) != NULL
)
1986 if (((char *)value
)[0] == '/')
1989 * Value (incorrectly) has a leading slash already...
1992 memcpy(resource
, value
, valueLen
);
1993 resource
[valueLen
] = '\0';
1998 * Convert to resource by concatenating with a leading "/"...
2002 memcpy(resource
+ 1, value
, valueLen
);
2003 resource
[valueLen
+ 1] = '\0';
2009 * Use the default value...
2012 strlcpy(resource
, resdefault
, sizeof(resource
));
2016 * Lookup the FQDN if needed...
2019 if ((uribuf
->options
& _HTTP_RESOLVE_FQDN
) &&
2020 (hostptr
= hostTarget
+ strlen(hostTarget
) - 7) > hostTarget
&&
2021 !_cups_strcasecmp(hostptr
, ".local."))
2024 * OK, we got a .local name but the caller needs a real domain. Start by
2025 * getting the IP address of the .local name and then do reverse-lookups...
2028 http_addrlist_t
*addrlist
, /* List of addresses */
2029 *addr
; /* Current address */
2031 DEBUG_printf(("8http_resolve_cb: Looking up \"%s\".", hostTarget
));
2033 snprintf(fqdn
, sizeof(fqdn
), "%d", ntohs(port
));
2034 if ((addrlist
= httpAddrGetList(hostTarget
, AF_UNSPEC
, fqdn
)) != NULL
)
2036 for (addr
= addrlist
; addr
; addr
= addr
->next
)
2038 int error
= getnameinfo(&(addr
->addr
.addr
),
2039 httpAddrLength(&(addr
->addr
)),
2040 fqdn
, sizeof(fqdn
), NULL
, 0, NI_NAMEREQD
);
2044 DEBUG_printf(("8http_resolve_cb: Found \"%s\".", fqdn
));
2046 if ((hostptr
= fqdn
+ strlen(fqdn
) - 6) <= fqdn
||
2047 _cups_strcasecmp(hostptr
, ".local"))
2055 DEBUG_printf(("8http_resolve_cb: \"%s\" did not resolve: %d",
2056 httpAddrString(&(addr
->addr
), fqdn
, sizeof(fqdn
)),
2064 * Assemble the final device URI...
2067 httpAssembleURI(HTTP_URI_CODING_ALL
, uribuf
->buffer
, uribuf
->bufsize
, scheme
,
2068 NULL
, hostTarget
, ntohs(port
), resource
);
2070 DEBUG_printf(("8http_resolve_cb: Resolved URI is \"%s\"...", uribuf
->buffer
));
2073 #elif defined(HAVE_AVAHI)
2075 * 'http_poll_cb()' - Wait for input on the specified file descriptors.
2077 * Note: This function is needed because avahi_simple_poll_iterate is broken
2078 * and always uses a timeout of 0 (!) milliseconds.
2079 * (Avahi Ticket #364)
2082 static int /* O - Number of file descriptors matching */
2084 struct pollfd
*pollfds
, /* I - File descriptors */
2085 unsigned int num_pollfds
, /* I - Number of file descriptors */
2086 int timeout
, /* I - Timeout in milliseconds (used) */
2087 void *context
) /* I - User data (unused) */
2092 return (poll(pollfds
, num_pollfds
, 2000));
2097 * 'http_resolve_cb()' - Build a device URI for the given service name.
2102 AvahiServiceResolver
*resolver
, /* I - Resolver (unused) */
2103 AvahiIfIndex interface
, /* I - Interface index (unused) */
2104 AvahiProtocol protocol
, /* I - Network protocol (unused) */
2105 AvahiResolverEvent event
, /* I - Event (found, etc.) */
2106 const char *name
, /* I - Service name */
2107 const char *type
, /* I - Registration type */
2108 const char *domain
, /* I - Domain (unused) */
2109 const char *hostTarget
, /* I - Hostname */
2110 const AvahiAddress
*address
, /* I - Address (unused) */
2111 uint16_t port
, /* I - Port number */
2112 AvahiStringList
*txt
, /* I - TXT record */
2113 AvahiLookupResultFlags flags
, /* I - Lookup flags (unused) */
2114 void *context
) /* I - Pointer to URI buffer */
2116 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
2118 const char *scheme
, /* URI scheme */
2119 *hostptr
, /* Pointer into hostTarget */
2120 *reskey
, /* "rp" or "rfo" */
2121 *resdefault
; /* Default path */
2122 char resource
[257], /* Remote path */
2123 fqdn
[256]; /* FQDN of the .local name */
2124 AvahiStringList
*pair
; /* Current TXT record key/value pair */
2125 char *value
; /* Value for "rp" key */
2126 size_t valueLen
= 0; /* Length of "rp" key */
2129 DEBUG_printf(("7http_resolve_cb(resolver=%p, "
2130 "interface=%d, protocol=%d, event=%d, name=\"%s\", "
2131 "type=\"%s\", domain=\"%s\", hostTarget=\"%s\", address=%p, "
2132 "port=%d, txt=%p, flags=%d, context=%p)",
2133 resolver
, interface
, protocol
, event
, name
, type
, domain
,
2134 hostTarget
, address
, port
, txt
, flags
, context
));
2136 if (event
!= AVAHI_RESOLVER_FOUND
)
2138 avahi_service_resolver_free(resolver
);
2139 avahi_simple_poll_quit(uribuf
->poll
);
2144 * Figure out the scheme from the full name...
2147 if (strstr(type
, "_ipp."))
2149 else if (strstr(type
, "_printer."))
2151 else if (strstr(type
, "_pdl-datastream."))
2154 scheme
= "riousbprint";
2156 if (!strncmp(type
, "_ipps.", 6) || !strncmp(type
, "_ipp-tls.", 9))
2158 else if (!strncmp(type
, "_ipp.", 5) || !strncmp(type
, "_fax-ipp.", 9))
2160 else if (!strncmp(type
, "_http.", 6))
2162 else if (!strncmp(type
, "_https.", 7))
2164 else if (!strncmp(type
, "_printer.", 9))
2166 else if (!strncmp(type
, "_pdl-datastream.", 16))
2170 avahi_service_resolver_free(resolver
);
2171 avahi_simple_poll_quit(uribuf
->poll
);
2176 * Extract the remote resource key from the TXT record...
2179 if ((uribuf
->options
& _HTTP_RESOLVE_FAXOUT
) &&
2180 (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")))
2183 resdefault
= "/ipp/faxout";
2191 if ((pair
= avahi_string_list_find(txt
, reskey
)) != NULL
)
2193 avahi_string_list_get_pair(pair
, NULL
, &value
, &valueLen
);
2195 if (value
[0] == '/')
2198 * Value (incorrectly) has a leading slash already...
2201 memcpy(resource
, value
, valueLen
);
2202 resource
[valueLen
] = '\0';
2207 * Convert to resource by concatenating with a leading "/"...
2211 memcpy(resource
+ 1, value
, valueLen
);
2212 resource
[valueLen
+ 1] = '\0';
2218 * Use the default value...
2221 strlcpy(resource
, resdefault
, sizeof(resource
));
2225 * Lookup the FQDN if needed...
2228 if ((uribuf
->options
& _HTTP_RESOLVE_FQDN
) &&
2229 (hostptr
= hostTarget
+ strlen(hostTarget
) - 6) > hostTarget
&&
2230 !_cups_strcasecmp(hostptr
, ".local"))
2233 * OK, we got a .local name but the caller needs a real domain. Start by
2234 * getting the IP address of the .local name and then do reverse-lookups...
2237 http_addrlist_t
*addrlist
, /* List of addresses */
2238 *addr
; /* Current address */
2240 DEBUG_printf(("8http_resolve_cb: Looking up \"%s\".", hostTarget
));
2242 snprintf(fqdn
, sizeof(fqdn
), "%d", ntohs(port
));
2243 if ((addrlist
= httpAddrGetList(hostTarget
, AF_UNSPEC
, fqdn
)) != NULL
)
2245 for (addr
= addrlist
; addr
; addr
= addr
->next
)
2247 int error
= getnameinfo(&(addr
->addr
.addr
),
2248 httpAddrLength(&(addr
->addr
)),
2249 fqdn
, sizeof(fqdn
), NULL
, 0, NI_NAMEREQD
);
2253 DEBUG_printf(("8http_resolve_cb: Found \"%s\".", fqdn
));
2255 if ((hostptr
= fqdn
+ strlen(fqdn
) - 6) <= fqdn
||
2256 _cups_strcasecmp(hostptr
, ".local"))
2264 DEBUG_printf(("8http_resolve_cb: \"%s\" did not resolve: %d",
2265 httpAddrString(&(addr
->addr
), fqdn
, sizeof(fqdn
)),
2273 * Assemble the final device URI using the resolved hostname...
2276 httpAssembleURI(HTTP_URI_CODING_ALL
, uribuf
->buffer
, uribuf
->bufsize
, scheme
,
2277 NULL
, hostTarget
, port
, resource
);
2278 DEBUG_printf(("8http_resolve_cb: Resolved URI is \"%s\".", uribuf
->buffer
));
2280 avahi_simple_poll_quit(uribuf
->poll
);
2282 #endif /* HAVE_DNSSD */
2286 * End of "$Id: http-support.c 7952 2008-09-17 00:56:20Z mike $".