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_STATUS_BAD_ARGUMENTS
);
200 * Assemble the URI starting with the scheme...
203 end
= uri
+ urilen
- 1;
204 ptr
= http_copy_encode(uri
, scheme
, end
, NULL
, NULL
, 0);
207 goto assemble_overflow
;
209 if (!strcmp(scheme
, "mailto"))
212 * mailto: only has :, no //...
218 goto assemble_overflow
;
223 * Schemes other than mailto: all have //...
233 goto assemble_overflow
;
237 * Next the username and hostname, if any...
242 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_STATUS_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_STATUS_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_STATUS_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_STATUS_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.
481 char * /* I - UUID string */
482 httpAssembleUUID(const char *server
, /* I - Server name */
483 int port
, /* I - Port number */
484 const char *name
, /* I - Object name or NULL */
485 int number
, /* I - Object number or 0 */
486 char *buffer
, /* I - String buffer */
487 size_t bufsize
) /* I - Size of buffer */
489 char data
[1024]; /* Source string for MD5 */
490 _cups_md5_state_t md5state
; /* MD5 state */
491 unsigned char md5sum
[16]; /* MD5 digest/sum */
495 * Build a version 3 UUID conforming to RFC 4122.
497 * Start with the MD5 sum of the server, port, object name and
498 * number, and some random data on the end.
501 snprintf(data
, sizeof(data
), "%s:%d:%s:%d:%04x:%04x", server
,
502 port
, name
? name
: server
, number
,
503 (unsigned)CUPS_RAND() & 0xffff, (unsigned)CUPS_RAND() & 0xffff);
505 _cupsMD5Init(&md5state
);
506 _cupsMD5Append(&md5state
, (unsigned char *)data
, strlen(data
));
507 _cupsMD5Finish(&md5state
, md5sum
);
510 * Generate the UUID from the MD5...
513 snprintf(buffer
, bufsize
,
514 "urn:uuid:%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-"
515 "%02x%02x%02x%02x%02x%02x",
516 md5sum
[0], md5sum
[1], md5sum
[2], md5sum
[3], md5sum
[4], md5sum
[5],
517 (md5sum
[6] & 15) | 0x30, md5sum
[7], (md5sum
[8] & 0x3f) | 0x40,
518 md5sum
[9], md5sum
[10], md5sum
[11], md5sum
[12], md5sum
[13],
519 md5sum
[14], md5sum
[15]);
524 /* For OS X 10.8 and earlier */
525 char *_httpAssembleUUID(const char *server
, int port
, const char *name
,
526 int number
, char *buffer
, size_t bufsize
)
528 return (httpAssembleUUID(server
, port
, name
, number
, buffer
, bufsize
));
533 * 'httpDecode64()' - Base64-decode a string.
535 * This function is deprecated. Use the httpDecode64_2() function instead
536 * which provides buffer length arguments.
541 char * /* O - Decoded string */
542 httpDecode64(char *out
, /* I - String to write to */
543 const char *in
) /* I - String to read from */
545 int outlen
; /* Output buffer length */
549 * Use the old maximum buffer size for binary compatibility...
554 return (httpDecode64_2(out
, &outlen
, in
));
559 * 'httpDecode64_2()' - Base64-decode a string.
561 * @since CUPS 1.1.21/OS X 10.4@
564 char * /* O - Decoded string */
565 httpDecode64_2(char *out
, /* I - String to write to */
566 int *outlen
, /* IO - Size of output string */
567 const char *in
) /* I - String to read from */
569 int pos
, /* Bit position */
570 base64
; /* Value of this character */
571 char *outptr
, /* Output pointer */
572 *outend
; /* End of output buffer */
576 * Range check input...
579 if (!out
|| !outlen
|| *outlen
< 1 || !in
)
591 * Convert from base-64 to bytes...
594 for (outptr
= out
, outend
= out
+ *outlen
- 1, pos
= 0; *in
!= '\0'; in
++)
597 * Decode this character into a number from 0 to 63...
600 if (*in
>= 'A' && *in
<= 'Z')
602 else if (*in
>= 'a' && *in
<= 'z')
603 base64
= *in
- 'a' + 26;
604 else if (*in
>= '0' && *in
<= '9')
605 base64
= *in
- '0' + 52;
616 * Store the result in the appropriate chars...
623 *outptr
= base64
<< 2;
628 *outptr
++ |= (base64
>> 4) & 3;
630 *outptr
= (base64
<< 4) & 255;
635 *outptr
++ |= (base64
>> 2) & 15;
637 *outptr
= (base64
<< 6) & 255;
651 * Return the decoded string and size...
654 *outlen
= (int)(outptr
- out
);
661 * 'httpEncode64()' - Base64-encode a string.
663 * This function is deprecated. Use the httpEncode64_2() function instead
664 * which provides buffer length arguments.
669 char * /* O - Encoded string */
670 httpEncode64(char *out
, /* I - String to write to */
671 const char *in
) /* I - String to read from */
673 return (httpEncode64_2(out
, 512, in
, (int)strlen(in
)));
678 * 'httpEncode64_2()' - Base64-encode a string.
680 * @since CUPS 1.1.21/OS X 10.4@
683 char * /* O - Encoded string */
684 httpEncode64_2(char *out
, /* I - String to write to */
685 int outlen
, /* I - Size of output string */
686 const char *in
, /* I - String to read from */
687 int inlen
) /* I - Size of input string */
689 char *outptr
, /* Output pointer */
690 *outend
; /* End of output buffer */
691 static const char base64
[] = /* Base64 characters... */
693 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
694 "abcdefghijklmnopqrstuvwxyz"
701 * Range check input...
704 if (!out
|| outlen
< 1 || !in
)
708 * Convert bytes to base-64...
711 for (outptr
= out
, outend
= out
+ outlen
- 1; inlen
> 0; in
++, inlen
--)
714 * Encode the up to 3 characters as 4 Base64 numbers...
718 *outptr
++ = base64
[(in
[0] & 255) >> 2];
723 *outptr
++ = base64
[(((in
[0] & 255) << 4) | ((in
[1] & 255) >> 4)) & 63];
725 *outptr
++ = base64
[((in
[0] & 255) << 4) & 63];
742 *outptr
++ = base64
[(((in
[0] & 255) << 2) | ((in
[1] & 255) >> 6)) & 63];
744 *outptr
++ = base64
[((in
[0] & 255) << 2) & 63];
757 *outptr
++ = base64
[in
[0] & 63];
763 * Return the encoded string...
771 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
776 const char * /* O - Date/time string */
777 httpGetDateString(time_t t
) /* I - UNIX time */
779 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
782 return (httpGetDateString2(t
, cg
->http_date
, sizeof(cg
->http_date
)));
787 * 'httpGetDateString2()' - Get a formatted date/time string from a time value.
789 * @since CUPS 1.2/OS X 10.5@
792 const char * /* O - Date/time string */
793 httpGetDateString2(time_t t
, /* I - UNIX time */
794 char *s
, /* I - String buffer */
795 int slen
) /* I - Size of string buffer */
797 struct tm
*tdate
; /* UNIX date/time data */
802 snprintf(s
, slen
, "%s, %02d %s %d %02d:%02d:%02d GMT",
803 http_days
[tdate
->tm_wday
], tdate
->tm_mday
,
804 http_months
[tdate
->tm_mon
], tdate
->tm_year
+ 1900,
805 tdate
->tm_hour
, tdate
->tm_min
, tdate
->tm_sec
);
814 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
817 time_t /* O - UNIX time */
818 httpGetDateTime(const char *s
) /* I - Date/time string */
820 int i
; /* Looping var */
821 char mon
[16]; /* Abbreviated month name */
822 int day
, year
; /* Day of month and year */
823 int hour
, min
, sec
; /* Time */
824 int days
; /* Number of days since 1970 */
825 static const int normal_days
[] = /* Days to a month, normal years */
826 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
827 static const int leap_days
[] = /* Days to a month, leap years */
828 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 };
831 DEBUG_printf(("2httpGetDateTime(s=\"%s\")", s
));
834 * Extract the date and time from the formatted string...
837 if (sscanf(s
, "%*s%d%15s%d%d:%d:%d", &day
, mon
, &year
, &hour
, &min
, &sec
) < 6)
840 DEBUG_printf(("4httpGetDateTime: day=%d, mon=\"%s\", year=%d, hour=%d, "
841 "min=%d, sec=%d", day
, mon
, year
, hour
, min
, sec
));
844 * Convert the month name to a number from 0 to 11.
847 for (i
= 0; i
< 12; i
++)
848 if (!_cups_strcasecmp(mon
, http_months
[i
]))
854 DEBUG_printf(("4httpGetDateTime: i=%d", i
));
857 * Now convert the date and time to a UNIX time value in seconds since
858 * 1970. We can't use mktime() since the timezone may not be UTC but
859 * the date/time string *is* UTC.
862 if ((year
& 3) == 0 && ((year
% 100) != 0 || (year
% 400) == 0))
863 days
= leap_days
[i
] + day
- 1;
865 days
= normal_days
[i
] + day
- 1;
867 DEBUG_printf(("4httpGetDateTime: days=%d", days
));
869 days
+= (year
- 1970) * 365 + /* 365 days per year (normally) */
870 ((year
- 1) / 4 - 492) - /* + leap days */
871 ((year
- 1) / 100 - 19) + /* - 100 year days */
872 ((year
- 1) / 400 - 4); /* + 400 year days */
874 DEBUG_printf(("4httpGetDateTime: days=%d\n", days
));
876 return (days
* 86400 + hour
* 3600 + min
* 60 + sec
);
881 * 'httpSeparate()' - Separate a Universal Resource Identifier into its
884 * This function is deprecated; use the httpSeparateURI() function instead.
890 httpSeparate(const char *uri
, /* I - Universal Resource Identifier */
891 char *scheme
, /* O - Scheme [32] (http, https, etc.) */
892 char *username
, /* O - Username [1024] */
893 char *host
, /* O - Hostname [1024] */
894 int *port
, /* O - Port number to use */
895 char *resource
) /* O - Resource/filename [1024] */
897 httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, 32, username
,
898 HTTP_MAX_URI
, host
, HTTP_MAX_URI
, port
, resource
,
904 * 'httpSeparate2()' - Separate a Universal Resource Identifier into its
907 * This function is deprecated; use the httpSeparateURI() function instead.
909 * @since CUPS 1.1.21/OS X 10.4@
914 httpSeparate2(const char *uri
, /* I - Universal Resource Identifier */
915 char *scheme
, /* O - Scheme (http, https, etc.) */
916 int schemelen
, /* I - Size of scheme buffer */
917 char *username
, /* O - Username */
918 int usernamelen
, /* I - Size of username buffer */
919 char *host
, /* O - Hostname */
920 int hostlen
, /* I - Size of hostname buffer */
921 int *port
, /* O - Port number to use */
922 char *resource
, /* O - Resource/filename */
923 int resourcelen
) /* I - Size of resource buffer */
925 httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, schemelen
, username
,
926 usernamelen
, host
, hostlen
, port
, resource
, resourcelen
);
931 * 'httpSeparateURI()' - Separate a Universal Resource Identifier into its
934 * @since CUPS 1.2/OS X 10.5@
937 http_uri_status_t
/* O - Result of separation */
939 http_uri_coding_t decoding
, /* I - Decoding flags */
940 const char *uri
, /* I - Universal Resource Identifier */
941 char *scheme
, /* O - Scheme (http, https, etc.) */
942 int schemelen
, /* I - Size of scheme buffer */
943 char *username
, /* O - Username */
944 int usernamelen
, /* I - Size of username buffer */
945 char *host
, /* O - Hostname */
946 int hostlen
, /* I - Size of hostname buffer */
947 int *port
, /* O - Port number to use */
948 char *resource
, /* O - Resource/filename */
949 int resourcelen
) /* I - Size of resource buffer */
951 char *ptr
, /* Pointer into string... */
952 *end
; /* End of string */
953 const char *sep
; /* Separator character */
954 http_uri_status_t status
; /* Result of separation */
958 * Initialize everything to blank...
961 if (scheme
&& schemelen
> 0)
964 if (username
&& usernamelen
> 0)
967 if (host
&& hostlen
> 0)
973 if (resource
&& resourcelen
> 0)
977 * Range check input...
980 if (!uri
|| !port
|| !scheme
|| schemelen
<= 0 || !username
||
981 usernamelen
<= 0 || !host
|| hostlen
<= 0 || !resource
||
983 return (HTTP_URI_STATUS_BAD_ARGUMENTS
);
986 return (HTTP_URI_STATUS_BAD_URI
);
989 * Grab the scheme portion of the URI...
992 status
= HTTP_URI_STATUS_OK
;
994 if (!strncmp(uri
, "//", 2))
997 * Workaround for HP IPP client bug...
1000 strlcpy(scheme
, "ipp", schemelen
);
1001 status
= HTTP_URI_STATUS_MISSING_SCHEME
;
1003 else if (*uri
== '/')
1009 strlcpy(scheme
, "file", schemelen
);
1010 status
= HTTP_URI_STATUS_MISSING_SCHEME
;
1015 * Standard URI with scheme...
1018 for (ptr
= scheme
, end
= scheme
+ schemelen
- 1;
1019 *uri
&& *uri
!= ':' && ptr
< end
;)
1020 if (strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1021 "abcdefghijklmnopqrstuvwxyz"
1022 "0123456789-+.", *uri
) != NULL
)
1032 return (HTTP_URI_STATUS_BAD_SCHEME
);
1039 * Set the default port number...
1042 if (!strcmp(scheme
, "http"))
1044 else if (!strcmp(scheme
, "https"))
1046 else if (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps"))
1048 else if (!_cups_strcasecmp(scheme
, "lpd"))
1050 else if (!strcmp(scheme
, "socket")) /* Not yet registered with IANA... */
1052 else if (strcmp(scheme
, "file") && strcmp(scheme
, "mailto"))
1053 status
= HTTP_URI_STATUS_UNKNOWN_SCHEME
;
1056 * Now see if we have a hostname...
1059 if (!strncmp(uri
, "//", 2))
1062 * Yes, extract it...
1068 * Grab the username, if any...
1071 if ((sep
= strpbrk(uri
, "@/")) != NULL
&& *sep
== '@')
1074 * Get a username:password combo...
1077 uri
= http_copy_decode(username
, uri
, usernamelen
, "@",
1078 decoding
& HTTP_URI_CODING_USERNAME
);
1083 return (HTTP_URI_STATUS_BAD_USERNAME
);
1090 * Then the hostname/IP address...
1096 * Grab IPv6 address...
1100 if (!strncmp(uri
, "v1.", 3))
1101 uri
+= 3; /* Skip IPvN leader... */
1103 uri
= http_copy_decode(host
, uri
, hostlen
, "]",
1104 decoding
& HTTP_URI_CODING_HOSTNAME
);
1109 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1119 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1124 for (ptr
= host
; *ptr
; ptr
++)
1128 * Convert zone separator to % and stop here...
1134 else if (*ptr
!= ':' && *ptr
!= '.' && !isxdigit(*ptr
& 255))
1137 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1143 * Validate the hostname or IPv4 address first...
1146 for (ptr
= (char *)uri
; *ptr
; ptr
++)
1147 if (strchr(":?/", *ptr
))
1149 else if (!strchr("abcdefghijklmnopqrstuvwxyz"
1150 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1154 "!$&'()*+,;=\\", *ptr
))
1157 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1161 * Then copy the hostname or IPv4 address to the buffer...
1164 uri
= http_copy_decode(host
, uri
, hostlen
, ":?/",
1165 decoding
& HTTP_URI_CODING_HOSTNAME
);
1170 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1175 * Validate hostname for file scheme - only empty and localhost are
1179 if (!strcmp(scheme
, "file") && strcmp(host
, "localhost") && host
[0])
1182 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1186 * See if we have a port number...
1192 * Yes, collect the port number...
1195 if (!isdigit(uri
[1] & 255))
1198 return (HTTP_URI_STATUS_BAD_PORT
);
1201 *port
= strtol(uri
+ 1, (char **)&uri
, 10);
1203 if (*uri
!= '/' && *uri
)
1206 return (HTTP_URI_STATUS_BAD_PORT
);
1212 * The remaining portion is the resource string...
1215 if (*uri
== '?' || !*uri
)
1218 * Hostname but no path...
1221 status
= HTTP_URI_STATUS_MISSING_RESOURCE
;
1225 * Copy any query string...
1229 uri
= http_copy_decode(resource
+ 1, uri
, resourcelen
- 1, NULL
,
1230 decoding
& HTTP_URI_CODING_QUERY
);
1236 uri
= http_copy_decode(resource
, uri
, resourcelen
, "?",
1237 decoding
& HTTP_URI_CODING_RESOURCE
);
1239 if (uri
&& *uri
== '?')
1242 * Concatenate any query string...
1245 char *resptr
= resource
+ strlen(resource
);
1247 uri
= http_copy_decode(resptr
, uri
, resourcelen
- (int)(resptr
- resource
),
1248 NULL
, decoding
& HTTP_URI_CODING_QUERY
);
1255 return (HTTP_URI_STATUS_BAD_RESOURCE
);
1259 * Return the URI separation status...
1267 * 'httpStatus()' - Return a short string describing a HTTP status code.
1269 * The returned string is localized to the current POSIX locale and is based
1270 * on the status strings defined in RFC 2616.
1273 const char * /* O - Localized status string */
1274 httpStatus(http_status_t status
) /* I - HTTP status code */
1276 const char *s
; /* Status string */
1277 _cups_globals_t
*cg
= _cupsGlobals(); /* Global data */
1280 if (!cg
->lang_default
)
1281 cg
->lang_default
= cupsLangDefault();
1285 case HTTP_STATUS_CONTINUE
:
1288 case HTTP_STATUS_SWITCHING_PROTOCOLS
:
1289 s
= _("Switching Protocols");
1291 case HTTP_STATUS_OK
:
1294 case HTTP_STATUS_CREATED
:
1297 case HTTP_STATUS_ACCEPTED
:
1300 case HTTP_STATUS_NO_CONTENT
:
1301 s
= _("No Content");
1303 case HTTP_STATUS_MOVED_PERMANENTLY
:
1304 s
= _("Moved Permanently");
1306 case HTTP_STATUS_SEE_OTHER
:
1309 case HTTP_STATUS_NOT_MODIFIED
:
1310 s
= _("Not Modified");
1312 case HTTP_STATUS_BAD_REQUEST
:
1313 s
= _("Bad Request");
1315 case HTTP_STATUS_UNAUTHORIZED
:
1316 case HTTP_STATUS_CUPS_AUTHORIZATION_CANCELED
:
1317 s
= _("Unauthorized");
1319 case HTTP_STATUS_FORBIDDEN
:
1322 case HTTP_STATUS_NOT_FOUND
:
1325 case HTTP_STATUS_REQUEST_TOO_LARGE
:
1326 s
= _("Request Entity Too Large");
1328 case HTTP_STATUS_URI_TOO_LONG
:
1329 s
= _("URI Too Long");
1331 case HTTP_STATUS_UPGRADE_REQUIRED
:
1332 s
= _("Upgrade Required");
1334 case HTTP_STATUS_NOT_IMPLEMENTED
:
1335 s
= _("Not Implemented");
1337 case HTTP_STATUS_NOT_SUPPORTED
:
1338 s
= _("Not Supported");
1340 case HTTP_STATUS_EXPECTATION_FAILED
:
1341 s
= _("Expectation Failed");
1343 case HTTP_STATUS_SERVICE_UNAVAILABLE
:
1344 s
= _("Service Unavailable");
1346 case HTTP_STATUS_SERVER_ERROR
:
1347 s
= _("Internal Server Error");
1349 case HTTP_STATUS_CUPS_PKI_ERROR
:
1350 s
= _("SSL/TLS Negotiation Error");
1352 case HTTP_STATUS_CUPS_WEBIF_DISABLED
:
1353 s
= _("Web Interface is Disabled");
1361 return (_cupsLangString(cg
->lang_default
, s
));
1365 #ifndef HAVE_HSTRERROR
1367 * '_cups_hstrerror()' - hstrerror() emulation function for Solaris and others.
1370 const char * /* O - Error string */
1371 _cups_hstrerror(int error
) /* I - Error number */
1373 static const char * const errors
[] = /* Error strings */
1378 "Unrecoverable lookup error.",
1379 "No data associated with name."
1383 if (error
< 0 || error
> 4)
1384 return ("Unknown hostname lookup error.");
1386 return (errors
[error
]);
1388 #endif /* !HAVE_HSTRERROR */
1392 * '_httpDecodeURI()' - Percent-decode a HTTP request URI.
1395 char * /* O - Decoded URI or NULL on error */
1396 _httpDecodeURI(char *dst
, /* I - Destination buffer */
1397 const char *src
, /* I - Source URI */
1398 size_t dstsize
) /* I - Size of destination buffer */
1400 if (http_copy_decode(dst
, src
, (int)dstsize
, NULL
, 1))
1408 * '_httpEncodeURI()' - Percent-encode a HTTP request URI.
1411 char * /* O - Encoded URI */
1412 _httpEncodeURI(char *dst
, /* I - Destination buffer */
1413 const char *src
, /* I - Source URI */
1414 size_t dstsize
) /* I - Size of destination buffer */
1416 http_copy_encode(dst
, src
, dst
+ dstsize
- 1, NULL
, NULL
, 1);
1422 * '_httpResolveURI()' - Resolve a DNS-SD URI.
1425 const char * /* O - Resolved URI */
1427 const char *uri
, /* I - DNS-SD URI */
1428 char *resolved_uri
, /* I - Buffer for resolved URI */
1429 size_t resolved_size
, /* I - Size of URI buffer */
1430 int options
, /* I - Resolve options */
1431 int (*cb
)(void *context
), /* I - Continue callback function */
1432 void *context
) /* I - Context pointer for callback */
1434 char scheme
[32], /* URI components... */
1440 http_uri_status_t status
; /* URI decode status */
1444 DEBUG_printf(("4_httpResolveURI(uri=\"%s\", resolved_uri=%p, "
1445 "resolved_size=" CUPS_LLFMT
")", uri
, resolved_uri
,
1446 CUPS_LLCAST resolved_size
));
1449 * Get the device URI...
1453 if ((status
= httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
,
1454 sizeof(scheme
), userpass
, sizeof(userpass
),
1455 hostname
, sizeof(hostname
), &port
, resource
,
1456 sizeof(resource
))) < HTTP_URI_STATUS_OK
)
1458 if (httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
,
1459 sizeof(scheme
), userpass
, sizeof(userpass
),
1460 hostname
, sizeof(hostname
), &port
, resource
,
1461 sizeof(resource
)) < HTTP_URI_STATUS_OK
)
1464 if (options
& _HTTP_RESOLVE_STDERR
)
1465 _cupsLangPrintFilter(stderr
, "ERROR", _("Bad device-uri \"%s\"."), uri
);
1467 DEBUG_printf(("6_httpResolveURI: httpSeparateURI returned %d!", status
));
1468 DEBUG_puts("5_httpResolveURI: Returning NULL");
1473 * Resolve it as needed...
1476 if (strstr(hostname
, "._tcp"))
1478 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
1479 char *regtype
, /* Pointer to type in hostname */
1480 *domain
; /* Pointer to domain in hostname */
1481 _http_uribuf_t uribuf
; /* URI buffer */
1482 int offline
= 0; /* offline-report state set? */
1485 # pragma comment(lib, "dnssd.lib")
1487 DNSServiceRef ref
, /* DNS-SD master service reference */
1488 domainref
, /* DNS-SD service reference for domain */
1489 localref
; /* DNS-SD service reference for .local */
1490 int domainsent
= 0; /* Send the domain resolve? */
1492 struct pollfd polldata
; /* Polling data */
1493 # else /* select() */
1494 fd_set input_set
; /* Input set for select() */
1495 struct timeval stimeout
; /* Timeout value for select() */
1496 # endif /* HAVE_POLL */
1497 # elif defined(HAVE_AVAHI)
1498 AvahiClient
*client
; /* Client information */
1499 int error
; /* Status */
1500 # endif /* HAVE_DNSSD */
1502 if (options
& _HTTP_RESOLVE_STDERR
)
1503 fprintf(stderr
, "DEBUG: Resolving \"%s\"...\n", hostname
);
1506 * Separate the hostname into service name, registration type, and domain...
1509 for (regtype
= strstr(hostname
, "._tcp") - 2;
1512 if (regtype
[0] == '.' && regtype
[1] == '_')
1515 * Found ._servicetype in front of ._tcp...
1522 if (regtype
<= hostname
)
1524 DEBUG_puts("5_httpResolveURI: Bad hostname, returning NULL");
1528 for (domain
= strchr(regtype
, '.');
1530 domain
= strchr(domain
+ 1, '.'))
1531 if (domain
[1] != '_')
1537 uribuf
.buffer
= resolved_uri
;
1538 uribuf
.bufsize
= resolved_size
;
1539 uribuf
.options
= options
;
1540 uribuf
.resource
= resource
;
1542 resolved_uri
[0] = '\0';
1544 DEBUG_printf(("6_httpResolveURI: Resolving hostname=\"%s\", regtype=\"%s\", "
1545 "domain=\"%s\"\n", hostname
, regtype
, domain
));
1546 if (options
& _HTTP_RESOLVE_STDERR
)
1548 fputs("STATE: +connecting-to-device\n", stderr
);
1549 fprintf(stderr
, "DEBUG: Resolving \"%s\", regtype=\"%s\", "
1550 "domain=\"local.\"...\n", hostname
, regtype
);
1556 if (DNSServiceCreateConnection(&ref
) == kDNSServiceErr_NoError
)
1558 int myinterface
= kDNSServiceInterfaceIndexAny
;
1559 /* Lookup on any interface */
1561 if (!strcmp(scheme
, "ippusb"))
1562 myinterface
= kDNSServiceInterfaceIndexLocalOnly
;
1565 if (DNSServiceResolve(&localref
,
1566 kDNSServiceFlagsShareConnection
, myinterface
,
1567 hostname
, regtype
, "local.", http_resolve_cb
,
1568 &uribuf
) == kDNSServiceErr_NoError
)
1570 int fds
; /* Number of ready descriptors */
1571 time_t timeout
, /* Poll timeout */
1572 start_time
= time(NULL
),/* Start time */
1573 end_time
= start_time
+ 90;
1576 while (time(NULL
) < end_time
)
1578 if (options
& _HTTP_RESOLVE_STDERR
)
1579 _cupsLangPrintFilter(stderr
, "INFO", _("Looking for printer."));
1581 if (cb
&& !(*cb
)(context
))
1583 DEBUG_puts("5_httpResolveURI: callback returned 0 (stop)");
1588 * Wakeup every 2 seconds to emit a "looking for printer" message...
1591 if ((timeout
= end_time
- time(NULL
)) > 2)
1595 polldata
.fd
= DNSServiceRefSockFD(ref
);
1596 polldata
.events
= POLLIN
;
1598 fds
= poll(&polldata
, 1, 1000 * timeout
);
1600 # else /* select() */
1601 FD_ZERO(&input_set
);
1602 FD_SET(DNSServiceRefSockFD(ref
), &input_set
);
1605 stimeout
.tv_sec
= (long)timeout
;
1607 stimeout
.tv_sec
= timeout
;
1609 stimeout
.tv_usec
= 0;
1611 fds
= select(DNSServiceRefSockFD(ref
)+1, &input_set
, NULL
, NULL
,
1613 # endif /* HAVE_POLL */
1617 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1619 DEBUG_printf(("5_httpResolveURI: poll error: %s", strerror(errno
)));
1626 * Wait 2 seconds for a response to the local resolve; if nothing
1627 * comes in, do an additional domain resolution...
1630 if (domainsent
== 0 && domain
&& _cups_strcasecmp(domain
, "local."))
1632 if (options
& _HTTP_RESOLVE_STDERR
)
1634 "DEBUG: Resolving \"%s\", regtype=\"%s\", "
1635 "domain=\"%s\"...\n", hostname
, regtype
,
1636 domain
? domain
: "");
1639 if (DNSServiceResolve(&domainref
,
1640 kDNSServiceFlagsShareConnection
,
1641 myinterface
, hostname
, regtype
, domain
,
1643 &uribuf
) == kDNSServiceErr_NoError
)
1648 * If it hasn't resolved within 5 seconds set the offline-report
1649 * printer-state-reason...
1652 if ((options
& _HTTP_RESOLVE_STDERR
) && offline
== 0 &&
1653 time(NULL
) > (start_time
+ 5))
1655 fputs("STATE: +offline-report\n", stderr
);
1661 if (DNSServiceProcessResult(ref
) == kDNSServiceErr_NoError
)
1670 DNSServiceRefDeallocate(domainref
);
1672 DNSServiceRefDeallocate(localref
);
1675 DNSServiceRefDeallocate(ref
);
1677 # else /* HAVE_AVAHI */
1678 if ((uribuf
.poll
= avahi_simple_poll_new()) != NULL
)
1680 avahi_simple_poll_set_func(uribuf
.poll
, http_poll_cb
, NULL
);
1682 if ((client
= avahi_client_new(avahi_simple_poll_get(uribuf
.poll
),
1684 &uribuf
, &error
)) != NULL
)
1686 if (avahi_service_resolver_new(client
, AVAHI_IF_UNSPEC
,
1687 AVAHI_PROTO_UNSPEC
, hostname
,
1688 regtype
, "local.", AVAHI_PROTO_UNSPEC
, 0,
1689 http_resolve_cb
, &uribuf
) != NULL
)
1691 time_t start_time
= time(NULL
),
1693 end_time
= start_time
+ 90;
1695 int pstatus
; /* Poll status */
1697 pstatus
= avahi_simple_poll_iterate(uribuf
.poll
, 2000);
1699 if (pstatus
== 0 && !resolved_uri
[0] && domain
&&
1700 _cups_strcasecmp(domain
, "local."))
1703 * Resolve for .local hasn't returned anything, try the listed
1707 avahi_service_resolver_new(client
, AVAHI_IF_UNSPEC
,
1708 AVAHI_PROTO_UNSPEC
, hostname
,
1709 regtype
, domain
, AVAHI_PROTO_UNSPEC
, 0,
1710 http_resolve_cb
, &uribuf
);
1713 while (!pstatus
&& !resolved_uri
[0] && time(NULL
) < end_time
)
1715 if ((pstatus
= avahi_simple_poll_iterate(uribuf
.poll
, 2000)) != 0)
1719 * If it hasn't resolved within 5 seconds set the offline-report
1720 * printer-state-reason...
1723 if ((options
& _HTTP_RESOLVE_STDERR
) && offline
== 0 &&
1724 time(NULL
) > (start_time
+ 5))
1726 fputs("STATE: +offline-report\n", stderr
);
1732 * Collect the result (if we got one).
1735 if (resolved_uri
[0])
1739 avahi_client_free(client
);
1742 avahi_simple_poll_free(uribuf
.poll
);
1744 # endif /* HAVE_DNSSD */
1746 if (options
& _HTTP_RESOLVE_STDERR
)
1750 fprintf(stderr
, "DEBUG: Resolved as \"%s\"...\n", uri
);
1751 fputs("STATE: -connecting-to-device,offline-report\n", stderr
);
1755 fputs("DEBUG: Unable to resolve URI\n", stderr
);
1756 fputs("STATE: -connecting-to-device\n", stderr
);
1760 #else /* HAVE_DNSSD || HAVE_AVAHI */
1762 * No DNS-SD support...
1766 #endif /* HAVE_DNSSD || HAVE_AVAHI */
1768 if ((options
& _HTTP_RESOLVE_STDERR
) && !uri
)
1769 _cupsLangPrintFilter(stderr
, "INFO", _("Unable to find printer."));
1774 * Nothing more to do...
1777 strlcpy(resolved_uri
, uri
, resolved_size
);
1781 DEBUG_printf(("5_httpResolveURI: Returning \"%s\"", uri
));
1789 * 'http_client_cb()' - Client callback for resolving URI.
1794 AvahiClient
*client
, /* I - Client information */
1795 AvahiClientState state
, /* I - Current state */
1796 void *context
) /* I - Pointer to URI buffer */
1798 DEBUG_printf(("7http_client_cb(client=%p, state=%d, context=%p)", client
,
1802 * If the connection drops, quit.
1805 if (state
== AVAHI_CLIENT_FAILURE
)
1807 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
1810 avahi_simple_poll_quit(uribuf
->poll
);
1813 #endif /* HAVE_AVAHI */
1817 * 'http_copy_decode()' - Copy and decode a URI.
1820 static const char * /* O - New source pointer or NULL on error */
1821 http_copy_decode(char *dst
, /* O - Destination buffer */
1822 const char *src
, /* I - Source pointer */
1823 int dstsize
, /* I - Destination size */
1824 const char *term
, /* I - Terminating characters */
1825 int decode
) /* I - Decode %-encoded values */
1827 char *ptr
, /* Pointer into buffer */
1828 *end
; /* End of buffer */
1829 int quoted
; /* Quoted character */
1833 * Copy the src to the destination until we hit a terminating character
1834 * or the end of the string.
1837 for (ptr
= dst
, end
= dst
+ dstsize
- 1;
1838 *src
&& (!term
|| !strchr(term
, *src
));
1842 if (*src
== '%' && decode
)
1844 if (isxdigit(src
[1] & 255) && isxdigit(src
[2] & 255))
1847 * Grab a hex-encoded character...
1852 quoted
= (tolower(*src
) - 'a' + 10) << 4;
1854 quoted
= (*src
- '0') << 4;
1858 quoted
|= tolower(*src
) - 'a' + 10;
1860 quoted
|= *src
- '0';
1867 * Bad hex-encoded character...
1874 else if ((*src
& 255) <= 0x20 || (*src
& 255) >= 0x7f)
1890 * 'http_copy_encode()' - Copy and encode a URI.
1893 static char * /* O - End of current URI */
1894 http_copy_encode(char *dst
, /* O - Destination buffer */
1895 const char *src
, /* I - Source pointer */
1896 char *dstend
, /* I - End of destination buffer */
1897 const char *reserved
, /* I - Extra reserved characters */
1898 const char *term
, /* I - Terminating characters */
1899 int encode
) /* I - %-encode reserved chars? */
1901 static const char hex
[] = "0123456789ABCDEF";
1904 while (*src
&& dst
< dstend
)
1906 if (term
&& *src
== *term
)
1909 if (encode
&& (*src
== '%' || *src
<= ' ' || *src
& 128 ||
1910 (reserved
&& strchr(reserved
, *src
))))
1913 * Hex encode reserved characters...
1916 if ((dst
+ 2) >= dstend
)
1920 *dst
++ = hex
[(*src
>> 4) & 15];
1921 *dst
++ = hex
[*src
& 15];
1940 * 'http_resolve_cb()' - Build a device URI for the given service name.
1943 static void DNSSD_API
1945 DNSServiceRef sdRef
, /* I - Service reference */
1946 DNSServiceFlags flags
, /* I - Results flags */
1947 uint32_t interfaceIndex
, /* I - Interface number */
1948 DNSServiceErrorType errorCode
, /* I - Error, if any */
1949 const char *fullName
, /* I - Full service name */
1950 const char *hostTarget
, /* I - Hostname */
1951 uint16_t port
, /* I - Port number */
1952 uint16_t txtLen
, /* I - Length of TXT record */
1953 const unsigned char *txtRecord
, /* I - TXT record data */
1954 void *context
) /* I - Pointer to URI buffer */
1956 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
1958 const char *scheme
, /* URI scheme */
1959 *hostptr
, /* Pointer into hostTarget */
1960 *reskey
, /* "rp" or "rfo" */
1961 *resdefault
; /* Default path */
1962 char resource
[257], /* Remote path */
1963 fqdn
[256]; /* FQDN of the .local name */
1964 const void *value
; /* Value from TXT record */
1965 uint8_t valueLen
; /* Length of value */
1968 DEBUG_printf(("7http_resolve_cb(sdRef=%p, flags=%x, interfaceIndex=%u, "
1969 "errorCode=%d, fullName=\"%s\", hostTarget=\"%s\", port=%u, "
1970 "txtLen=%u, txtRecord=%p, context=%p)", sdRef
, flags
,
1971 interfaceIndex
, errorCode
, fullName
, hostTarget
, port
, txtLen
,
1972 txtRecord
, context
));
1975 * Figure out the scheme from the full name...
1978 if (strstr(fullName
, "._ipps") || strstr(fullName
, "._ipp-tls"))
1980 else if (strstr(fullName
, "._ipp") || strstr(fullName
, "._fax-ipp"))
1982 else if (strstr(fullName
, "._http."))
1984 else if (strstr(fullName
, "._https."))
1986 else if (strstr(fullName
, "._printer."))
1988 else if (strstr(fullName
, "._pdl-datastream."))
1991 scheme
= "riousbprint";
1994 * Extract the "remote printer" key from the TXT record...
1997 if ((uribuf
->options
& _HTTP_RESOLVE_FAXOUT
) &&
1998 (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")))
2001 resdefault
= "/ipp/faxout";
2009 if ((value
= TXTRecordGetValuePtr(txtLen
, txtRecord
, reskey
,
2010 &valueLen
)) != NULL
)
2012 if (((char *)value
)[0] == '/')
2015 * Value (incorrectly) has a leading slash already...
2018 memcpy(resource
, value
, valueLen
);
2019 resource
[valueLen
] = '\0';
2024 * Convert to resource by concatenating with a leading "/"...
2028 memcpy(resource
+ 1, value
, valueLen
);
2029 resource
[valueLen
+ 1] = '\0';
2035 * Use the default value...
2038 strlcpy(resource
, resdefault
, sizeof(resource
));
2042 * Lookup the FQDN if needed...
2045 if ((uribuf
->options
& _HTTP_RESOLVE_FQDN
) &&
2046 (hostptr
= hostTarget
+ strlen(hostTarget
) - 7) > hostTarget
&&
2047 !_cups_strcasecmp(hostptr
, ".local."))
2050 * OK, we got a .local name but the caller needs a real domain. Start by
2051 * getting the IP address of the .local name and then do reverse-lookups...
2054 http_addrlist_t
*addrlist
, /* List of addresses */
2055 *addr
; /* Current address */
2057 DEBUG_printf(("8http_resolve_cb: Looking up \"%s\".", hostTarget
));
2059 snprintf(fqdn
, sizeof(fqdn
), "%d", ntohs(port
));
2060 if ((addrlist
= httpAddrGetList(hostTarget
, AF_UNSPEC
, fqdn
)) != NULL
)
2062 for (addr
= addrlist
; addr
; addr
= addr
->next
)
2064 int error
= getnameinfo(&(addr
->addr
.addr
),
2065 httpAddrLength(&(addr
->addr
)),
2066 fqdn
, sizeof(fqdn
), NULL
, 0, NI_NAMEREQD
);
2070 DEBUG_printf(("8http_resolve_cb: Found \"%s\".", fqdn
));
2072 if ((hostptr
= fqdn
+ strlen(fqdn
) - 6) <= fqdn
||
2073 _cups_strcasecmp(hostptr
, ".local"))
2081 DEBUG_printf(("8http_resolve_cb: \"%s\" did not resolve: %d",
2082 httpAddrString(&(addr
->addr
), fqdn
, sizeof(fqdn
)),
2087 httpAddrFreeList(addrlist
);
2092 * Assemble the final device URI...
2095 if ((!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")) &&
2096 !strcmp(uribuf
->resource
, "/cups"))
2097 httpAssembleURIf(HTTP_URI_CODING_ALL
, uribuf
->buffer
, uribuf
->bufsize
,
2098 scheme
, NULL
, hostTarget
, ntohs(port
), "%s?snmp=false",
2101 httpAssembleURI(HTTP_URI_CODING_ALL
, uribuf
->buffer
, uribuf
->bufsize
,
2102 scheme
, NULL
, hostTarget
, ntohs(port
), resource
);
2104 DEBUG_printf(("8http_resolve_cb: Resolved URI is \"%s\"...", uribuf
->buffer
));
2107 #elif defined(HAVE_AVAHI)
2109 * 'http_poll_cb()' - Wait for input on the specified file descriptors.
2111 * Note: This function is needed because avahi_simple_poll_iterate is broken
2112 * and always uses a timeout of 0 (!) milliseconds.
2113 * (Avahi Ticket #364)
2116 static int /* O - Number of file descriptors matching */
2118 struct pollfd
*pollfds
, /* I - File descriptors */
2119 unsigned int num_pollfds
, /* I - Number of file descriptors */
2120 int timeout
, /* I - Timeout in milliseconds (used) */
2121 void *context
) /* I - User data (unused) */
2126 return (poll(pollfds
, num_pollfds
, 2000));
2131 * 'http_resolve_cb()' - Build a device URI for the given service name.
2136 AvahiServiceResolver
*resolver
, /* I - Resolver (unused) */
2137 AvahiIfIndex interface
, /* I - Interface index (unused) */
2138 AvahiProtocol protocol
, /* I - Network protocol (unused) */
2139 AvahiResolverEvent event
, /* I - Event (found, etc.) */
2140 const char *name
, /* I - Service name */
2141 const char *type
, /* I - Registration type */
2142 const char *domain
, /* I - Domain (unused) */
2143 const char *hostTarget
, /* I - Hostname */
2144 const AvahiAddress
*address
, /* I - Address (unused) */
2145 uint16_t port
, /* I - Port number */
2146 AvahiStringList
*txt
, /* I - TXT record */
2147 AvahiLookupResultFlags flags
, /* I - Lookup flags (unused) */
2148 void *context
) /* I - Pointer to URI buffer */
2150 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
2152 const char *scheme
, /* URI scheme */
2153 *hostptr
, /* Pointer into hostTarget */
2154 *reskey
, /* "rp" or "rfo" */
2155 *resdefault
; /* Default path */
2156 char resource
[257], /* Remote path */
2157 fqdn
[256]; /* FQDN of the .local name */
2158 AvahiStringList
*pair
; /* Current TXT record key/value pair */
2159 char *value
; /* Value for "rp" key */
2160 size_t valueLen
= 0; /* Length of "rp" key */
2163 DEBUG_printf(("7http_resolve_cb(resolver=%p, "
2164 "interface=%d, protocol=%d, event=%d, name=\"%s\", "
2165 "type=\"%s\", domain=\"%s\", hostTarget=\"%s\", address=%p, "
2166 "port=%d, txt=%p, flags=%d, context=%p)",
2167 resolver
, interface
, protocol
, event
, name
, type
, domain
,
2168 hostTarget
, address
, port
, txt
, flags
, context
));
2170 if (event
!= AVAHI_RESOLVER_FOUND
)
2172 avahi_service_resolver_free(resolver
);
2173 avahi_simple_poll_quit(uribuf
->poll
);
2178 * Figure out the scheme from the full name...
2181 if (strstr(type
, "_ipp."))
2183 else if (strstr(type
, "_printer."))
2185 else if (strstr(type
, "_pdl-datastream."))
2188 scheme
= "riousbprint";
2190 if (!strncmp(type
, "_ipps.", 6) || !strncmp(type
, "_ipp-tls.", 9))
2192 else if (!strncmp(type
, "_ipp.", 5) || !strncmp(type
, "_fax-ipp.", 9))
2194 else if (!strncmp(type
, "_http.", 6))
2196 else if (!strncmp(type
, "_https.", 7))
2198 else if (!strncmp(type
, "_printer.", 9))
2200 else if (!strncmp(type
, "_pdl-datastream.", 16))
2204 avahi_service_resolver_free(resolver
);
2205 avahi_simple_poll_quit(uribuf
->poll
);
2210 * Extract the remote resource key from the TXT record...
2213 if ((uribuf
->options
& _HTTP_RESOLVE_FAXOUT
) &&
2214 (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")))
2217 resdefault
= "/ipp/faxout";
2225 if ((pair
= avahi_string_list_find(txt
, reskey
)) != NULL
)
2227 avahi_string_list_get_pair(pair
, NULL
, &value
, &valueLen
);
2229 if (value
[0] == '/')
2232 * Value (incorrectly) has a leading slash already...
2235 memcpy(resource
, value
, valueLen
);
2236 resource
[valueLen
] = '\0';
2241 * Convert to resource by concatenating with a leading "/"...
2245 memcpy(resource
+ 1, value
, valueLen
);
2246 resource
[valueLen
+ 1] = '\0';
2252 * Use the default value...
2255 strlcpy(resource
, resdefault
, sizeof(resource
));
2259 * Lookup the FQDN if needed...
2262 if ((uribuf
->options
& _HTTP_RESOLVE_FQDN
) &&
2263 (hostptr
= hostTarget
+ strlen(hostTarget
) - 6) > hostTarget
&&
2264 !_cups_strcasecmp(hostptr
, ".local"))
2267 * OK, we got a .local name but the caller needs a real domain. Start by
2268 * getting the IP address of the .local name and then do reverse-lookups...
2271 http_addrlist_t
*addrlist
, /* List of addresses */
2272 *addr
; /* Current address */
2274 DEBUG_printf(("8http_resolve_cb: Looking up \"%s\".", hostTarget
));
2276 snprintf(fqdn
, sizeof(fqdn
), "%d", ntohs(port
));
2277 if ((addrlist
= httpAddrGetList(hostTarget
, AF_UNSPEC
, fqdn
)) != NULL
)
2279 for (addr
= addrlist
; addr
; addr
= addr
->next
)
2281 int error
= getnameinfo(&(addr
->addr
.addr
),
2282 httpAddrLength(&(addr
->addr
)),
2283 fqdn
, sizeof(fqdn
), NULL
, 0, NI_NAMEREQD
);
2287 DEBUG_printf(("8http_resolve_cb: Found \"%s\".", fqdn
));
2289 if ((hostptr
= fqdn
+ strlen(fqdn
) - 6) <= fqdn
||
2290 _cups_strcasecmp(hostptr
, ".local"))
2298 DEBUG_printf(("8http_resolve_cb: \"%s\" did not resolve: %d",
2299 httpAddrString(&(addr
->addr
), fqdn
, sizeof(fqdn
)),
2304 httpAddrFreeList(addrlist
);
2309 * Assemble the final device URI using the resolved hostname...
2312 httpAssembleURI(HTTP_URI_CODING_ALL
, uribuf
->buffer
, uribuf
->bufsize
, scheme
,
2313 NULL
, hostTarget
, port
, resource
);
2314 DEBUG_printf(("8http_resolve_cb: Resolved URI is \"%s\".", uribuf
->buffer
));
2316 avahi_simple_poll_quit(uribuf
->poll
);
2318 #endif /* HAVE_DNSSD */
2322 * End of "$Id: http-support.c 7952 2008-09-17 00:56:20Z mike $".