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 * resolve_callback() - 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 */
80 static const char * const http_days
[7] =
90 static const char * const http_months
[12] =
111 static const char *http_copy_decode(char *dst
, const char *src
,
112 int dstsize
, const char *term
,
114 static char *http_copy_encode(char *dst
, const char *src
,
115 char *dstend
, const char *reserved
,
116 const char *term
, int encode
);
118 static void DNSSD_API
resolve_callback(DNSServiceRef sdRef
,
119 DNSServiceFlags flags
,
120 uint32_t interfaceIndex
,
121 DNSServiceErrorType errorCode
,
122 const char *fullName
,
123 const char *hostTarget
,
124 uint16_t port
, uint16_t txtLen
,
125 const unsigned char *txtRecord
,
127 #endif /* HAVE_DNSSD */
131 * 'httpAssembleURI()' - Assemble a uniform resource identifier from its
134 * This function escapes reserved characters in the URI depending on the
135 * value of the "encoding" argument. You should use this function in
136 * place of traditional string functions whenever you need to create a
139 * @since CUPS 1.2/Mac OS X 10.5@
142 http_uri_status_t
/* O - URI status */
144 http_uri_coding_t encoding
, /* I - Encoding flags */
145 char *uri
, /* I - URI buffer */
146 int urilen
, /* I - Size of URI buffer */
147 const char *scheme
, /* I - Scheme name */
148 const char *username
, /* I - Username */
149 const char *host
, /* I - Hostname or address */
150 int port
, /* I - Port number */
151 const char *resource
) /* I - Resource */
153 char *ptr
, /* Pointer into URI buffer */
154 *end
; /* End of URI buffer */
158 * Range check input...
161 if (!uri
|| urilen
< 1 || !scheme
|| port
< 0)
166 return (HTTP_URI_BAD_ARGUMENTS
);
170 * Assemble the URI starting with the scheme...
173 end
= uri
+ urilen
- 1;
174 ptr
= http_copy_encode(uri
, scheme
, end
, NULL
, NULL
, 0);
177 goto assemble_overflow
;
179 if (!strcmp(scheme
, "mailto"))
182 * mailto: only has :, no //...
188 goto assemble_overflow
;
193 * Schemes other than mailto: all have //...
203 goto assemble_overflow
;
207 * Next the username and hostname, if any...
212 if (username
&& *username
)
215 * Add username@ first...
218 ptr
= http_copy_encode(ptr
, username
, end
, "/?@", NULL
,
219 encoding
& HTTP_URI_CODING_USERNAME
);
222 goto assemble_overflow
;
227 goto assemble_overflow
;
231 * Then add the hostname. Since IPv6 is a particular pain to deal
232 * with, we have several special cases to deal with. If we get
233 * an IPv6 address with brackets around it, assume it is already in
234 * URI format. Since DNS-SD service names can sometimes look like
235 * raw IPv6 addresses, we specifically look for "._tcp" in the name,
239 if (host
[0] != '[' && strchr(host
, ':') && !strstr(host
, "._tcp"))
242 * We have a raw IPv6 address...
245 if (strchr(host
, '%'))
248 * We have a link-local address, add "[v1." prefix...
259 goto assemble_overflow
;
264 * We have a normal address, add "[" prefix...
270 goto assemble_overflow
;
274 * Copy the rest of the IPv6 address, and terminate with "]".
277 while (ptr
< end
&& *host
)
281 *ptr
++ = '+'; /* Convert zone separator */
289 goto assemble_overflow
;
294 goto assemble_overflow
;
299 * Otherwise, just copy the host string...
302 ptr
= http_copy_encode(ptr
, host
, end
, ":/?#[]@\\\"", NULL
,
303 encoding
& HTTP_URI_CODING_HOSTNAME
);
306 goto assemble_overflow
;
310 * Finish things off with the port number...
315 snprintf(ptr
, end
- ptr
+ 1, ":%d", port
);
319 goto assemble_overflow
;
324 * Last but not least, add the resource string...
329 char *query
; /* Pointer to query string */
333 * Copy the resource string up to the query string if present...
336 query
= strchr(resource
, '?');
337 ptr
= http_copy_encode(ptr
, resource
, end
, NULL
, "?",
338 encoding
& HTTP_URI_CODING_RESOURCE
);
340 goto assemble_overflow
;
345 * Copy query string without encoding...
348 ptr
= http_copy_encode(ptr
, query
, end
, NULL
, NULL
,
349 encoding
& HTTP_URI_CODING_QUERY
);
351 goto assemble_overflow
;
357 goto assemble_overflow
;
360 * Nul-terminate the URI buffer and return with no errors...
365 return (HTTP_URI_OK
);
368 * Clear the URI string and return an overflow error; I don't usually
369 * like goto's, but in this case it makes sense...
375 return (HTTP_URI_OVERFLOW
);
380 * 'httpAssembleURIf()' - Assemble a uniform resource identifier from its
381 * components with a formatted resource.
383 * This function creates a formatted version of the resource string
384 * argument "resourcef" and escapes reserved characters in the URI
385 * depending on the value of the "encoding" argument. You should use
386 * this function in place of traditional string functions whenever
387 * you need to create a URI string.
389 * @since CUPS 1.2/Mac OS X 10.5@
392 http_uri_status_t
/* O - URI status */
394 http_uri_coding_t encoding
, /* I - Encoding flags */
395 char *uri
, /* I - URI buffer */
396 int urilen
, /* I - Size of URI buffer */
397 const char *scheme
, /* I - Scheme name */
398 const char *username
, /* I - Username */
399 const char *host
, /* I - Hostname or address */
400 int port
, /* I - Port number */
401 const char *resourcef
, /* I - Printf-style resource */
402 ...) /* I - Additional arguments as needed */
404 va_list ap
; /* Pointer to additional arguments */
405 char resource
[1024]; /* Formatted resource string */
406 int bytes
; /* Bytes in formatted string */
410 * Range check input...
413 if (!uri
|| urilen
< 1 || !scheme
|| port
< 0 || !resourcef
)
418 return (HTTP_URI_BAD_ARGUMENTS
);
422 * Format the resource string and assemble the URI...
425 va_start(ap
, resourcef
);
426 bytes
= vsnprintf(resource
, sizeof(resource
), resourcef
, ap
);
429 if (bytes
>= sizeof(resource
))
432 return (HTTP_URI_OVERFLOW
);
435 return (httpAssembleURI(encoding
, uri
, urilen
, scheme
, username
, host
,
441 * '_httpAssembleUUID()' - Make a UUID URI conforming to RFC 4122.
443 * The buffer needs to be at least 46 bytes in size.
446 char * /* I - UUID string */
447 _httpAssembleUUID(const char *server
, /* I - Server name */
448 int port
, /* I - Port number */
449 const char *name
, /* I - Object name or NULL */
450 int number
, /* I - Object number or 0 */
451 char *buffer
, /* I - String buffer */
452 size_t bufsize
) /* I - Size of buffer */
454 char data
[1024]; /* Source string for MD5 */
455 _cups_md5_state_t md5state
; /* MD5 state */
456 unsigned char md5sum
[16]; /* MD5 digest/sum */
460 * Build a version 3 UUID conforming to RFC 4122.
462 * Start with the MD5 sum of the server, port, object name and
463 * number, and some random data on the end.
466 snprintf(data
, sizeof(data
), "%s:%d:%s:%d:%04x:%04x", server
,
467 port
, name
? name
: server
, number
,
468 CUPS_RAND() & 0xffff, CUPS_RAND() & 0xffff);
470 _cupsMD5Init(&md5state
);
471 _cupsMD5Append(&md5state
, (unsigned char *)data
, strlen(data
));
472 _cupsMD5Finish(&md5state
, md5sum
);
475 * Generate the UUID from the MD5...
478 snprintf(buffer
, bufsize
,
479 "urn:uuid:%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-"
480 "%02x%02x%02x%02x%02x%02x",
481 md5sum
[0], md5sum
[1], md5sum
[2], md5sum
[3], md5sum
[4], md5sum
[5],
482 (md5sum
[6] & 15) | 0x30, md5sum
[7], (md5sum
[8] & 0x3f) | 0x40,
483 md5sum
[9], md5sum
[10], md5sum
[11], md5sum
[12], md5sum
[13],
484 md5sum
[14], md5sum
[15]);
491 * 'httpDecode64()' - Base64-decode a string.
493 * This function is deprecated. Use the httpDecode64_2() function instead
494 * which provides buffer length arguments.
499 char * /* O - Decoded string */
500 httpDecode64(char *out
, /* I - String to write to */
501 const char *in
) /* I - String to read from */
503 int outlen
; /* Output buffer length */
507 * Use the old maximum buffer size for binary compatibility...
512 return (httpDecode64_2(out
, &outlen
, in
));
517 * 'httpDecode64_2()' - Base64-decode a string.
519 * @since CUPS 1.1.21/Mac OS X 10.4@
522 char * /* O - Decoded string */
523 httpDecode64_2(char *out
, /* I - String to write to */
524 int *outlen
, /* IO - Size of output string */
525 const char *in
) /* I - String to read from */
527 int pos
, /* Bit position */
528 base64
; /* Value of this character */
529 char *outptr
, /* Output pointer */
530 *outend
; /* End of output buffer */
534 * Range check input...
537 if (!out
|| !outlen
|| *outlen
< 1 || !in
)
549 * Convert from base-64 to bytes...
552 for (outptr
= out
, outend
= out
+ *outlen
- 1, pos
= 0; *in
!= '\0'; in
++)
555 * Decode this character into a number from 0 to 63...
558 if (*in
>= 'A' && *in
<= 'Z')
560 else if (*in
>= 'a' && *in
<= 'z')
561 base64
= *in
- 'a' + 26;
562 else if (*in
>= '0' && *in
<= '9')
563 base64
= *in
- '0' + 52;
574 * Store the result in the appropriate chars...
581 *outptr
= base64
<< 2;
586 *outptr
++ |= (base64
>> 4) & 3;
588 *outptr
= (base64
<< 4) & 255;
593 *outptr
++ |= (base64
>> 2) & 15;
595 *outptr
= (base64
<< 6) & 255;
609 * Return the decoded string and size...
612 *outlen
= (int)(outptr
- out
);
619 * 'httpEncode64()' - Base64-encode a string.
621 * This function is deprecated. Use the httpEncode64_2() function instead
622 * which provides buffer length arguments.
627 char * /* O - Encoded string */
628 httpEncode64(char *out
, /* I - String to write to */
629 const char *in
) /* I - String to read from */
631 return (httpEncode64_2(out
, 512, in
, (int)strlen(in
)));
636 * 'httpEncode64_2()' - Base64-encode a string.
638 * @since CUPS 1.1.21/Mac OS X 10.4@
641 char * /* O - Encoded string */
642 httpEncode64_2(char *out
, /* I - String to write to */
643 int outlen
, /* I - Size of output string */
644 const char *in
, /* I - String to read from */
645 int inlen
) /* I - Size of input string */
647 char *outptr
, /* Output pointer */
648 *outend
; /* End of output buffer */
649 static const char base64
[] = /* Base64 characters... */
651 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
652 "abcdefghijklmnopqrstuvwxyz"
659 * Range check input...
662 if (!out
|| outlen
< 1 || !in
)
666 * Convert bytes to base-64...
669 for (outptr
= out
, outend
= out
+ outlen
- 1; inlen
> 0; in
++, inlen
--)
672 * Encode the up to 3 characters as 4 Base64 numbers...
676 *outptr
++ = base64
[(in
[0] & 255) >> 2];
681 *outptr
++ = base64
[(((in
[0] & 255) << 4) | ((in
[1] & 255) >> 4)) & 63];
683 *outptr
++ = base64
[((in
[0] & 255) << 4) & 63];
700 *outptr
++ = base64
[(((in
[0] & 255) << 2) | ((in
[1] & 255) >> 6)) & 63];
702 *outptr
++ = base64
[((in
[0] & 255) << 2) & 63];
715 *outptr
++ = base64
[in
[0] & 63];
721 * Return the encoded string...
729 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
734 const char * /* O - Date/time string */
735 httpGetDateString(time_t t
) /* I - UNIX time */
737 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
740 return (httpGetDateString2(t
, cg
->http_date
, sizeof(cg
->http_date
)));
745 * 'httpGetDateString2()' - Get a formatted date/time string from a time value.
747 * @since CUPS 1.2/Mac OS X 10.5@
750 const char * /* O - Date/time string */
751 httpGetDateString2(time_t t
, /* I - UNIX time */
752 char *s
, /* I - String buffer */
753 int slen
) /* I - Size of string buffer */
755 struct tm
*tdate
; /* UNIX date/time data */
759 snprintf(s
, slen
, "%s, %02d %s %d %02d:%02d:%02d GMT",
760 http_days
[tdate
->tm_wday
], tdate
->tm_mday
,
761 http_months
[tdate
->tm_mon
], tdate
->tm_year
+ 1900,
762 tdate
->tm_hour
, tdate
->tm_min
, tdate
->tm_sec
);
769 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
772 time_t /* O - UNIX time */
773 httpGetDateTime(const char *s
) /* I - Date/time string */
775 int i
; /* Looping var */
776 char mon
[16]; /* Abbreviated month name */
777 int day
, year
; /* Day of month and year */
778 int hour
, min
, sec
; /* Time */
779 int days
; /* Number of days since 1970 */
780 static const int normal_days
[] = /* Days to a month, normal years */
781 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
782 static const int leap_days
[] = /* Days to a month, leap years */
783 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 };
786 DEBUG_printf(("2httpGetDateTime(s=\"%s\")", s
));
789 * Extract the date and time from the formatted string...
792 if (sscanf(s
, "%*s%d%15s%d%d:%d:%d", &day
, mon
, &year
, &hour
, &min
, &sec
) < 6)
795 DEBUG_printf(("4httpGetDateTime: day=%d, mon=\"%s\", year=%d, hour=%d, "
796 "min=%d, sec=%d", day
, mon
, year
, hour
, min
, sec
));
799 * Convert the month name to a number from 0 to 11.
802 for (i
= 0; i
< 12; i
++)
803 if (!strcasecmp(mon
, http_months
[i
]))
809 DEBUG_printf(("4httpGetDateTime: i=%d", i
));
812 * Now convert the date and time to a UNIX time value in seconds since
813 * 1970. We can't use mktime() since the timezone may not be UTC but
814 * the date/time string *is* UTC.
817 if ((year
& 3) == 0 && ((year
% 100) != 0 || (year
% 400) == 0))
818 days
= leap_days
[i
] + day
- 1;
820 days
= normal_days
[i
] + day
- 1;
822 DEBUG_printf(("4httpGetDateTime: days=%d", days
));
824 days
+= (year
- 1970) * 365 + /* 365 days per year (normally) */
825 ((year
- 1) / 4 - 492) - /* + leap days */
826 ((year
- 1) / 100 - 19) + /* - 100 year days */
827 ((year
- 1) / 400 - 4); /* + 400 year days */
829 DEBUG_printf(("4httpGetDateTime: days=%d\n", days
));
831 return (days
* 86400 + hour
* 3600 + min
* 60 + sec
);
836 * 'httpSeparate()' - Separate a Universal Resource Identifier into its
839 * This function is deprecated; use the httpSeparateURI() function instead.
845 httpSeparate(const char *uri
, /* I - Universal Resource Identifier */
846 char *scheme
, /* O - Scheme [32] (http, https, etc.) */
847 char *username
, /* O - Username [1024] */
848 char *host
, /* O - Hostname [1024] */
849 int *port
, /* O - Port number to use */
850 char *resource
) /* O - Resource/filename [1024] */
852 httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, 32, username
,
853 HTTP_MAX_URI
, host
, HTTP_MAX_URI
, port
, resource
,
859 * 'httpSeparate2()' - Separate a Universal Resource Identifier into its
862 * This function is deprecated; use the httpSeparateURI() function instead.
864 * @since CUPS 1.1.21/Mac OS X 10.4@
869 httpSeparate2(const char *uri
, /* I - Universal Resource Identifier */
870 char *scheme
, /* O - Scheme (http, https, etc.) */
871 int schemelen
, /* I - Size of scheme buffer */
872 char *username
, /* O - Username */
873 int usernamelen
, /* I - Size of username buffer */
874 char *host
, /* O - Hostname */
875 int hostlen
, /* I - Size of hostname buffer */
876 int *port
, /* O - Port number to use */
877 char *resource
, /* O - Resource/filename */
878 int resourcelen
) /* I - Size of resource buffer */
880 httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, schemelen
, username
,
881 usernamelen
, host
, hostlen
, port
, resource
, resourcelen
);
886 * 'httpSeparateURI()' - Separate a Universal Resource Identifier into its
889 * @since CUPS 1.2/Mac OS X 10.5@
892 http_uri_status_t
/* O - Result of separation */
894 http_uri_coding_t decoding
, /* I - Decoding flags */
895 const char *uri
, /* I - Universal Resource Identifier */
896 char *scheme
, /* O - Scheme (http, https, etc.) */
897 int schemelen
, /* I - Size of scheme buffer */
898 char *username
, /* O - Username */
899 int usernamelen
, /* I - Size of username buffer */
900 char *host
, /* O - Hostname */
901 int hostlen
, /* I - Size of hostname buffer */
902 int *port
, /* O - Port number to use */
903 char *resource
, /* O - Resource/filename */
904 int resourcelen
) /* I - Size of resource buffer */
906 char *ptr
, /* Pointer into string... */
907 *end
; /* End of string */
908 const char *sep
; /* Separator character */
909 http_uri_status_t status
; /* Result of separation */
913 * Initialize everything to blank...
916 if (scheme
&& schemelen
> 0)
919 if (username
&& usernamelen
> 0)
922 if (host
&& hostlen
> 0)
928 if (resource
&& resourcelen
> 0)
932 * Range check input...
935 if (!uri
|| !port
|| !scheme
|| schemelen
<= 0 || !username
||
936 usernamelen
<= 0 || !host
|| hostlen
<= 0 || !resource
||
938 return (HTTP_URI_BAD_ARGUMENTS
);
941 return (HTTP_URI_BAD_URI
);
944 * Grab the scheme portion of the URI...
947 status
= HTTP_URI_OK
;
949 if (!strncmp(uri
, "//", 2))
952 * Workaround for HP IPP client bug...
955 strlcpy(scheme
, "ipp", schemelen
);
956 status
= HTTP_URI_MISSING_SCHEME
;
958 else if (*uri
== '/')
964 strlcpy(scheme
, "file", schemelen
);
965 status
= HTTP_URI_MISSING_SCHEME
;
970 * Standard URI with scheme...
973 for (ptr
= scheme
, end
= scheme
+ schemelen
- 1;
974 *uri
&& *uri
!= ':' && ptr
< end
;)
975 if (strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
976 "abcdefghijklmnopqrstuvwxyz"
977 "0123456789-+.", *uri
) != NULL
)
987 return (HTTP_URI_BAD_SCHEME
);
994 * Set the default port number...
997 if (!strcmp(scheme
, "http"))
999 else if (!strcmp(scheme
, "https"))
1001 else if (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps"))
1003 else if (!strcasecmp(scheme
, "lpd"))
1005 else if (!strcmp(scheme
, "socket")) /* Not yet registered with IANA... */
1007 else if (strcmp(scheme
, "file") && strcmp(scheme
, "mailto"))
1008 status
= HTTP_URI_UNKNOWN_SCHEME
;
1011 * Now see if we have a hostname...
1014 if (!strncmp(uri
, "//", 2))
1017 * Yes, extract it...
1023 * Grab the username, if any...
1026 if ((sep
= strpbrk(uri
, "@/")) != NULL
&& *sep
== '@')
1029 * Get a username:password combo...
1032 uri
= http_copy_decode(username
, uri
, usernamelen
, "@",
1033 decoding
& HTTP_URI_CODING_USERNAME
);
1038 return (HTTP_URI_BAD_USERNAME
);
1045 * Then the hostname/IP address...
1051 * Grab IPv6 address...
1055 if (!strncmp(uri
, "v1.", 3))
1056 uri
+= 3; /* Skip IPvN leader... */
1058 uri
= http_copy_decode(host
, uri
, hostlen
, "]",
1059 decoding
& HTTP_URI_CODING_HOSTNAME
);
1064 return (HTTP_URI_BAD_HOSTNAME
);
1074 return (HTTP_URI_BAD_HOSTNAME
);
1079 for (ptr
= host
; *ptr
; ptr
++)
1083 * Convert zone separator to % and stop here...
1089 else if (*ptr
!= ':' && *ptr
!= '.' && !isxdigit(*ptr
& 255))
1092 return (HTTP_URI_BAD_HOSTNAME
);
1098 * Validate the hostname or IPv4 address first...
1101 for (ptr
= (char *)uri
; *ptr
; ptr
++)
1102 if (strchr(":?/", *ptr
))
1104 else if (!strchr("abcdefghijklmnopqrstuvwxyz"
1105 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1109 "!$&'()*+,;=\\", *ptr
))
1112 return (HTTP_URI_BAD_HOSTNAME
);
1116 * Then copy the hostname or IPv4 address to the buffer...
1119 uri
= http_copy_decode(host
, uri
, hostlen
, ":?/",
1120 decoding
& HTTP_URI_CODING_HOSTNAME
);
1125 return (HTTP_URI_BAD_HOSTNAME
);
1130 * Validate hostname for file scheme - only empty and localhost are
1134 if (!strcmp(scheme
, "file") && strcmp(host
, "localhost") && host
[0])
1137 return (HTTP_URI_BAD_HOSTNAME
);
1141 * See if we have a port number...
1147 * Yes, collect the port number...
1150 if (!isdigit(uri
[1] & 255))
1153 return (HTTP_URI_BAD_PORT
);
1156 *port
= strtol(uri
+ 1, (char **)&uri
, 10);
1158 if (*uri
!= '/' && *uri
)
1161 return (HTTP_URI_BAD_PORT
);
1167 * The remaining portion is the resource string...
1170 if (*uri
== '?' || !*uri
)
1173 * Hostname but no path...
1176 status
= HTTP_URI_MISSING_RESOURCE
;
1180 * Copy any query string...
1184 uri
= http_copy_decode(resource
+ 1, uri
, resourcelen
- 1, NULL
,
1185 decoding
& HTTP_URI_CODING_QUERY
);
1191 uri
= http_copy_decode(resource
, uri
, resourcelen
, "?",
1192 decoding
& HTTP_URI_CODING_RESOURCE
);
1194 if (uri
&& *uri
== '?')
1197 * Concatenate any query string...
1200 char *resptr
= resource
+ strlen(resource
);
1202 uri
= http_copy_decode(resptr
, uri
, resourcelen
- (int)(resptr
- resource
),
1203 NULL
, decoding
& HTTP_URI_CODING_QUERY
);
1210 return (HTTP_URI_BAD_RESOURCE
);
1214 * Return the URI separation status...
1222 * 'httpStatus()' - Return a short string describing a HTTP status code.
1224 * The returned string is localized to the current POSIX locale and is based
1225 * on the status strings defined in RFC 2616.
1228 const char * /* O - Localized status string */
1229 httpStatus(http_status_t status
) /* I - HTTP status code */
1231 const char *s
; /* Status string */
1232 _cups_globals_t
*cg
= _cupsGlobals(); /* Global data */
1235 if (!cg
->lang_default
)
1236 cg
->lang_default
= cupsLangDefault();
1240 case HTTP_CONTINUE
:
1243 case HTTP_SWITCHING_PROTOCOLS
:
1244 s
= _("Switching Protocols");
1252 case HTTP_ACCEPTED
:
1255 case HTTP_NO_CONTENT
:
1256 s
= _("No Content");
1258 case HTTP_MOVED_PERMANENTLY
:
1259 s
= _("Moved Permanently");
1261 case HTTP_SEE_OTHER
:
1264 case HTTP_NOT_MODIFIED
:
1265 s
= _("Not Modified");
1267 case HTTP_BAD_REQUEST
:
1268 s
= _("Bad Request");
1270 case HTTP_UNAUTHORIZED
:
1271 case HTTP_AUTHORIZATION_CANCELED
:
1272 s
= _("Unauthorized");
1274 case HTTP_FORBIDDEN
:
1277 case HTTP_NOT_FOUND
:
1280 case HTTP_REQUEST_TOO_LARGE
:
1281 s
= _("Request Entity Too Large");
1283 case HTTP_URI_TOO_LONG
:
1284 s
= _("URI Too Long");
1286 case HTTP_UPGRADE_REQUIRED
:
1287 s
= _("Upgrade Required");
1289 case HTTP_NOT_IMPLEMENTED
:
1290 s
= _("Not Implemented");
1292 case HTTP_NOT_SUPPORTED
:
1293 s
= _("Not Supported");
1295 case HTTP_EXPECTATION_FAILED
:
1296 s
= _("Expectation Failed");
1298 case HTTP_SERVICE_UNAVAILABLE
:
1299 s
= _("Service Unavailable");
1301 case HTTP_SERVER_ERROR
:
1302 s
= _("Internal Server Error");
1304 case HTTP_PKI_ERROR
:
1305 s
= _("SSL/TLS Negotiation Error");
1307 case HTTP_WEBIF_DISABLED
:
1308 s
= _("Web Interface is Disabled");
1316 return (_cupsLangString(cg
->lang_default
, s
));
1320 #ifndef HAVE_HSTRERROR
1322 * '_cups_hstrerror()' - hstrerror() emulation function for Solaris and others...
1325 const char * /* O - Error string */
1326 _cups_hstrerror(int error
) /* I - Error number */
1328 static const char * const errors
[] = /* Error strings */
1333 "Unrecoverable lookup error.",
1334 "No data associated with name."
1338 if (error
< 0 || error
> 4)
1339 return ("Unknown hostname lookup error.");
1341 return (errors
[error
]);
1343 #endif /* !HAVE_HSTRERROR */
1347 * '_httpDecodeURI()' - Percent-decode a HTTP request URI.
1350 char * /* O - Decoded URI or NULL on error */
1351 _httpDecodeURI(char *dst
, /* I - Destination buffer */
1352 const char *src
, /* I - Source URI */
1353 size_t dstsize
) /* I - Size of destination buffer */
1355 if (http_copy_decode(dst
, src
, (int)dstsize
, NULL
, 1))
1363 * '_httpEncodeURI()' - Percent-encode a HTTP request URI.
1366 char * /* O - Encoded URI */
1367 _httpEncodeURI(char *dst
, /* I - Destination buffer */
1368 const char *src
, /* I - Source URI */
1369 size_t dstsize
) /* I - Size of destination buffer */
1371 http_copy_encode(dst
, src
, dst
+ dstsize
- 1, NULL
, NULL
, 1);
1377 * '_httpResolveURI()' - Resolve a DNS-SD URI.
1380 const char * /* O - Resolved URI */
1382 const char *uri
, /* I - DNS-SD URI */
1383 char *resolved_uri
, /* I - Buffer for resolved URI */
1384 size_t resolved_size
, /* I - Size of URI buffer */
1385 int logit
, /* I - Log progress to stderr? */
1386 int (*cb
)(void *context
), /* I - Continue callback function */
1387 void *context
) /* I - Context pointer for callback */
1389 char scheme
[32], /* URI components... */
1395 http_uri_status_t status
; /* URI decode status */
1399 DEBUG_printf(("4_httpResolveURI(uri=\"%s\", resolved_uri=%p, "
1400 "resolved_size=" CUPS_LLFMT
")", uri
, resolved_uri
,
1401 CUPS_LLCAST resolved_size
));
1404 * Get the device URI...
1408 if ((status
= httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
,
1409 sizeof(scheme
), userpass
, sizeof(userpass
),
1410 hostname
, sizeof(hostname
), &port
, resource
,
1411 sizeof(resource
))) < HTTP_URI_OK
)
1413 if (httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
,
1414 sizeof(scheme
), userpass
, sizeof(userpass
),
1415 hostname
, sizeof(hostname
), &port
, resource
,
1416 sizeof(resource
)) < HTTP_URI_OK
)
1420 _cupsLangPrintFilter(stderr
, "ERROR", _("Bad device-uri \"%s\"."), uri
);
1422 DEBUG_printf(("6_httpResolveURI: httpSeparateURI returned %d!", status
));
1423 DEBUG_puts("5_httpResolveURI: Returning NULL");
1428 * Resolve it as needed...
1431 if (strstr(hostname
, "._tcp"))
1435 # pragma comment(lib, "dnssd.lib")
1437 DNSServiceRef ref
, /* DNS-SD master service reference */
1438 domainref
, /* DNS-SD service reference for domain */
1439 localref
; /* DNS-SD service reference for .local */
1440 int domainsent
= 0, /* Send the domain resolve? */
1441 offline
= 0; /* offline-report state set? */
1442 char *regtype
, /* Pointer to type in hostname */
1443 *domain
; /* Pointer to domain in hostname */
1444 _http_uribuf_t uribuf
; /* URI buffer */
1446 struct pollfd polldata
; /* Polling data */
1447 #else /* select() */
1448 fd_set input_set
; /* Input set for select() */
1449 struct timeval stimeout
; /* Timeout value for select() */
1450 #endif /* HAVE_POLL */
1453 fprintf(stderr
, "DEBUG: Resolving \"%s\"...\n", hostname
);
1456 * Separate the hostname into service name, registration type, and domain...
1459 for (regtype
= strstr(hostname
, "._tcp") - 2;
1462 if (regtype
[0] == '.' && regtype
[1] == '_')
1465 * Found ._servicetype in front of ._tcp...
1472 if (regtype
<= hostname
)
1474 DEBUG_puts("5_httpResolveURI: Bad hostname, returning NULL");
1478 for (domain
= strchr(regtype
, '.');
1480 domain
= strchr(domain
+ 1, '.'))
1481 if (domain
[1] != '_')
1487 uribuf
.buffer
= resolved_uri
;
1488 uribuf
.bufsize
= resolved_size
;
1490 resolved_uri
[0] = '\0';
1492 DEBUG_printf(("6_httpResolveURI: Resolving hostname=\"%s\", regtype=\"%s\", "
1493 "domain=\"%s\"\n", hostname
, regtype
, domain
));
1496 fputs("STATE: +connecting-to-device\n", stderr
);
1497 fprintf(stderr
, "DEBUG: Resolving \"%s\", regtype=\"%s\", "
1498 "domain=\"local.\"...\n", hostname
, regtype
);
1503 if (DNSServiceCreateConnection(&ref
) == kDNSServiceErr_NoError
)
1506 if (DNSServiceResolve(&localref
, kDNSServiceFlagsShareConnection
, 0,
1507 hostname
, regtype
, "local.", resolve_callback
,
1508 &uribuf
) == kDNSServiceErr_NoError
)
1510 int fds
; /* Number of ready descriptors */
1511 time_t timeout
, /* Poll timeout */
1512 start_time
= time(NULL
);/* Start time */
1517 _cupsLangPrintFilter(stderr
, "INFO", _("Looking for printer."));
1519 if (cb
&& !(*cb
)(context
))
1521 DEBUG_puts("5_httpResolveURI: callback returned 0 (stop)");
1526 * For the first minute (or forever if we have a callback), wakeup
1527 * every 2 seconds to emit a "looking for printer" message...
1530 timeout
= (time(NULL
) < (start_time
+ 60) || cb
) ? 2000 : -1;
1533 polldata
.fd
= DNSServiceRefSockFD(ref
);
1534 polldata
.events
= POLLIN
;
1536 fds
= poll(&polldata
, 1, timeout
);
1538 #else /* select() */
1539 FD_ZERO(&input_set
);
1540 FD_SET(DNSServiceRefSockFD(ref
), &input_set
);
1542 stimeout
.tv_sec
= ((int)timeout
) / 1000;
1543 stimeout
.tv_usec
= ((int)(timeout
) * 1000) % 1000000;
1545 fds
= select(DNSServiceRefSockFD(ref
)+1, &input_set
, NULL
, NULL
,
1546 timeout
< 0.0 ? NULL
: &stimeout
);
1547 #endif /* HAVE_POLL */
1551 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1553 DEBUG_printf(("5_httpResolveURI: poll error: %s", strerror(errno
)));
1560 * Wait 2 seconds for a response to the local resolve; if nothing
1561 * comes in, do an additional domain resolution...
1564 if (domainsent
== 0 && strcasecmp(domain
, "local."))
1568 "DEBUG: Resolving \"%s\", regtype=\"%s\", "
1569 "domain=\"%s\"...\n", hostname
, regtype
, domain
);
1572 if (DNSServiceResolve(&domainref
, kDNSServiceFlagsShareConnection
, 0,
1573 hostname
, regtype
, domain
, resolve_callback
,
1574 &uribuf
) == kDNSServiceErr_NoError
)
1579 * If it hasn't resolved within 5 seconds set the offline-report
1580 * printer-state-reason...
1583 if (logit
&& offline
== 0 && time(NULL
) > (start_time
+ 5))
1585 fputs("STATE: +offline-report\n", stderr
);
1591 if (DNSServiceProcessResult(ref
) == kDNSServiceErr_NoError
)
1600 DNSServiceRefDeallocate(domainref
);
1602 DNSServiceRefDeallocate(localref
);
1605 DNSServiceRefDeallocate(ref
);
1611 fprintf(stderr
, "DEBUG: Resolved as \"%s\"...\n", uri
);
1613 fputs("DEBUG: Unable to resolve URI\n", stderr
);
1615 fputs("STATE: -connecting-to-device,offline-report\n", stderr
);
1620 * No DNS-SD support...
1624 #endif /* HAVE_DNSSD */
1627 _cupsLangPrintFilter(stderr
, "ERROR", _("Unable to find printer."));
1630 DEBUG_printf(("5_httpResolveURI: Returning \"%s\"", uri
));
1637 * 'http_copy_decode()' - Copy and decode a URI.
1640 static const char * /* O - New source pointer or NULL on error */
1641 http_copy_decode(char *dst
, /* O - Destination buffer */
1642 const char *src
, /* I - Source pointer */
1643 int dstsize
, /* I - Destination size */
1644 const char *term
, /* I - Terminating characters */
1645 int decode
) /* I - Decode %-encoded values */
1647 char *ptr
, /* Pointer into buffer */
1648 *end
; /* End of buffer */
1649 int quoted
; /* Quoted character */
1653 * Copy the src to the destination until we hit a terminating character
1654 * or the end of the string.
1657 for (ptr
= dst
, end
= dst
+ dstsize
- 1;
1658 *src
&& (!term
|| !strchr(term
, *src
));
1662 if (*src
== '%' && decode
)
1664 if (isxdigit(src
[1] & 255) && isxdigit(src
[2] & 255))
1667 * Grab a hex-encoded character...
1672 quoted
= (tolower(*src
) - 'a' + 10) << 4;
1674 quoted
= (*src
- '0') << 4;
1678 quoted
|= tolower(*src
) - 'a' + 10;
1680 quoted
|= *src
- '0';
1687 * Bad hex-encoded character...
1705 * 'http_copy_encode()' - Copy and encode a URI.
1708 static char * /* O - End of current URI */
1709 http_copy_encode(char *dst
, /* O - Destination buffer */
1710 const char *src
, /* I - Source pointer */
1711 char *dstend
, /* I - End of destination buffer */
1712 const char *reserved
, /* I - Extra reserved characters */
1713 const char *term
, /* I - Terminating characters */
1714 int encode
) /* I - %-encode reserved chars? */
1716 static const char hex
[] = "0123456789ABCDEF";
1719 while (*src
&& dst
< dstend
)
1721 if (term
&& *src
== *term
)
1724 if (encode
&& (*src
== '%' || *src
<= ' ' || *src
& 128 ||
1725 (reserved
&& strchr(reserved
, *src
))))
1728 * Hex encode reserved characters...
1731 if ((dst
+ 2) >= dstend
)
1735 *dst
++ = hex
[(*src
>> 4) & 15];
1736 *dst
++ = hex
[*src
& 15];
1755 * 'resolve_callback()' - Build a device URI for the given service name.
1758 static void DNSSD_API
1760 DNSServiceRef sdRef
, /* I - Service reference */
1761 DNSServiceFlags flags
, /* I - Results flags */
1762 uint32_t interfaceIndex
, /* I - Interface number */
1763 DNSServiceErrorType errorCode
, /* I - Error, if any */
1764 const char *fullName
, /* I - Full service name */
1765 const char *hostTarget
, /* I - Hostname */
1766 uint16_t port
, /* I - Port number */
1767 uint16_t txtLen
, /* I - Length of TXT record */
1768 const unsigned char *txtRecord
, /* I - TXT record data */
1769 void *context
) /* I - Pointer to URI buffer */
1771 const char *scheme
; /* URI scheme */
1772 char rp
[257]; /* Remote printer */
1773 const void *value
; /* Value from TXT record */
1774 uint8_t valueLen
; /* Length of value */
1775 _http_uribuf_t
*uribuf
; /* URI buffer */
1778 DEBUG_printf(("7resolve_callback(sdRef=%p, flags=%x, interfaceIndex=%u, "
1779 "errorCode=%d, fullName=\"%s\", hostTarget=\"%s\", port=%u, "
1780 "txtLen=%u, txtRecord=%p, context=%p)", sdRef
, flags
,
1781 interfaceIndex
, errorCode
, fullName
, hostTarget
, port
, txtLen
,
1782 txtRecord
, context
));
1785 * Figure out the scheme from the full name...
1788 if (strstr(fullName
, "._ipp") || strstr(fullName
, "._fax-ipp"))
1790 else if (strstr(fullName
, "._printer."))
1792 else if (strstr(fullName
, "._pdl-datastream."))
1795 scheme
= "riousbprint";
1798 * Extract the "remote printer" key from the TXT record...
1801 if ((value
= TXTRecordGetValuePtr(txtLen
, txtRecord
, "rp",
1802 &valueLen
)) != NULL
)
1805 * Convert to resource by concatenating with a leading "/"...
1809 memcpy(rp
+ 1, value
, valueLen
);
1810 rp
[valueLen
+ 1] = '\0';
1816 * Assemble the final device URI...
1819 uribuf
= (_http_uribuf_t
*)context
;
1821 httpAssembleURI(HTTP_URI_CODING_ALL
, uribuf
->buffer
, uribuf
->bufsize
, scheme
,
1822 NULL
, hostTarget
, ntohs(port
), rp
);
1824 DEBUG_printf(("8resolve_callback: Resolved URI is \"%s\"...",
1827 #endif /* HAVE_DNSSD */
1831 * End of "$Id: http-support.c 7952 2008-09-17 00:56:20Z mike $".