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