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