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
, '%') && !(encoding
& HTTP_URI_CODING_RFC6874
))
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
)
312 * Convert/encode zone separator
315 if (encoding
& HTTP_URI_CODING_RFC6874
)
317 if (ptr
>= (end
- 2))
318 goto assemble_overflow
;
334 goto assemble_overflow
;
339 goto assemble_overflow
;
344 * Otherwise, just copy the host string...
346 ptr
= http_copy_encode(ptr
, host
, end
, "<>{}|^:/?#[]@\\\"", NULL
,
347 encoding
& HTTP_URI_CODING_HOSTNAME
);
350 goto assemble_overflow
;
354 * Finish things off with the port number...
359 snprintf(ptr
, end
- ptr
+ 1, ":%d", port
);
363 goto assemble_overflow
;
368 * Last but not least, add the resource string...
373 char *query
; /* Pointer to query string */
377 * Copy the resource string up to the query string if present...
380 query
= strchr(resource
, '?');
381 ptr
= http_copy_encode(ptr
, resource
, end
, NULL
, "?",
382 encoding
& HTTP_URI_CODING_RESOURCE
);
384 goto assemble_overflow
;
389 * Copy query string without encoding...
392 ptr
= http_copy_encode(ptr
, query
, end
, NULL
, NULL
,
393 encoding
& HTTP_URI_CODING_QUERY
);
395 goto assemble_overflow
;
401 goto assemble_overflow
;
404 * Nul-terminate the URI buffer and return with no errors...
409 return (HTTP_URI_STATUS_OK
);
412 * Clear the URI string and return an overflow error; I don't usually
413 * like goto's, but in this case it makes sense...
419 return (HTTP_URI_STATUS_OVERFLOW
);
424 * 'httpAssembleURIf()' - Assemble a uniform resource identifier from its
425 * components with a formatted resource.
427 * This function creates a formatted version of the resource string
428 * argument "resourcef" and escapes reserved characters in the URI
429 * depending on the value of the "encoding" argument. You should use
430 * this function in place of traditional string functions whenever
431 * you need to create a URI string.
433 * @since CUPS 1.2/OS X 10.5@
436 http_uri_status_t
/* O - URI status */
438 http_uri_coding_t encoding
, /* I - Encoding flags */
439 char *uri
, /* I - URI buffer */
440 int urilen
, /* I - Size of URI buffer */
441 const char *scheme
, /* I - Scheme name */
442 const char *username
, /* I - Username */
443 const char *host
, /* I - Hostname or address */
444 int port
, /* I - Port number */
445 const char *resourcef
, /* I - Printf-style resource */
446 ...) /* I - Additional arguments as needed */
448 va_list ap
; /* Pointer to additional arguments */
449 char resource
[1024]; /* Formatted resource string */
450 int bytes
; /* Bytes in formatted string */
454 * Range check input...
457 if (!uri
|| urilen
< 1 || !scheme
|| port
< 0 || !resourcef
)
462 return (HTTP_URI_STATUS_BAD_ARGUMENTS
);
466 * Format the resource string and assemble the URI...
469 va_start(ap
, resourcef
);
470 bytes
= vsnprintf(resource
, sizeof(resource
), resourcef
, ap
);
473 if (bytes
>= sizeof(resource
))
476 return (HTTP_URI_STATUS_OVERFLOW
);
479 return (httpAssembleURI(encoding
, uri
, urilen
, scheme
, username
, host
,
485 * 'httpAssembleUUID()' - Assemble a name-based UUID URN conforming to RFC 4122.
487 * This function creates a unique 128-bit identifying number using the server
488 * name, port number, random data, and optionally an object name and/or object
489 * number. The result is formatted as a UUID URN as defined in RFC 4122.
491 * The buffer needs to be at least 46 bytes in size.
496 char * /* I - UUID string */
497 httpAssembleUUID(const char *server
, /* I - Server name */
498 int port
, /* I - Port number */
499 const char *name
, /* I - Object name or NULL */
500 int number
, /* I - Object number or 0 */
501 char *buffer
, /* I - String buffer */
502 size_t bufsize
) /* I - Size of buffer */
504 char data
[1024]; /* Source string for MD5 */
505 _cups_md5_state_t md5state
; /* MD5 state */
506 unsigned char md5sum
[16]; /* MD5 digest/sum */
510 * Build a version 3 UUID conforming to RFC 4122.
512 * Start with the MD5 sum of the server, port, object name and
513 * number, and some random data on the end.
516 snprintf(data
, sizeof(data
), "%s:%d:%s:%d:%04x:%04x", server
,
517 port
, name
? name
: server
, number
,
518 (unsigned)CUPS_RAND() & 0xffff, (unsigned)CUPS_RAND() & 0xffff);
520 _cupsMD5Init(&md5state
);
521 _cupsMD5Append(&md5state
, (unsigned char *)data
, strlen(data
));
522 _cupsMD5Finish(&md5state
, md5sum
);
525 * Generate the UUID from the MD5...
528 snprintf(buffer
, bufsize
,
529 "urn:uuid:%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-"
530 "%02x%02x%02x%02x%02x%02x",
531 md5sum
[0], md5sum
[1], md5sum
[2], md5sum
[3], md5sum
[4], md5sum
[5],
532 (md5sum
[6] & 15) | 0x30, md5sum
[7], (md5sum
[8] & 0x3f) | 0x40,
533 md5sum
[9], md5sum
[10], md5sum
[11], md5sum
[12], md5sum
[13],
534 md5sum
[14], md5sum
[15]);
539 /* For OS X 10.8 and earlier */
540 char *_httpAssembleUUID(const char *server
, int port
, const char *name
,
541 int number
, char *buffer
, size_t bufsize
)
543 return (httpAssembleUUID(server
, port
, name
, number
, buffer
, bufsize
));
548 * 'httpDecode64()' - Base64-decode a string.
550 * This function is deprecated. Use the httpDecode64_2() function instead
551 * which provides buffer length arguments.
556 char * /* O - Decoded string */
557 httpDecode64(char *out
, /* I - String to write to */
558 const char *in
) /* I - String to read from */
560 int outlen
; /* Output buffer length */
564 * Use the old maximum buffer size for binary compatibility...
569 return (httpDecode64_2(out
, &outlen
, in
));
574 * 'httpDecode64_2()' - Base64-decode a string.
576 * @since CUPS 1.1.21/OS X 10.4@
579 char * /* O - Decoded string */
580 httpDecode64_2(char *out
, /* I - String to write to */
581 int *outlen
, /* IO - Size of output string */
582 const char *in
) /* I - String to read from */
584 int pos
, /* Bit position */
585 base64
; /* Value of this character */
586 char *outptr
, /* Output pointer */
587 *outend
; /* End of output buffer */
591 * Range check input...
594 if (!out
|| !outlen
|| *outlen
< 1 || !in
)
606 * Convert from base-64 to bytes...
609 for (outptr
= out
, outend
= out
+ *outlen
- 1, pos
= 0; *in
!= '\0'; in
++)
612 * Decode this character into a number from 0 to 63...
615 if (*in
>= 'A' && *in
<= 'Z')
617 else if (*in
>= 'a' && *in
<= 'z')
618 base64
= *in
- 'a' + 26;
619 else if (*in
>= '0' && *in
<= '9')
620 base64
= *in
- '0' + 52;
631 * Store the result in the appropriate chars...
638 *outptr
= base64
<< 2;
643 *outptr
++ |= (base64
>> 4) & 3;
645 *outptr
= (base64
<< 4) & 255;
650 *outptr
++ |= (base64
>> 2) & 15;
652 *outptr
= (base64
<< 6) & 255;
666 * Return the decoded string and size...
669 *outlen
= (int)(outptr
- out
);
676 * 'httpEncode64()' - Base64-encode a string.
678 * This function is deprecated. Use the httpEncode64_2() function instead
679 * which provides buffer length arguments.
684 char * /* O - Encoded string */
685 httpEncode64(char *out
, /* I - String to write to */
686 const char *in
) /* I - String to read from */
688 return (httpEncode64_2(out
, 512, in
, (int)strlen(in
)));
693 * 'httpEncode64_2()' - Base64-encode a string.
695 * @since CUPS 1.1.21/OS X 10.4@
698 char * /* O - Encoded string */
699 httpEncode64_2(char *out
, /* I - String to write to */
700 int outlen
, /* I - Size of output string */
701 const char *in
, /* I - String to read from */
702 int inlen
) /* I - Size of input string */
704 char *outptr
, /* Output pointer */
705 *outend
; /* End of output buffer */
706 static const char base64
[] = /* Base64 characters... */
708 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
709 "abcdefghijklmnopqrstuvwxyz"
716 * Range check input...
719 if (!out
|| outlen
< 1 || !in
)
723 * Convert bytes to base-64...
726 for (outptr
= out
, outend
= out
+ outlen
- 1; inlen
> 0; in
++, inlen
--)
729 * Encode the up to 3 characters as 4 Base64 numbers...
733 *outptr
++ = base64
[(in
[0] & 255) >> 2];
738 *outptr
++ = base64
[(((in
[0] & 255) << 4) | ((in
[1] & 255) >> 4)) & 63];
740 *outptr
++ = base64
[((in
[0] & 255) << 4) & 63];
757 *outptr
++ = base64
[(((in
[0] & 255) << 2) | ((in
[1] & 255) >> 6)) & 63];
759 *outptr
++ = base64
[((in
[0] & 255) << 2) & 63];
772 *outptr
++ = base64
[in
[0] & 63];
778 * Return the encoded string...
786 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
791 const char * /* O - Date/time string */
792 httpGetDateString(time_t t
) /* I - UNIX time */
794 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
797 return (httpGetDateString2(t
, cg
->http_date
, sizeof(cg
->http_date
)));
802 * 'httpGetDateString2()' - Get a formatted date/time string from a time value.
804 * @since CUPS 1.2/OS X 10.5@
807 const char * /* O - Date/time string */
808 httpGetDateString2(time_t t
, /* I - UNIX time */
809 char *s
, /* I - String buffer */
810 int slen
) /* I - Size of string buffer */
812 struct tm
*tdate
; /* UNIX date/time data */
817 snprintf(s
, slen
, "%s, %02d %s %d %02d:%02d:%02d GMT",
818 http_days
[tdate
->tm_wday
], tdate
->tm_mday
,
819 http_months
[tdate
->tm_mon
], tdate
->tm_year
+ 1900,
820 tdate
->tm_hour
, tdate
->tm_min
, tdate
->tm_sec
);
829 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
832 time_t /* O - UNIX time */
833 httpGetDateTime(const char *s
) /* I - Date/time string */
835 int i
; /* Looping var */
836 char mon
[16]; /* Abbreviated month name */
837 int day
, year
; /* Day of month and year */
838 int hour
, min
, sec
; /* Time */
839 int days
; /* Number of days since 1970 */
840 static const int normal_days
[] = /* Days to a month, normal years */
841 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
842 static const int leap_days
[] = /* Days to a month, leap years */
843 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 };
846 DEBUG_printf(("2httpGetDateTime(s=\"%s\")", s
));
849 * Extract the date and time from the formatted string...
852 if (sscanf(s
, "%*s%d%15s%d%d:%d:%d", &day
, mon
, &year
, &hour
, &min
, &sec
) < 6)
855 DEBUG_printf(("4httpGetDateTime: day=%d, mon=\"%s\", year=%d, hour=%d, "
856 "min=%d, sec=%d", day
, mon
, year
, hour
, min
, sec
));
859 * Convert the month name to a number from 0 to 11.
862 for (i
= 0; i
< 12; i
++)
863 if (!_cups_strcasecmp(mon
, http_months
[i
]))
869 DEBUG_printf(("4httpGetDateTime: i=%d", i
));
872 * Now convert the date and time to a UNIX time value in seconds since
873 * 1970. We can't use mktime() since the timezone may not be UTC but
874 * the date/time string *is* UTC.
877 if ((year
& 3) == 0 && ((year
% 100) != 0 || (year
% 400) == 0))
878 days
= leap_days
[i
] + day
- 1;
880 days
= normal_days
[i
] + day
- 1;
882 DEBUG_printf(("4httpGetDateTime: days=%d", days
));
884 days
+= (year
- 1970) * 365 + /* 365 days per year (normally) */
885 ((year
- 1) / 4 - 492) - /* + leap days */
886 ((year
- 1) / 100 - 19) + /* - 100 year days */
887 ((year
- 1) / 400 - 4); /* + 400 year days */
889 DEBUG_printf(("4httpGetDateTime: days=%d\n", days
));
891 return (days
* 86400 + hour
* 3600 + min
* 60 + sec
);
896 * 'httpSeparate()' - Separate a Universal Resource Identifier into its
899 * This function is deprecated; use the httpSeparateURI() function instead.
905 httpSeparate(const char *uri
, /* I - Universal Resource Identifier */
906 char *scheme
, /* O - Scheme [32] (http, https, etc.) */
907 char *username
, /* O - Username [1024] */
908 char *host
, /* O - Hostname [1024] */
909 int *port
, /* O - Port number to use */
910 char *resource
) /* O - Resource/filename [1024] */
912 httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, 32, username
,
913 HTTP_MAX_URI
, host
, HTTP_MAX_URI
, port
, resource
,
919 * 'httpSeparate2()' - Separate a Universal Resource Identifier into its
922 * This function is deprecated; use the httpSeparateURI() function instead.
924 * @since CUPS 1.1.21/OS X 10.4@
929 httpSeparate2(const char *uri
, /* I - Universal Resource Identifier */
930 char *scheme
, /* O - Scheme (http, https, etc.) */
931 int schemelen
, /* I - Size of scheme buffer */
932 char *username
, /* O - Username */
933 int usernamelen
, /* I - Size of username buffer */
934 char *host
, /* O - Hostname */
935 int hostlen
, /* I - Size of hostname buffer */
936 int *port
, /* O - Port number to use */
937 char *resource
, /* O - Resource/filename */
938 int resourcelen
) /* I - Size of resource buffer */
940 httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, schemelen
, username
,
941 usernamelen
, host
, hostlen
, port
, resource
, resourcelen
);
946 * 'httpSeparateURI()' - Separate a Universal Resource Identifier into its
949 * @since CUPS 1.2/OS X 10.5@
952 http_uri_status_t
/* O - Result of separation */
954 http_uri_coding_t decoding
, /* I - Decoding flags */
955 const char *uri
, /* I - Universal Resource Identifier */
956 char *scheme
, /* O - Scheme (http, https, etc.) */
957 int schemelen
, /* I - Size of scheme buffer */
958 char *username
, /* O - Username */
959 int usernamelen
, /* I - Size of username buffer */
960 char *host
, /* O - Hostname */
961 int hostlen
, /* I - Size of hostname buffer */
962 int *port
, /* O - Port number to use */
963 char *resource
, /* O - Resource/filename */
964 int resourcelen
) /* I - Size of resource buffer */
966 char *ptr
, /* Pointer into string... */
967 *end
; /* End of string */
968 const char *sep
; /* Separator character */
969 http_uri_status_t status
; /* Result of separation */
973 * Initialize everything to blank...
976 if (scheme
&& schemelen
> 0)
979 if (username
&& usernamelen
> 0)
982 if (host
&& hostlen
> 0)
988 if (resource
&& resourcelen
> 0)
992 * Range check input...
995 if (!uri
|| !port
|| !scheme
|| schemelen
<= 0 || !username
||
996 usernamelen
<= 0 || !host
|| hostlen
<= 0 || !resource
||
998 return (HTTP_URI_STATUS_BAD_ARGUMENTS
);
1001 return (HTTP_URI_STATUS_BAD_URI
);
1004 * Grab the scheme portion of the URI...
1007 status
= HTTP_URI_STATUS_OK
;
1009 if (!strncmp(uri
, "//", 2))
1012 * Workaround for HP IPP client bug...
1015 strlcpy(scheme
, "ipp", schemelen
);
1016 status
= HTTP_URI_STATUS_MISSING_SCHEME
;
1018 else if (*uri
== '/')
1024 strlcpy(scheme
, "file", schemelen
);
1025 status
= HTTP_URI_STATUS_MISSING_SCHEME
;
1030 * Standard URI with scheme...
1033 for (ptr
= scheme
, end
= scheme
+ schemelen
- 1;
1034 *uri
&& *uri
!= ':' && ptr
< end
;)
1035 if (strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1036 "abcdefghijklmnopqrstuvwxyz"
1037 "0123456789-+.", *uri
) != NULL
)
1047 return (HTTP_URI_STATUS_BAD_SCHEME
);
1054 * Set the default port number...
1057 if (!strcmp(scheme
, "http"))
1059 else if (!strcmp(scheme
, "https"))
1061 else if (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps"))
1063 else if (!_cups_strcasecmp(scheme
, "lpd"))
1065 else if (!strcmp(scheme
, "socket")) /* Not yet registered with IANA... */
1067 else if (strcmp(scheme
, "file") && strcmp(scheme
, "mailto"))
1068 status
= HTTP_URI_STATUS_UNKNOWN_SCHEME
;
1071 * Now see if we have a hostname...
1074 if (!strncmp(uri
, "//", 2))
1077 * Yes, extract it...
1083 * Grab the username, if any...
1086 if ((sep
= strpbrk(uri
, "@/")) != NULL
&& *sep
== '@')
1089 * Get a username:password combo...
1092 uri
= http_copy_decode(username
, uri
, usernamelen
, "@",
1093 decoding
& HTTP_URI_CODING_USERNAME
);
1098 return (HTTP_URI_STATUS_BAD_USERNAME
);
1105 * Then the hostname/IP address...
1111 * Grab IPv6 address...
1118 * Skip IPvFuture ("vXXXX.") prefix...
1123 while (isxdigit(*uri
& 255))
1129 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1135 uri
= http_copy_decode(host
, uri
, hostlen
, "]",
1136 decoding
& HTTP_URI_CODING_HOSTNAME
);
1141 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1151 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1156 for (ptr
= host
; *ptr
; ptr
++)
1160 * Convert zone separator to % and stop here...
1166 else if (*ptr
== '%')
1169 * Stop at zone separator (RFC 6874)
1174 else if (*ptr
!= ':' && *ptr
!= '.' && !isxdigit(*ptr
& 255))
1177 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1183 * Validate the hostname or IPv4 address first...
1186 for (ptr
= (char *)uri
; *ptr
; ptr
++)
1187 if (strchr(":?/", *ptr
))
1189 else if (!strchr("abcdefghijklmnopqrstuvwxyz"
1190 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1194 "!$&'()*+,;=\\", *ptr
))
1197 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1201 * Then copy the hostname or IPv4 address to the buffer...
1204 uri
= http_copy_decode(host
, uri
, hostlen
, ":?/",
1205 decoding
& HTTP_URI_CODING_HOSTNAME
);
1210 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1215 * Validate hostname for file scheme - only empty and localhost are
1219 if (!strcmp(scheme
, "file") && strcmp(host
, "localhost") && host
[0])
1222 return (HTTP_URI_STATUS_BAD_HOSTNAME
);
1226 * See if we have a port number...
1232 * Yes, collect the port number...
1235 if (!isdigit(uri
[1] & 255))
1238 return (HTTP_URI_STATUS_BAD_PORT
);
1241 *port
= strtol(uri
+ 1, (char **)&uri
, 10);
1243 if (*uri
!= '/' && *uri
)
1246 return (HTTP_URI_STATUS_BAD_PORT
);
1252 * The remaining portion is the resource string...
1255 if (*uri
== '?' || !*uri
)
1258 * Hostname but no path...
1261 status
= HTTP_URI_STATUS_MISSING_RESOURCE
;
1265 * Copy any query string...
1269 uri
= http_copy_decode(resource
+ 1, uri
, resourcelen
- 1, NULL
,
1270 decoding
& HTTP_URI_CODING_QUERY
);
1276 uri
= http_copy_decode(resource
, uri
, resourcelen
, "?",
1277 decoding
& HTTP_URI_CODING_RESOURCE
);
1279 if (uri
&& *uri
== '?')
1282 * Concatenate any query string...
1285 char *resptr
= resource
+ strlen(resource
);
1287 uri
= http_copy_decode(resptr
, uri
, resourcelen
- (int)(resptr
- resource
),
1288 NULL
, decoding
& HTTP_URI_CODING_QUERY
);
1295 return (HTTP_URI_STATUS_BAD_RESOURCE
);
1299 * Return the URI separation status...
1307 * 'httpStatus()' - Return a short string describing a HTTP status code.
1309 * The returned string is localized to the current POSIX locale and is based
1310 * on the status strings defined in RFC 2616.
1313 const char * /* O - Localized status string */
1314 httpStatus(http_status_t status
) /* I - HTTP status code */
1316 const char *s
; /* Status string */
1317 _cups_globals_t
*cg
= _cupsGlobals(); /* Global data */
1320 if (!cg
->lang_default
)
1321 cg
->lang_default
= cupsLangDefault();
1325 case HTTP_STATUS_CONTINUE
:
1328 case HTTP_STATUS_SWITCHING_PROTOCOLS
:
1329 s
= _("Switching Protocols");
1331 case HTTP_STATUS_OK
:
1334 case HTTP_STATUS_CREATED
:
1337 case HTTP_STATUS_ACCEPTED
:
1340 case HTTP_STATUS_NO_CONTENT
:
1341 s
= _("No Content");
1343 case HTTP_STATUS_MOVED_PERMANENTLY
:
1344 s
= _("Moved Permanently");
1346 case HTTP_STATUS_SEE_OTHER
:
1349 case HTTP_STATUS_NOT_MODIFIED
:
1350 s
= _("Not Modified");
1352 case HTTP_STATUS_BAD_REQUEST
:
1353 s
= _("Bad Request");
1355 case HTTP_STATUS_UNAUTHORIZED
:
1356 case HTTP_STATUS_CUPS_AUTHORIZATION_CANCELED
:
1357 s
= _("Unauthorized");
1359 case HTTP_STATUS_FORBIDDEN
:
1362 case HTTP_STATUS_NOT_FOUND
:
1365 case HTTP_STATUS_REQUEST_TOO_LARGE
:
1366 s
= _("Request Entity Too Large");
1368 case HTTP_STATUS_URI_TOO_LONG
:
1369 s
= _("URI Too Long");
1371 case HTTP_STATUS_UPGRADE_REQUIRED
:
1372 s
= _("Upgrade Required");
1374 case HTTP_STATUS_NOT_IMPLEMENTED
:
1375 s
= _("Not Implemented");
1377 case HTTP_STATUS_NOT_SUPPORTED
:
1378 s
= _("Not Supported");
1380 case HTTP_STATUS_EXPECTATION_FAILED
:
1381 s
= _("Expectation Failed");
1383 case HTTP_STATUS_SERVICE_UNAVAILABLE
:
1384 s
= _("Service Unavailable");
1386 case HTTP_STATUS_SERVER_ERROR
:
1387 s
= _("Internal Server Error");
1389 case HTTP_STATUS_CUPS_PKI_ERROR
:
1390 s
= _("SSL/TLS Negotiation Error");
1392 case HTTP_STATUS_CUPS_WEBIF_DISABLED
:
1393 s
= _("Web Interface is Disabled");
1401 return (_cupsLangString(cg
->lang_default
, s
));
1405 #ifndef HAVE_HSTRERROR
1407 * '_cups_hstrerror()' - hstrerror() emulation function for Solaris and others.
1410 const char * /* O - Error string */
1411 _cups_hstrerror(int error
) /* I - Error number */
1413 static const char * const errors
[] = /* Error strings */
1418 "Unrecoverable lookup error.",
1419 "No data associated with name."
1423 if (error
< 0 || error
> 4)
1424 return ("Unknown hostname lookup error.");
1426 return (errors
[error
]);
1428 #endif /* !HAVE_HSTRERROR */
1432 * '_httpDecodeURI()' - Percent-decode a HTTP request URI.
1435 char * /* O - Decoded URI or NULL on error */
1436 _httpDecodeURI(char *dst
, /* I - Destination buffer */
1437 const char *src
, /* I - Source URI */
1438 size_t dstsize
) /* I - Size of destination buffer */
1440 if (http_copy_decode(dst
, src
, (int)dstsize
, NULL
, 1))
1448 * '_httpEncodeURI()' - Percent-encode a HTTP request URI.
1451 char * /* O - Encoded URI */
1452 _httpEncodeURI(char *dst
, /* I - Destination buffer */
1453 const char *src
, /* I - Source URI */
1454 size_t dstsize
) /* I - Size of destination buffer */
1456 http_copy_encode(dst
, src
, dst
+ dstsize
- 1, NULL
, NULL
, 1);
1462 * '_httpResolveURI()' - Resolve a DNS-SD URI.
1465 const char * /* O - Resolved URI */
1467 const char *uri
, /* I - DNS-SD URI */
1468 char *resolved_uri
, /* I - Buffer for resolved URI */
1469 size_t resolved_size
, /* I - Size of URI buffer */
1470 int options
, /* I - Resolve options */
1471 int (*cb
)(void *context
), /* I - Continue callback function */
1472 void *context
) /* I - Context pointer for callback */
1474 char scheme
[32], /* URI components... */
1480 http_uri_status_t status
; /* URI decode status */
1484 DEBUG_printf(("4_httpResolveURI(uri=\"%s\", resolved_uri=%p, "
1485 "resolved_size=" CUPS_LLFMT
")", uri
, resolved_uri
,
1486 CUPS_LLCAST resolved_size
));
1489 * Get the device URI...
1493 if ((status
= httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
,
1494 sizeof(scheme
), userpass
, sizeof(userpass
),
1495 hostname
, sizeof(hostname
), &port
, resource
,
1496 sizeof(resource
))) < HTTP_URI_STATUS_OK
)
1498 if (httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
,
1499 sizeof(scheme
), userpass
, sizeof(userpass
),
1500 hostname
, sizeof(hostname
), &port
, resource
,
1501 sizeof(resource
)) < HTTP_URI_STATUS_OK
)
1504 if (options
& _HTTP_RESOLVE_STDERR
)
1505 _cupsLangPrintFilter(stderr
, "ERROR", _("Bad device-uri \"%s\"."), uri
);
1507 DEBUG_printf(("6_httpResolveURI: httpSeparateURI returned %d!", status
));
1508 DEBUG_puts("5_httpResolveURI: Returning NULL");
1513 * Resolve it as needed...
1516 if (strstr(hostname
, "._tcp"))
1518 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
1519 char *regtype
, /* Pointer to type in hostname */
1520 *domain
; /* Pointer to domain in hostname */
1521 _http_uribuf_t uribuf
; /* URI buffer */
1522 int offline
= 0; /* offline-report state set? */
1525 # pragma comment(lib, "dnssd.lib")
1527 DNSServiceRef ref
, /* DNS-SD master service reference */
1528 domainref
, /* DNS-SD service reference for domain */
1529 localref
; /* DNS-SD service reference for .local */
1530 int domainsent
= 0; /* Send the domain resolve? */
1532 struct pollfd polldata
; /* Polling data */
1533 # else /* select() */
1534 fd_set input_set
; /* Input set for select() */
1535 struct timeval stimeout
; /* Timeout value for select() */
1536 # endif /* HAVE_POLL */
1537 # elif defined(HAVE_AVAHI)
1538 AvahiClient
*client
; /* Client information */
1539 int error
; /* Status */
1540 # endif /* HAVE_DNSSD */
1542 if (options
& _HTTP_RESOLVE_STDERR
)
1543 fprintf(stderr
, "DEBUG: Resolving \"%s\"...\n", hostname
);
1546 * Separate the hostname into service name, registration type, and domain...
1549 for (regtype
= strstr(hostname
, "._tcp") - 2;
1552 if (regtype
[0] == '.' && regtype
[1] == '_')
1555 * Found ._servicetype in front of ._tcp...
1562 if (regtype
<= hostname
)
1564 DEBUG_puts("5_httpResolveURI: Bad hostname, returning NULL");
1568 for (domain
= strchr(regtype
, '.');
1570 domain
= strchr(domain
+ 1, '.'))
1571 if (domain
[1] != '_')
1577 uribuf
.buffer
= resolved_uri
;
1578 uribuf
.bufsize
= resolved_size
;
1579 uribuf
.options
= options
;
1580 uribuf
.resource
= resource
;
1582 resolved_uri
[0] = '\0';
1584 DEBUG_printf(("6_httpResolveURI: Resolving hostname=\"%s\", regtype=\"%s\", "
1585 "domain=\"%s\"\n", hostname
, regtype
, domain
));
1586 if (options
& _HTTP_RESOLVE_STDERR
)
1588 fputs("STATE: +connecting-to-device\n", stderr
);
1589 fprintf(stderr
, "DEBUG: Resolving \"%s\", regtype=\"%s\", "
1590 "domain=\"local.\"...\n", hostname
, regtype
);
1596 if (DNSServiceCreateConnection(&ref
) == kDNSServiceErr_NoError
)
1598 int myinterface
= kDNSServiceInterfaceIndexAny
;
1599 /* Lookup on any interface */
1601 if (!strcmp(scheme
, "ippusb"))
1602 myinterface
= kDNSServiceInterfaceIndexLocalOnly
;
1605 if (DNSServiceResolve(&localref
,
1606 kDNSServiceFlagsShareConnection
, myinterface
,
1607 hostname
, regtype
, "local.", http_resolve_cb
,
1608 &uribuf
) == kDNSServiceErr_NoError
)
1610 int fds
; /* Number of ready descriptors */
1611 time_t timeout
, /* Poll timeout */
1612 start_time
= time(NULL
),/* Start time */
1613 end_time
= start_time
+ 90;
1616 while (time(NULL
) < end_time
)
1618 if (options
& _HTTP_RESOLVE_STDERR
)
1619 _cupsLangPrintFilter(stderr
, "INFO", _("Looking for printer."));
1621 if (cb
&& !(*cb
)(context
))
1623 DEBUG_puts("5_httpResolveURI: callback returned 0 (stop)");
1628 * Wakeup every 2 seconds to emit a "looking for printer" message...
1631 if ((timeout
= end_time
- time(NULL
)) > 2)
1635 polldata
.fd
= DNSServiceRefSockFD(ref
);
1636 polldata
.events
= POLLIN
;
1638 fds
= poll(&polldata
, 1, 1000 * timeout
);
1640 # else /* select() */
1641 FD_ZERO(&input_set
);
1642 FD_SET(DNSServiceRefSockFD(ref
), &input_set
);
1645 stimeout
.tv_sec
= (long)timeout
;
1647 stimeout
.tv_sec
= timeout
;
1649 stimeout
.tv_usec
= 0;
1651 fds
= select(DNSServiceRefSockFD(ref
)+1, &input_set
, NULL
, NULL
,
1653 # endif /* HAVE_POLL */
1657 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1659 DEBUG_printf(("5_httpResolveURI: poll error: %s", strerror(errno
)));
1666 * Wait 2 seconds for a response to the local resolve; if nothing
1667 * comes in, do an additional domain resolution...
1670 if (domainsent
== 0 && domain
&& _cups_strcasecmp(domain
, "local."))
1672 if (options
& _HTTP_RESOLVE_STDERR
)
1674 "DEBUG: Resolving \"%s\", regtype=\"%s\", "
1675 "domain=\"%s\"...\n", hostname
, regtype
,
1676 domain
? domain
: "");
1679 if (DNSServiceResolve(&domainref
,
1680 kDNSServiceFlagsShareConnection
,
1681 myinterface
, hostname
, regtype
, domain
,
1683 &uribuf
) == kDNSServiceErr_NoError
)
1688 * If it hasn't resolved within 5 seconds set the offline-report
1689 * printer-state-reason...
1692 if ((options
& _HTTP_RESOLVE_STDERR
) && offline
== 0 &&
1693 time(NULL
) > (start_time
+ 5))
1695 fputs("STATE: +offline-report\n", stderr
);
1701 if (DNSServiceProcessResult(ref
) == kDNSServiceErr_NoError
)
1710 DNSServiceRefDeallocate(domainref
);
1712 DNSServiceRefDeallocate(localref
);
1715 DNSServiceRefDeallocate(ref
);
1717 # else /* HAVE_AVAHI */
1718 if ((uribuf
.poll
= avahi_simple_poll_new()) != NULL
)
1720 avahi_simple_poll_set_func(uribuf
.poll
, http_poll_cb
, NULL
);
1722 if ((client
= avahi_client_new(avahi_simple_poll_get(uribuf
.poll
),
1724 &uribuf
, &error
)) != NULL
)
1726 if (avahi_service_resolver_new(client
, AVAHI_IF_UNSPEC
,
1727 AVAHI_PROTO_UNSPEC
, hostname
,
1728 regtype
, "local.", AVAHI_PROTO_UNSPEC
, 0,
1729 http_resolve_cb
, &uribuf
) != NULL
)
1731 time_t start_time
= time(NULL
),
1733 end_time
= start_time
+ 90;
1735 int pstatus
; /* Poll status */
1737 pstatus
= avahi_simple_poll_iterate(uribuf
.poll
, 2000);
1739 if (pstatus
== 0 && !resolved_uri
[0] && domain
&&
1740 _cups_strcasecmp(domain
, "local."))
1743 * Resolve for .local hasn't returned anything, try the listed
1747 avahi_service_resolver_new(client
, AVAHI_IF_UNSPEC
,
1748 AVAHI_PROTO_UNSPEC
, hostname
,
1749 regtype
, domain
, AVAHI_PROTO_UNSPEC
, 0,
1750 http_resolve_cb
, &uribuf
);
1753 while (!pstatus
&& !resolved_uri
[0] && time(NULL
) < end_time
)
1755 if ((pstatus
= avahi_simple_poll_iterate(uribuf
.poll
, 2000)) != 0)
1759 * If it hasn't resolved within 5 seconds set the offline-report
1760 * printer-state-reason...
1763 if ((options
& _HTTP_RESOLVE_STDERR
) && offline
== 0 &&
1764 time(NULL
) > (start_time
+ 5))
1766 fputs("STATE: +offline-report\n", stderr
);
1772 * Collect the result (if we got one).
1775 if (resolved_uri
[0])
1779 avahi_client_free(client
);
1782 avahi_simple_poll_free(uribuf
.poll
);
1784 # endif /* HAVE_DNSSD */
1786 if (options
& _HTTP_RESOLVE_STDERR
)
1790 fprintf(stderr
, "DEBUG: Resolved as \"%s\"...\n", uri
);
1791 fputs("STATE: -connecting-to-device,offline-report\n", stderr
);
1795 fputs("DEBUG: Unable to resolve URI\n", stderr
);
1796 fputs("STATE: -connecting-to-device\n", stderr
);
1800 #else /* HAVE_DNSSD || HAVE_AVAHI */
1802 * No DNS-SD support...
1806 #endif /* HAVE_DNSSD || HAVE_AVAHI */
1808 if ((options
& _HTTP_RESOLVE_STDERR
) && !uri
)
1809 _cupsLangPrintFilter(stderr
, "INFO", _("Unable to find printer."));
1814 * Nothing more to do...
1817 strlcpy(resolved_uri
, uri
, resolved_size
);
1821 DEBUG_printf(("5_httpResolveURI: Returning \"%s\"", uri
));
1829 * 'http_client_cb()' - Client callback for resolving URI.
1834 AvahiClient
*client
, /* I - Client information */
1835 AvahiClientState state
, /* I - Current state */
1836 void *context
) /* I - Pointer to URI buffer */
1838 DEBUG_printf(("7http_client_cb(client=%p, state=%d, context=%p)", client
,
1842 * If the connection drops, quit.
1845 if (state
== AVAHI_CLIENT_FAILURE
)
1847 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
1850 avahi_simple_poll_quit(uribuf
->poll
);
1853 #endif /* HAVE_AVAHI */
1857 * 'http_copy_decode()' - Copy and decode a URI.
1860 static const char * /* O - New source pointer or NULL on error */
1861 http_copy_decode(char *dst
, /* O - Destination buffer */
1862 const char *src
, /* I - Source pointer */
1863 int dstsize
, /* I - Destination size */
1864 const char *term
, /* I - Terminating characters */
1865 int decode
) /* I - Decode %-encoded values */
1867 char *ptr
, /* Pointer into buffer */
1868 *end
; /* End of buffer */
1869 int quoted
; /* Quoted character */
1873 * Copy the src to the destination until we hit a terminating character
1874 * or the end of the string.
1877 for (ptr
= dst
, end
= dst
+ dstsize
- 1;
1878 *src
&& (!term
|| !strchr(term
, *src
));
1882 if (*src
== '%' && decode
)
1884 if (isxdigit(src
[1] & 255) && isxdigit(src
[2] & 255))
1887 * Grab a hex-encoded character...
1892 quoted
= (tolower(*src
) - 'a' + 10) << 4;
1894 quoted
= (*src
- '0') << 4;
1898 quoted
|= tolower(*src
) - 'a' + 10;
1900 quoted
|= *src
- '0';
1907 * Bad hex-encoded character...
1914 else if ((*src
& 255) <= 0x20 || (*src
& 255) >= 0x7f)
1930 * 'http_copy_encode()' - Copy and encode a URI.
1933 static char * /* O - End of current URI */
1934 http_copy_encode(char *dst
, /* O - Destination buffer */
1935 const char *src
, /* I - Source pointer */
1936 char *dstend
, /* I - End of destination buffer */
1937 const char *reserved
, /* I - Extra reserved characters */
1938 const char *term
, /* I - Terminating characters */
1939 int encode
) /* I - %-encode reserved chars? */
1941 static const char hex
[] = "0123456789ABCDEF";
1944 while (*src
&& dst
< dstend
)
1946 if (term
&& *src
== *term
)
1949 if (encode
&& (*src
== '%' || *src
<= ' ' || *src
& 128 ||
1950 (reserved
&& strchr(reserved
, *src
))))
1953 * Hex encode reserved characters...
1956 if ((dst
+ 2) >= dstend
)
1960 *dst
++ = hex
[(*src
>> 4) & 15];
1961 *dst
++ = hex
[*src
& 15];
1980 * 'http_resolve_cb()' - Build a device URI for the given service name.
1983 static void DNSSD_API
1985 DNSServiceRef sdRef
, /* I - Service reference */
1986 DNSServiceFlags flags
, /* I - Results flags */
1987 uint32_t interfaceIndex
, /* I - Interface number */
1988 DNSServiceErrorType errorCode
, /* I - Error, if any */
1989 const char *fullName
, /* I - Full service name */
1990 const char *hostTarget
, /* I - Hostname */
1991 uint16_t port
, /* I - Port number */
1992 uint16_t txtLen
, /* I - Length of TXT record */
1993 const unsigned char *txtRecord
, /* I - TXT record data */
1994 void *context
) /* I - Pointer to URI buffer */
1996 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
1998 const char *scheme
, /* URI scheme */
1999 *hostptr
, /* Pointer into hostTarget */
2000 *reskey
, /* "rp" or "rfo" */
2001 *resdefault
; /* Default path */
2002 char resource
[257], /* Remote path */
2003 fqdn
[256]; /* FQDN of the .local name */
2004 const void *value
; /* Value from TXT record */
2005 uint8_t valueLen
; /* Length of value */
2008 DEBUG_printf(("7http_resolve_cb(sdRef=%p, flags=%x, interfaceIndex=%u, "
2009 "errorCode=%d, fullName=\"%s\", hostTarget=\"%s\", port=%u, "
2010 "txtLen=%u, txtRecord=%p, context=%p)", sdRef
, flags
,
2011 interfaceIndex
, errorCode
, fullName
, hostTarget
, port
, txtLen
,
2012 txtRecord
, context
));
2015 * Figure out the scheme from the full name...
2018 if (strstr(fullName
, "._ipps") || strstr(fullName
, "._ipp-tls"))
2020 else if (strstr(fullName
, "._ipp") || strstr(fullName
, "._fax-ipp"))
2022 else if (strstr(fullName
, "._http."))
2024 else if (strstr(fullName
, "._https."))
2026 else if (strstr(fullName
, "._printer."))
2028 else if (strstr(fullName
, "._pdl-datastream."))
2031 scheme
= "riousbprint";
2034 * Extract the "remote printer" key from the TXT record...
2037 if ((uribuf
->options
& _HTTP_RESOLVE_FAXOUT
) &&
2038 (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")))
2041 resdefault
= "/ipp/faxout";
2049 if ((value
= TXTRecordGetValuePtr(txtLen
, txtRecord
, reskey
,
2050 &valueLen
)) != NULL
)
2052 if (((char *)value
)[0] == '/')
2055 * Value (incorrectly) has a leading slash already...
2058 memcpy(resource
, value
, valueLen
);
2059 resource
[valueLen
] = '\0';
2064 * Convert to resource by concatenating with a leading "/"...
2068 memcpy(resource
+ 1, value
, valueLen
);
2069 resource
[valueLen
+ 1] = '\0';
2075 * Use the default value...
2078 strlcpy(resource
, resdefault
, sizeof(resource
));
2082 * Lookup the FQDN if needed...
2085 if ((uribuf
->options
& _HTTP_RESOLVE_FQDN
) &&
2086 (hostptr
= hostTarget
+ strlen(hostTarget
) - 7) > hostTarget
&&
2087 !_cups_strcasecmp(hostptr
, ".local."))
2090 * OK, we got a .local name but the caller needs a real domain. Start by
2091 * getting the IP address of the .local name and then do reverse-lookups...
2094 http_addrlist_t
*addrlist
, /* List of addresses */
2095 *addr
; /* Current address */
2097 DEBUG_printf(("8http_resolve_cb: Looking up \"%s\".", hostTarget
));
2099 snprintf(fqdn
, sizeof(fqdn
), "%d", ntohs(port
));
2100 if ((addrlist
= httpAddrGetList(hostTarget
, AF_UNSPEC
, fqdn
)) != NULL
)
2102 for (addr
= addrlist
; addr
; addr
= addr
->next
)
2104 int error
= getnameinfo(&(addr
->addr
.addr
),
2105 httpAddrLength(&(addr
->addr
)),
2106 fqdn
, sizeof(fqdn
), NULL
, 0, NI_NAMEREQD
);
2110 DEBUG_printf(("8http_resolve_cb: Found \"%s\".", fqdn
));
2112 if ((hostptr
= fqdn
+ strlen(fqdn
) - 6) <= fqdn
||
2113 _cups_strcasecmp(hostptr
, ".local"))
2121 DEBUG_printf(("8http_resolve_cb: \"%s\" did not resolve: %d",
2122 httpAddrString(&(addr
->addr
), fqdn
, sizeof(fqdn
)),
2127 httpAddrFreeList(addrlist
);
2132 * Assemble the final device URI...
2135 if ((!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")) &&
2136 !strcmp(uribuf
->resource
, "/cups"))
2137 httpAssembleURIf(HTTP_URI_CODING_ALL
, uribuf
->buffer
, uribuf
->bufsize
,
2138 scheme
, NULL
, hostTarget
, ntohs(port
), "%s?snmp=false",
2141 httpAssembleURI(HTTP_URI_CODING_ALL
, uribuf
->buffer
, uribuf
->bufsize
,
2142 scheme
, NULL
, hostTarget
, ntohs(port
), resource
);
2144 DEBUG_printf(("8http_resolve_cb: Resolved URI is \"%s\"...", uribuf
->buffer
));
2147 #elif defined(HAVE_AVAHI)
2149 * 'http_poll_cb()' - Wait for input on the specified file descriptors.
2151 * Note: This function is needed because avahi_simple_poll_iterate is broken
2152 * and always uses a timeout of 0 (!) milliseconds.
2153 * (Avahi Ticket #364)
2156 static int /* O - Number of file descriptors matching */
2158 struct pollfd
*pollfds
, /* I - File descriptors */
2159 unsigned int num_pollfds
, /* I - Number of file descriptors */
2160 int timeout
, /* I - Timeout in milliseconds (used) */
2161 void *context
) /* I - User data (unused) */
2166 return (poll(pollfds
, num_pollfds
, 2000));
2171 * 'http_resolve_cb()' - Build a device URI for the given service name.
2176 AvahiServiceResolver
*resolver
, /* I - Resolver (unused) */
2177 AvahiIfIndex interface
, /* I - Interface index (unused) */
2178 AvahiProtocol protocol
, /* I - Network protocol (unused) */
2179 AvahiResolverEvent event
, /* I - Event (found, etc.) */
2180 const char *name
, /* I - Service name */
2181 const char *type
, /* I - Registration type */
2182 const char *domain
, /* I - Domain (unused) */
2183 const char *hostTarget
, /* I - Hostname */
2184 const AvahiAddress
*address
, /* I - Address (unused) */
2185 uint16_t port
, /* I - Port number */
2186 AvahiStringList
*txt
, /* I - TXT record */
2187 AvahiLookupResultFlags flags
, /* I - Lookup flags (unused) */
2188 void *context
) /* I - Pointer to URI buffer */
2190 _http_uribuf_t
*uribuf
= (_http_uribuf_t
*)context
;
2192 const char *scheme
, /* URI scheme */
2193 *hostptr
, /* Pointer into hostTarget */
2194 *reskey
, /* "rp" or "rfo" */
2195 *resdefault
; /* Default path */
2196 char resource
[257], /* Remote path */
2197 fqdn
[256]; /* FQDN of the .local name */
2198 AvahiStringList
*pair
; /* Current TXT record key/value pair */
2199 char *value
; /* Value for "rp" key */
2200 size_t valueLen
= 0; /* Length of "rp" key */
2203 DEBUG_printf(("7http_resolve_cb(resolver=%p, "
2204 "interface=%d, protocol=%d, event=%d, name=\"%s\", "
2205 "type=\"%s\", domain=\"%s\", hostTarget=\"%s\", address=%p, "
2206 "port=%d, txt=%p, flags=%d, context=%p)",
2207 resolver
, interface
, protocol
, event
, name
, type
, domain
,
2208 hostTarget
, address
, port
, txt
, flags
, context
));
2210 if (event
!= AVAHI_RESOLVER_FOUND
)
2212 avahi_service_resolver_free(resolver
);
2213 avahi_simple_poll_quit(uribuf
->poll
);
2218 * Figure out the scheme from the full name...
2221 if (strstr(type
, "_ipp."))
2223 else if (strstr(type
, "_printer."))
2225 else if (strstr(type
, "_pdl-datastream."))
2228 scheme
= "riousbprint";
2230 if (!strncmp(type
, "_ipps.", 6) || !strncmp(type
, "_ipp-tls.", 9))
2232 else if (!strncmp(type
, "_ipp.", 5) || !strncmp(type
, "_fax-ipp.", 9))
2234 else if (!strncmp(type
, "_http.", 6))
2236 else if (!strncmp(type
, "_https.", 7))
2238 else if (!strncmp(type
, "_printer.", 9))
2240 else if (!strncmp(type
, "_pdl-datastream.", 16))
2244 avahi_service_resolver_free(resolver
);
2245 avahi_simple_poll_quit(uribuf
->poll
);
2250 * Extract the remote resource key from the TXT record...
2253 if ((uribuf
->options
& _HTTP_RESOLVE_FAXOUT
) &&
2254 (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps")))
2257 resdefault
= "/ipp/faxout";
2265 if ((pair
= avahi_string_list_find(txt
, reskey
)) != NULL
)
2267 avahi_string_list_get_pair(pair
, NULL
, &value
, &valueLen
);
2269 if (value
[0] == '/')
2272 * Value (incorrectly) has a leading slash already...
2275 memcpy(resource
, value
, valueLen
);
2276 resource
[valueLen
] = '\0';
2281 * Convert to resource by concatenating with a leading "/"...
2285 memcpy(resource
+ 1, value
, valueLen
);
2286 resource
[valueLen
+ 1] = '\0';
2292 * Use the default value...
2295 strlcpy(resource
, resdefault
, sizeof(resource
));
2299 * Lookup the FQDN if needed...
2302 if ((uribuf
->options
& _HTTP_RESOLVE_FQDN
) &&
2303 (hostptr
= hostTarget
+ strlen(hostTarget
) - 6) > hostTarget
&&
2304 !_cups_strcasecmp(hostptr
, ".local"))
2307 * OK, we got a .local name but the caller needs a real domain. Start by
2308 * getting the IP address of the .local name and then do reverse-lookups...
2311 http_addrlist_t
*addrlist
, /* List of addresses */
2312 *addr
; /* Current address */
2314 DEBUG_printf(("8http_resolve_cb: Looking up \"%s\".", hostTarget
));
2316 snprintf(fqdn
, sizeof(fqdn
), "%d", ntohs(port
));
2317 if ((addrlist
= httpAddrGetList(hostTarget
, AF_UNSPEC
, fqdn
)) != NULL
)
2319 for (addr
= addrlist
; addr
; addr
= addr
->next
)
2321 int error
= getnameinfo(&(addr
->addr
.addr
),
2322 httpAddrLength(&(addr
->addr
)),
2323 fqdn
, sizeof(fqdn
), NULL
, 0, NI_NAMEREQD
);
2327 DEBUG_printf(("8http_resolve_cb: Found \"%s\".", fqdn
));
2329 if ((hostptr
= fqdn
+ strlen(fqdn
) - 6) <= fqdn
||
2330 _cups_strcasecmp(hostptr
, ".local"))
2338 DEBUG_printf(("8http_resolve_cb: \"%s\" did not resolve: %d",
2339 httpAddrString(&(addr
->addr
), fqdn
, sizeof(fqdn
)),
2344 httpAddrFreeList(addrlist
);
2349 * Assemble the final device URI using the resolved hostname...
2352 httpAssembleURI(HTTP_URI_CODING_ALL
, uribuf
->buffer
, uribuf
->bufsize
, scheme
,
2353 NULL
, hostTarget
, port
, resource
);
2354 DEBUG_printf(("8http_resolve_cb: Resolved URI is \"%s\".", uribuf
->buffer
));
2356 avahi_simple_poll_quit(uribuf
->poll
);
2358 #endif /* HAVE_DNSSD */