]> git.ipfire.org Git - thirdparty/cups.git/blob - cups/http-support.c
Merge changes from CUPS 1.4svn-r8469.
[thirdparty/cups.git] / cups / http-support.c
1 /*
2 * "$Id: http-support.c 7952 2008-09-17 00:56:20Z mike $"
3 *
4 * HTTP support routines for the Common UNIX Printing System (CUPS) scheduler.
5 *
6 * Copyright 2007-2009 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
8 *
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/".
14 *
15 * This file is subject to the Apple OS-Developed Software exception.
16 *
17 * Contents:
18 *
19 * httpAssembleURI() - Assemble a uniform resource identifier from its
20 * components.
21 * httpAssembleURIf() - Assemble a uniform resource identifier from its
22 * components with a formatted resource.
23 * httpDecode64() - Base64-decode a string.
24 * httpDecode64_2() - Base64-decode a string.
25 * httpEncode64() - Base64-encode a string.
26 * httpEncode64_2() - Base64-encode a string.
27 * httpGetDateString() - Get a formatted date/time string from a time value.
28 * httpGetDateString2() - Get a formatted date/time string from a time value.
29 * httpGetDateTime() - Get a time value from a formatted date/time string.
30 * httpSeparate() - Separate a Universal Resource Identifier into its
31 * components.
32 * httpSeparate2() - Separate a Universal Resource Identifier into its
33 * components.
34 * httpSeparateURI() - Separate a Universal Resource Identifier into its
35 * components.
36 * httpStatus() - Return a short string describing a HTTP status code.
37 * _cups_hstrerror() - hstrerror() emulation function for Solaris and
38 * others...
39 * _httpEncodeURI() - Percent-encode a HTTP request URI.
40 * _httpResolveURI() - Resolve a DNS-SD URI.
41 * http_copy_decode() - Copy and decode a URI.
42 * http_copy_encode() - Copy and encode a URI.
43 * resolve_callback() - Build a device URI for the given service name.
44 */
45
46 /*
47 * Include necessary headers...
48 */
49
50 #include "debug.h"
51 #include "globals.h"
52 #include <stdlib.h>
53 #ifdef HAVE_DNSSD
54 # include <dns_sd.h>
55 #endif /* HAVE_DNSSD */
56
57
58 /*
59 * Local types...
60 */
61
62 typedef struct _http_uribuf_s /* URI buffer */
63 {
64 char *buffer; /* Pointer to buffer */
65 size_t bufsize; /* Size of buffer */
66 } _http_uribuf_t;
67
68
69 /*
70 * Local globals...
71 */
72
73 static const char * const http_days[7] =
74 {
75 "Sun",
76 "Mon",
77 "Tue",
78 "Wed",
79 "Thu",
80 "Fri",
81 "Sat"
82 };
83 static const char * const http_months[12] =
84 {
85 "Jan",
86 "Feb",
87 "Mar",
88 "Apr",
89 "May",
90 "Jun",
91 "Jul",
92 "Aug",
93 "Sep",
94 "Oct",
95 "Nov",
96 "Dec"
97 };
98
99
100 /*
101 * Local functions...
102 */
103
104 static const char *http_copy_decode(char *dst, const char *src,
105 int dstsize, const char *term,
106 int decode);
107 static char *http_copy_encode(char *dst, const char *src,
108 char *dstend, const char *reserved,
109 const char *term, int encode);
110 #ifdef HAVE_DNSSD
111 static void resolve_callback(DNSServiceRef sdRef,
112 DNSServiceFlags flags,
113 uint32_t interfaceIndex,
114 DNSServiceErrorType errorCode,
115 const char *fullName,
116 const char *hostTarget,
117 uint16_t port, uint16_t txtLen,
118 const unsigned char *txtRecord,
119 void *context);
120 #endif /* HAVE_DNSSD */
121
122
123 /*
124 * 'httpAssembleURI()' - Assemble a uniform resource identifier from its
125 * components.
126 *
127 * This function escapes reserved characters in the URI depending on the
128 * value of the "encoding" argument. You should use this function in
129 * place of traditional string functions whenever you need to create a
130 * URI string.
131 *
132 * @since CUPS 1.2/Mac OS X 10.5@
133 */
134
135 http_uri_status_t /* O - URI status */
136 httpAssembleURI(
137 http_uri_coding_t encoding, /* I - Encoding flags */
138 char *uri, /* I - URI buffer */
139 int urilen, /* I - Size of URI buffer */
140 const char *scheme, /* I - Scheme name */
141 const char *username, /* I - Username */
142 const char *host, /* I - Hostname or address */
143 int port, /* I - Port number */
144 const char *resource) /* I - Resource */
145 {
146 char *ptr, /* Pointer into URI buffer */
147 *end; /* End of URI buffer */
148
149
150 /*
151 * Range check input...
152 */
153
154 if (!uri || urilen < 1 || !scheme || port < 0)
155 {
156 if (uri)
157 *uri = '\0';
158
159 return (HTTP_URI_BAD_ARGUMENTS);
160 }
161
162 /*
163 * Assemble the URI starting with the scheme...
164 */
165
166 end = uri + urilen - 1;
167 ptr = http_copy_encode(uri, scheme, end, NULL, NULL, 0);
168
169 if (!ptr)
170 goto assemble_overflow;
171
172 if (!strcmp(scheme, "mailto"))
173 {
174 /*
175 * mailto: only has :, no //...
176 */
177
178 if (ptr < end)
179 *ptr++ = ':';
180 else
181 goto assemble_overflow;
182 }
183 else
184 {
185 /*
186 * Schemes other than mailto: all have //...
187 */
188
189 if ((ptr + 2) < end)
190 {
191 *ptr++ = ':';
192 *ptr++ = '/';
193 *ptr++ = '/';
194 }
195 else
196 goto assemble_overflow;
197 }
198
199 /*
200 * Next the username and hostname, if any...
201 */
202
203 if (host)
204 {
205 if (username && *username)
206 {
207 /*
208 * Add username@ first...
209 */
210
211 ptr = http_copy_encode(ptr, username, end, "/?@", NULL,
212 encoding & HTTP_URI_CODING_USERNAME);
213
214 if (!ptr)
215 goto assemble_overflow;
216
217 if (ptr < end)
218 *ptr++ = '@';
219 else
220 goto assemble_overflow;
221 }
222
223 /*
224 * Then add the hostname. Since IPv6 is a particular pain to deal
225 * with, we have several special cases to deal with. If we get
226 * an IPv6 address with brackets around it, assume it is already in
227 * URI format. Since DNS-SD service names can sometimes look like
228 * raw IPv6 addresses, we specifically look for "._tcp" in the name,
229 * too...
230 */
231
232 if (host[0] != '[' && strchr(host, ':') && !strstr(host, "._tcp"))
233 {
234 /*
235 * We have a raw IPv6 address...
236 */
237
238 if (strchr(host, '%'))
239 {
240 /*
241 * We have a link-local address, add "[v1." prefix...
242 */
243
244 if ((ptr + 4) < end)
245 {
246 *ptr++ = '[';
247 *ptr++ = 'v';
248 *ptr++ = '1';
249 *ptr++ = '.';
250 }
251 else
252 goto assemble_overflow;
253 }
254 else
255 {
256 /*
257 * We have a normal address, add "[" prefix...
258 */
259
260 if (ptr < end)
261 *ptr++ = '[';
262 else
263 goto assemble_overflow;
264 }
265
266 /*
267 * Copy the rest of the IPv6 address, and terminate with "]".
268 */
269
270 while (ptr < end && *host)
271 {
272 if (*host == '%')
273 {
274 *ptr++ = '+'; /* Convert zone separator */
275 host ++;
276 }
277 else
278 *ptr++ = *host++;
279 }
280
281 if (*host)
282 goto assemble_overflow;
283
284 if (ptr < end)
285 *ptr++ = ']';
286 else
287 goto assemble_overflow;
288 }
289 else
290 {
291 /*
292 * Otherwise, just copy the host string...
293 */
294
295 ptr = http_copy_encode(ptr, host, end, ":/?#[]@\\", NULL,
296 encoding & HTTP_URI_CODING_HOSTNAME);
297
298 if (!ptr)
299 goto assemble_overflow;
300 }
301
302 /*
303 * Finish things off with the port number...
304 */
305
306 if (port > 0)
307 {
308 snprintf(ptr, end - ptr + 1, ":%d", port);
309 ptr += strlen(ptr);
310
311 if (ptr >= end)
312 goto assemble_overflow;
313 }
314 }
315
316 /*
317 * Last but not least, add the resource string...
318 */
319
320 if (resource)
321 {
322 char *query; /* Pointer to query string */
323
324
325 /*
326 * Copy the resource string up to the query string if present...
327 */
328
329 query = strchr(resource, '?');
330 ptr = http_copy_encode(ptr, resource, end, NULL, "?",
331 encoding & HTTP_URI_CODING_RESOURCE);
332 if (!ptr)
333 goto assemble_overflow;
334
335 if (query)
336 {
337 /*
338 * Copy query string without encoding...
339 */
340
341 ptr = http_copy_encode(ptr, query, end, NULL, NULL,
342 encoding & HTTP_URI_CODING_QUERY);
343 if (!ptr)
344 goto assemble_overflow;
345 }
346 }
347 else if (ptr < end)
348 *ptr++ = '/';
349 else
350 goto assemble_overflow;
351
352 /*
353 * Nul-terminate the URI buffer and return with no errors...
354 */
355
356 *ptr = '\0';
357
358 return (HTTP_URI_OK);
359
360 /*
361 * Clear the URI string and return an overflow error; I don't usually
362 * like goto's, but in this case it makes sense...
363 */
364
365 assemble_overflow:
366
367 *uri = '\0';
368 return (HTTP_URI_OVERFLOW);
369 }
370
371
372 /*
373 * 'httpAssembleURIf()' - Assemble a uniform resource identifier from its
374 * components with a formatted resource.
375 *
376 * This function creates a formatted version of the resource string
377 * argument "resourcef" and escapes reserved characters in the URI
378 * depending on the value of the "encoding" argument. You should use
379 * this function in place of traditional string functions whenever
380 * you need to create a URI string.
381 *
382 * @since CUPS 1.2/Mac OS X 10.5@
383 */
384
385 http_uri_status_t /* O - URI status */
386 httpAssembleURIf(
387 http_uri_coding_t encoding, /* I - Encoding flags */
388 char *uri, /* I - URI buffer */
389 int urilen, /* I - Size of URI buffer */
390 const char *scheme, /* I - Scheme name */
391 const char *username, /* I - Username */
392 const char *host, /* I - Hostname or address */
393 int port, /* I - Port number */
394 const char *resourcef, /* I - Printf-style resource */
395 ...) /* I - Additional arguments as needed */
396 {
397 va_list ap; /* Pointer to additional arguments */
398 char resource[1024]; /* Formatted resource string */
399 int bytes; /* Bytes in formatted string */
400
401
402 /*
403 * Range check input...
404 */
405
406 if (!uri || urilen < 1 || !scheme || port < 0 || !resourcef)
407 {
408 if (uri)
409 *uri = '\0';
410
411 return (HTTP_URI_BAD_ARGUMENTS);
412 }
413
414 /*
415 * Format the resource string and assemble the URI...
416 */
417
418 va_start(ap, resourcef);
419 bytes = vsnprintf(resource, sizeof(resource), resourcef, ap);
420 va_end(ap);
421
422 if (bytes >= sizeof(resource))
423 {
424 *uri = '\0';
425 return (HTTP_URI_OVERFLOW);
426 }
427 else
428 return (httpAssembleURI(encoding, uri, urilen, scheme, username, host,
429 port, resource));
430 }
431
432
433 /*
434 * 'httpDecode64()' - Base64-decode a string.
435 *
436 * This function is deprecated. Use the httpDecode64_2() function instead
437 * which provides buffer length arguments.
438 *
439 * @deprecated@
440 */
441
442 char * /* O - Decoded string */
443 httpDecode64(char *out, /* I - String to write to */
444 const char *in) /* I - String to read from */
445 {
446 int outlen; /* Output buffer length */
447
448
449 /*
450 * Use the old maximum buffer size for binary compatibility...
451 */
452
453 outlen = 512;
454
455 return (httpDecode64_2(out, &outlen, in));
456 }
457
458
459 /*
460 * 'httpDecode64_2()' - Base64-decode a string.
461 *
462 * @since CUPS 1.1.21/Mac OS X 10.4@
463 */
464
465 char * /* O - Decoded string */
466 httpDecode64_2(char *out, /* I - String to write to */
467 int *outlen, /* IO - Size of output string */
468 const char *in) /* I - String to read from */
469 {
470 int pos, /* Bit position */
471 base64; /* Value of this character */
472 char *outptr, /* Output pointer */
473 *outend; /* End of output buffer */
474
475
476 /*
477 * Range check input...
478 */
479
480 if (!out || !outlen || *outlen < 1 || !in)
481 return (NULL);
482
483 if (!*in)
484 {
485 *out = '\0';
486 *outlen = 0;
487
488 return (out);
489 }
490
491 /*
492 * Convert from base-64 to bytes...
493 */
494
495 for (outptr = out, outend = out + *outlen - 1, pos = 0; *in != '\0'; in ++)
496 {
497 /*
498 * Decode this character into a number from 0 to 63...
499 */
500
501 if (*in >= 'A' && *in <= 'Z')
502 base64 = *in - 'A';
503 else if (*in >= 'a' && *in <= 'z')
504 base64 = *in - 'a' + 26;
505 else if (*in >= '0' && *in <= '9')
506 base64 = *in - '0' + 52;
507 else if (*in == '+')
508 base64 = 62;
509 else if (*in == '/')
510 base64 = 63;
511 else if (*in == '=')
512 break;
513 else
514 continue;
515
516 /*
517 * Store the result in the appropriate chars...
518 */
519
520 switch (pos)
521 {
522 case 0 :
523 if (outptr < outend)
524 *outptr = base64 << 2;
525 pos ++;
526 break;
527 case 1 :
528 if (outptr < outend)
529 *outptr++ |= (base64 >> 4) & 3;
530 if (outptr < outend)
531 *outptr = (base64 << 4) & 255;
532 pos ++;
533 break;
534 case 2 :
535 if (outptr < outend)
536 *outptr++ |= (base64 >> 2) & 15;
537 if (outptr < outend)
538 *outptr = (base64 << 6) & 255;
539 pos ++;
540 break;
541 case 3 :
542 if (outptr < outend)
543 *outptr++ |= base64;
544 pos = 0;
545 break;
546 }
547 }
548
549 *outptr = '\0';
550
551 /*
552 * Return the decoded string and size...
553 */
554
555 *outlen = (int)(outptr - out);
556
557 return (out);
558 }
559
560
561 /*
562 * 'httpEncode64()' - Base64-encode a string.
563 *
564 * This function is deprecated. Use the httpEncode64_2() function instead
565 * which provides buffer length arguments.
566 *
567 * @deprecated@
568 */
569
570 char * /* O - Encoded string */
571 httpEncode64(char *out, /* I - String to write to */
572 const char *in) /* I - String to read from */
573 {
574 return (httpEncode64_2(out, 512, in, (int)strlen(in)));
575 }
576
577
578 /*
579 * 'httpEncode64_2()' - Base64-encode a string.
580 *
581 * @since CUPS 1.1.21/Mac OS X 10.4@
582 */
583
584 char * /* O - Encoded string */
585 httpEncode64_2(char *out, /* I - String to write to */
586 int outlen, /* I - Size of output string */
587 const char *in, /* I - String to read from */
588 int inlen) /* I - Size of input string */
589 {
590 char *outptr, /* Output pointer */
591 *outend; /* End of output buffer */
592 static const char base64[] = /* Base64 characters... */
593 {
594 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
595 "abcdefghijklmnopqrstuvwxyz"
596 "0123456789"
597 "+/"
598 };
599
600
601 /*
602 * Range check input...
603 */
604
605 if (!out || outlen < 1 || !in)
606 return (NULL);
607
608 /*
609 * Convert bytes to base-64...
610 */
611
612 for (outptr = out, outend = out + outlen - 1; inlen > 0; in ++, inlen --)
613 {
614 /*
615 * Encode the up to 3 characters as 4 Base64 numbers...
616 */
617
618 if (outptr < outend)
619 *outptr ++ = base64[(in[0] & 255) >> 2];
620
621 if (outptr < outend)
622 {
623 if (inlen > 1)
624 *outptr ++ = base64[(((in[0] & 255) << 4) | ((in[1] & 255) >> 4)) & 63];
625 else
626 *outptr ++ = base64[((in[0] & 255) << 4) & 63];
627 }
628
629 in ++;
630 inlen --;
631 if (inlen <= 0)
632 {
633 if (outptr < outend)
634 *outptr ++ = '=';
635 if (outptr < outend)
636 *outptr ++ = '=';
637 break;
638 }
639
640 if (outptr < outend)
641 {
642 if (inlen > 1)
643 *outptr ++ = base64[(((in[0] & 255) << 2) | ((in[1] & 255) >> 6)) & 63];
644 else
645 *outptr ++ = base64[((in[0] & 255) << 2) & 63];
646 }
647
648 in ++;
649 inlen --;
650 if (inlen <= 0)
651 {
652 if (outptr < outend)
653 *outptr ++ = '=';
654 break;
655 }
656
657 if (outptr < outend)
658 *outptr ++ = base64[in[0] & 63];
659 }
660
661 *outptr = '\0';
662
663 /*
664 * Return the encoded string...
665 */
666
667 return (out);
668 }
669
670
671 /*
672 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
673 *
674 * @deprecated@
675 */
676
677 const char * /* O - Date/time string */
678 httpGetDateString(time_t t) /* I - UNIX time */
679 {
680 _cups_globals_t *cg = _cupsGlobals(); /* Pointer to library globals */
681
682
683 return (httpGetDateString2(t, cg->http_date, sizeof(cg->http_date)));
684 }
685
686
687 /*
688 * 'httpGetDateString2()' - Get a formatted date/time string from a time value.
689 *
690 * @since CUPS 1.2/Mac OS X 10.5@
691 */
692
693 const char * /* O - Date/time string */
694 httpGetDateString2(time_t t, /* I - UNIX time */
695 char *s, /* I - String buffer */
696 int slen) /* I - Size of string buffer */
697 {
698 struct tm *tdate; /* UNIX date/time data */
699
700
701 tdate = gmtime(&t);
702 snprintf(s, slen, "%s, %02d %s %d %02d:%02d:%02d GMT",
703 http_days[tdate->tm_wday], tdate->tm_mday,
704 http_months[tdate->tm_mon], tdate->tm_year + 1900,
705 tdate->tm_hour, tdate->tm_min, tdate->tm_sec);
706
707 return (s);
708 }
709
710
711 /*
712 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
713 */
714
715 time_t /* O - UNIX time */
716 httpGetDateTime(const char *s) /* I - Date/time string */
717 {
718 int i; /* Looping var */
719 char mon[16]; /* Abbreviated month name */
720 int day, year; /* Day of month and year */
721 int hour, min, sec; /* Time */
722 int days; /* Number of days since 1970 */
723 static const int normal_days[] = /* Days to a month, normal years */
724 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
725 static const int leap_days[] = /* Days to a month, leap years */
726 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 };
727
728
729 DEBUG_printf(("httpGetDateTime(s=\"%s\")\n", s));
730
731 /*
732 * Extract the date and time from the formatted string...
733 */
734
735 if (sscanf(s, "%*s%d%15s%d%d:%d:%d", &day, mon, &year, &hour, &min, &sec) < 6)
736 return (0);
737
738 DEBUG_printf((" day=%d, mon=\"%s\", year=%d, hour=%d, min=%d, sec=%d\n",
739 day, mon, year, hour, min, sec));
740
741 /*
742 * Convert the month name to a number from 0 to 11.
743 */
744
745 for (i = 0; i < 12; i ++)
746 if (!strcasecmp(mon, http_months[i]))
747 break;
748
749 if (i >= 12)
750 return (0);
751
752 DEBUG_printf((" i=%d\n", i));
753
754 /*
755 * Now convert the date and time to a UNIX time value in seconds since
756 * 1970. We can't use mktime() since the timezone may not be UTC but
757 * the date/time string *is* UTC.
758 */
759
760 if ((year & 3) == 0 && ((year % 100) != 0 || (year % 400) == 0))
761 days = leap_days[i] + day - 1;
762 else
763 days = normal_days[i] + day - 1;
764
765 DEBUG_printf((" days=%d\n", days));
766
767 days += (year - 1970) * 365 + /* 365 days per year (normally) */
768 ((year - 1) / 4 - 492) - /* + leap days */
769 ((year - 1) / 100 - 19) + /* - 100 year days */
770 ((year - 1) / 400 - 4); /* + 400 year days */
771
772 DEBUG_printf((" days=%d\n", days));
773
774 return (days * 86400 + hour * 3600 + min * 60 + sec);
775 }
776
777
778 /*
779 * 'httpSeparate()' - Separate a Universal Resource Identifier into its
780 * components.
781 *
782 * This function is deprecated; use the httpSeparateURI() function instead.
783 *
784 * @deprecated@
785 */
786
787 void
788 httpSeparate(const char *uri, /* I - Universal Resource Identifier */
789 char *scheme, /* O - Scheme [32] (http, https, etc.) */
790 char *username, /* O - Username [1024] */
791 char *host, /* O - Hostname [1024] */
792 int *port, /* O - Port number to use */
793 char *resource) /* O - Resource/filename [1024] */
794 {
795 httpSeparateURI(HTTP_URI_CODING_ALL, uri, scheme, 32, username,
796 HTTP_MAX_URI, host, HTTP_MAX_URI, port, resource,
797 HTTP_MAX_URI);
798 }
799
800
801 /*
802 * 'httpSeparate2()' - Separate a Universal Resource Identifier into its
803 * components.
804 *
805 * This function is deprecated; use the httpSeparateURI() function instead.
806 *
807 * @since CUPS 1.1.21/Mac OS X 10.4@
808 * @deprecated@
809 */
810
811 void
812 httpSeparate2(const char *uri, /* I - Universal Resource Identifier */
813 char *scheme, /* O - Scheme (http, https, etc.) */
814 int schemelen, /* I - Size of scheme buffer */
815 char *username, /* O - Username */
816 int usernamelen, /* I - Size of username buffer */
817 char *host, /* O - Hostname */
818 int hostlen, /* I - Size of hostname buffer */
819 int *port, /* O - Port number to use */
820 char *resource, /* O - Resource/filename */
821 int resourcelen) /* I - Size of resource buffer */
822 {
823 httpSeparateURI(HTTP_URI_CODING_ALL, uri, scheme, schemelen, username,
824 usernamelen, host, hostlen, port, resource, resourcelen);
825 }
826
827
828 /*
829 * 'httpSeparateURI()' - Separate a Universal Resource Identifier into its
830 * components.
831 *
832 * @since CUPS 1.2/Mac OS X 10.5@
833 */
834
835 http_uri_status_t /* O - Result of separation */
836 httpSeparateURI(
837 http_uri_coding_t decoding, /* I - Decoding flags */
838 const char *uri, /* I - Universal Resource Identifier */
839 char *scheme, /* O - Scheme (http, https, etc.) */
840 int schemelen, /* I - Size of scheme buffer */
841 char *username, /* O - Username */
842 int usernamelen, /* I - Size of username buffer */
843 char *host, /* O - Hostname */
844 int hostlen, /* I - Size of hostname buffer */
845 int *port, /* O - Port number to use */
846 char *resource, /* O - Resource/filename */
847 int resourcelen) /* I - Size of resource buffer */
848 {
849 char *ptr, /* Pointer into string... */
850 *end; /* End of string */
851 const char *sep; /* Separator character */
852 http_uri_status_t status; /* Result of separation */
853
854
855 /*
856 * Initialize everything to blank...
857 */
858
859 if (scheme && schemelen > 0)
860 *scheme = '\0';
861
862 if (username && usernamelen > 0)
863 *username = '\0';
864
865 if (host && hostlen > 0)
866 *host = '\0';
867
868 if (port)
869 *port = 0;
870
871 if (resource && resourcelen > 0)
872 *resource = '\0';
873
874 /*
875 * Range check input...
876 */
877
878 if (!uri || !port || !scheme || schemelen <= 0 || !username ||
879 usernamelen <= 0 || !host || hostlen <= 0 || !resource ||
880 resourcelen <= 0)
881 return (HTTP_URI_BAD_ARGUMENTS);
882
883 if (!*uri)
884 return (HTTP_URI_BAD_URI);
885
886 /*
887 * Grab the scheme portion of the URI...
888 */
889
890 status = HTTP_URI_OK;
891
892 if (!strncmp(uri, "//", 2))
893 {
894 /*
895 * Workaround for HP IPP client bug...
896 */
897
898 strlcpy(scheme, "ipp", schemelen);
899 status = HTTP_URI_MISSING_SCHEME;
900 }
901 else if (*uri == '/')
902 {
903 /*
904 * Filename...
905 */
906
907 strlcpy(scheme, "file", schemelen);
908 status = HTTP_URI_MISSING_SCHEME;
909 }
910 else
911 {
912 /*
913 * Standard URI with scheme...
914 */
915
916 for (ptr = scheme, end = scheme + schemelen - 1;
917 *uri && *uri != ':' && ptr < end;)
918 if (isalnum(*uri & 255) || *uri == '-' || *uri == '+' || *uri == '.')
919 *ptr++ = *uri++;
920 else
921 break;
922
923 *ptr = '\0';
924
925 if (*uri != ':')
926 {
927 *scheme = '\0';
928 return (HTTP_URI_BAD_SCHEME);
929 }
930
931 uri ++;
932 }
933
934 /*
935 * Set the default port number...
936 */
937
938 if (!strcmp(scheme, "http"))
939 *port = 80;
940 else if (!strcmp(scheme, "https"))
941 *port = 443;
942 else if (!strcmp(scheme, "ipp"))
943 *port = 631;
944 else if (!strcasecmp(scheme, "lpd"))
945 *port = 515;
946 else if (!strcmp(scheme, "socket")) /* Not yet registered with IANA... */
947 *port = 9100;
948 else if (strcmp(scheme, "file") && strcmp(scheme, "mailto"))
949 status = HTTP_URI_UNKNOWN_SCHEME;
950
951 /*
952 * Now see if we have a hostname...
953 */
954
955 if (!strncmp(uri, "//", 2))
956 {
957 /*
958 * Yes, extract it...
959 */
960
961 uri += 2;
962
963 /*
964 * Grab the username, if any...
965 */
966
967 if ((sep = strpbrk(uri, "@/")) != NULL && *sep == '@')
968 {
969 /*
970 * Get a username:password combo...
971 */
972
973 uri = http_copy_decode(username, uri, usernamelen, "@",
974 decoding & HTTP_URI_CODING_USERNAME);
975
976 if (!uri)
977 {
978 *username = '\0';
979 return (HTTP_URI_BAD_USERNAME);
980 }
981
982 uri ++;
983 }
984
985 /*
986 * Then the hostname/IP address...
987 */
988
989 if (*uri == '[')
990 {
991 /*
992 * Grab IPv6 address...
993 */
994
995 uri ++;
996 if (!strncmp(uri, "v1.", 3))
997 uri += 3; /* Skip IPvN leader... */
998
999 uri = http_copy_decode(host, uri, hostlen, "]",
1000 decoding & HTTP_URI_CODING_HOSTNAME);
1001
1002 if (!uri)
1003 {
1004 *host = '\0';
1005 return (HTTP_URI_BAD_HOSTNAME);
1006 }
1007
1008 /*
1009 * Validate value...
1010 */
1011
1012 if (*uri != ']')
1013 {
1014 *host = '\0';
1015 return (HTTP_URI_BAD_HOSTNAME);
1016 }
1017
1018 uri ++;
1019
1020 for (ptr = host; *ptr; ptr ++)
1021 if (*ptr == '+')
1022 {
1023 /*
1024 * Convert zone separator to % and stop here...
1025 */
1026
1027 *ptr = '%';
1028 break;
1029 }
1030 else if (*ptr != ':' && *ptr != '.' && !isxdigit(*ptr & 255))
1031 {
1032 *host = '\0';
1033 return (HTTP_URI_BAD_HOSTNAME);
1034 }
1035 }
1036 else
1037 {
1038 /*
1039 * Validate the hostname or IPv4 address first...
1040 */
1041
1042 for (ptr = (char *)uri; *ptr; ptr ++)
1043 if (strchr(":?/", *ptr))
1044 break;
1045 else if (!strchr("abcdefghijklmnopqrstuvwxyz"
1046 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1047 "0123456789"
1048 "-._~"
1049 "%"
1050 "!$&'()*+,;=\\", *ptr))
1051 {
1052 *host = '\0';
1053 return (HTTP_URI_BAD_HOSTNAME);
1054 }
1055
1056 /*
1057 * Then copy the hostname or IPv4 address to the buffer...
1058 */
1059
1060 uri = http_copy_decode(host, uri, hostlen, ":?/",
1061 decoding & HTTP_URI_CODING_HOSTNAME);
1062
1063 if (!uri)
1064 {
1065 *host = '\0';
1066 return (HTTP_URI_BAD_HOSTNAME);
1067 }
1068 }
1069
1070 /*
1071 * Validate hostname for file scheme - only empty and localhost are
1072 * acceptable.
1073 */
1074
1075 if (!strcmp(scheme, "file") && strcmp(host, "localhost") && host[0])
1076 {
1077 *host = '\0';
1078 return (HTTP_URI_BAD_HOSTNAME);
1079 }
1080
1081 /*
1082 * See if we have a port number...
1083 */
1084
1085 if (*uri == ':')
1086 {
1087 /*
1088 * Yes, collect the port number...
1089 */
1090
1091 if (!isdigit(uri[1] & 255))
1092 {
1093 *port = 0;
1094 return (HTTP_URI_BAD_PORT);
1095 }
1096
1097 *port = strtol(uri + 1, (char **)&uri, 10);
1098
1099 if (*uri != '/' && *uri)
1100 {
1101 *port = 0;
1102 return (HTTP_URI_BAD_PORT);
1103 }
1104 }
1105 }
1106
1107 /*
1108 * The remaining portion is the resource string...
1109 */
1110
1111 if (*uri == '?' || !*uri)
1112 {
1113 /*
1114 * Hostname but no path...
1115 */
1116
1117 status = HTTP_URI_MISSING_RESOURCE;
1118 *resource = '/';
1119
1120 /*
1121 * Copy any query string...
1122 */
1123
1124 if (*uri == '?')
1125 uri = http_copy_decode(resource + 1, uri, resourcelen - 1, NULL,
1126 decoding & HTTP_URI_CODING_QUERY);
1127 else
1128 resource[1] = '\0';
1129 }
1130 else
1131 {
1132 uri = http_copy_decode(resource, uri, resourcelen, "?",
1133 decoding & HTTP_URI_CODING_RESOURCE);
1134
1135 if (uri && *uri == '?')
1136 {
1137 /*
1138 * Concatenate any query string...
1139 */
1140
1141 char *resptr = resource + strlen(resource);
1142
1143 uri = http_copy_decode(resptr, uri, resourcelen - (int)(resptr - resource),
1144 NULL, decoding & HTTP_URI_CODING_QUERY);
1145 }
1146 }
1147
1148 if (!uri)
1149 {
1150 *resource = '\0';
1151 return (HTTP_URI_BAD_RESOURCE);
1152 }
1153
1154 /*
1155 * Return the URI separation status...
1156 */
1157
1158 return (status);
1159 }
1160
1161
1162 /*
1163 * 'httpStatus()' - Return a short string describing a HTTP status code.
1164 *
1165 * The returned string is localized to the current POSIX locale and is based
1166 * on the status strings defined in RFC 2616.
1167 */
1168
1169 const char * /* O - Localized status string */
1170 httpStatus(http_status_t status) /* I - HTTP status code */
1171 {
1172 const char *s; /* Status string */
1173 _cups_globals_t *cg = _cupsGlobals(); /* Global data */
1174
1175
1176 if (!cg->lang_default)
1177 cg->lang_default = cupsLangDefault();
1178
1179 switch (status)
1180 {
1181 case HTTP_CONTINUE :
1182 s = _("Continue");
1183 break;
1184 case HTTP_SWITCHING_PROTOCOLS :
1185 s = _("Switching Protocols");
1186 break;
1187 case HTTP_OK :
1188 s = _("OK");
1189 break;
1190 case HTTP_CREATED :
1191 s = _("Created");
1192 break;
1193 case HTTP_ACCEPTED :
1194 s = _("Accepted");
1195 break;
1196 case HTTP_NO_CONTENT :
1197 s = _("No Content");
1198 break;
1199 case HTTP_MOVED_PERMANENTLY :
1200 s = _("Moved Permanently");
1201 break;
1202 case HTTP_SEE_OTHER :
1203 s = _("See Other");
1204 break;
1205 case HTTP_NOT_MODIFIED :
1206 s = _("Not Modified");
1207 break;
1208 case HTTP_BAD_REQUEST :
1209 s = _("Bad Request");
1210 break;
1211 case HTTP_UNAUTHORIZED :
1212 s = _("Unauthorized");
1213 break;
1214 case HTTP_FORBIDDEN :
1215 s = _("Forbidden");
1216 break;
1217 case HTTP_NOT_FOUND :
1218 s = _("Not Found");
1219 break;
1220 case HTTP_REQUEST_TOO_LARGE :
1221 s = _("Request Entity Too Large");
1222 break;
1223 case HTTP_URI_TOO_LONG :
1224 s = _("URI Too Long");
1225 break;
1226 case HTTP_UPGRADE_REQUIRED :
1227 s = _("Upgrade Required");
1228 break;
1229 case HTTP_NOT_IMPLEMENTED :
1230 s = _("Not Implemented");
1231 break;
1232 case HTTP_NOT_SUPPORTED :
1233 s = _("Not Supported");
1234 break;
1235 case HTTP_EXPECTATION_FAILED :
1236 s = _("Expectation Failed");
1237 break;
1238 case HTTP_SERVICE_UNAVAILABLE :
1239 s = _("Service Unavailable");
1240 break;
1241 case HTTP_SERVER_ERROR :
1242 s = _("Internal Server Error");
1243 break;
1244
1245 default :
1246 s = _("Unknown");
1247 break;
1248 }
1249
1250 return (_cupsLangString(cg->lang_default, s));
1251 }
1252
1253
1254 #ifndef HAVE_HSTRERROR
1255 /*
1256 * '_cups_hstrerror()' - hstrerror() emulation function for Solaris and others...
1257 */
1258
1259 const char * /* O - Error string */
1260 _cups_hstrerror(int error) /* I - Error number */
1261 {
1262 static const char * const errors[] = /* Error strings */
1263 {
1264 "OK",
1265 "Host not found.",
1266 "Try again.",
1267 "Unrecoverable lookup error.",
1268 "No data associated with name."
1269 };
1270
1271
1272 if (error < 0 || error > 4)
1273 return ("Unknown hostname lookup error.");
1274 else
1275 return (errors[error]);
1276 }
1277 #endif /* !HAVE_HSTRERROR */
1278
1279
1280 /*
1281 * '_httpEncodeURI()' - Percent-encode a HTTP request URI.
1282 */
1283
1284 char * /* O - Encoded URI */
1285 _httpEncodeURI(char *dst, /* I - Destination buffer */
1286 const char *src, /* I - Source URI */
1287 size_t dstsize) /* I - Size of destination buffer */
1288 {
1289 http_copy_encode(dst, src, dst + dstsize - 1, NULL, NULL, 1);
1290 return (dst);
1291 }
1292
1293
1294 /*
1295 * '_httpResolveURI()' - Resolve a DNS-SD URI.
1296 */
1297
1298 const char * /* O - Resolved URI */
1299 _httpResolveURI(
1300 const char *uri, /* I - DNS-SD URI */
1301 char *resolved_uri, /* I - Buffer for resolved URI */
1302 size_t resolved_size, /* I - Size of URI buffer */
1303 int logit) /* I - Log progress to stderr? */
1304 {
1305 char scheme[32], /* URI components... */
1306 userpass[256],
1307 hostname[1024],
1308 resource[1024];
1309 int port;
1310 #ifdef DEBUG
1311 http_uri_status_t status; /* URI decode status */
1312 #endif /* DEBUG */
1313
1314
1315 DEBUG_printf(("_httpResolveURI(uri=\"%s\", resolved_uri=%p, "
1316 "resolved_size=" CUPS_LLFMT ")\n", uri, resolved_uri,
1317 CUPS_LLCAST resolved_size));
1318
1319 /*
1320 * Get the device URI...
1321 */
1322
1323 #ifdef DEBUG
1324 if ((status = httpSeparateURI(HTTP_URI_CODING_ALL, uri, scheme,
1325 sizeof(scheme), userpass, sizeof(userpass),
1326 hostname, sizeof(hostname), &port, resource,
1327 sizeof(resource))) < HTTP_URI_OK)
1328 #else
1329 if (httpSeparateURI(HTTP_URI_CODING_ALL, uri, scheme,
1330 sizeof(scheme), userpass, sizeof(userpass),
1331 hostname, sizeof(hostname), &port, resource,
1332 sizeof(resource)) < HTTP_URI_OK)
1333 #endif /* DEBUG */
1334 {
1335 if (logit)
1336 _cupsLangPrintf(stderr, _("Bad device URI \"%s\"!\n"), uri);
1337
1338 DEBUG_printf(("_httpResolveURI: httpSeparateURI returned %d!\n", status));
1339 DEBUG_puts("_httpResolveURI: Returning NULL");
1340 return (NULL);
1341 }
1342
1343 /*
1344 * Resolve it as needed...
1345 */
1346
1347 if (strstr(hostname, "._tcp"))
1348 {
1349 #ifdef HAVE_DNSSD
1350 DNSServiceRef ref; /* DNS-SD service reference */
1351 char *regtype, /* Pointer to type in hostname */
1352 *domain; /* Pointer to domain in hostname */
1353 _http_uribuf_t uribuf; /* URI buffer */
1354
1355 /*
1356 * Separate the hostname into service name, registration type, and domain...
1357 */
1358
1359 for (regtype = strstr(hostname, "._tcp") - 2;
1360 regtype > hostname;
1361 regtype --)
1362 if (regtype[0] == '.' && regtype[1] == '_')
1363 {
1364 /*
1365 * Found ._servicetype in front of ._tcp...
1366 */
1367
1368 *regtype++ = '\0';
1369 break;
1370 }
1371
1372 if (regtype <= hostname)
1373 {
1374 DEBUG_puts("_httpResolveURI: Bad hostname, returning NULL");
1375 return (NULL);
1376 }
1377
1378 domain = regtype + strlen(regtype) - 1;
1379 if (domain > regtype && *domain == '.')
1380 *domain = '\0';
1381
1382 for (domain = strchr(regtype, '.');
1383 domain;
1384 domain = strchr(domain + 1, '.'))
1385 if (domain[1] != '_')
1386 break;
1387
1388 if (domain)
1389 *domain++ = '\0';
1390
1391 uribuf.buffer = resolved_uri;
1392 uribuf.bufsize = resolved_size;
1393
1394 resolved_uri[0] = '\0';
1395
1396 DEBUG_printf(("_httpResolveURI: Resolving hostname=\"%s\", regtype=\"%s\", "
1397 "domain=\"%s\"\n", hostname, regtype, domain));
1398 if (logit)
1399 {
1400 fputs("STATE: +connecting-to-device\n", stderr);
1401 fprintf(stderr, "DEBUG: Resolving %s, regtype=%s, domain=%s...\n",
1402 hostname, regtype, domain);
1403 _cupsLangPuts(stderr, _("INFO: Looking for printer...\n"));
1404 }
1405
1406 if (DNSServiceResolve(&ref, 0, 0, hostname, regtype, domain,
1407 resolve_callback,
1408 &uribuf) == kDNSServiceErr_NoError)
1409 {
1410 if (DNSServiceProcessResult(ref) != kDNSServiceErr_NoError &&
1411 resolved_uri[0])
1412 uri = NULL;
1413 else
1414 uri = resolved_uri;
1415
1416 DNSServiceRefDeallocate(ref);
1417 }
1418 else
1419 uri = NULL;
1420
1421 if (logit)
1422 fputs("STATE: -connecting-to-device\n", stderr);
1423
1424 #else
1425 /*
1426 * No DNS-SD support...
1427 */
1428
1429 uri = NULL;
1430 #endif /* HAVE_DNSSD */
1431
1432 if (logit && !uri)
1433 _cupsLangPuts(stderr, _("Unable to find printer!\n"));
1434 }
1435
1436 DEBUG_printf(("_httpResolveURI: Returning \"%s\"\n", uri));
1437
1438 return (uri);
1439 }
1440
1441
1442 /*
1443 * 'http_copy_decode()' - Copy and decode a URI.
1444 */
1445
1446 static const char * /* O - New source pointer or NULL on error */
1447 http_copy_decode(char *dst, /* O - Destination buffer */
1448 const char *src, /* I - Source pointer */
1449 int dstsize, /* I - Destination size */
1450 const char *term, /* I - Terminating characters */
1451 int decode) /* I - Decode %-encoded values */
1452 {
1453 char *ptr, /* Pointer into buffer */
1454 *end; /* End of buffer */
1455 int quoted; /* Quoted character */
1456
1457
1458 /*
1459 * Copy the src to the destination until we hit a terminating character
1460 * or the end of the string.
1461 */
1462
1463 for (ptr = dst, end = dst + dstsize - 1;
1464 *src && (!term || !strchr(term, *src));
1465 src ++)
1466 if (ptr < end)
1467 {
1468 if (*src == '%' && decode)
1469 {
1470 if (isxdigit(src[1] & 255) && isxdigit(src[2] & 255))
1471 {
1472 /*
1473 * Grab a hex-encoded character...
1474 */
1475
1476 src ++;
1477 if (isalpha(*src))
1478 quoted = (tolower(*src) - 'a' + 10) << 4;
1479 else
1480 quoted = (*src - '0') << 4;
1481
1482 src ++;
1483 if (isalpha(*src))
1484 quoted |= tolower(*src) - 'a' + 10;
1485 else
1486 quoted |= *src - '0';
1487
1488 *ptr++ = quoted;
1489 }
1490 else
1491 {
1492 /*
1493 * Bad hex-encoded character...
1494 */
1495
1496 *ptr = '\0';
1497 return (NULL);
1498 }
1499 }
1500 else
1501 *ptr++ = *src;
1502 }
1503
1504 *ptr = '\0';
1505
1506 return (src);
1507 }
1508
1509
1510 /*
1511 * 'http_copy_encode()' - Copy and encode a URI.
1512 */
1513
1514 static char * /* O - End of current URI */
1515 http_copy_encode(char *dst, /* O - Destination buffer */
1516 const char *src, /* I - Source pointer */
1517 char *dstend, /* I - End of destination buffer */
1518 const char *reserved, /* I - Extra reserved characters */
1519 const char *term, /* I - Terminating characters */
1520 int encode) /* I - %-encode reserved chars? */
1521 {
1522 static const char hex[] = "0123456789ABCDEF";
1523
1524
1525 while (*src && dst < dstend)
1526 {
1527 if (term && *src == *term)
1528 return (dst);
1529
1530 if (encode && (*src == '%' || *src <= ' ' || *src & 128 ||
1531 (reserved && strchr(reserved, *src))))
1532 {
1533 /*
1534 * Hex encode reserved characters...
1535 */
1536
1537 if ((dst + 2) >= dstend)
1538 break;
1539
1540 *dst++ = '%';
1541 *dst++ = hex[(*src >> 4) & 15];
1542 *dst++ = hex[*src & 15];
1543
1544 src ++;
1545 }
1546 else
1547 *dst++ = *src++;
1548 }
1549
1550 *dst = '\0';
1551
1552 if (*src)
1553 return (NULL);
1554 else
1555 return (dst);
1556 }
1557
1558
1559 #ifdef HAVE_DNSSD
1560 /*
1561 * 'resolve_callback()' - Build a device URI for the given service name.
1562 */
1563
1564 static void
1565 resolve_callback(
1566 DNSServiceRef sdRef, /* I - Service reference */
1567 DNSServiceFlags flags, /* I - Results flags */
1568 uint32_t interfaceIndex, /* I - Interface number */
1569 DNSServiceErrorType errorCode, /* I - Error, if any */
1570 const char *fullName, /* I - Full service name */
1571 const char *hostTarget, /* I - Hostname */
1572 uint16_t port, /* I - Port number */
1573 uint16_t txtLen, /* I - Length of TXT record */
1574 const unsigned char *txtRecord, /* I - TXT record data */
1575 void *context) /* I - Pointer to URI buffer */
1576 {
1577 const char *scheme; /* URI scheme */
1578 char rp[257]; /* Remote printer */
1579 const void *value; /* Value from TXT record */
1580 uint8_t valueLen; /* Length of value */
1581 _http_uribuf_t *uribuf; /* URI buffer */
1582
1583
1584 DEBUG_printf(("resolve_callback(sdRef=%p, flags=%x, interfaceIndex=%u, "
1585 "errorCode=%d, fullName=\"%s\", hostTarget=\"%s\", port=%u, "
1586 "txtLen=%u, txtRecord=%p, context=%p)\n", sdRef, flags,
1587 interfaceIndex, errorCode, fullName, hostTarget, port, txtLen,
1588 txtRecord, context));
1589
1590 /*
1591 * Figure out the scheme from the full name...
1592 */
1593
1594 if (strstr(fullName, "._ipp"))
1595 scheme = "ipp";
1596 else if (strstr(fullName, "._printer."))
1597 scheme = "lpd";
1598 else if (strstr(fullName, "._pdl-datastream."))
1599 scheme = "socket";
1600 else
1601 scheme = "riousbprint";
1602
1603 /*
1604 * Extract the "remote printer" key from the TXT record...
1605 */
1606
1607 if ((value = TXTRecordGetValuePtr(txtLen, txtRecord, "rp",
1608 &valueLen)) != NULL)
1609 {
1610 /*
1611 * Convert to resource by concatenating with a leading "/"...
1612 */
1613
1614 rp[0] = '/';
1615 memcpy(rp + 1, value, valueLen);
1616 rp[valueLen + 1] = '\0';
1617 }
1618 else
1619 rp[0] = '\0';
1620
1621 /*
1622 * Assemble the final device URI...
1623 */
1624
1625 uribuf = (_http_uribuf_t *)context;
1626
1627 httpAssembleURI(HTTP_URI_CODING_ALL, uribuf->buffer, uribuf->bufsize, scheme,
1628 NULL, hostTarget, ntohs(port), rp);
1629
1630 DEBUG_printf(("resolve_callback: Resolved URI is \"%s\"...\n",
1631 uribuf->buffer));
1632 }
1633 #endif /* HAVE_DNSSD */
1634
1635
1636 /*
1637 * End of "$Id: http-support.c 7952 2008-09-17 00:56:20Z mike $".
1638 */