]> git.ipfire.org Git - thirdparty/cups.git/blob - cups/http-support.c
Merge changes from CUPS 1.6svn-r9968.
[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 CUPS.
5 *
6 * Copyright 2007-2011 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 * _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
32 * components.
33 * httpSeparate2() - Separate a Universal Resource Identifier into its
34 * components.
35 * httpSeparateURI() - Separate a Universal Resource Identifier into its
36 * components.
37 * httpStatus() - Return a short string describing a HTTP status code.
38 * _cups_hstrerror() - hstrerror() emulation function for Solaris and
39 * others.
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.
46 */
47
48 /*
49 * Include necessary headers...
50 */
51
52 #include "cups-private.h"
53 #ifdef HAVE_DNSSD
54 # include <dns_sd.h>
55 # ifdef WIN32
56 # include <io.h>
57 # elif defined(HAVE_POLL)
58 # include <poll.h>
59 # else
60 # include <sys/select.h>
61 # endif /* WIN32 */
62 #endif /* HAVE_DNSSD */
63
64
65 /*
66 * Local types...
67 */
68
69 typedef struct _http_uribuf_s /* URI buffer */
70 {
71 char *buffer; /* Pointer to buffer */
72 size_t bufsize; /* Size of buffer */
73 int options; /* Options passed to _httpResolveURI */
74 } _http_uribuf_t;
75
76
77 /*
78 * Local globals...
79 */
80
81 static const char * const http_days[7] =
82 {
83 "Sun",
84 "Mon",
85 "Tue",
86 "Wed",
87 "Thu",
88 "Fri",
89 "Sat"
90 };
91 static const char * const http_months[12] =
92 {
93 "Jan",
94 "Feb",
95 "Mar",
96 "Apr",
97 "May",
98 "Jun",
99 "Jul",
100 "Aug",
101 "Sep",
102 "Oct",
103 "Nov",
104 "Dec"
105 };
106
107
108 /*
109 * Local functions...
110 */
111
112 static const char *http_copy_decode(char *dst, const char *src,
113 int dstsize, const char *term,
114 int decode);
115 static char *http_copy_encode(char *dst, const char *src,
116 char *dstend, const char *reserved,
117 const char *term, int encode);
118 #ifdef HAVE_DNSSD
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,
127 void *context);
128 #endif /* HAVE_DNSSD */
129
130
131 /*
132 * 'httpAssembleURI()' - Assemble a uniform resource identifier from its
133 * components.
134 *
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
138 * URI string.
139 *
140 * @since CUPS 1.2/Mac OS X 10.5@
141 */
142
143 http_uri_status_t /* O - URI status */
144 httpAssembleURI(
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 */
153 {
154 char *ptr, /* Pointer into URI buffer */
155 *end; /* End of URI buffer */
156
157
158 /*
159 * Range check input...
160 */
161
162 if (!uri || urilen < 1 || !scheme || port < 0)
163 {
164 if (uri)
165 *uri = '\0';
166
167 return (HTTP_URI_BAD_ARGUMENTS);
168 }
169
170 /*
171 * Assemble the URI starting with the scheme...
172 */
173
174 end = uri + urilen - 1;
175 ptr = http_copy_encode(uri, scheme, end, NULL, NULL, 0);
176
177 if (!ptr)
178 goto assemble_overflow;
179
180 if (!strcmp(scheme, "mailto"))
181 {
182 /*
183 * mailto: only has :, no //...
184 */
185
186 if (ptr < end)
187 *ptr++ = ':';
188 else
189 goto assemble_overflow;
190 }
191 else
192 {
193 /*
194 * Schemes other than mailto: all have //...
195 */
196
197 if ((ptr + 2) < end)
198 {
199 *ptr++ = ':';
200 *ptr++ = '/';
201 *ptr++ = '/';
202 }
203 else
204 goto assemble_overflow;
205 }
206
207 /*
208 * Next the username and hostname, if any...
209 */
210
211 if (host)
212 {
213 if (username && *username)
214 {
215 /*
216 * Add username@ first...
217 */
218
219 ptr = http_copy_encode(ptr, username, end, "/?#[]@", NULL,
220 encoding & HTTP_URI_CODING_USERNAME);
221
222 if (!ptr)
223 goto assemble_overflow;
224
225 if (ptr < end)
226 *ptr++ = '@';
227 else
228 goto assemble_overflow;
229 }
230
231 /*
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,
237 * too...
238 */
239
240 if (host[0] != '[' && strchr(host, ':') && !strstr(host, "._tcp"))
241 {
242 /*
243 * We have a raw IPv6 address...
244 */
245
246 if (strchr(host, '%'))
247 {
248 /*
249 * We have a link-local address, add "[v1." prefix...
250 */
251
252 if ((ptr + 4) < end)
253 {
254 *ptr++ = '[';
255 *ptr++ = 'v';
256 *ptr++ = '1';
257 *ptr++ = '.';
258 }
259 else
260 goto assemble_overflow;
261 }
262 else
263 {
264 /*
265 * We have a normal address, add "[" prefix...
266 */
267
268 if (ptr < end)
269 *ptr++ = '[';
270 else
271 goto assemble_overflow;
272 }
273
274 /*
275 * Copy the rest of the IPv6 address, and terminate with "]".
276 */
277
278 while (ptr < end && *host)
279 {
280 if (*host == '%')
281 {
282 *ptr++ = '+'; /* Convert zone separator */
283 host ++;
284 }
285 else
286 *ptr++ = *host++;
287 }
288
289 if (*host)
290 goto assemble_overflow;
291
292 if (ptr < end)
293 *ptr++ = ']';
294 else
295 goto assemble_overflow;
296 }
297 else
298 {
299 /*
300 * Otherwise, just copy the host string...
301 */
302
303 ptr = http_copy_encode(ptr, host, end, ":/?#[]@\\\"", NULL,
304 encoding & HTTP_URI_CODING_HOSTNAME);
305
306 if (!ptr)
307 goto assemble_overflow;
308 }
309
310 /*
311 * Finish things off with the port number...
312 */
313
314 if (port > 0)
315 {
316 snprintf(ptr, end - ptr + 1, ":%d", port);
317 ptr += strlen(ptr);
318
319 if (ptr >= end)
320 goto assemble_overflow;
321 }
322 }
323
324 /*
325 * Last but not least, add the resource string...
326 */
327
328 if (resource)
329 {
330 char *query; /* Pointer to query string */
331
332
333 /*
334 * Copy the resource string up to the query string if present...
335 */
336
337 query = strchr(resource, '?');
338 ptr = http_copy_encode(ptr, resource, end, NULL, "?",
339 encoding & HTTP_URI_CODING_RESOURCE);
340 if (!ptr)
341 goto assemble_overflow;
342
343 if (query)
344 {
345 /*
346 * Copy query string without encoding...
347 */
348
349 ptr = http_copy_encode(ptr, query, end, NULL, NULL,
350 encoding & HTTP_URI_CODING_QUERY);
351 if (!ptr)
352 goto assemble_overflow;
353 }
354 }
355 else if (ptr < end)
356 *ptr++ = '/';
357 else
358 goto assemble_overflow;
359
360 /*
361 * Nul-terminate the URI buffer and return with no errors...
362 */
363
364 *ptr = '\0';
365
366 return (HTTP_URI_OK);
367
368 /*
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...
371 */
372
373 assemble_overflow:
374
375 *uri = '\0';
376 return (HTTP_URI_OVERFLOW);
377 }
378
379
380 /*
381 * 'httpAssembleURIf()' - Assemble a uniform resource identifier from its
382 * components with a formatted resource.
383 *
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.
389 *
390 * @since CUPS 1.2/Mac OS X 10.5@
391 */
392
393 http_uri_status_t /* O - URI status */
394 httpAssembleURIf(
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 */
404 {
405 va_list ap; /* Pointer to additional arguments */
406 char resource[1024]; /* Formatted resource string */
407 int bytes; /* Bytes in formatted string */
408
409
410 /*
411 * Range check input...
412 */
413
414 if (!uri || urilen < 1 || !scheme || port < 0 || !resourcef)
415 {
416 if (uri)
417 *uri = '\0';
418
419 return (HTTP_URI_BAD_ARGUMENTS);
420 }
421
422 /*
423 * Format the resource string and assemble the URI...
424 */
425
426 va_start(ap, resourcef);
427 bytes = vsnprintf(resource, sizeof(resource), resourcef, ap);
428 va_end(ap);
429
430 if (bytes >= sizeof(resource))
431 {
432 *uri = '\0';
433 return (HTTP_URI_OVERFLOW);
434 }
435 else
436 return (httpAssembleURI(encoding, uri, urilen, scheme, username, host,
437 port, resource));
438 }
439
440
441 /*
442 * '_httpAssembleUUID()' - Make a UUID URI conforming to RFC 4122.
443 *
444 * The buffer needs to be at least 46 bytes in size.
445 */
446
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 */
454 {
455 char data[1024]; /* Source string for MD5 */
456 _cups_md5_state_t md5state; /* MD5 state */
457 unsigned char md5sum[16]; /* MD5 digest/sum */
458
459
460 /*
461 * Build a version 3 UUID conforming to RFC 4122.
462 *
463 * Start with the MD5 sum of the server, port, object name and
464 * number, and some random data on the end.
465 */
466
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);
470
471 _cupsMD5Init(&md5state);
472 _cupsMD5Append(&md5state, (unsigned char *)data, strlen(data));
473 _cupsMD5Finish(&md5state, md5sum);
474
475 /*
476 * Generate the UUID from the MD5...
477 */
478
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]);
486
487 return (buffer);
488 }
489
490
491 /*
492 * 'httpDecode64()' - Base64-decode a string.
493 *
494 * This function is deprecated. Use the httpDecode64_2() function instead
495 * which provides buffer length arguments.
496 *
497 * @deprecated@
498 */
499
500 char * /* O - Decoded string */
501 httpDecode64(char *out, /* I - String to write to */
502 const char *in) /* I - String to read from */
503 {
504 int outlen; /* Output buffer length */
505
506
507 /*
508 * Use the old maximum buffer size for binary compatibility...
509 */
510
511 outlen = 512;
512
513 return (httpDecode64_2(out, &outlen, in));
514 }
515
516
517 /*
518 * 'httpDecode64_2()' - Base64-decode a string.
519 *
520 * @since CUPS 1.1.21/Mac OS X 10.4@
521 */
522
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 */
527 {
528 int pos, /* Bit position */
529 base64; /* Value of this character */
530 char *outptr, /* Output pointer */
531 *outend; /* End of output buffer */
532
533
534 /*
535 * Range check input...
536 */
537
538 if (!out || !outlen || *outlen < 1 || !in)
539 return (NULL);
540
541 if (!*in)
542 {
543 *out = '\0';
544 *outlen = 0;
545
546 return (out);
547 }
548
549 /*
550 * Convert from base-64 to bytes...
551 */
552
553 for (outptr = out, outend = out + *outlen - 1, pos = 0; *in != '\0'; in ++)
554 {
555 /*
556 * Decode this character into a number from 0 to 63...
557 */
558
559 if (*in >= 'A' && *in <= 'Z')
560 base64 = *in - 'A';
561 else if (*in >= 'a' && *in <= 'z')
562 base64 = *in - 'a' + 26;
563 else if (*in >= '0' && *in <= '9')
564 base64 = *in - '0' + 52;
565 else if (*in == '+')
566 base64 = 62;
567 else if (*in == '/')
568 base64 = 63;
569 else if (*in == '=')
570 break;
571 else
572 continue;
573
574 /*
575 * Store the result in the appropriate chars...
576 */
577
578 switch (pos)
579 {
580 case 0 :
581 if (outptr < outend)
582 *outptr = base64 << 2;
583 pos ++;
584 break;
585 case 1 :
586 if (outptr < outend)
587 *outptr++ |= (base64 >> 4) & 3;
588 if (outptr < outend)
589 *outptr = (base64 << 4) & 255;
590 pos ++;
591 break;
592 case 2 :
593 if (outptr < outend)
594 *outptr++ |= (base64 >> 2) & 15;
595 if (outptr < outend)
596 *outptr = (base64 << 6) & 255;
597 pos ++;
598 break;
599 case 3 :
600 if (outptr < outend)
601 *outptr++ |= base64;
602 pos = 0;
603 break;
604 }
605 }
606
607 *outptr = '\0';
608
609 /*
610 * Return the decoded string and size...
611 */
612
613 *outlen = (int)(outptr - out);
614
615 return (out);
616 }
617
618
619 /*
620 * 'httpEncode64()' - Base64-encode a string.
621 *
622 * This function is deprecated. Use the httpEncode64_2() function instead
623 * which provides buffer length arguments.
624 *
625 * @deprecated@
626 */
627
628 char * /* O - Encoded string */
629 httpEncode64(char *out, /* I - String to write to */
630 const char *in) /* I - String to read from */
631 {
632 return (httpEncode64_2(out, 512, in, (int)strlen(in)));
633 }
634
635
636 /*
637 * 'httpEncode64_2()' - Base64-encode a string.
638 *
639 * @since CUPS 1.1.21/Mac OS X 10.4@
640 */
641
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 */
647 {
648 char *outptr, /* Output pointer */
649 *outend; /* End of output buffer */
650 static const char base64[] = /* Base64 characters... */
651 {
652 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
653 "abcdefghijklmnopqrstuvwxyz"
654 "0123456789"
655 "+/"
656 };
657
658
659 /*
660 * Range check input...
661 */
662
663 if (!out || outlen < 1 || !in)
664 return (NULL);
665
666 /*
667 * Convert bytes to base-64...
668 */
669
670 for (outptr = out, outend = out + outlen - 1; inlen > 0; in ++, inlen --)
671 {
672 /*
673 * Encode the up to 3 characters as 4 Base64 numbers...
674 */
675
676 if (outptr < outend)
677 *outptr ++ = base64[(in[0] & 255) >> 2];
678
679 if (outptr < outend)
680 {
681 if (inlen > 1)
682 *outptr ++ = base64[(((in[0] & 255) << 4) | ((in[1] & 255) >> 4)) & 63];
683 else
684 *outptr ++ = base64[((in[0] & 255) << 4) & 63];
685 }
686
687 in ++;
688 inlen --;
689 if (inlen <= 0)
690 {
691 if (outptr < outend)
692 *outptr ++ = '=';
693 if (outptr < outend)
694 *outptr ++ = '=';
695 break;
696 }
697
698 if (outptr < outend)
699 {
700 if (inlen > 1)
701 *outptr ++ = base64[(((in[0] & 255) << 2) | ((in[1] & 255) >> 6)) & 63];
702 else
703 *outptr ++ = base64[((in[0] & 255) << 2) & 63];
704 }
705
706 in ++;
707 inlen --;
708 if (inlen <= 0)
709 {
710 if (outptr < outend)
711 *outptr ++ = '=';
712 break;
713 }
714
715 if (outptr < outend)
716 *outptr ++ = base64[in[0] & 63];
717 }
718
719 *outptr = '\0';
720
721 /*
722 * Return the encoded string...
723 */
724
725 return (out);
726 }
727
728
729 /*
730 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
731 *
732 * @deprecated@
733 */
734
735 const char * /* O - Date/time string */
736 httpGetDateString(time_t t) /* I - UNIX time */
737 {
738 _cups_globals_t *cg = _cupsGlobals(); /* Pointer to library globals */
739
740
741 return (httpGetDateString2(t, cg->http_date, sizeof(cg->http_date)));
742 }
743
744
745 /*
746 * 'httpGetDateString2()' - Get a formatted date/time string from a time value.
747 *
748 * @since CUPS 1.2/Mac OS X 10.5@
749 */
750
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 */
755 {
756 struct tm *tdate; /* UNIX date/time data */
757
758
759 tdate = gmtime(&t);
760 snprintf(s, slen, "%s, %02d %s %d %02d:%02d:%02d GMT",
761 http_days[tdate->tm_wday], tdate->tm_mday,
762 http_months[tdate->tm_mon], tdate->tm_year + 1900,
763 tdate->tm_hour, tdate->tm_min, tdate->tm_sec);
764
765 return (s);
766 }
767
768
769 /*
770 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
771 */
772
773 time_t /* O - UNIX time */
774 httpGetDateTime(const char *s) /* I - Date/time string */
775 {
776 int i; /* Looping var */
777 char mon[16]; /* Abbreviated month name */
778 int day, year; /* Day of month and year */
779 int hour, min, sec; /* Time */
780 int days; /* Number of days since 1970 */
781 static const int normal_days[] = /* Days to a month, normal years */
782 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
783 static const int leap_days[] = /* Days to a month, leap years */
784 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 };
785
786
787 DEBUG_printf(("2httpGetDateTime(s=\"%s\")", s));
788
789 /*
790 * Extract the date and time from the formatted string...
791 */
792
793 if (sscanf(s, "%*s%d%15s%d%d:%d:%d", &day, mon, &year, &hour, &min, &sec) < 6)
794 return (0);
795
796 DEBUG_printf(("4httpGetDateTime: day=%d, mon=\"%s\", year=%d, hour=%d, "
797 "min=%d, sec=%d", day, mon, year, hour, min, sec));
798
799 /*
800 * Convert the month name to a number from 0 to 11.
801 */
802
803 for (i = 0; i < 12; i ++)
804 if (!_cups_strcasecmp(mon, http_months[i]))
805 break;
806
807 if (i >= 12)
808 return (0);
809
810 DEBUG_printf(("4httpGetDateTime: i=%d", i));
811
812 /*
813 * Now convert the date and time to a UNIX time value in seconds since
814 * 1970. We can't use mktime() since the timezone may not be UTC but
815 * the date/time string *is* UTC.
816 */
817
818 if ((year & 3) == 0 && ((year % 100) != 0 || (year % 400) == 0))
819 days = leap_days[i] + day - 1;
820 else
821 days = normal_days[i] + day - 1;
822
823 DEBUG_printf(("4httpGetDateTime: days=%d", days));
824
825 days += (year - 1970) * 365 + /* 365 days per year (normally) */
826 ((year - 1) / 4 - 492) - /* + leap days */
827 ((year - 1) / 100 - 19) + /* - 100 year days */
828 ((year - 1) / 400 - 4); /* + 400 year days */
829
830 DEBUG_printf(("4httpGetDateTime: days=%d\n", days));
831
832 return (days * 86400 + hour * 3600 + min * 60 + sec);
833 }
834
835
836 /*
837 * 'httpSeparate()' - Separate a Universal Resource Identifier into its
838 * components.
839 *
840 * This function is deprecated; use the httpSeparateURI() function instead.
841 *
842 * @deprecated@
843 */
844
845 void
846 httpSeparate(const char *uri, /* I - Universal Resource Identifier */
847 char *scheme, /* O - Scheme [32] (http, https, etc.) */
848 char *username, /* O - Username [1024] */
849 char *host, /* O - Hostname [1024] */
850 int *port, /* O - Port number to use */
851 char *resource) /* O - Resource/filename [1024] */
852 {
853 httpSeparateURI(HTTP_URI_CODING_ALL, uri, scheme, 32, username,
854 HTTP_MAX_URI, host, HTTP_MAX_URI, port, resource,
855 HTTP_MAX_URI);
856 }
857
858
859 /*
860 * 'httpSeparate2()' - Separate a Universal Resource Identifier into its
861 * components.
862 *
863 * This function is deprecated; use the httpSeparateURI() function instead.
864 *
865 * @since CUPS 1.1.21/Mac OS X 10.4@
866 * @deprecated@
867 */
868
869 void
870 httpSeparate2(const char *uri, /* I - Universal Resource Identifier */
871 char *scheme, /* O - Scheme (http, https, etc.) */
872 int schemelen, /* I - Size of scheme buffer */
873 char *username, /* O - Username */
874 int usernamelen, /* I - Size of username buffer */
875 char *host, /* O - Hostname */
876 int hostlen, /* I - Size of hostname buffer */
877 int *port, /* O - Port number to use */
878 char *resource, /* O - Resource/filename */
879 int resourcelen) /* I - Size of resource buffer */
880 {
881 httpSeparateURI(HTTP_URI_CODING_ALL, uri, scheme, schemelen, username,
882 usernamelen, host, hostlen, port, resource, resourcelen);
883 }
884
885
886 /*
887 * 'httpSeparateURI()' - Separate a Universal Resource Identifier into its
888 * components.
889 *
890 * @since CUPS 1.2/Mac OS X 10.5@
891 */
892
893 http_uri_status_t /* O - Result of separation */
894 httpSeparateURI(
895 http_uri_coding_t decoding, /* I - Decoding flags */
896 const char *uri, /* I - Universal Resource Identifier */
897 char *scheme, /* O - Scheme (http, https, etc.) */
898 int schemelen, /* I - Size of scheme buffer */
899 char *username, /* O - Username */
900 int usernamelen, /* I - Size of username buffer */
901 char *host, /* O - Hostname */
902 int hostlen, /* I - Size of hostname buffer */
903 int *port, /* O - Port number to use */
904 char *resource, /* O - Resource/filename */
905 int resourcelen) /* I - Size of resource buffer */
906 {
907 char *ptr, /* Pointer into string... */
908 *end; /* End of string */
909 const char *sep; /* Separator character */
910 http_uri_status_t status; /* Result of separation */
911
912
913 /*
914 * Initialize everything to blank...
915 */
916
917 if (scheme && schemelen > 0)
918 *scheme = '\0';
919
920 if (username && usernamelen > 0)
921 *username = '\0';
922
923 if (host && hostlen > 0)
924 *host = '\0';
925
926 if (port)
927 *port = 0;
928
929 if (resource && resourcelen > 0)
930 *resource = '\0';
931
932 /*
933 * Range check input...
934 */
935
936 if (!uri || !port || !scheme || schemelen <= 0 || !username ||
937 usernamelen <= 0 || !host || hostlen <= 0 || !resource ||
938 resourcelen <= 0)
939 return (HTTP_URI_BAD_ARGUMENTS);
940
941 if (!*uri)
942 return (HTTP_URI_BAD_URI);
943
944 /*
945 * Grab the scheme portion of the URI...
946 */
947
948 status = HTTP_URI_OK;
949
950 if (!strncmp(uri, "//", 2))
951 {
952 /*
953 * Workaround for HP IPP client bug...
954 */
955
956 strlcpy(scheme, "ipp", schemelen);
957 status = HTTP_URI_MISSING_SCHEME;
958 }
959 else if (*uri == '/')
960 {
961 /*
962 * Filename...
963 */
964
965 strlcpy(scheme, "file", schemelen);
966 status = HTTP_URI_MISSING_SCHEME;
967 }
968 else
969 {
970 /*
971 * Standard URI with scheme...
972 */
973
974 for (ptr = scheme, end = scheme + schemelen - 1;
975 *uri && *uri != ':' && ptr < end;)
976 if (strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
977 "abcdefghijklmnopqrstuvwxyz"
978 "0123456789-+.", *uri) != NULL)
979 *ptr++ = *uri++;
980 else
981 break;
982
983 *ptr = '\0';
984
985 if (*uri != ':')
986 {
987 *scheme = '\0';
988 return (HTTP_URI_BAD_SCHEME);
989 }
990
991 uri ++;
992 }
993
994 /*
995 * Set the default port number...
996 */
997
998 if (!strcmp(scheme, "http"))
999 *port = 80;
1000 else if (!strcmp(scheme, "https"))
1001 *port = 443;
1002 else if (!strcmp(scheme, "ipp") || !strcmp(scheme, "ipps"))
1003 *port = 631;
1004 else if (!_cups_strcasecmp(scheme, "lpd"))
1005 *port = 515;
1006 else if (!strcmp(scheme, "socket")) /* Not yet registered with IANA... */
1007 *port = 9100;
1008 else if (strcmp(scheme, "file") && strcmp(scheme, "mailto"))
1009 status = HTTP_URI_UNKNOWN_SCHEME;
1010
1011 /*
1012 * Now see if we have a hostname...
1013 */
1014
1015 if (!strncmp(uri, "//", 2))
1016 {
1017 /*
1018 * Yes, extract it...
1019 */
1020
1021 uri += 2;
1022
1023 /*
1024 * Grab the username, if any...
1025 */
1026
1027 if ((sep = strpbrk(uri, "@/")) != NULL && *sep == '@')
1028 {
1029 /*
1030 * Get a username:password combo...
1031 */
1032
1033 uri = http_copy_decode(username, uri, usernamelen, "@",
1034 decoding & HTTP_URI_CODING_USERNAME);
1035
1036 if (!uri)
1037 {
1038 *username = '\0';
1039 return (HTTP_URI_BAD_USERNAME);
1040 }
1041
1042 uri ++;
1043 }
1044
1045 /*
1046 * Then the hostname/IP address...
1047 */
1048
1049 if (*uri == '[')
1050 {
1051 /*
1052 * Grab IPv6 address...
1053 */
1054
1055 uri ++;
1056 if (!strncmp(uri, "v1.", 3))
1057 uri += 3; /* Skip IPvN leader... */
1058
1059 uri = http_copy_decode(host, uri, hostlen, "]",
1060 decoding & HTTP_URI_CODING_HOSTNAME);
1061
1062 if (!uri)
1063 {
1064 *host = '\0';
1065 return (HTTP_URI_BAD_HOSTNAME);
1066 }
1067
1068 /*
1069 * Validate value...
1070 */
1071
1072 if (*uri != ']')
1073 {
1074 *host = '\0';
1075 return (HTTP_URI_BAD_HOSTNAME);
1076 }
1077
1078 uri ++;
1079
1080 for (ptr = host; *ptr; ptr ++)
1081 if (*ptr == '+')
1082 {
1083 /*
1084 * Convert zone separator to % and stop here...
1085 */
1086
1087 *ptr = '%';
1088 break;
1089 }
1090 else if (*ptr != ':' && *ptr != '.' && !isxdigit(*ptr & 255))
1091 {
1092 *host = '\0';
1093 return (HTTP_URI_BAD_HOSTNAME);
1094 }
1095 }
1096 else
1097 {
1098 /*
1099 * Validate the hostname or IPv4 address first...
1100 */
1101
1102 for (ptr = (char *)uri; *ptr; ptr ++)
1103 if (strchr(":?/", *ptr))
1104 break;
1105 else if (!strchr("abcdefghijklmnopqrstuvwxyz"
1106 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1107 "0123456789"
1108 "-._~"
1109 "%"
1110 "!$&'()*+,;=\\", *ptr))
1111 {
1112 *host = '\0';
1113 return (HTTP_URI_BAD_HOSTNAME);
1114 }
1115
1116 /*
1117 * Then copy the hostname or IPv4 address to the buffer...
1118 */
1119
1120 uri = http_copy_decode(host, uri, hostlen, ":?/",
1121 decoding & HTTP_URI_CODING_HOSTNAME);
1122
1123 if (!uri)
1124 {
1125 *host = '\0';
1126 return (HTTP_URI_BAD_HOSTNAME);
1127 }
1128 }
1129
1130 /*
1131 * Validate hostname for file scheme - only empty and localhost are
1132 * acceptable.
1133 */
1134
1135 if (!strcmp(scheme, "file") && strcmp(host, "localhost") && host[0])
1136 {
1137 *host = '\0';
1138 return (HTTP_URI_BAD_HOSTNAME);
1139 }
1140
1141 /*
1142 * See if we have a port number...
1143 */
1144
1145 if (*uri == ':')
1146 {
1147 /*
1148 * Yes, collect the port number...
1149 */
1150
1151 if (!isdigit(uri[1] & 255))
1152 {
1153 *port = 0;
1154 return (HTTP_URI_BAD_PORT);
1155 }
1156
1157 *port = strtol(uri + 1, (char **)&uri, 10);
1158
1159 if (*uri != '/' && *uri)
1160 {
1161 *port = 0;
1162 return (HTTP_URI_BAD_PORT);
1163 }
1164 }
1165 }
1166
1167 /*
1168 * The remaining portion is the resource string...
1169 */
1170
1171 if (*uri == '?' || !*uri)
1172 {
1173 /*
1174 * Hostname but no path...
1175 */
1176
1177 status = HTTP_URI_MISSING_RESOURCE;
1178 *resource = '/';
1179
1180 /*
1181 * Copy any query string...
1182 */
1183
1184 if (*uri == '?')
1185 uri = http_copy_decode(resource + 1, uri, resourcelen - 1, NULL,
1186 decoding & HTTP_URI_CODING_QUERY);
1187 else
1188 resource[1] = '\0';
1189 }
1190 else
1191 {
1192 uri = http_copy_decode(resource, uri, resourcelen, "?",
1193 decoding & HTTP_URI_CODING_RESOURCE);
1194
1195 if (uri && *uri == '?')
1196 {
1197 /*
1198 * Concatenate any query string...
1199 */
1200
1201 char *resptr = resource + strlen(resource);
1202
1203 uri = http_copy_decode(resptr, uri, resourcelen - (int)(resptr - resource),
1204 NULL, decoding & HTTP_URI_CODING_QUERY);
1205 }
1206 }
1207
1208 if (!uri)
1209 {
1210 *resource = '\0';
1211 return (HTTP_URI_BAD_RESOURCE);
1212 }
1213
1214 /*
1215 * Return the URI separation status...
1216 */
1217
1218 return (status);
1219 }
1220
1221
1222 /*
1223 * 'httpStatus()' - Return a short string describing a HTTP status code.
1224 *
1225 * The returned string is localized to the current POSIX locale and is based
1226 * on the status strings defined in RFC 2616.
1227 */
1228
1229 const char * /* O - Localized status string */
1230 httpStatus(http_status_t status) /* I - HTTP status code */
1231 {
1232 const char *s; /* Status string */
1233 _cups_globals_t *cg = _cupsGlobals(); /* Global data */
1234
1235
1236 if (!cg->lang_default)
1237 cg->lang_default = cupsLangDefault();
1238
1239 switch (status)
1240 {
1241 case HTTP_CONTINUE :
1242 s = _("Continue");
1243 break;
1244 case HTTP_SWITCHING_PROTOCOLS :
1245 s = _("Switching Protocols");
1246 break;
1247 case HTTP_OK :
1248 s = _("OK");
1249 break;
1250 case HTTP_CREATED :
1251 s = _("Created");
1252 break;
1253 case HTTP_ACCEPTED :
1254 s = _("Accepted");
1255 break;
1256 case HTTP_NO_CONTENT :
1257 s = _("No Content");
1258 break;
1259 case HTTP_MOVED_PERMANENTLY :
1260 s = _("Moved Permanently");
1261 break;
1262 case HTTP_SEE_OTHER :
1263 s = _("See Other");
1264 break;
1265 case HTTP_NOT_MODIFIED :
1266 s = _("Not Modified");
1267 break;
1268 case HTTP_BAD_REQUEST :
1269 s = _("Bad Request");
1270 break;
1271 case HTTP_UNAUTHORIZED :
1272 case HTTP_AUTHORIZATION_CANCELED :
1273 s = _("Unauthorized");
1274 break;
1275 case HTTP_FORBIDDEN :
1276 s = _("Forbidden");
1277 break;
1278 case HTTP_NOT_FOUND :
1279 s = _("Not Found");
1280 break;
1281 case HTTP_REQUEST_TOO_LARGE :
1282 s = _("Request Entity Too Large");
1283 break;
1284 case HTTP_URI_TOO_LONG :
1285 s = _("URI Too Long");
1286 break;
1287 case HTTP_UPGRADE_REQUIRED :
1288 s = _("Upgrade Required");
1289 break;
1290 case HTTP_NOT_IMPLEMENTED :
1291 s = _("Not Implemented");
1292 break;
1293 case HTTP_NOT_SUPPORTED :
1294 s = _("Not Supported");
1295 break;
1296 case HTTP_EXPECTATION_FAILED :
1297 s = _("Expectation Failed");
1298 break;
1299 case HTTP_SERVICE_UNAVAILABLE :
1300 s = _("Service Unavailable");
1301 break;
1302 case HTTP_SERVER_ERROR :
1303 s = _("Internal Server Error");
1304 break;
1305 case HTTP_PKI_ERROR :
1306 s = _("SSL/TLS Negotiation Error");
1307 break;
1308 case HTTP_WEBIF_DISABLED :
1309 s = _("Web Interface is Disabled");
1310 break;
1311
1312 default :
1313 s = _("Unknown");
1314 break;
1315 }
1316
1317 return (_cupsLangString(cg->lang_default, s));
1318 }
1319
1320
1321 #ifndef HAVE_HSTRERROR
1322 /*
1323 * '_cups_hstrerror()' - hstrerror() emulation function for Solaris and others.
1324 */
1325
1326 const char * /* O - Error string */
1327 _cups_hstrerror(int error) /* I - Error number */
1328 {
1329 static const char * const errors[] = /* Error strings */
1330 {
1331 "OK",
1332 "Host not found.",
1333 "Try again.",
1334 "Unrecoverable lookup error.",
1335 "No data associated with name."
1336 };
1337
1338
1339 if (error < 0 || error > 4)
1340 return ("Unknown hostname lookup error.");
1341 else
1342 return (errors[error]);
1343 }
1344 #endif /* !HAVE_HSTRERROR */
1345
1346
1347 /*
1348 * '_httpDecodeURI()' - Percent-decode a HTTP request URI.
1349 */
1350
1351 char * /* O - Decoded URI or NULL on error */
1352 _httpDecodeURI(char *dst, /* I - Destination buffer */
1353 const char *src, /* I - Source URI */
1354 size_t dstsize) /* I - Size of destination buffer */
1355 {
1356 if (http_copy_decode(dst, src, (int)dstsize, NULL, 1))
1357 return (dst);
1358 else
1359 return (NULL);
1360 }
1361
1362
1363 /*
1364 * '_httpEncodeURI()' - Percent-encode a HTTP request URI.
1365 */
1366
1367 char * /* O - Encoded URI */
1368 _httpEncodeURI(char *dst, /* I - Destination buffer */
1369 const char *src, /* I - Source URI */
1370 size_t dstsize) /* I - Size of destination buffer */
1371 {
1372 http_copy_encode(dst, src, dst + dstsize - 1, NULL, NULL, 1);
1373 return (dst);
1374 }
1375
1376
1377 /*
1378 * '_httpResolveURI()' - Resolve a DNS-SD URI.
1379 */
1380
1381 const char * /* O - Resolved URI */
1382 _httpResolveURI(
1383 const char *uri, /* I - DNS-SD URI */
1384 char *resolved_uri, /* I - Buffer for resolved URI */
1385 size_t resolved_size, /* I - Size of URI buffer */
1386 int options, /* I - Resolve options */
1387 int (*cb)(void *context), /* I - Continue callback function */
1388 void *context) /* I - Context pointer for callback */
1389 {
1390 char scheme[32], /* URI components... */
1391 userpass[256],
1392 hostname[1024],
1393 resource[1024];
1394 int port;
1395 #ifdef DEBUG
1396 http_uri_status_t status; /* URI decode status */
1397 #endif /* DEBUG */
1398
1399
1400 DEBUG_printf(("4_httpResolveURI(uri=\"%s\", resolved_uri=%p, "
1401 "resolved_size=" CUPS_LLFMT ")", uri, resolved_uri,
1402 CUPS_LLCAST resolved_size));
1403
1404 /*
1405 * Get the device URI...
1406 */
1407
1408 #ifdef DEBUG
1409 if ((status = httpSeparateURI(HTTP_URI_CODING_ALL, uri, scheme,
1410 sizeof(scheme), userpass, sizeof(userpass),
1411 hostname, sizeof(hostname), &port, resource,
1412 sizeof(resource))) < HTTP_URI_OK)
1413 #else
1414 if (httpSeparateURI(HTTP_URI_CODING_ALL, uri, scheme,
1415 sizeof(scheme), userpass, sizeof(userpass),
1416 hostname, sizeof(hostname), &port, resource,
1417 sizeof(resource)) < HTTP_URI_OK)
1418 #endif /* DEBUG */
1419 {
1420 if (options & _HTTP_RESOLVE_STDERR)
1421 _cupsLangPrintFilter(stderr, "ERROR", _("Bad device-uri \"%s\"."), uri);
1422
1423 DEBUG_printf(("6_httpResolveURI: httpSeparateURI returned %d!", status));
1424 DEBUG_puts("5_httpResolveURI: Returning NULL");
1425 return (NULL);
1426 }
1427
1428 /*
1429 * Resolve it as needed...
1430 */
1431
1432 if (strstr(hostname, "._tcp"))
1433 {
1434 #ifdef HAVE_DNSSD
1435 # ifdef WIN32
1436 # pragma comment(lib, "dnssd.lib")
1437 # endif /* WIN32 */
1438 DNSServiceRef ref, /* DNS-SD master service reference */
1439 domainref, /* DNS-SD service reference for domain */
1440 localref; /* DNS-SD service reference for .local */
1441 int domainsent = 0, /* Send the domain resolve? */
1442 offline = 0; /* offline-report state set? */
1443 char *regtype, /* Pointer to type in hostname */
1444 *domain; /* Pointer to domain in hostname */
1445 _http_uribuf_t uribuf; /* URI buffer */
1446 #ifdef HAVE_POLL
1447 struct pollfd polldata; /* Polling data */
1448 #else /* select() */
1449 fd_set input_set; /* Input set for select() */
1450 struct timeval stimeout; /* Timeout value for select() */
1451 #endif /* HAVE_POLL */
1452
1453 if (options & _HTTP_RESOLVE_STDERR)
1454 fprintf(stderr, "DEBUG: Resolving \"%s\"...\n", hostname);
1455
1456 /*
1457 * Separate the hostname into service name, registration type, and domain...
1458 */
1459
1460 for (regtype = strstr(hostname, "._tcp") - 2;
1461 regtype > hostname;
1462 regtype --)
1463 if (regtype[0] == '.' && regtype[1] == '_')
1464 {
1465 /*
1466 * Found ._servicetype in front of ._tcp...
1467 */
1468
1469 *regtype++ = '\0';
1470 break;
1471 }
1472
1473 if (regtype <= hostname)
1474 {
1475 DEBUG_puts("5_httpResolveURI: Bad hostname, returning NULL");
1476 return (NULL);
1477 }
1478
1479 for (domain = strchr(regtype, '.');
1480 domain;
1481 domain = strchr(domain + 1, '.'))
1482 if (domain[1] != '_')
1483 break;
1484
1485 if (domain)
1486 *domain++ = '\0';
1487
1488 uribuf.buffer = resolved_uri;
1489 uribuf.bufsize = resolved_size;
1490 uribuf.options = options;
1491 resolved_uri[0] = '\0';
1492
1493 DEBUG_printf(("6_httpResolveURI: Resolving hostname=\"%s\", regtype=\"%s\", "
1494 "domain=\"%s\"\n", hostname, regtype, domain));
1495 if (options & _HTTP_RESOLVE_STDERR)
1496 {
1497 fputs("STATE: +connecting-to-device\n", stderr);
1498 fprintf(stderr, "DEBUG: Resolving \"%s\", regtype=\"%s\", "
1499 "domain=\"local.\"...\n", hostname, regtype);
1500 }
1501
1502 uri = NULL;
1503
1504 if (DNSServiceCreateConnection(&ref) == kDNSServiceErr_NoError)
1505 {
1506 localref = ref;
1507 if (DNSServiceResolve(&localref, kDNSServiceFlagsShareConnection, 0,
1508 hostname, regtype, "local.", http_resolve_cb,
1509 &uribuf) == kDNSServiceErr_NoError)
1510 {
1511 int fds; /* Number of ready descriptors */
1512 time_t timeout, /* Poll timeout */
1513 start_time = time(NULL);/* Start time */
1514
1515 for (;;)
1516 {
1517 if (options & _HTTP_RESOLVE_STDERR)
1518 _cupsLangPrintFilter(stderr, "INFO", _("Looking for printer."));
1519
1520 if (cb && !(*cb)(context))
1521 {
1522 DEBUG_puts("5_httpResolveURI: callback returned 0 (stop)");
1523 break;
1524 }
1525
1526 /*
1527 * For the first minute (or forever if we have a callback), wakeup
1528 * every 2 seconds to emit a "looking for printer" message...
1529 */
1530
1531 timeout = (time(NULL) < (start_time + 60) || cb) ? 2000 : -1;
1532
1533 #ifdef HAVE_POLL
1534 polldata.fd = DNSServiceRefSockFD(ref);
1535 polldata.events = POLLIN;
1536
1537 fds = poll(&polldata, 1, timeout);
1538
1539 #else /* select() */
1540 FD_ZERO(&input_set);
1541 FD_SET(DNSServiceRefSockFD(ref), &input_set);
1542
1543 stimeout.tv_sec = ((int)timeout) / 1000;
1544 stimeout.tv_usec = ((int)(timeout) * 1000) % 1000000;
1545
1546 fds = select(DNSServiceRefSockFD(ref)+1, &input_set, NULL, NULL,
1547 timeout < 0.0 ? NULL : &stimeout);
1548 #endif /* HAVE_POLL */
1549
1550 if (fds < 0)
1551 {
1552 if (errno != EINTR && errno != EAGAIN)
1553 {
1554 DEBUG_printf(("5_httpResolveURI: poll error: %s", strerror(errno)));
1555 break;
1556 }
1557 }
1558 else if (fds == 0)
1559 {
1560 /*
1561 * Wait 2 seconds for a response to the local resolve; if nothing
1562 * comes in, do an additional domain resolution...
1563 */
1564
1565 if (domainsent == 0 && (domain && _cups_strcasecmp(domain, "local.")))
1566 {
1567 if (options & _HTTP_RESOLVE_STDERR)
1568 fprintf(stderr,
1569 "DEBUG: Resolving \"%s\", regtype=\"%s\", "
1570 "domain=\"%s\"...\n", hostname, regtype,
1571 domain ? domain : "");
1572
1573 domainref = ref;
1574 if (DNSServiceResolve(&domainref, kDNSServiceFlagsShareConnection,
1575 0, hostname, regtype, domain,
1576 http_resolve_cb, &uribuf)
1577 == kDNSServiceErr_NoError)
1578 domainsent = 1;
1579 }
1580
1581 /*
1582 * If it hasn't resolved within 5 seconds set the offline-report
1583 * printer-state-reason...
1584 */
1585
1586 if ((options & _HTTP_RESOLVE_STDERR) && offline == 0 &&
1587 time(NULL) > (start_time + 5))
1588 {
1589 fputs("STATE: +offline-report\n", stderr);
1590 offline = 1;
1591 }
1592 }
1593 else
1594 {
1595 if (DNSServiceProcessResult(ref) == kDNSServiceErr_NoError)
1596 {
1597 uri = resolved_uri;
1598 break;
1599 }
1600 }
1601 }
1602
1603 if (domainsent)
1604 DNSServiceRefDeallocate(domainref);
1605
1606 DNSServiceRefDeallocate(localref);
1607 }
1608
1609 DNSServiceRefDeallocate(ref);
1610 }
1611
1612 if (options & _HTTP_RESOLVE_STDERR)
1613 {
1614 if (uri)
1615 fprintf(stderr, "DEBUG: Resolved as \"%s\"...\n", uri);
1616 else
1617 fputs("DEBUG: Unable to resolve URI\n", stderr);
1618
1619 fputs("STATE: -connecting-to-device,offline-report\n", stderr);
1620 }
1621
1622 #else
1623 /*
1624 * No DNS-SD support...
1625 */
1626
1627 uri = NULL;
1628 #endif /* HAVE_DNSSD */
1629
1630 if ((options & _HTTP_RESOLVE_STDERR) && !uri)
1631 _cupsLangPrintFilter(stderr, "ERROR", _("Unable to find printer."));
1632 }
1633 else
1634 {
1635 /*
1636 * Nothing more to do...
1637 */
1638
1639 strlcpy(resolved_uri, uri, resolved_size);
1640 uri = resolved_uri;
1641 }
1642
1643 DEBUG_printf(("5_httpResolveURI: Returning \"%s\"", uri));
1644
1645 return (uri);
1646 }
1647
1648
1649 /*
1650 * 'http_copy_decode()' - Copy and decode a URI.
1651 */
1652
1653 static const char * /* O - New source pointer or NULL on error */
1654 http_copy_decode(char *dst, /* O - Destination buffer */
1655 const char *src, /* I - Source pointer */
1656 int dstsize, /* I - Destination size */
1657 const char *term, /* I - Terminating characters */
1658 int decode) /* I - Decode %-encoded values */
1659 {
1660 char *ptr, /* Pointer into buffer */
1661 *end; /* End of buffer */
1662 int quoted; /* Quoted character */
1663
1664
1665 /*
1666 * Copy the src to the destination until we hit a terminating character
1667 * or the end of the string.
1668 */
1669
1670 for (ptr = dst, end = dst + dstsize - 1;
1671 *src && (!term || !strchr(term, *src));
1672 src ++)
1673 if (ptr < end)
1674 {
1675 if (*src == '%' && decode)
1676 {
1677 if (isxdigit(src[1] & 255) && isxdigit(src[2] & 255))
1678 {
1679 /*
1680 * Grab a hex-encoded character...
1681 */
1682
1683 src ++;
1684 if (isalpha(*src))
1685 quoted = (tolower(*src) - 'a' + 10) << 4;
1686 else
1687 quoted = (*src - '0') << 4;
1688
1689 src ++;
1690 if (isalpha(*src))
1691 quoted |= tolower(*src) - 'a' + 10;
1692 else
1693 quoted |= *src - '0';
1694
1695 *ptr++ = quoted;
1696 }
1697 else
1698 {
1699 /*
1700 * Bad hex-encoded character...
1701 */
1702
1703 *ptr = '\0';
1704 return (NULL);
1705 }
1706 }
1707 else
1708 *ptr++ = *src;
1709 }
1710
1711 *ptr = '\0';
1712
1713 return (src);
1714 }
1715
1716
1717 /*
1718 * 'http_copy_encode()' - Copy and encode a URI.
1719 */
1720
1721 static char * /* O - End of current URI */
1722 http_copy_encode(char *dst, /* O - Destination buffer */
1723 const char *src, /* I - Source pointer */
1724 char *dstend, /* I - End of destination buffer */
1725 const char *reserved, /* I - Extra reserved characters */
1726 const char *term, /* I - Terminating characters */
1727 int encode) /* I - %-encode reserved chars? */
1728 {
1729 static const char hex[] = "0123456789ABCDEF";
1730
1731
1732 while (*src && dst < dstend)
1733 {
1734 if (term && *src == *term)
1735 return (dst);
1736
1737 if (encode && (*src == '%' || *src <= ' ' || *src & 128 ||
1738 (reserved && strchr(reserved, *src))))
1739 {
1740 /*
1741 * Hex encode reserved characters...
1742 */
1743
1744 if ((dst + 2) >= dstend)
1745 break;
1746
1747 *dst++ = '%';
1748 *dst++ = hex[(*src >> 4) & 15];
1749 *dst++ = hex[*src & 15];
1750
1751 src ++;
1752 }
1753 else
1754 *dst++ = *src++;
1755 }
1756
1757 *dst = '\0';
1758
1759 if (*src)
1760 return (NULL);
1761 else
1762 return (dst);
1763 }
1764
1765
1766 #ifdef HAVE_DNSSD
1767 /*
1768 * 'http_resolve_cb()' - Build a device URI for the given service name.
1769 */
1770
1771 static void DNSSD_API
1772 http_resolve_cb(
1773 DNSServiceRef sdRef, /* I - Service reference */
1774 DNSServiceFlags flags, /* I - Results flags */
1775 uint32_t interfaceIndex, /* I - Interface number */
1776 DNSServiceErrorType errorCode, /* I - Error, if any */
1777 const char *fullName, /* I - Full service name */
1778 const char *hostTarget, /* I - Hostname */
1779 uint16_t port, /* I - Port number */
1780 uint16_t txtLen, /* I - Length of TXT record */
1781 const unsigned char *txtRecord, /* I - TXT record data */
1782 void *context) /* I - Pointer to URI buffer */
1783 {
1784 const char *scheme, /* URI scheme */
1785 *hostptr; /* Pointer into hostTarget */
1786 char rp[257], /* Remote printer */
1787 fqdn[256]; /* FQDN of the .local name */
1788 const void *value; /* Value from TXT record */
1789 uint8_t valueLen; /* Length of value */
1790 _http_uribuf_t *uribuf; /* URI buffer */
1791
1792
1793 DEBUG_printf(("7http_resolve_cb(sdRef=%p, flags=%x, interfaceIndex=%u, "
1794 "errorCode=%d, fullName=\"%s\", hostTarget=\"%s\", port=%u, "
1795 "txtLen=%u, txtRecord=%p, context=%p)", sdRef, flags,
1796 interfaceIndex, errorCode, fullName, hostTarget, port, txtLen,
1797 txtRecord, context));
1798
1799 uribuf = (_http_uribuf_t *)context;
1800
1801 /*
1802 * Figure out the scheme from the full name...
1803 */
1804
1805 if (strstr(fullName, "._ipps") || strstr(fullName, "._ipp-tls"))
1806 scheme = "ipps";
1807 else if (strstr(fullName, "._ipp") || strstr(fullName, "._fax-ipp"))
1808 scheme = "ipp";
1809 else if (strstr(fullName, "._http."))
1810 scheme = "http";
1811 else if (strstr(fullName, "._https."))
1812 scheme = "https";
1813 else if (strstr(fullName, "._printer."))
1814 scheme = "lpd";
1815 else if (strstr(fullName, "._pdl-datastream."))
1816 scheme = "socket";
1817 else
1818 scheme = "riousbprint";
1819
1820 /*
1821 * Extract the "remote printer" key from the TXT record...
1822 */
1823
1824 if ((value = TXTRecordGetValuePtr(txtLen, txtRecord, "rp",
1825 &valueLen)) != NULL)
1826 {
1827 /*
1828 * Convert to resource by concatenating with a leading "/"...
1829 */
1830
1831 rp[0] = '/';
1832 memcpy(rp + 1, value, valueLen);
1833 rp[valueLen + 1] = '\0';
1834 }
1835 else
1836 rp[0] = '\0';
1837
1838 /*
1839 * Lookup the FQDN if needed...
1840 */
1841
1842 if ((uribuf->options & _HTTP_RESOLVE_FQDN) &&
1843 (hostptr = hostTarget + strlen(hostTarget) - 7) > hostTarget &&
1844 !_cups_strcasecmp(hostptr, ".local."))
1845 {
1846 /*
1847 * OK, we got a .local name but the caller needs a real domain. Start by
1848 * getting the IP address of the .local name and then do reverse-lookups...
1849 */
1850
1851 http_addrlist_t *addrlist, /* List of addresses */
1852 *addr; /* Current address */
1853
1854 DEBUG_printf(("8http_resolve_cb: Looking up \"%s\".", hostTarget));
1855
1856 snprintf(fqdn, sizeof(fqdn), "%d", ntohs(port));
1857 if ((addrlist = httpAddrGetList(hostTarget, AF_UNSPEC, fqdn)) != NULL)
1858 {
1859 for (addr = addrlist; addr; addr = addr->next)
1860 {
1861 int error = getnameinfo(&(addr->addr.addr),
1862 httpAddrLength(&(addr->addr)),
1863 fqdn, sizeof(fqdn), NULL, 0, NI_NAMEREQD);
1864
1865 if (!error)
1866 {
1867 DEBUG_printf(("8http_resolve_cb: Found \"%s\".", fqdn));
1868
1869 if ((hostptr = fqdn + strlen(fqdn) - 6) <= fqdn ||
1870 _cups_strcasecmp(hostptr, ".local"))
1871 {
1872 hostTarget = fqdn;
1873 break;
1874 }
1875 }
1876 #ifdef DEBUG
1877 else
1878 DEBUG_printf(("8http_resolve_cb: \"%s\" did not resolve: %d",
1879 httpAddrString(&(addr->addr), fqdn, sizeof(fqdn)),
1880 error));
1881 #endif /* DEBUG */
1882 }
1883 }
1884 }
1885
1886 /*
1887 * Assemble the final device URI...
1888 */
1889
1890 httpAssembleURI(HTTP_URI_CODING_ALL, uribuf->buffer, uribuf->bufsize, scheme,
1891 NULL, hostTarget, ntohs(port), rp);
1892
1893 DEBUG_printf(("8http_resolve_cb: Resolved URI is \"%s\"...", uribuf->buffer));
1894 }
1895 #endif /* HAVE_DNSSD */
1896
1897
1898 /*
1899 * End of "$Id: http-support.c 7952 2008-09-17 00:56:20Z mike $".
1900 */