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 */
761 snprintf(s
, slen
, "%s, %02d %s %d %02d:%02d:%02d GMT",
762 http_days
[tdate
->tm_wday
], tdate
->tm_mday
,
763 http_months
[tdate
->tm_mon
], tdate
->tm_year
+ 1900,
764 tdate
->tm_hour
, tdate
->tm_min
, tdate
->tm_sec
);
773 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
776 time_t /* O - UNIX time */
777 httpGetDateTime(const char *s
) /* I - Date/time string */
779 int i
; /* Looping var */
780 char mon
[16]; /* Abbreviated month name */
781 int day
, year
; /* Day of month and year */
782 int hour
, min
, sec
; /* Time */
783 int days
; /* Number of days since 1970 */
784 static const int normal_days
[] = /* Days to a month, normal years */
785 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
786 static const int leap_days
[] = /* Days to a month, leap years */
787 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 };
790 DEBUG_printf(("2httpGetDateTime(s=\"%s\")", s
));
793 * Extract the date and time from the formatted string...
796 if (sscanf(s
, "%*s%d%15s%d%d:%d:%d", &day
, mon
, &year
, &hour
, &min
, &sec
) < 6)
799 DEBUG_printf(("4httpGetDateTime: day=%d, mon=\"%s\", year=%d, hour=%d, "
800 "min=%d, sec=%d", day
, mon
, year
, hour
, min
, sec
));
803 * Convert the month name to a number from 0 to 11.
806 for (i
= 0; i
< 12; i
++)
807 if (!_cups_strcasecmp(mon
, http_months
[i
]))
813 DEBUG_printf(("4httpGetDateTime: i=%d", i
));
816 * Now convert the date and time to a UNIX time value in seconds since
817 * 1970. We can't use mktime() since the timezone may not be UTC but
818 * the date/time string *is* UTC.
821 if ((year
& 3) == 0 && ((year
% 100) != 0 || (year
% 400) == 0))
822 days
= leap_days
[i
] + day
- 1;
824 days
= normal_days
[i
] + day
- 1;
826 DEBUG_printf(("4httpGetDateTime: days=%d", days
));
828 days
+= (year
- 1970) * 365 + /* 365 days per year (normally) */
829 ((year
- 1) / 4 - 492) - /* + leap days */
830 ((year
- 1) / 100 - 19) + /* - 100 year days */
831 ((year
- 1) / 400 - 4); /* + 400 year days */
833 DEBUG_printf(("4httpGetDateTime: days=%d\n", days
));
835 return (days
* 86400 + hour
* 3600 + min
* 60 + sec
);
840 * 'httpSeparate()' - Separate a Universal Resource Identifier into its
843 * This function is deprecated; use the httpSeparateURI() function instead.
849 httpSeparate(const char *uri
, /* I - Universal Resource Identifier */
850 char *scheme
, /* O - Scheme [32] (http, https, etc.) */
851 char *username
, /* O - Username [1024] */
852 char *host
, /* O - Hostname [1024] */
853 int *port
, /* O - Port number to use */
854 char *resource
) /* O - Resource/filename [1024] */
856 httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, 32, username
,
857 HTTP_MAX_URI
, host
, HTTP_MAX_URI
, port
, resource
,
863 * 'httpSeparate2()' - Separate a Universal Resource Identifier into its
866 * This function is deprecated; use the httpSeparateURI() function instead.
868 * @since CUPS 1.1.21/Mac OS X 10.4@
873 httpSeparate2(const char *uri
, /* I - Universal Resource Identifier */
874 char *scheme
, /* O - Scheme (http, https, etc.) */
875 int schemelen
, /* I - Size of scheme buffer */
876 char *username
, /* O - Username */
877 int usernamelen
, /* I - Size of username buffer */
878 char *host
, /* O - Hostname */
879 int hostlen
, /* I - Size of hostname buffer */
880 int *port
, /* O - Port number to use */
881 char *resource
, /* O - Resource/filename */
882 int resourcelen
) /* I - Size of resource buffer */
884 httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, schemelen
, username
,
885 usernamelen
, host
, hostlen
, port
, resource
, resourcelen
);
890 * 'httpSeparateURI()' - Separate a Universal Resource Identifier into its
893 * @since CUPS 1.2/Mac OS X 10.5@
896 http_uri_status_t
/* O - Result of separation */
898 http_uri_coding_t decoding
, /* I - Decoding flags */
899 const char *uri
, /* I - Universal Resource Identifier */
900 char *scheme
, /* O - Scheme (http, https, etc.) */
901 int schemelen
, /* I - Size of scheme buffer */
902 char *username
, /* O - Username */
903 int usernamelen
, /* I - Size of username buffer */
904 char *host
, /* O - Hostname */
905 int hostlen
, /* I - Size of hostname buffer */
906 int *port
, /* O - Port number to use */
907 char *resource
, /* O - Resource/filename */
908 int resourcelen
) /* I - Size of resource buffer */
910 char *ptr
, /* Pointer into string... */
911 *end
; /* End of string */
912 const char *sep
; /* Separator character */
913 http_uri_status_t status
; /* Result of separation */
917 * Initialize everything to blank...
920 if (scheme
&& schemelen
> 0)
923 if (username
&& usernamelen
> 0)
926 if (host
&& hostlen
> 0)
932 if (resource
&& resourcelen
> 0)
936 * Range check input...
939 if (!uri
|| !port
|| !scheme
|| schemelen
<= 0 || !username
||
940 usernamelen
<= 0 || !host
|| hostlen
<= 0 || !resource
||
942 return (HTTP_URI_BAD_ARGUMENTS
);
945 return (HTTP_URI_BAD_URI
);
948 * Grab the scheme portion of the URI...
951 status
= HTTP_URI_OK
;
953 if (!strncmp(uri
, "//", 2))
956 * Workaround for HP IPP client bug...
959 strlcpy(scheme
, "ipp", schemelen
);
960 status
= HTTP_URI_MISSING_SCHEME
;
962 else if (*uri
== '/')
968 strlcpy(scheme
, "file", schemelen
);
969 status
= HTTP_URI_MISSING_SCHEME
;
974 * Standard URI with scheme...
977 for (ptr
= scheme
, end
= scheme
+ schemelen
- 1;
978 *uri
&& *uri
!= ':' && ptr
< end
;)
979 if (strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
980 "abcdefghijklmnopqrstuvwxyz"
981 "0123456789-+.", *uri
) != NULL
)
991 return (HTTP_URI_BAD_SCHEME
);
998 * Set the default port number...
1001 if (!strcmp(scheme
, "http"))
1003 else if (!strcmp(scheme
, "https"))
1005 else if (!strcmp(scheme
, "ipp") || !strcmp(scheme
, "ipps"))
1007 else if (!_cups_strcasecmp(scheme
, "lpd"))
1009 else if (!strcmp(scheme
, "socket")) /* Not yet registered with IANA... */
1011 else if (strcmp(scheme
, "file") && strcmp(scheme
, "mailto"))
1012 status
= HTTP_URI_UNKNOWN_SCHEME
;
1015 * Now see if we have a hostname...
1018 if (!strncmp(uri
, "//", 2))
1021 * Yes, extract it...
1027 * Grab the username, if any...
1030 if ((sep
= strpbrk(uri
, "@/")) != NULL
&& *sep
== '@')
1033 * Get a username:password combo...
1036 uri
= http_copy_decode(username
, uri
, usernamelen
, "@",
1037 decoding
& HTTP_URI_CODING_USERNAME
);
1042 return (HTTP_URI_BAD_USERNAME
);
1049 * Then the hostname/IP address...
1055 * Grab IPv6 address...
1059 if (!strncmp(uri
, "v1.", 3))
1060 uri
+= 3; /* Skip IPvN leader... */
1062 uri
= http_copy_decode(host
, uri
, hostlen
, "]",
1063 decoding
& HTTP_URI_CODING_HOSTNAME
);
1068 return (HTTP_URI_BAD_HOSTNAME
);
1078 return (HTTP_URI_BAD_HOSTNAME
);
1083 for (ptr
= host
; *ptr
; ptr
++)
1087 * Convert zone separator to % and stop here...
1093 else if (*ptr
!= ':' && *ptr
!= '.' && !isxdigit(*ptr
& 255))
1096 return (HTTP_URI_BAD_HOSTNAME
);
1102 * Validate the hostname or IPv4 address first...
1105 for (ptr
= (char *)uri
; *ptr
; ptr
++)
1106 if (strchr(":?/", *ptr
))
1108 else if (!strchr("abcdefghijklmnopqrstuvwxyz"
1109 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1113 "!$&'()*+,;=\\", *ptr
))
1116 return (HTTP_URI_BAD_HOSTNAME
);
1120 * Then copy the hostname or IPv4 address to the buffer...
1123 uri
= http_copy_decode(host
, uri
, hostlen
, ":?/",
1124 decoding
& HTTP_URI_CODING_HOSTNAME
);
1129 return (HTTP_URI_BAD_HOSTNAME
);
1134 * Validate hostname for file scheme - only empty and localhost are
1138 if (!strcmp(scheme
, "file") && strcmp(host
, "localhost") && host
[0])
1141 return (HTTP_URI_BAD_HOSTNAME
);
1145 * See if we have a port number...
1151 * Yes, collect the port number...
1154 if (!isdigit(uri
[1] & 255))
1157 return (HTTP_URI_BAD_PORT
);
1160 *port
= strtol(uri
+ 1, (char **)&uri
, 10);
1162 if (*uri
!= '/' && *uri
)
1165 return (HTTP_URI_BAD_PORT
);
1171 * The remaining portion is the resource string...
1174 if (*uri
== '?' || !*uri
)
1177 * Hostname but no path...
1180 status
= HTTP_URI_MISSING_RESOURCE
;
1184 * Copy any query string...
1188 uri
= http_copy_decode(resource
+ 1, uri
, resourcelen
- 1, NULL
,
1189 decoding
& HTTP_URI_CODING_QUERY
);
1195 uri
= http_copy_decode(resource
, uri
, resourcelen
, "?",
1196 decoding
& HTTP_URI_CODING_RESOURCE
);
1198 if (uri
&& *uri
== '?')
1201 * Concatenate any query string...
1204 char *resptr
= resource
+ strlen(resource
);
1206 uri
= http_copy_decode(resptr
, uri
, resourcelen
- (int)(resptr
- resource
),
1207 NULL
, decoding
& HTTP_URI_CODING_QUERY
);
1214 return (HTTP_URI_BAD_RESOURCE
);
1218 * Return the URI separation status...
1226 * 'httpStatus()' - Return a short string describing a HTTP status code.
1228 * The returned string is localized to the current POSIX locale and is based
1229 * on the status strings defined in RFC 2616.
1232 const char * /* O - Localized status string */
1233 httpStatus(http_status_t status
) /* I - HTTP status code */
1235 const char *s
; /* Status string */
1236 _cups_globals_t
*cg
= _cupsGlobals(); /* Global data */
1239 if (!cg
->lang_default
)
1240 cg
->lang_default
= cupsLangDefault();
1244 case HTTP_CONTINUE
:
1247 case HTTP_SWITCHING_PROTOCOLS
:
1248 s
= _("Switching Protocols");
1256 case HTTP_ACCEPTED
:
1259 case HTTP_NO_CONTENT
:
1260 s
= _("No Content");
1262 case HTTP_MOVED_PERMANENTLY
:
1263 s
= _("Moved Permanently");
1265 case HTTP_SEE_OTHER
:
1268 case HTTP_NOT_MODIFIED
:
1269 s
= _("Not Modified");
1271 case HTTP_BAD_REQUEST
:
1272 s
= _("Bad Request");
1274 case HTTP_UNAUTHORIZED
:
1275 case HTTP_AUTHORIZATION_CANCELED
:
1276 s
= _("Unauthorized");
1278 case HTTP_FORBIDDEN
:
1281 case HTTP_NOT_FOUND
:
1284 case HTTP_REQUEST_TOO_LARGE
:
1285 s
= _("Request Entity Too Large");
1287 case HTTP_URI_TOO_LONG
:
1288 s
= _("URI Too Long");
1290 case HTTP_UPGRADE_REQUIRED
:
1291 s
= _("Upgrade Required");
1293 case HTTP_NOT_IMPLEMENTED
:
1294 s
= _("Not Implemented");
1296 case HTTP_NOT_SUPPORTED
:
1297 s
= _("Not Supported");
1299 case HTTP_EXPECTATION_FAILED
:
1300 s
= _("Expectation Failed");
1302 case HTTP_SERVICE_UNAVAILABLE
:
1303 s
= _("Service Unavailable");
1305 case HTTP_SERVER_ERROR
:
1306 s
= _("Internal Server Error");
1308 case HTTP_PKI_ERROR
:
1309 s
= _("SSL/TLS Negotiation Error");
1311 case HTTP_WEBIF_DISABLED
:
1312 s
= _("Web Interface is Disabled");
1320 return (_cupsLangString(cg
->lang_default
, s
));
1324 #ifndef HAVE_HSTRERROR
1326 * '_cups_hstrerror()' - hstrerror() emulation function for Solaris and others.
1329 const char * /* O - Error string */
1330 _cups_hstrerror(int error
) /* I - Error number */
1332 static const char * const errors
[] = /* Error strings */
1337 "Unrecoverable lookup error.",
1338 "No data associated with name."
1342 if (error
< 0 || error
> 4)
1343 return ("Unknown hostname lookup error.");
1345 return (errors
[error
]);
1347 #endif /* !HAVE_HSTRERROR */
1351 * '_httpDecodeURI()' - Percent-decode a HTTP request URI.
1354 char * /* O - Decoded URI or NULL on error */
1355 _httpDecodeURI(char *dst
, /* I - Destination buffer */
1356 const char *src
, /* I - Source URI */
1357 size_t dstsize
) /* I - Size of destination buffer */
1359 if (http_copy_decode(dst
, src
, (int)dstsize
, NULL
, 1))
1367 * '_httpEncodeURI()' - Percent-encode a HTTP request URI.
1370 char * /* O - Encoded URI */
1371 _httpEncodeURI(char *dst
, /* I - Destination buffer */
1372 const char *src
, /* I - Source URI */
1373 size_t dstsize
) /* I - Size of destination buffer */
1375 http_copy_encode(dst
, src
, dst
+ dstsize
- 1, NULL
, NULL
, 1);
1381 * '_httpResolveURI()' - Resolve a DNS-SD URI.
1384 const char * /* O - Resolved URI */
1386 const char *uri
, /* I - DNS-SD URI */
1387 char *resolved_uri
, /* I - Buffer for resolved URI */
1388 size_t resolved_size
, /* I - Size of URI buffer */
1389 int options
, /* I - Resolve options */
1390 int (*cb
)(void *context
), /* I - Continue callback function */
1391 void *context
) /* I - Context pointer for callback */
1393 char scheme
[32], /* URI components... */
1399 http_uri_status_t status
; /* URI decode status */
1403 DEBUG_printf(("4_httpResolveURI(uri=\"%s\", resolved_uri=%p, "
1404 "resolved_size=" CUPS_LLFMT
")", uri
, resolved_uri
,
1405 CUPS_LLCAST resolved_size
));
1408 * Get the device URI...
1412 if ((status
= httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
,
1413 sizeof(scheme
), userpass
, sizeof(userpass
),
1414 hostname
, sizeof(hostname
), &port
, resource
,
1415 sizeof(resource
))) < HTTP_URI_OK
)
1417 if (httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
,
1418 sizeof(scheme
), userpass
, sizeof(userpass
),
1419 hostname
, sizeof(hostname
), &port
, resource
,
1420 sizeof(resource
)) < HTTP_URI_OK
)
1423 if (options
& _HTTP_RESOLVE_STDERR
)
1424 _cupsLangPrintFilter(stderr
, "ERROR", _("Bad device-uri \"%s\"."), uri
);
1426 DEBUG_printf(("6_httpResolveURI: httpSeparateURI returned %d!", status
));
1427 DEBUG_puts("5_httpResolveURI: Returning NULL");
1432 * Resolve it as needed...
1435 if (strstr(hostname
, "._tcp"))
1439 # pragma comment(lib, "dnssd.lib")
1441 DNSServiceRef ref
, /* DNS-SD master service reference */
1442 domainref
, /* DNS-SD service reference for domain */
1443 localref
; /* DNS-SD service reference for .local */
1444 int domainsent
= 0, /* Send the domain resolve? */
1445 offline
= 0; /* offline-report state set? */
1446 char *regtype
, /* Pointer to type in hostname */
1447 *domain
; /* Pointer to domain in hostname */
1448 _http_uribuf_t uribuf
; /* URI buffer */
1450 struct pollfd polldata
; /* Polling data */
1451 #else /* select() */
1452 fd_set input_set
; /* Input set for select() */
1453 struct timeval stimeout
; /* Timeout value for select() */
1454 #endif /* HAVE_POLL */
1456 if (options
& _HTTP_RESOLVE_STDERR
)
1457 fprintf(stderr
, "DEBUG: Resolving \"%s\"...\n", hostname
);
1460 * Separate the hostname into service name, registration type, and domain...
1463 for (regtype
= strstr(hostname
, "._tcp") - 2;
1466 if (regtype
[0] == '.' && regtype
[1] == '_')
1469 * Found ._servicetype in front of ._tcp...
1476 if (regtype
<= hostname
)
1478 DEBUG_puts("5_httpResolveURI: Bad hostname, returning NULL");
1482 for (domain
= strchr(regtype
, '.');
1484 domain
= strchr(domain
+ 1, '.'))
1485 if (domain
[1] != '_')
1491 uribuf
.buffer
= resolved_uri
;
1492 uribuf
.bufsize
= resolved_size
;
1493 uribuf
.options
= options
;
1494 resolved_uri
[0] = '\0';
1496 DEBUG_printf(("6_httpResolveURI: Resolving hostname=\"%s\", regtype=\"%s\", "
1497 "domain=\"%s\"\n", hostname
, regtype
, domain
));
1498 if (options
& _HTTP_RESOLVE_STDERR
)
1500 fputs("STATE: +connecting-to-device\n", stderr
);
1501 fprintf(stderr
, "DEBUG: Resolving \"%s\", regtype=\"%s\", "
1502 "domain=\"local.\"...\n", hostname
, regtype
);
1507 if (DNSServiceCreateConnection(&ref
) == kDNSServiceErr_NoError
)
1510 if (DNSServiceResolve(&localref
,
1511 kDNSServiceFlagsShareConnection
, 0, hostname
, regtype
,
1512 "local.", http_resolve_cb
,
1513 &uribuf
) == kDNSServiceErr_NoError
)
1515 int fds
; /* Number of ready descriptors */
1516 time_t timeout
, /* Poll timeout */
1517 start_time
= time(NULL
),/* Start time */
1518 end_time
= start_time
+ 90;
1521 while (time(NULL
) < end_time
)
1523 if (options
& _HTTP_RESOLVE_STDERR
)
1524 _cupsLangPrintFilter(stderr
, "INFO", _("Looking for printer."));
1526 if (cb
&& !(*cb
)(context
))
1528 DEBUG_puts("5_httpResolveURI: callback returned 0 (stop)");
1533 * Wakeup every 2 seconds to emit a "looking for printer" message...
1536 if ((timeout
= end_time
- time(NULL
)) > 2)
1540 polldata
.fd
= DNSServiceRefSockFD(ref
);
1541 polldata
.events
= POLLIN
;
1543 fds
= poll(&polldata
, 1, 1000 * timeout
);
1545 #else /* select() */
1546 FD_ZERO(&input_set
);
1547 FD_SET(DNSServiceRefSockFD(ref
), &input_set
);
1550 stimeout
.tv_sec
= (long)timeout
;
1552 stimeout
.tv_sec
= timeout
;
1554 stimeout
.tv_usec
= 0;
1556 fds
= select(DNSServiceRefSockFD(ref
)+1, &input_set
, NULL
, NULL
,
1558 #endif /* HAVE_POLL */
1562 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1564 DEBUG_printf(("5_httpResolveURI: poll error: %s", strerror(errno
)));
1571 * Wait 2 seconds for a response to the local resolve; if nothing
1572 * comes in, do an additional domain resolution...
1575 if (domainsent
== 0 && domain
&& _cups_strcasecmp(domain
, "local."))
1577 if (options
& _HTTP_RESOLVE_STDERR
)
1579 "DEBUG: Resolving \"%s\", regtype=\"%s\", "
1580 "domain=\"%s\"...\n", hostname
, regtype
,
1581 domain
? domain
: "");
1584 if (DNSServiceResolve(&domainref
,
1585 kDNSServiceFlagsShareConnection
,
1586 0, hostname
, regtype
, domain
,
1588 &uribuf
) == kDNSServiceErr_NoError
)
1593 * If it hasn't resolved within 5 seconds set the offline-report
1594 * printer-state-reason...
1597 if ((options
& _HTTP_RESOLVE_STDERR
) && offline
== 0 &&
1598 time(NULL
) > (start_time
+ 5))
1600 fputs("STATE: +offline-report\n", stderr
);
1606 if (DNSServiceProcessResult(ref
) == kDNSServiceErr_NoError
)
1615 DNSServiceRefDeallocate(domainref
);
1617 DNSServiceRefDeallocate(localref
);
1620 DNSServiceRefDeallocate(ref
);
1623 if (options
& _HTTP_RESOLVE_STDERR
)
1627 fprintf(stderr
, "DEBUG: Resolved as \"%s\"...\n", uri
);
1628 fputs("STATE: -connecting-to-device,offline-report\n", stderr
);
1632 fputs("DEBUG: Unable to resolve URI\n", stderr
);
1633 fputs("STATE: -connecting-to-device\n", stderr
);
1639 * No DNS-SD support...
1643 #endif /* HAVE_DNSSD */
1645 if ((options
& _HTTP_RESOLVE_STDERR
) && !uri
)
1646 _cupsLangPrintFilter(stderr
, "ERROR", _("Unable to find printer."));
1651 * Nothing more to do...
1654 strlcpy(resolved_uri
, uri
, resolved_size
);
1658 DEBUG_printf(("5_httpResolveURI: Returning \"%s\"", uri
));
1665 * 'http_copy_decode()' - Copy and decode a URI.
1668 static const char * /* O - New source pointer or NULL on error */
1669 http_copy_decode(char *dst
, /* O - Destination buffer */
1670 const char *src
, /* I - Source pointer */
1671 int dstsize
, /* I - Destination size */
1672 const char *term
, /* I - Terminating characters */
1673 int decode
) /* I - Decode %-encoded values */
1675 char *ptr
, /* Pointer into buffer */
1676 *end
; /* End of buffer */
1677 int quoted
; /* Quoted character */
1681 * Copy the src to the destination until we hit a terminating character
1682 * or the end of the string.
1685 for (ptr
= dst
, end
= dst
+ dstsize
- 1;
1686 *src
&& (!term
|| !strchr(term
, *src
));
1690 if (*src
== '%' && decode
)
1692 if (isxdigit(src
[1] & 255) && isxdigit(src
[2] & 255))
1695 * Grab a hex-encoded character...
1700 quoted
= (tolower(*src
) - 'a' + 10) << 4;
1702 quoted
= (*src
- '0') << 4;
1706 quoted
|= tolower(*src
) - 'a' + 10;
1708 quoted
|= *src
- '0';
1715 * Bad hex-encoded character...
1733 * 'http_copy_encode()' - Copy and encode a URI.
1736 static char * /* O - End of current URI */
1737 http_copy_encode(char *dst
, /* O - Destination buffer */
1738 const char *src
, /* I - Source pointer */
1739 char *dstend
, /* I - End of destination buffer */
1740 const char *reserved
, /* I - Extra reserved characters */
1741 const char *term
, /* I - Terminating characters */
1742 int encode
) /* I - %-encode reserved chars? */
1744 static const char hex
[] = "0123456789ABCDEF";
1747 while (*src
&& dst
< dstend
)
1749 if (term
&& *src
== *term
)
1752 if (encode
&& (*src
== '%' || *src
<= ' ' || *src
& 128 ||
1753 (reserved
&& strchr(reserved
, *src
))))
1756 * Hex encode reserved characters...
1759 if ((dst
+ 2) >= dstend
)
1763 *dst
++ = hex
[(*src
>> 4) & 15];
1764 *dst
++ = hex
[*src
& 15];
1783 * 'http_resolve_cb()' - Build a device URI for the given service name.
1786 static void DNSSD_API
1788 DNSServiceRef sdRef
, /* I - Service reference */
1789 DNSServiceFlags flags
, /* I - Results flags */
1790 uint32_t interfaceIndex
, /* I - Interface number */
1791 DNSServiceErrorType errorCode
, /* I - Error, if any */
1792 const char *fullName
, /* I - Full service name */
1793 const char *hostTarget
, /* I - Hostname */
1794 uint16_t port
, /* I - Port number */
1795 uint16_t txtLen
, /* I - Length of TXT record */
1796 const unsigned char *txtRecord
, /* I - TXT record data */
1797 void *context
) /* I - Pointer to URI buffer */
1799 const char *scheme
, /* URI scheme */
1800 *hostptr
; /* Pointer into hostTarget */
1801 char rp
[257], /* Remote printer */
1802 fqdn
[256]; /* FQDN of the .local name */
1803 const void *value
; /* Value from TXT record */
1804 uint8_t valueLen
; /* Length of value */
1805 _http_uribuf_t
*uribuf
; /* URI buffer */
1808 DEBUG_printf(("7http_resolve_cb(sdRef=%p, flags=%x, interfaceIndex=%u, "
1809 "errorCode=%d, fullName=\"%s\", hostTarget=\"%s\", port=%u, "
1810 "txtLen=%u, txtRecord=%p, context=%p)", sdRef
, flags
,
1811 interfaceIndex
, errorCode
, fullName
, hostTarget
, port
, txtLen
,
1812 txtRecord
, context
));
1814 uribuf
= (_http_uribuf_t
*)context
;
1817 * Figure out the scheme from the full name...
1820 if (strstr(fullName
, "._ipps") || strstr(fullName
, "._ipp-tls"))
1822 else if (strstr(fullName
, "._ipp") || strstr(fullName
, "._fax-ipp"))
1824 else if (strstr(fullName
, "._http."))
1826 else if (strstr(fullName
, "._https."))
1828 else if (strstr(fullName
, "._printer."))
1830 else if (strstr(fullName
, "._pdl-datastream."))
1833 scheme
= "riousbprint";
1836 * Extract the "remote printer" key from the TXT record...
1839 if ((value
= TXTRecordGetValuePtr(txtLen
, txtRecord
, "rp",
1840 &valueLen
)) != NULL
)
1842 if (((char *)value
)[0] == '/')
1845 * "rp" value (incorrectly) has a leading slash already...
1848 memcpy(rp
, value
, valueLen
);
1849 rp
[valueLen
] = '\0';
1854 * Convert to resource by concatenating with a leading "/"...
1858 memcpy(rp
+ 1, value
, valueLen
);
1859 rp
[valueLen
+ 1] = '\0';
1865 * Default "rp" value is blank, mapping to a path of "/"...
1873 * Lookup the FQDN if needed...
1876 if ((uribuf
->options
& _HTTP_RESOLVE_FQDN
) &&
1877 (hostptr
= hostTarget
+ strlen(hostTarget
) - 7) > hostTarget
&&
1878 !_cups_strcasecmp(hostptr
, ".local."))
1881 * OK, we got a .local name but the caller needs a real domain. Start by
1882 * getting the IP address of the .local name and then do reverse-lookups...
1885 http_addrlist_t
*addrlist
, /* List of addresses */
1886 *addr
; /* Current address */
1888 DEBUG_printf(("8http_resolve_cb: Looking up \"%s\".", hostTarget
));
1890 snprintf(fqdn
, sizeof(fqdn
), "%d", ntohs(port
));
1891 if ((addrlist
= httpAddrGetList(hostTarget
, AF_UNSPEC
, fqdn
)) != NULL
)
1893 for (addr
= addrlist
; addr
; addr
= addr
->next
)
1895 int error
= getnameinfo(&(addr
->addr
.addr
),
1896 httpAddrLength(&(addr
->addr
)),
1897 fqdn
, sizeof(fqdn
), NULL
, 0, NI_NAMEREQD
);
1901 DEBUG_printf(("8http_resolve_cb: Found \"%s\".", fqdn
));
1903 if ((hostptr
= fqdn
+ strlen(fqdn
) - 6) <= fqdn
||
1904 _cups_strcasecmp(hostptr
, ".local"))
1912 DEBUG_printf(("8http_resolve_cb: \"%s\" did not resolve: %d",
1913 httpAddrString(&(addr
->addr
), fqdn
, sizeof(fqdn
)),
1921 * Assemble the final device URI...
1924 httpAssembleURI(HTTP_URI_CODING_ALL
, uribuf
->buffer
, uribuf
->bufsize
, scheme
,
1925 NULL
, hostTarget
, ntohs(port
), rp
);
1927 DEBUG_printf(("8http_resolve_cb: Resolved URI is \"%s\"...", uribuf
->buffer
));
1929 #endif /* HAVE_DNSSD */
1933 * End of "$Id: http-support.c 7952 2008-09-17 00:56:20Z mike $".