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