2 * "$Id: http-support.c 7952 2008-09-17 00:56:20Z mike $"
4 * HTTP support routines for CUPS.
6 * Copyright 2007-2011 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * These coded instructions, statements, and computer programs are the
10 * property of Apple Inc. and are protected by Federal copyright
11 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
12 * which should have been included with this file. If this file is
13 * file is missing or damaged, see the license at "http://www.cups.org/".
15 * This file is subject to the Apple OS-Developed Software exception.
19 * httpAssembleURI() - Assemble a uniform resource identifier from its
21 * httpAssembleURIf() - Assemble a uniform resource identifier from its
22 * components with a formatted resource.
23 * _httpAssembleUUID() - Make a UUID URI conforming to RFC 4122.
24 * httpDecode64() - Base64-decode a string.
25 * httpDecode64_2() - Base64-decode a string.
26 * httpEncode64() - Base64-encode a string.
27 * httpEncode64_2() - Base64-encode a string.
28 * httpGetDateString() - Get a formatted date/time string from a time value.
29 * httpGetDateString2() - Get a formatted date/time string from a time value.
30 * httpGetDateTime() - Get a time value from a formatted date/time string.
31 * httpSeparate() - Separate a Universal Resource Identifier into its
33 * httpSeparate2() - Separate a Universal Resource Identifier into its
35 * httpSeparateURI() - Separate a Universal Resource Identifier into its
37 * httpStatus() - Return a short string describing a HTTP status code.
38 * _cups_hstrerror() - hstrerror() emulation function for Solaris and
40 * _httpDecodeURI() - Percent-decode a HTTP request URI.
41 * _httpEncodeURI() - Percent-encode a HTTP request URI.
42 * _httpResolveURI() - Resolve a DNS-SD URI.
43 * http_copy_decode() - Copy and decode a URI.
44 * http_copy_encode() - Copy and encode a URI.
45 * http_resolve_cb() - Build a device URI for the given service name.
49 * Include necessary headers...
52 #include "cups-private.h"
57 # elif defined(HAVE_POLL)
60 # include <sys/select.h>
62 #endif /* HAVE_DNSSD */
69 typedef struct _http_uribuf_s
/* URI buffer */
71 char *buffer
; /* Pointer to buffer */
72 size_t bufsize
; /* Size of buffer */
73 int options
; /* Options passed to _httpResolveURI */
81 static const char * const http_days
[7] =
91 static const char * const http_months
[12] =
112 static const char *http_copy_decode(char *dst
, const char *src
,
113 int dstsize
, const char *term
,
115 static char *http_copy_encode(char *dst
, const char *src
,
116 char *dstend
, const char *reserved
,
117 const char *term
, int encode
);
119 static void DNSSD_API
http_resolve_cb(DNSServiceRef sdRef
,
120 DNSServiceFlags flags
,
121 uint32_t interfaceIndex
,
122 DNSServiceErrorType errorCode
,
123 const char *fullName
,
124 const char *hostTarget
,
125 uint16_t port
, uint16_t txtLen
,
126 const unsigned char *txtRecord
,
128 #endif /* HAVE_DNSSD */
132 * 'httpAssembleURI()' - Assemble a uniform resource identifier from its
135 * This function escapes reserved characters in the URI depending on the
136 * value of the "encoding" argument. You should use this function in
137 * place of traditional string functions whenever you need to create a
140 * @since CUPS 1.2/Mac OS X 10.5@
143 http_uri_status_t
/* O - URI status */
145 http_uri_coding_t encoding
, /* I - Encoding flags */
146 char *uri
, /* I - URI buffer */
147 int urilen
, /* I - Size of URI buffer */
148 const char *scheme
, /* I - Scheme name */
149 const char *username
, /* I - Username */
150 const char *host
, /* I - Hostname or address */
151 int port
, /* I - Port number */
152 const char *resource
) /* I - Resource */
154 char *ptr
, /* Pointer into URI buffer */
155 *end
; /* End of URI buffer */
159 * Range check input...
162 if (!uri
|| urilen
< 1 || !scheme
|| port
< 0)
167 return (HTTP_URI_BAD_ARGUMENTS
);
171 * Assemble the URI starting with the scheme...
174 end
= uri
+ urilen
- 1;
175 ptr
= http_copy_encode(uri
, scheme
, end
, NULL
, NULL
, 0);
178 goto assemble_overflow
;
180 if (!strcmp(scheme
, "mailto"))
183 * mailto: only has :, no //...
189 goto assemble_overflow
;
194 * Schemes other than mailto: all have //...
204 goto assemble_overflow
;
208 * Next the username and hostname, if any...
213 if (username
&& *username
)
216 * Add username@ first...
219 ptr
= http_copy_encode(ptr
, username
, end
, "/?#[]@", NULL
,
220 encoding
& HTTP_URI_CODING_USERNAME
);
223 goto assemble_overflow
;
228 goto assemble_overflow
;
232 * Then add the hostname. Since IPv6 is a particular pain to deal
233 * with, we have several special cases to deal with. If we get
234 * an IPv6 address with brackets around it, assume it is already in
235 * URI format. Since DNS-SD service names can sometimes look like
236 * raw IPv6 addresses, we specifically look for "._tcp" in the name,
240 if (host
[0] != '[' && strchr(host
, ':') && !strstr(host
, "._tcp"))
243 * We have a raw IPv6 address...
246 if (strchr(host
, '%'))
249 * We have a link-local address, add "[v1." prefix...
260 goto assemble_overflow
;
265 * We have a normal address, add "[" prefix...
271 goto assemble_overflow
;
275 * Copy the rest of the IPv6 address, and terminate with "]".
278 while (ptr
< end
&& *host
)
282 *ptr
++ = '+'; /* Convert zone separator */
290 goto assemble_overflow
;
295 goto assemble_overflow
;
300 * Otherwise, just copy the host string...
303 ptr
= http_copy_encode(ptr
, host
, end
, ":/?#[]@\\\"", NULL
,
304 encoding
& HTTP_URI_CODING_HOSTNAME
);
307 goto assemble_overflow
;
311 * Finish things off with the port number...
316 snprintf(ptr
, end
- ptr
+ 1, ":%d", port
);
320 goto assemble_overflow
;
325 * Last but not least, add the resource string...
330 char *query
; /* Pointer to query string */
334 * Copy the resource string up to the query string if present...
337 query
= strchr(resource
, '?');
338 ptr
= http_copy_encode(ptr
, resource
, end
, NULL
, "?",
339 encoding
& HTTP_URI_CODING_RESOURCE
);
341 goto assemble_overflow
;
346 * Copy query string without encoding...
349 ptr
= http_copy_encode(ptr
, query
, end
, NULL
, NULL
,
350 encoding
& HTTP_URI_CODING_QUERY
);
352 goto assemble_overflow
;
358 goto assemble_overflow
;
361 * Nul-terminate the URI buffer and return with no errors...
366 return (HTTP_URI_OK
);
369 * Clear the URI string and return an overflow error; I don't usually
370 * like goto's, but in this case it makes sense...
376 return (HTTP_URI_OVERFLOW
);
381 * 'httpAssembleURIf()' - Assemble a uniform resource identifier from its
382 * components with a formatted resource.
384 * This function creates a formatted version of the resource string
385 * argument "resourcef" and escapes reserved characters in the URI
386 * depending on the value of the "encoding" argument. You should use
387 * this function in place of traditional string functions whenever
388 * you need to create a URI string.
390 * @since CUPS 1.2/Mac OS X 10.5@
393 http_uri_status_t
/* O - URI status */
395 http_uri_coding_t encoding
, /* I - Encoding flags */
396 char *uri
, /* I - URI buffer */
397 int urilen
, /* I - Size of URI buffer */
398 const char *scheme
, /* I - Scheme name */
399 const char *username
, /* I - Username */
400 const char *host
, /* I - Hostname or address */
401 int port
, /* I - Port number */
402 const char *resourcef
, /* I - Printf-style resource */
403 ...) /* I - Additional arguments as needed */
405 va_list ap
; /* Pointer to additional arguments */
406 char resource
[1024]; /* Formatted resource string */
407 int bytes
; /* Bytes in formatted string */
411 * Range check input...
414 if (!uri
|| urilen
< 1 || !scheme
|| port
< 0 || !resourcef
)
419 return (HTTP_URI_BAD_ARGUMENTS
);
423 * Format the resource string and assemble the URI...
426 va_start(ap
, resourcef
);
427 bytes
= vsnprintf(resource
, sizeof(resource
), resourcef
, ap
);
430 if (bytes
>= sizeof(resource
))
433 return (HTTP_URI_OVERFLOW
);
436 return (httpAssembleURI(encoding
, uri
, urilen
, scheme
, username
, host
,
442 * '_httpAssembleUUID()' - Make a UUID URI conforming to RFC 4122.
444 * The buffer needs to be at least 46 bytes in size.
447 char * /* I - UUID string */
448 _httpAssembleUUID(const char *server
, /* I - Server name */
449 int port
, /* I - Port number */
450 const char *name
, /* I - Object name or NULL */
451 int number
, /* I - Object number or 0 */
452 char *buffer
, /* I - String buffer */
453 size_t bufsize
) /* I - Size of buffer */
455 char data
[1024]; /* Source string for MD5 */
456 _cups_md5_state_t md5state
; /* MD5 state */
457 unsigned char md5sum
[16]; /* MD5 digest/sum */
461 * Build a version 3 UUID conforming to RFC 4122.
463 * Start with the MD5 sum of the server, port, object name and
464 * number, and some random data on the end.
467 snprintf(data
, sizeof(data
), "%s:%d:%s:%d:%04x:%04x", server
,
468 port
, name
? name
: server
, number
,
469 (unsigned)CUPS_RAND() & 0xffff, (unsigned)CUPS_RAND() & 0xffff);
471 _cupsMD5Init(&md5state
);
472 _cupsMD5Append(&md5state
, (unsigned char *)data
, strlen(data
));
473 _cupsMD5Finish(&md5state
, md5sum
);
476 * Generate the UUID from the MD5...
479 snprintf(buffer
, bufsize
,
480 "urn:uuid:%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-"
481 "%02x%02x%02x%02x%02x%02x",
482 md5sum
[0], md5sum
[1], md5sum
[2], md5sum
[3], md5sum
[4], md5sum
[5],
483 (md5sum
[6] & 15) | 0x30, md5sum
[7], (md5sum
[8] & 0x3f) | 0x40,
484 md5sum
[9], md5sum
[10], md5sum
[11], md5sum
[12], md5sum
[13],
485 md5sum
[14], md5sum
[15]);
492 * 'httpDecode64()' - Base64-decode a string.
494 * This function is deprecated. Use the httpDecode64_2() function instead
495 * which provides buffer length arguments.
500 char * /* O - Decoded string */
501 httpDecode64(char *out
, /* I - String to write to */
502 const char *in
) /* I - String to read from */
504 int outlen
; /* Output buffer length */
508 * Use the old maximum buffer size for binary compatibility...
513 return (httpDecode64_2(out
, &outlen
, in
));
518 * 'httpDecode64_2()' - Base64-decode a string.
520 * @since CUPS 1.1.21/Mac OS X 10.4@
523 char * /* O - Decoded string */
524 httpDecode64_2(char *out
, /* I - String to write to */
525 int *outlen
, /* IO - Size of output string */
526 const char *in
) /* I - String to read from */
528 int pos
, /* Bit position */
529 base64
; /* Value of this character */
530 char *outptr
, /* Output pointer */
531 *outend
; /* End of output buffer */
535 * Range check input...
538 if (!out
|| !outlen
|| *outlen
< 1 || !in
)
550 * Convert from base-64 to bytes...
553 for (outptr
= out
, outend
= out
+ *outlen
- 1, pos
= 0; *in
!= '\0'; in
++)
556 * Decode this character into a number from 0 to 63...
559 if (*in
>= 'A' && *in
<= 'Z')
561 else if (*in
>= 'a' && *in
<= 'z')
562 base64
= *in
- 'a' + 26;
563 else if (*in
>= '0' && *in
<= '9')
564 base64
= *in
- '0' + 52;
575 * Store the result in the appropriate chars...
582 *outptr
= base64
<< 2;
587 *outptr
++ |= (base64
>> 4) & 3;
589 *outptr
= (base64
<< 4) & 255;
594 *outptr
++ |= (base64
>> 2) & 15;
596 *outptr
= (base64
<< 6) & 255;
610 * Return the decoded string and size...
613 *outlen
= (int)(outptr
- out
);
620 * 'httpEncode64()' - Base64-encode a string.
622 * This function is deprecated. Use the httpEncode64_2() function instead
623 * which provides buffer length arguments.
628 char * /* O - Encoded string */
629 httpEncode64(char *out
, /* I - String to write to */
630 const char *in
) /* I - String to read from */
632 return (httpEncode64_2(out
, 512, in
, (int)strlen(in
)));
637 * 'httpEncode64_2()' - Base64-encode a string.
639 * @since CUPS 1.1.21/Mac OS X 10.4@
642 char * /* O - Encoded string */
643 httpEncode64_2(char *out
, /* I - String to write to */
644 int outlen
, /* I - Size of output string */
645 const char *in
, /* I - String to read from */
646 int inlen
) /* I - Size of input string */
648 char *outptr
, /* Output pointer */
649 *outend
; /* End of output buffer */
650 static const char base64
[] = /* Base64 characters... */
652 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
653 "abcdefghijklmnopqrstuvwxyz"
660 * Range check input...
663 if (!out
|| outlen
< 1 || !in
)
667 * Convert bytes to base-64...
670 for (outptr
= out
, outend
= out
+ outlen
- 1; inlen
> 0; in
++, inlen
--)
673 * Encode the up to 3 characters as 4 Base64 numbers...
677 *outptr
++ = base64
[(in
[0] & 255) >> 2];
682 *outptr
++ = base64
[(((in
[0] & 255) << 4) | ((in
[1] & 255) >> 4)) & 63];
684 *outptr
++ = base64
[((in
[0] & 255) << 4) & 63];
701 *outptr
++ = base64
[(((in
[0] & 255) << 2) | ((in
[1] & 255) >> 6)) & 63];
703 *outptr
++ = base64
[((in
[0] & 255) << 2) & 63];
716 *outptr
++ = base64
[in
[0] & 63];
722 * Return the encoded string...
730 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
735 const char * /* O - Date/time string */
736 httpGetDateString(time_t t
) /* I - UNIX time */
738 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
741 return (httpGetDateString2(t
, cg
->http_date
, sizeof(cg
->http_date
)));
746 * 'httpGetDateString2()' - Get a formatted date/time string from a time value.
748 * @since CUPS 1.2/Mac OS X 10.5@
751 const char * /* O - Date/time string */
752 httpGetDateString2(time_t t
, /* I - UNIX time */
753 char *s
, /* I - String buffer */
754 int slen
) /* I - Size of string buffer */
756 struct tm
*tdate
; /* UNIX date/time data */
760 snprintf(s
, slen
, "%s, %02d %s %d %02d:%02d:%02d GMT",
761 http_days
[tdate
->tm_wday
], tdate
->tm_mday
,
762 http_months
[tdate
->tm_mon
], tdate
->tm_year
+ 1900,
763 tdate
->tm_hour
, tdate
->tm_min
, tdate
->tm_sec
);
770 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
773 time_t /* O - UNIX time */
774 httpGetDateTime(const char *s
) /* I - Date/time string */
776 int i
; /* Looping var */
777 char mon
[16]; /* Abbreviated month name */
778 int day
, year
; /* Day of month and year */
779 int hour
, min
, sec
; /* Time */
780 int days
; /* Number of days since 1970 */
781 static const int normal_days
[] = /* Days to a month, normal years */
782 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
783 static const int leap_days
[] = /* Days to a month, leap years */
784 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 };
787 DEBUG_printf(("2httpGetDateTime(s=\"%s\")", s
));
790 * Extract the date and time from the formatted string...
793 if (sscanf(s
, "%*s%d%15s%d%d:%d:%d", &day
, mon
, &year
, &hour
, &min
, &sec
) < 6)
796 DEBUG_printf(("4httpGetDateTime: day=%d, mon=\"%s\", year=%d, hour=%d, "
797 "min=%d, sec=%d", day
, mon
, year
, hour
, min
, sec
));
800 * Convert the month name to a number from 0 to 11.
803 for (i
= 0; i
< 12; i
++)
804 if (!_cups_strcasecmp(mon
, http_months
[i
]))
810 DEBUG_printf(("4httpGetDateTime: i=%d", i
));
813 * Now convert the date and time to a UNIX time value in seconds since
814 * 1970. We can't use mktime() since the timezone may not be UTC but
815 * the date/time string *is* UTC.
818 if ((year
& 3) == 0 && ((year
% 100) != 0 || (year
% 400) == 0))
819 days
= leap_days
[i
] + day
- 1;
821 days
= normal_days
[i
] + day
- 1;
823 DEBUG_printf(("4httpGetDateTime: days=%d", days
));
825 days
+= (year
- 1970) * 365 + /* 365 days per year (normally) */
826 ((year
- 1) / 4 - 492) - /* + leap days */
827 ((year
- 1) / 100 - 19) + /* - 100 year days */
828 ((year
- 1) / 400 - 4); /* + 400 year days */
830 DEBUG_printf(("4httpGetDateTime: days=%d\n", days
));
832 return (days
* 86400 + hour
* 3600 + min
* 60 + sec
);
837 * 'httpSeparate()' - Separate a Universal Resource Identifier into its
840 * This function is deprecated; use the httpSeparateURI() function instead.
846 httpSeparate(const char *uri
, /* I - Universal Resource Identifier */
847 char *scheme
, /* O - Scheme [32] (http, https, etc.) */
848 char *username
, /* O - Username [1024] */
849 char *host
, /* O - Hostname [1024] */
850 int *port
, /* O - Port number to use */
851 char *resource
) /* O - Resource/filename [1024] */
853 httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, 32, username
,
854 HTTP_MAX_URI
, host
, HTTP_MAX_URI
, port
, resource
,
860 * 'httpSeparate2()' - Separate a Universal Resource Identifier into its
863 * This function is deprecated; use the httpSeparateURI() function instead.
865 * @since CUPS 1.1.21/Mac OS X 10.4@
870 httpSeparate2(const char *uri
, /* I - Universal Resource Identifier */
871 char *scheme
, /* O - Scheme (http, https, etc.) */
872 int schemelen
, /* I - Size of scheme buffer */
873 char *username
, /* O - Username */
874 int usernamelen
, /* I - Size of username buffer */
875 char *host
, /* O - Hostname */
876 int hostlen
, /* I - Size of hostname buffer */
877 int *port
, /* O - Port number to use */
878 char *resource
, /* O - Resource/filename */
879 int resourcelen
) /* I - Size of resource buffer */
881 httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, schemelen
, username
,
882 usernamelen
, host
, hostlen
, port
, resource
, resourcelen
);
887 * 'httpSeparateURI()' - Separate a Universal Resource Identifier into its
890 * @since CUPS 1.2/Mac OS X 10.5@
893 http_uri_status_t
/* O - Result of separation */
895 http_uri_coding_t decoding
, /* I - Decoding flags */
896 const char *uri
, /* I - Universal Resource Identifier */
897 char *scheme
, /* O - Scheme (http, https, etc.) */
898 int schemelen
, /* I - Size of scheme buffer */
899 char *username
, /* O - Username */
900 int usernamelen
, /* I - Size of username buffer */
901 char *host
, /* O - Hostname */
902 int hostlen
, /* I - Size of hostname buffer */
903 int *port
, /* O - Port number to use */
904 char *resource
, /* O - Resource/filename */
905 int resourcelen
) /* I - Size of resource buffer */
907 char *ptr
, /* Pointer into string... */
908 *end
; /* End of string */
909 const char *sep
; /* Separator character */
910 http_uri_status_t status
; /* Result of separation */
914 * Initialize everything to blank...
917 if (scheme
&& schemelen
> 0)
920 if (username
&& usernamelen
> 0)
923 if (host
&& hostlen
> 0)
929 if (resource
&& resourcelen
> 0)
933 * Range check input...
936 if (!uri
|| !port
|| !scheme
|| schemelen
<= 0 || !username
||
937 usernamelen
<= 0 || !host
|| hostlen
<= 0 || !resource
||
939 return (HTTP_URI_BAD_ARGUMENTS
);
942 return (HTTP_URI_BAD_URI
);
945 * Grab the scheme portion of the URI...
948 status
= HTTP_URI_OK
;
950 if (!strncmp(uri
, "//", 2))
953 * Workaround for HP IPP client bug...
956 strlcpy(scheme
, "ipp", schemelen
);
957 status
= HTTP_URI_MISSING_SCHEME
;
959 else if (*uri
== '/')
965 strlcpy(scheme
, "file", schemelen
);
966 status
= HTTP_URI_MISSING_SCHEME
;
971 * Standard URI with scheme...
974 for (ptr
= scheme
, end
= scheme
+ schemelen
- 1;
975 *uri
&& *uri
!= ':' && ptr
< end
;)
976 if (strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
977 "abcdefghijklmnopqrstuvwxyz"
978 "0123456789-+.", *uri
) != NULL
)
988 return (HTTP_URI_BAD_SCHEME
);
995 * Set the default port number...
998 if (!strcmp(scheme
, "http"))
1000 else if (!strcmp(scheme
, "https"))
1002 else if (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps"))
1004 else if (!_cups_strcasecmp(scheme
, "lpd"))
1006 else if (!strcmp(scheme
, "socket")) /* Not yet registered with IANA... */
1008 else if (strcmp(scheme
, "file") && strcmp(scheme
, "mailto"))
1009 status
= HTTP_URI_UNKNOWN_SCHEME
;
1012 * Now see if we have a hostname...
1015 if (!strncmp(uri
, "//", 2))
1018 * Yes, extract it...
1024 * Grab the username, if any...
1027 if ((sep
= strpbrk(uri
, "@/")) != NULL
&& *sep
== '@')
1030 * Get a username:password combo...
1033 uri
= http_copy_decode(username
, uri
, usernamelen
, "@",
1034 decoding
& HTTP_URI_CODING_USERNAME
);
1039 return (HTTP_URI_BAD_USERNAME
);
1046 * Then the hostname/IP address...
1052 * Grab IPv6 address...
1056 if (!strncmp(uri
, "v1.", 3))
1057 uri
+= 3; /* Skip IPvN leader... */
1059 uri
= http_copy_decode(host
, uri
, hostlen
, "]",
1060 decoding
& HTTP_URI_CODING_HOSTNAME
);
1065 return (HTTP_URI_BAD_HOSTNAME
);
1075 return (HTTP_URI_BAD_HOSTNAME
);
1080 for (ptr
= host
; *ptr
; ptr
++)
1084 * Convert zone separator to % and stop here...
1090 else if (*ptr
!= ':' && *ptr
!= '.' && !isxdigit(*ptr
& 255))
1093 return (HTTP_URI_BAD_HOSTNAME
);
1099 * Validate the hostname or IPv4 address first...
1102 for (ptr
= (char *)uri
; *ptr
; ptr
++)
1103 if (strchr(":?/", *ptr
))
1105 else if (!strchr("abcdefghijklmnopqrstuvwxyz"
1106 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1110 "!$&'()*+,;=\\", *ptr
))
1113 return (HTTP_URI_BAD_HOSTNAME
);
1117 * Then copy the hostname or IPv4 address to the buffer...
1120 uri
= http_copy_decode(host
, uri
, hostlen
, ":?/",
1121 decoding
& HTTP_URI_CODING_HOSTNAME
);
1126 return (HTTP_URI_BAD_HOSTNAME
);
1131 * Validate hostname for file scheme - only empty and localhost are
1135 if (!strcmp(scheme
, "file") && strcmp(host
, "localhost") && host
[0])
1138 return (HTTP_URI_BAD_HOSTNAME
);
1142 * See if we have a port number...
1148 * Yes, collect the port number...
1151 if (!isdigit(uri
[1] & 255))
1154 return (HTTP_URI_BAD_PORT
);
1157 *port
= strtol(uri
+ 1, (char **)&uri
, 10);
1159 if (*uri
!= '/' && *uri
)
1162 return (HTTP_URI_BAD_PORT
);
1168 * The remaining portion is the resource string...
1171 if (*uri
== '?' || !*uri
)
1174 * Hostname but no path...
1177 status
= HTTP_URI_MISSING_RESOURCE
;
1181 * Copy any query string...
1185 uri
= http_copy_decode(resource
+ 1, uri
, resourcelen
- 1, NULL
,
1186 decoding
& HTTP_URI_CODING_QUERY
);
1192 uri
= http_copy_decode(resource
, uri
, resourcelen
, "?",
1193 decoding
& HTTP_URI_CODING_RESOURCE
);
1195 if (uri
&& *uri
== '?')
1198 * Concatenate any query string...
1201 char *resptr
= resource
+ strlen(resource
);
1203 uri
= http_copy_decode(resptr
, uri
, resourcelen
- (int)(resptr
- resource
),
1204 NULL
, decoding
& HTTP_URI_CODING_QUERY
);
1211 return (HTTP_URI_BAD_RESOURCE
);
1215 * Return the URI separation status...
1223 * 'httpStatus()' - Return a short string describing a HTTP status code.
1225 * The returned string is localized to the current POSIX locale and is based
1226 * on the status strings defined in RFC 2616.
1229 const char * /* O - Localized status string */
1230 httpStatus(http_status_t status
) /* I - HTTP status code */
1232 const char *s
; /* Status string */
1233 _cups_globals_t
*cg
= _cupsGlobals(); /* Global data */
1236 if (!cg
->lang_default
)
1237 cg
->lang_default
= cupsLangDefault();
1241 case HTTP_CONTINUE
:
1244 case HTTP_SWITCHING_PROTOCOLS
:
1245 s
= _("Switching Protocols");
1253 case HTTP_ACCEPTED
:
1256 case HTTP_NO_CONTENT
:
1257 s
= _("No Content");
1259 case HTTP_MOVED_PERMANENTLY
:
1260 s
= _("Moved Permanently");
1262 case HTTP_SEE_OTHER
:
1265 case HTTP_NOT_MODIFIED
:
1266 s
= _("Not Modified");
1268 case HTTP_BAD_REQUEST
:
1269 s
= _("Bad Request");
1271 case HTTP_UNAUTHORIZED
:
1272 case HTTP_AUTHORIZATION_CANCELED
:
1273 s
= _("Unauthorized");
1275 case HTTP_FORBIDDEN
:
1278 case HTTP_NOT_FOUND
:
1281 case HTTP_REQUEST_TOO_LARGE
:
1282 s
= _("Request Entity Too Large");
1284 case HTTP_URI_TOO_LONG
:
1285 s
= _("URI Too Long");
1287 case HTTP_UPGRADE_REQUIRED
:
1288 s
= _("Upgrade Required");
1290 case HTTP_NOT_IMPLEMENTED
:
1291 s
= _("Not Implemented");
1293 case HTTP_NOT_SUPPORTED
:
1294 s
= _("Not Supported");
1296 case HTTP_EXPECTATION_FAILED
:
1297 s
= _("Expectation Failed");
1299 case HTTP_SERVICE_UNAVAILABLE
:
1300 s
= _("Service Unavailable");
1302 case HTTP_SERVER_ERROR
:
1303 s
= _("Internal Server Error");
1305 case HTTP_PKI_ERROR
:
1306 s
= _("SSL/TLS Negotiation Error");
1308 case HTTP_WEBIF_DISABLED
:
1309 s
= _("Web Interface is Disabled");
1317 return (_cupsLangString(cg
->lang_default
, s
));
1321 #ifndef HAVE_HSTRERROR
1323 * '_cups_hstrerror()' - hstrerror() emulation function for Solaris and others.
1326 const char * /* O - Error string */
1327 _cups_hstrerror(int error
) /* I - Error number */
1329 static const char * const errors
[] = /* Error strings */
1334 "Unrecoverable lookup error.",
1335 "No data associated with name."
1339 if (error
< 0 || error
> 4)
1340 return ("Unknown hostname lookup error.");
1342 return (errors
[error
]);
1344 #endif /* !HAVE_HSTRERROR */
1348 * '_httpDecodeURI()' - Percent-decode a HTTP request URI.
1351 char * /* O - Decoded URI or NULL on error */
1352 _httpDecodeURI(char *dst
, /* I - Destination buffer */
1353 const char *src
, /* I - Source URI */
1354 size_t dstsize
) /* I - Size of destination buffer */
1356 if (http_copy_decode(dst
, src
, (int)dstsize
, NULL
, 1))
1364 * '_httpEncodeURI()' - Percent-encode a HTTP request URI.
1367 char * /* O - Encoded URI */
1368 _httpEncodeURI(char *dst
, /* I - Destination buffer */
1369 const char *src
, /* I - Source URI */
1370 size_t dstsize
) /* I - Size of destination buffer */
1372 http_copy_encode(dst
, src
, dst
+ dstsize
- 1, NULL
, NULL
, 1);
1378 * '_httpResolveURI()' - Resolve a DNS-SD URI.
1381 const char * /* O - Resolved URI */
1383 const char *uri
, /* I - DNS-SD URI */
1384 char *resolved_uri
, /* I - Buffer for resolved URI */
1385 size_t resolved_size
, /* I - Size of URI buffer */
1386 int options
, /* I - Resolve options */
1387 int (*cb
)(void *context
), /* I - Continue callback function */
1388 void *context
) /* I - Context pointer for callback */
1390 char scheme
[32], /* URI components... */
1396 http_uri_status_t status
; /* URI decode status */
1400 DEBUG_printf(("4_httpResolveURI(uri=\"%s\", resolved_uri=%p, "
1401 "resolved_size=" CUPS_LLFMT
")", uri
, resolved_uri
,
1402 CUPS_LLCAST resolved_size
));
1405 * Get the device URI...
1409 if ((status
= httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
,
1410 sizeof(scheme
), userpass
, sizeof(userpass
),
1411 hostname
, sizeof(hostname
), &port
, resource
,
1412 sizeof(resource
))) < HTTP_URI_OK
)
1414 if (httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
,
1415 sizeof(scheme
), userpass
, sizeof(userpass
),
1416 hostname
, sizeof(hostname
), &port
, resource
,
1417 sizeof(resource
)) < HTTP_URI_OK
)
1420 if (options
& _HTTP_RESOLVE_STDERR
)
1421 _cupsLangPrintFilter(stderr
, "ERROR", _("Bad device-uri \"%s\"."), uri
);
1423 DEBUG_printf(("6_httpResolveURI: httpSeparateURI returned %d!", status
));
1424 DEBUG_puts("5_httpResolveURI: Returning NULL");
1429 * Resolve it as needed...
1432 if (strstr(hostname
, "._tcp"))
1436 # pragma comment(lib, "dnssd.lib")
1438 DNSServiceRef ref
, /* DNS-SD master service reference */
1439 domainref
, /* DNS-SD service reference for domain */
1440 localref
; /* DNS-SD service reference for .local */
1441 int domainsent
= 0, /* Send the domain resolve? */
1442 offline
= 0; /* offline-report state set? */
1443 char *regtype
, /* Pointer to type in hostname */
1444 *domain
; /* Pointer to domain in hostname */
1445 _http_uribuf_t uribuf
; /* URI buffer */
1447 struct pollfd polldata
; /* Polling data */
1448 #else /* select() */
1449 fd_set input_set
; /* Input set for select() */
1450 struct timeval stimeout
; /* Timeout value for select() */
1451 #endif /* HAVE_POLL */
1453 if (options
& _HTTP_RESOLVE_STDERR
)
1454 fprintf(stderr
, "DEBUG: Resolving \"%s\"...\n", hostname
);
1457 * Separate the hostname into service name, registration type, and domain...
1460 for (regtype
= strstr(hostname
, "._tcp") - 2;
1463 if (regtype
[0] == '.' && regtype
[1] == '_')
1466 * Found ._servicetype in front of ._tcp...
1473 if (regtype
<= hostname
)
1475 DEBUG_puts("5_httpResolveURI: Bad hostname, returning NULL");
1479 for (domain
= strchr(regtype
, '.');
1481 domain
= strchr(domain
+ 1, '.'))
1482 if (domain
[1] != '_')
1488 uribuf
.buffer
= resolved_uri
;
1489 uribuf
.bufsize
= resolved_size
;
1490 uribuf
.options
= options
;
1491 resolved_uri
[0] = '\0';
1493 DEBUG_printf(("6_httpResolveURI: Resolving hostname=\"%s\", regtype=\"%s\", "
1494 "domain=\"%s\"\n", hostname
, regtype
, domain
));
1495 if (options
& _HTTP_RESOLVE_STDERR
)
1497 fputs("STATE: +connecting-to-device\n", stderr
);
1498 fprintf(stderr
, "DEBUG: Resolving \"%s\", regtype=\"%s\", "
1499 "domain=\"local.\"...\n", hostname
, regtype
);
1504 if (DNSServiceCreateConnection(&ref
) == kDNSServiceErr_NoError
)
1507 if (DNSServiceResolve(&localref
, kDNSServiceFlagsShareConnection
, 0,
1508 hostname
, regtype
, "local.", http_resolve_cb
,
1509 &uribuf
) == kDNSServiceErr_NoError
)
1511 int fds
; /* Number of ready descriptors */
1512 time_t timeout
, /* Poll timeout */
1513 start_time
= time(NULL
);/* Start time */
1517 if (options
& _HTTP_RESOLVE_STDERR
)
1518 _cupsLangPrintFilter(stderr
, "INFO", _("Looking for printer."));
1520 if (cb
&& !(*cb
)(context
))
1522 DEBUG_puts("5_httpResolveURI: callback returned 0 (stop)");
1527 * For the first minute (or forever if we have a callback), wakeup
1528 * every 2 seconds to emit a "looking for printer" message...
1531 timeout
= (time(NULL
) < (start_time
+ 60) || cb
) ? 2000 : -1;
1534 polldata
.fd
= DNSServiceRefSockFD(ref
);
1535 polldata
.events
= POLLIN
;
1537 fds
= poll(&polldata
, 1, timeout
);
1539 #else /* select() */
1540 FD_ZERO(&input_set
);
1541 FD_SET(DNSServiceRefSockFD(ref
), &input_set
);
1543 stimeout
.tv_sec
= ((int)timeout
) / 1000;
1544 stimeout
.tv_usec
= ((int)(timeout
) * 1000) % 1000000;
1546 fds
= select(DNSServiceRefSockFD(ref
)+1, &input_set
, NULL
, NULL
,
1547 timeout
< 0.0 ? NULL
: &stimeout
);
1548 #endif /* HAVE_POLL */
1552 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1554 DEBUG_printf(("5_httpResolveURI: poll error: %s", strerror(errno
)));
1561 * Wait 2 seconds for a response to the local resolve; if nothing
1562 * comes in, do an additional domain resolution...
1565 if (domainsent
== 0 && (domain
&& _cups_strcasecmp(domain
, "local.")))
1567 if (options
& _HTTP_RESOLVE_STDERR
)
1569 "DEBUG: Resolving \"%s\", regtype=\"%s\", "
1570 "domain=\"%s\"...\n", hostname
, regtype
,
1571 domain
? domain
: "");
1574 if (DNSServiceResolve(&domainref
, kDNSServiceFlagsShareConnection
,
1575 0, hostname
, regtype
, domain
,
1576 http_resolve_cb
, &uribuf
)
1577 == kDNSServiceErr_NoError
)
1582 * If it hasn't resolved within 5 seconds set the offline-report
1583 * printer-state-reason...
1586 if ((options
& _HTTP_RESOLVE_STDERR
) && offline
== 0 &&
1587 time(NULL
) > (start_time
+ 5))
1589 fputs("STATE: +offline-report\n", stderr
);
1595 if (DNSServiceProcessResult(ref
) == kDNSServiceErr_NoError
)
1604 DNSServiceRefDeallocate(domainref
);
1606 DNSServiceRefDeallocate(localref
);
1609 DNSServiceRefDeallocate(ref
);
1612 if (options
& _HTTP_RESOLVE_STDERR
)
1615 fprintf(stderr
, "DEBUG: Resolved as \"%s\"...\n", uri
);
1617 fputs("DEBUG: Unable to resolve URI\n", stderr
);
1619 fputs("STATE: -connecting-to-device,offline-report\n", stderr
);
1624 * No DNS-SD support...
1628 #endif /* HAVE_DNSSD */
1630 if ((options
& _HTTP_RESOLVE_STDERR
) && !uri
)
1631 _cupsLangPrintFilter(stderr
, "ERROR", _("Unable to find printer."));
1636 * Nothing more to do...
1639 strlcpy(resolved_uri
, uri
, resolved_size
);
1643 DEBUG_printf(("5_httpResolveURI: Returning \"%s\"", uri
));
1650 * 'http_copy_decode()' - Copy and decode a URI.
1653 static const char * /* O - New source pointer or NULL on error */
1654 http_copy_decode(char *dst
, /* O - Destination buffer */
1655 const char *src
, /* I - Source pointer */
1656 int dstsize
, /* I - Destination size */
1657 const char *term
, /* I - Terminating characters */
1658 int decode
) /* I - Decode %-encoded values */
1660 char *ptr
, /* Pointer into buffer */
1661 *end
; /* End of buffer */
1662 int quoted
; /* Quoted character */
1666 * Copy the src to the destination until we hit a terminating character
1667 * or the end of the string.
1670 for (ptr
= dst
, end
= dst
+ dstsize
- 1;
1671 *src
&& (!term
|| !strchr(term
, *src
));
1675 if (*src
== '%' && decode
)
1677 if (isxdigit(src
[1] & 255) && isxdigit(src
[2] & 255))
1680 * Grab a hex-encoded character...
1685 quoted
= (tolower(*src
) - 'a' + 10) << 4;
1687 quoted
= (*src
- '0') << 4;
1691 quoted
|= tolower(*src
) - 'a' + 10;
1693 quoted
|= *src
- '0';
1700 * Bad hex-encoded character...
1718 * 'http_copy_encode()' - Copy and encode a URI.
1721 static char * /* O - End of current URI */
1722 http_copy_encode(char *dst
, /* O - Destination buffer */
1723 const char *src
, /* I - Source pointer */
1724 char *dstend
, /* I - End of destination buffer */
1725 const char *reserved
, /* I - Extra reserved characters */
1726 const char *term
, /* I - Terminating characters */
1727 int encode
) /* I - %-encode reserved chars? */
1729 static const char hex
[] = "0123456789ABCDEF";
1732 while (*src
&& dst
< dstend
)
1734 if (term
&& *src
== *term
)
1737 if (encode
&& (*src
== '%' || *src
<= ' ' || *src
& 128 ||
1738 (reserved
&& strchr(reserved
, *src
))))
1741 * Hex encode reserved characters...
1744 if ((dst
+ 2) >= dstend
)
1748 *dst
++ = hex
[(*src
>> 4) & 15];
1749 *dst
++ = hex
[*src
& 15];
1768 * 'http_resolve_cb()' - Build a device URI for the given service name.
1771 static void DNSSD_API
1773 DNSServiceRef sdRef
, /* I - Service reference */
1774 DNSServiceFlags flags
, /* I - Results flags */
1775 uint32_t interfaceIndex
, /* I - Interface number */
1776 DNSServiceErrorType errorCode
, /* I - Error, if any */
1777 const char *fullName
, /* I - Full service name */
1778 const char *hostTarget
, /* I - Hostname */
1779 uint16_t port
, /* I - Port number */
1780 uint16_t txtLen
, /* I - Length of TXT record */
1781 const unsigned char *txtRecord
, /* I - TXT record data */
1782 void *context
) /* I - Pointer to URI buffer */
1784 const char *scheme
, /* URI scheme */
1785 *hostptr
; /* Pointer into hostTarget */
1786 char rp
[257], /* Remote printer */
1787 fqdn
[256]; /* FQDN of the .local name */
1788 const void *value
; /* Value from TXT record */
1789 uint8_t valueLen
; /* Length of value */
1790 _http_uribuf_t
*uribuf
; /* URI buffer */
1793 DEBUG_printf(("7http_resolve_cb(sdRef=%p, flags=%x, interfaceIndex=%u, "
1794 "errorCode=%d, fullName=\"%s\", hostTarget=\"%s\", port=%u, "
1795 "txtLen=%u, txtRecord=%p, context=%p)", sdRef
, flags
,
1796 interfaceIndex
, errorCode
, fullName
, hostTarget
, port
, txtLen
,
1797 txtRecord
, context
));
1799 uribuf
= (_http_uribuf_t
*)context
;
1802 * Figure out the scheme from the full name...
1805 if (strstr(fullName
, "._ipps") || strstr(fullName
, "._ipp-tls"))
1807 else if (strstr(fullName
, "._ipp") || strstr(fullName
, "._fax-ipp"))
1809 else if (strstr(fullName
, "._http."))
1811 else if (strstr(fullName
, "._https."))
1813 else if (strstr(fullName
, "._printer."))
1815 else if (strstr(fullName
, "._pdl-datastream."))
1818 scheme
= "riousbprint";
1821 * Extract the "remote printer" key from the TXT record...
1824 if ((value
= TXTRecordGetValuePtr(txtLen
, txtRecord
, "rp",
1825 &valueLen
)) != NULL
)
1828 * Convert to resource by concatenating with a leading "/"...
1832 memcpy(rp
+ 1, value
, valueLen
);
1833 rp
[valueLen
+ 1] = '\0';
1839 * Lookup the FQDN if needed...
1842 if ((uribuf
->options
& _HTTP_RESOLVE_FQDN
) &&
1843 (hostptr
= hostTarget
+ strlen(hostTarget
) - 7) > hostTarget
&&
1844 !_cups_strcasecmp(hostptr
, ".local."))
1847 * OK, we got a .local name but the caller needs a real domain. Start by
1848 * getting the IP address of the .local name and then do reverse-lookups...
1851 http_addrlist_t
*addrlist
, /* List of addresses */
1852 *addr
; /* Current address */
1854 DEBUG_printf(("8http_resolve_cb: Looking up \"%s\".", hostTarget
));
1856 snprintf(fqdn
, sizeof(fqdn
), "%d", ntohs(port
));
1857 if ((addrlist
= httpAddrGetList(hostTarget
, AF_UNSPEC
, fqdn
)) != NULL
)
1859 for (addr
= addrlist
; addr
; addr
= addr
->next
)
1861 int error
= getnameinfo(&(addr
->addr
.addr
),
1862 httpAddrLength(&(addr
->addr
)),
1863 fqdn
, sizeof(fqdn
), NULL
, 0, NI_NAMEREQD
);
1867 DEBUG_printf(("8http_resolve_cb: Found \"%s\".", fqdn
));
1869 if ((hostptr
= fqdn
+ strlen(fqdn
) - 6) <= fqdn
||
1870 _cups_strcasecmp(hostptr
, ".local"))
1878 DEBUG_printf(("8http_resolve_cb: \"%s\" did not resolve: %d",
1879 httpAddrString(&(addr
->addr
), fqdn
, sizeof(fqdn
)),
1887 * Assemble the final device URI...
1890 httpAssembleURI(HTTP_URI_CODING_ALL
, uribuf
->buffer
, uribuf
->bufsize
, scheme
,
1891 NULL
, hostTarget
, ntohs(port
), rp
);
1893 DEBUG_printf(("8http_resolve_cb: Resolved URI is \"%s\"...", uribuf
->buffer
));
1895 #endif /* HAVE_DNSSD */
1899 * End of "$Id: http-support.c 7952 2008-09-17 00:56:20Z mike $".