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