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