]> git.ipfire.org Git - thirdparty/cups.git/blob - cups/http-support.c
Add digest debugging and fix a small bug in the HTTP unit test.
[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 * '_httpDigest()' - Calculate a Digest authentication response using the
666 * appropriate RFC 2068/2617/7616 algorithm.
667 */
668
669 char * /* O - Response string */
670 _httpDigest(char *buffer, /* I - Response buffer */
671 size_t bufsize, /* I - Size of response buffer */
672 const char *algorithm, /* I - algorithm value or `NULL` */
673 const char *username, /* I - username value */
674 const char *realm, /* I - realm value */
675 const char *password, /* I - password value */
676 const char *nonce, /* I - nonce value */
677 unsigned nc, /* I - nc value */
678 const char *cnonce, /* I - cnonce value or `NULL` */
679 const char *qop, /* I - qop value */
680 const char *method, /* I - HTTP method */
681 const char *resource) /* I - HTTP resource path */
682 {
683 char ha1[65], /* Hash of username:realm:password */
684 ha2[65], /* Hash of method:request-uri */
685 temp[1024]; /* Temporary string */
686 unsigned char hash[32]; /* Hash buffer */
687 const char *hashalg; /* Hashing algorithm */
688 size_t hashsize; /* Size of hash */
689
690
691 DEBUG_printf(("2_httpDigest(buffer=%p, bufsize=" CUPS_LLFMT ", algorithm=\%s\", username=\"%s\", realm=\"%s\", password=\"%d chars\", nonce=\"%s\", nc=%u, cnonce=\"%s\", qop=\"%s\", method=\"%s\", resource=\"%s\")", buffer, CUPS_LLCAST bufsize, algorithm, username, realm, (int)strlen(password), nonce, nc, cnonce, qop, method, resource));
692
693 if (algorithm)
694 {
695 /*
696 * Follow RFC 2617/7616...
697 */
698
699 if (!_cups_strcasecmp(algorithm, "MD5"))
700 {
701 /*
702 * RFC 2617 Digest with MD5
703 */
704
705 hashalg = "md5";
706 }
707 else if (!_cups_strcasecmp(algorithm, "SHA-256"))
708 {
709 /*
710 * RFC 7616 Digest with SHA-256
711 */
712
713 hashalg = "sha2-256";
714 }
715 else
716 {
717 /*
718 * Some other algorithm we don't support, skip this one...
719 */
720
721 *buffer = '\0';
722
723 return (NULL);
724 }
725
726 /*
727 * Calculate digest value...
728 */
729
730 /* H(A1) = H(username:realm:password) */
731 snprintf(temp, sizeof(temp), "%s:%s:%s", username, realm, password);
732 hashsize = (size_t)cupsHashData(hashalg, (unsigned char *)temp, strlen(temp), hash, sizeof(hash));
733 cupsHashString(hash, hashsize, ha1, sizeof(ha1));
734
735 /* H(A2) = H(method:uri) */
736 snprintf(temp, sizeof(temp), "%s:%s", method, resource);
737 hashsize = (size_t)cupsHashData(hashalg, (unsigned char *)temp, strlen(temp), hash, sizeof(hash));
738 cupsHashString(hash, hashsize, ha2, sizeof(ha2));
739
740 /* KD = H(H(A1):nonce:nc:cnonce:qop:H(A2)) */
741 snprintf(temp, sizeof(temp), "%s:%s:%08x:%s:%s:%s", ha1, nonce, nc, cnonce, qop, ha2);
742 hashsize = (size_t)cupsHashData(hashalg, (unsigned char *)temp, strlen(temp), hash, sizeof(hash));
743 cupsHashString(hash, hashsize, buffer, bufsize);
744 }
745 else
746 {
747 /*
748 * Use old RFC 2069 Digest method...
749 */
750
751 /* H(A1) = H(username:realm:password) */
752 snprintf(temp, sizeof(temp), "%s:%s:%s", username, realm, password);
753 hashsize = (size_t)cupsHashData("md5", (unsigned char *)temp, strlen(temp), hash, sizeof(hash));
754 cupsHashString(hash, hashsize, ha1, sizeof(ha1));
755
756 /* H(A2) = H(method:uri) */
757 snprintf(temp, sizeof(temp), "%s:%s", method, resource);
758 hashsize = (size_t)cupsHashData("md5", (unsigned char *)temp, strlen(temp), hash, sizeof(hash));
759 cupsHashString(hash, hashsize, ha2, sizeof(ha2));
760
761 /* KD = H(H(A1):nonce:H(A2)) */
762 snprintf(temp, sizeof(temp), "%s:%s:%s", ha1, nonce, ha2);
763 hashsize = (size_t)cupsHashData("md5", (unsigned char *)temp, strlen(temp), hash, sizeof(hash));
764 cupsHashString(hash, hashsize, buffer, bufsize);
765 }
766
767 return (buffer);
768 }
769
770
771 /*
772 * 'httpEncode64()' - Base64-encode a string.
773 *
774 * This function is deprecated. Use the httpEncode64_2() function instead
775 * which provides buffer length arguments.
776 *
777 * @deprecated@ @exclude all@
778 */
779
780 char * /* O - Encoded string */
781 httpEncode64(char *out, /* I - String to write to */
782 const char *in) /* I - String to read from */
783 {
784 return (httpEncode64_2(out, 512, in, (int)strlen(in)));
785 }
786
787
788 /*
789 * 'httpEncode64_2()' - Base64-encode a string.
790 *
791 * @since CUPS 1.1.21/macOS 10.4@
792 */
793
794 char * /* O - Encoded string */
795 httpEncode64_2(char *out, /* I - String to write to */
796 int outlen, /* I - Maximum size of output string */
797 const char *in, /* I - String to read from */
798 int inlen) /* I - Size of input string */
799 {
800 char *outptr, /* Output pointer */
801 *outend; /* End of output buffer */
802 static const char base64[] = /* Base64 characters... */
803 {
804 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
805 "abcdefghijklmnopqrstuvwxyz"
806 "0123456789"
807 "+/"
808 };
809
810
811 /*
812 * Range check input...
813 */
814
815 if (!out || outlen < 1 || !in)
816 return (NULL);
817
818 /*
819 * Convert bytes to base-64...
820 */
821
822 for (outptr = out, outend = out + outlen - 1; inlen > 0; in ++, inlen --)
823 {
824 /*
825 * Encode the up to 3 characters as 4 Base64 numbers...
826 */
827
828 if (outptr < outend)
829 *outptr ++ = base64[(in[0] & 255) >> 2];
830
831 if (outptr < outend)
832 {
833 if (inlen > 1)
834 *outptr ++ = base64[(((in[0] & 255) << 4) | ((in[1] & 255) >> 4)) & 63];
835 else
836 *outptr ++ = base64[((in[0] & 255) << 4) & 63];
837 }
838
839 in ++;
840 inlen --;
841 if (inlen <= 0)
842 {
843 if (outptr < outend)
844 *outptr ++ = '=';
845 if (outptr < outend)
846 *outptr ++ = '=';
847 break;
848 }
849
850 if (outptr < outend)
851 {
852 if (inlen > 1)
853 *outptr ++ = base64[(((in[0] & 255) << 2) | ((in[1] & 255) >> 6)) & 63];
854 else
855 *outptr ++ = base64[((in[0] & 255) << 2) & 63];
856 }
857
858 in ++;
859 inlen --;
860 if (inlen <= 0)
861 {
862 if (outptr < outend)
863 *outptr ++ = '=';
864 break;
865 }
866
867 if (outptr < outend)
868 *outptr ++ = base64[in[0] & 63];
869 }
870
871 *outptr = '\0';
872
873 /*
874 * Return the encoded string...
875 */
876
877 return (out);
878 }
879
880
881 /*
882 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
883 *
884 * @deprecated@ @exclude all@
885 */
886
887 const char * /* O - Date/time string */
888 httpGetDateString(time_t t) /* I - Time in seconds */
889 {
890 _cups_globals_t *cg = _cupsGlobals(); /* Pointer to library globals */
891
892
893 return (httpGetDateString2(t, cg->http_date, sizeof(cg->http_date)));
894 }
895
896
897 /*
898 * 'httpGetDateString2()' - Get a formatted date/time string from a time value.
899 *
900 * @since CUPS 1.2/macOS 10.5@
901 */
902
903 const char * /* O - Date/time string */
904 httpGetDateString2(time_t t, /* I - Time in seconds */
905 char *s, /* I - String buffer */
906 int slen) /* I - Size of string buffer */
907 {
908 struct tm *tdate; /* UNIX date/time data */
909
910
911 tdate = gmtime(&t);
912 if (tdate)
913 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);
914 else
915 s[0] = '\0';
916
917 return (s);
918 }
919
920
921 /*
922 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
923 */
924
925 time_t /* O - Time in seconds */
926 httpGetDateTime(const char *s) /* I - Date/time string */
927 {
928 int i; /* Looping var */
929 char mon[16]; /* Abbreviated month name */
930 int day, year; /* Day of month and year */
931 int hour, min, sec; /* Time */
932 int days; /* Number of days since 1970 */
933 static const int normal_days[] = /* Days to a month, normal years */
934 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
935 static const int leap_days[] = /* Days to a month, leap years */
936 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 };
937
938
939 DEBUG_printf(("2httpGetDateTime(s=\"%s\")", s));
940
941 /*
942 * Extract the date and time from the formatted string...
943 */
944
945 if (sscanf(s, "%*s%d%15s%d%d:%d:%d", &day, mon, &year, &hour, &min, &sec) < 6)
946 return (0);
947
948 DEBUG_printf(("4httpGetDateTime: day=%d, mon=\"%s\", year=%d, hour=%d, "
949 "min=%d, sec=%d", day, mon, year, hour, min, sec));
950
951 /*
952 * Convert the month name to a number from 0 to 11.
953 */
954
955 for (i = 0; i < 12; i ++)
956 if (!_cups_strcasecmp(mon, http_months[i]))
957 break;
958
959 if (i >= 12)
960 return (0);
961
962 DEBUG_printf(("4httpGetDateTime: i=%d", i));
963
964 /*
965 * Now convert the date and time to a UNIX time value in seconds since
966 * 1970. We can't use mktime() since the timezone may not be UTC but
967 * the date/time string *is* UTC.
968 */
969
970 if ((year & 3) == 0 && ((year % 100) != 0 || (year % 400) == 0))
971 days = leap_days[i] + day - 1;
972 else
973 days = normal_days[i] + day - 1;
974
975 DEBUG_printf(("4httpGetDateTime: days=%d", days));
976
977 days += (year - 1970) * 365 + /* 365 days per year (normally) */
978 ((year - 1) / 4 - 492) - /* + leap days */
979 ((year - 1) / 100 - 19) + /* - 100 year days */
980 ((year - 1) / 400 - 4); /* + 400 year days */
981
982 DEBUG_printf(("4httpGetDateTime: days=%d\n", days));
983
984 return (days * 86400 + hour * 3600 + min * 60 + sec);
985 }
986
987
988 /*
989 * 'httpSeparate()' - Separate a Universal Resource Identifier into its
990 * components.
991 *
992 * This function is deprecated; use the httpSeparateURI() function instead.
993 *
994 * @deprecated@ @exclude all@
995 */
996
997 void
998 httpSeparate(const char *uri, /* I - Universal Resource Identifier */
999 char *scheme, /* O - Scheme [32] (http, https, etc.) */
1000 char *username, /* O - Username [1024] */
1001 char *host, /* O - Hostname [1024] */
1002 int *port, /* O - Port number to use */
1003 char *resource) /* O - Resource/filename [1024] */
1004 {
1005 httpSeparateURI(HTTP_URI_CODING_ALL, uri, scheme, 32, username,
1006 HTTP_MAX_URI, host, HTTP_MAX_URI, port, resource,
1007 HTTP_MAX_URI);
1008 }
1009
1010
1011 /*
1012 * 'httpSeparate2()' - Separate a Universal Resource Identifier into its
1013 * components.
1014 *
1015 * This function is deprecated; use the httpSeparateURI() function instead.
1016 *
1017 * @since CUPS 1.1.21/macOS 10.4@
1018 * @deprecated@ @exclude all@
1019 */
1020
1021 void
1022 httpSeparate2(const char *uri, /* I - Universal Resource Identifier */
1023 char *scheme, /* O - Scheme (http, https, etc.) */
1024 int schemelen, /* I - Size of scheme buffer */
1025 char *username, /* O - Username */
1026 int usernamelen, /* I - Size of username buffer */
1027 char *host, /* O - Hostname */
1028 int hostlen, /* I - Size of hostname buffer */
1029 int *port, /* O - Port number to use */
1030 char *resource, /* O - Resource/filename */
1031 int resourcelen) /* I - Size of resource buffer */
1032 {
1033 httpSeparateURI(HTTP_URI_CODING_ALL, uri, scheme, schemelen, username,
1034 usernamelen, host, hostlen, port, resource, resourcelen);
1035 }
1036
1037
1038 /*
1039 * 'httpSeparateURI()' - Separate a Universal Resource Identifier into its
1040 * components.
1041 *
1042 * @since CUPS 1.2/macOS 10.5@
1043 */
1044
1045 http_uri_status_t /* O - Result of separation */
1046 httpSeparateURI(
1047 http_uri_coding_t decoding, /* I - Decoding flags */
1048 const char *uri, /* I - Universal Resource Identifier */
1049 char *scheme, /* O - Scheme (http, https, etc.) */
1050 int schemelen, /* I - Size of scheme buffer */
1051 char *username, /* O - Username */
1052 int usernamelen, /* I - Size of username buffer */
1053 char *host, /* O - Hostname */
1054 int hostlen, /* I - Size of hostname buffer */
1055 int *port, /* O - Port number to use */
1056 char *resource, /* O - Resource/filename */
1057 int resourcelen) /* I - Size of resource buffer */
1058 {
1059 char *ptr, /* Pointer into string... */
1060 *end; /* End of string */
1061 const char *sep; /* Separator character */
1062 http_uri_status_t status; /* Result of separation */
1063
1064
1065 /*
1066 * Initialize everything to blank...
1067 */
1068
1069 if (scheme && schemelen > 0)
1070 *scheme = '\0';
1071
1072 if (username && usernamelen > 0)
1073 *username = '\0';
1074
1075 if (host && hostlen > 0)
1076 *host = '\0';
1077
1078 if (port)
1079 *port = 0;
1080
1081 if (resource && resourcelen > 0)
1082 *resource = '\0';
1083
1084 /*
1085 * Range check input...
1086 */
1087
1088 if (!uri || !port || !scheme || schemelen <= 0 || !username ||
1089 usernamelen <= 0 || !host || hostlen <= 0 || !resource ||
1090 resourcelen <= 0)
1091 return (HTTP_URI_STATUS_BAD_ARGUMENTS);
1092
1093 if (!*uri)
1094 return (HTTP_URI_STATUS_BAD_URI);
1095
1096 /*
1097 * Grab the scheme portion of the URI...
1098 */
1099
1100 status = HTTP_URI_STATUS_OK;
1101
1102 if (!strncmp(uri, "//", 2))
1103 {
1104 /*
1105 * Workaround for HP IPP client bug...
1106 */
1107
1108 strlcpy(scheme, "ipp", (size_t)schemelen);
1109 status = HTTP_URI_STATUS_MISSING_SCHEME;
1110 }
1111 else if (*uri == '/')
1112 {
1113 /*
1114 * Filename...
1115 */
1116
1117 strlcpy(scheme, "file", (size_t)schemelen);
1118 status = HTTP_URI_STATUS_MISSING_SCHEME;
1119 }
1120 else
1121 {
1122 /*
1123 * Standard URI with scheme...
1124 */
1125
1126 for (ptr = scheme, end = scheme + schemelen - 1;
1127 *uri && *uri != ':' && ptr < end;)
1128 if (strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1129 "abcdefghijklmnopqrstuvwxyz"
1130 "0123456789-+.", *uri) != NULL)
1131 *ptr++ = *uri++;
1132 else
1133 break;
1134
1135 *ptr = '\0';
1136
1137 if (*uri != ':' || *scheme == '.' || !*scheme)
1138 {
1139 *scheme = '\0';
1140 return (HTTP_URI_STATUS_BAD_SCHEME);
1141 }
1142
1143 uri ++;
1144 }
1145
1146 /*
1147 * Set the default port number...
1148 */
1149
1150 if (!strcmp(scheme, "http"))
1151 *port = 80;
1152 else if (!strcmp(scheme, "https"))
1153 *port = 443;
1154 else if (!strcmp(scheme, "ipp") || !strcmp(scheme, "ipps"))
1155 *port = 631;
1156 else if (!_cups_strcasecmp(scheme, "lpd"))
1157 *port = 515;
1158 else if (!strcmp(scheme, "socket")) /* Not yet registered with IANA... */
1159 *port = 9100;
1160 else if (strcmp(scheme, "file") && strcmp(scheme, "mailto") && strcmp(scheme, "tel"))
1161 status = HTTP_URI_STATUS_UNKNOWN_SCHEME;
1162
1163 /*
1164 * Now see if we have a hostname...
1165 */
1166
1167 if (!strncmp(uri, "//", 2))
1168 {
1169 /*
1170 * Yes, extract it...
1171 */
1172
1173 uri += 2;
1174
1175 /*
1176 * Grab the username, if any...
1177 */
1178
1179 if ((sep = strpbrk(uri, "@/")) != NULL && *sep == '@')
1180 {
1181 /*
1182 * Get a username:password combo...
1183 */
1184
1185 uri = http_copy_decode(username, uri, usernamelen, "@",
1186 decoding & HTTP_URI_CODING_USERNAME);
1187
1188 if (!uri)
1189 {
1190 *username = '\0';
1191 return (HTTP_URI_STATUS_BAD_USERNAME);
1192 }
1193
1194 uri ++;
1195 }
1196
1197 /*
1198 * Then the hostname/IP address...
1199 */
1200
1201 if (*uri == '[')
1202 {
1203 /*
1204 * Grab IPv6 address...
1205 */
1206
1207 uri ++;
1208 if (*uri == 'v')
1209 {
1210 /*
1211 * Skip IPvFuture ("vXXXX.") prefix...
1212 */
1213
1214 uri ++;
1215
1216 while (isxdigit(*uri & 255))
1217 uri ++;
1218
1219 if (*uri != '.')
1220 {
1221 *host = '\0';
1222 return (HTTP_URI_STATUS_BAD_HOSTNAME);
1223 }
1224
1225 uri ++;
1226 }
1227
1228 uri = http_copy_decode(host, uri, hostlen, "]",
1229 decoding & HTTP_URI_CODING_HOSTNAME);
1230
1231 if (!uri)
1232 {
1233 *host = '\0';
1234 return (HTTP_URI_STATUS_BAD_HOSTNAME);
1235 }
1236
1237 /*
1238 * Validate value...
1239 */
1240
1241 if (*uri != ']')
1242 {
1243 *host = '\0';
1244 return (HTTP_URI_STATUS_BAD_HOSTNAME);
1245 }
1246
1247 uri ++;
1248
1249 for (ptr = host; *ptr; ptr ++)
1250 if (*ptr == '+')
1251 {
1252 /*
1253 * Convert zone separator to % and stop here...
1254 */
1255
1256 *ptr = '%';
1257 break;
1258 }
1259 else if (*ptr == '%')
1260 {
1261 /*
1262 * Stop at zone separator (RFC 6874)
1263 */
1264
1265 break;
1266 }
1267 else if (*ptr != ':' && *ptr != '.' && !isxdigit(*ptr & 255))
1268 {
1269 *host = '\0';
1270 return (HTTP_URI_STATUS_BAD_HOSTNAME);
1271 }
1272 }
1273 else
1274 {
1275 /*
1276 * Validate the hostname or IPv4 address first...
1277 */
1278
1279 for (ptr = (char *)uri; *ptr; ptr ++)
1280 if (strchr(":?/", *ptr))
1281 break;
1282 else if (!strchr("abcdefghijklmnopqrstuvwxyz" /* unreserved */
1283 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" /* unreserved */
1284 "0123456789" /* unreserved */
1285 "-._~" /* unreserved */
1286 "%" /* pct-encoded */
1287 "!$&'()*+,;=" /* sub-delims */
1288 "\\", *ptr)) /* SMB domain */
1289 {
1290 *host = '\0';
1291 return (HTTP_URI_STATUS_BAD_HOSTNAME);
1292 }
1293
1294 /*
1295 * Then copy the hostname or IPv4 address to the buffer...
1296 */
1297
1298 uri = http_copy_decode(host, uri, hostlen, ":?/",
1299 decoding & HTTP_URI_CODING_HOSTNAME);
1300
1301 if (!uri)
1302 {
1303 *host = '\0';
1304 return (HTTP_URI_STATUS_BAD_HOSTNAME);
1305 }
1306 }
1307
1308 /*
1309 * Validate hostname for file scheme - only empty and localhost are
1310 * acceptable.
1311 */
1312
1313 if (!strcmp(scheme, "file") && strcmp(host, "localhost") && host[0])
1314 {
1315 *host = '\0';
1316 return (HTTP_URI_STATUS_BAD_HOSTNAME);
1317 }
1318
1319 /*
1320 * See if we have a port number...
1321 */
1322
1323 if (*uri == ':')
1324 {
1325 /*
1326 * Yes, collect the port number...
1327 */
1328
1329 if (!isdigit(uri[1] & 255))
1330 {
1331 *port = 0;
1332 return (HTTP_URI_STATUS_BAD_PORT);
1333 }
1334
1335 *port = (int)strtol(uri + 1, (char **)&uri, 10);
1336
1337 if (*port <= 0 || *port > 65535)
1338 {
1339 *port = 0;
1340 return (HTTP_URI_STATUS_BAD_PORT);
1341 }
1342
1343 if (*uri != '/' && *uri)
1344 {
1345 *port = 0;
1346 return (HTTP_URI_STATUS_BAD_PORT);
1347 }
1348 }
1349 }
1350
1351 /*
1352 * The remaining portion is the resource string...
1353 */
1354
1355 if (*uri == '?' || !*uri)
1356 {
1357 /*
1358 * Hostname but no path...
1359 */
1360
1361 status = HTTP_URI_STATUS_MISSING_RESOURCE;
1362 *resource = '/';
1363
1364 /*
1365 * Copy any query string...
1366 */
1367
1368 if (*uri == '?')
1369 uri = http_copy_decode(resource + 1, uri, resourcelen - 1, NULL,
1370 decoding & HTTP_URI_CODING_QUERY);
1371 else
1372 resource[1] = '\0';
1373 }
1374 else
1375 {
1376 uri = http_copy_decode(resource, uri, resourcelen, "?",
1377 decoding & HTTP_URI_CODING_RESOURCE);
1378
1379 if (uri && *uri == '?')
1380 {
1381 /*
1382 * Concatenate any query string...
1383 */
1384
1385 char *resptr = resource + strlen(resource);
1386
1387 uri = http_copy_decode(resptr, uri,
1388 resourcelen - (int)(resptr - resource), NULL,
1389 decoding & HTTP_URI_CODING_QUERY);
1390 }
1391 }
1392
1393 if (!uri)
1394 {
1395 *resource = '\0';
1396 return (HTTP_URI_STATUS_BAD_RESOURCE);
1397 }
1398
1399 /*
1400 * Return the URI separation status...
1401 */
1402
1403 return (status);
1404 }
1405
1406
1407 /*
1408 * 'httpStateString()' - Return the string describing a HTTP state value.
1409 *
1410 * @since CUPS 2.0/OS 10.10@
1411 */
1412
1413 const char * /* O - State string */
1414 httpStateString(http_state_t state) /* I - HTTP state value */
1415 {
1416 if (state < HTTP_STATE_ERROR || state > HTTP_STATE_UNKNOWN_VERSION)
1417 return ("HTTP_STATE_???");
1418 else
1419 return (http_states[state - HTTP_STATE_ERROR]);
1420 }
1421
1422
1423 /*
1424 * '_httpStatus()' - Return the localized string describing a HTTP status code.
1425 *
1426 * The returned string is localized using the passed message catalog.
1427 */
1428
1429 const char * /* O - Localized status string */
1430 _httpStatus(cups_lang_t *lang, /* I - Language */
1431 http_status_t status) /* I - HTTP status code */
1432 {
1433 const char *s; /* Status string */
1434
1435
1436 switch (status)
1437 {
1438 case HTTP_STATUS_ERROR :
1439 s = strerror(errno);
1440 break;
1441 case HTTP_STATUS_CONTINUE :
1442 s = _("Continue");
1443 break;
1444 case HTTP_STATUS_SWITCHING_PROTOCOLS :
1445 s = _("Switching Protocols");
1446 break;
1447 case HTTP_STATUS_OK :
1448 s = _("OK");
1449 break;
1450 case HTTP_STATUS_CREATED :
1451 s = _("Created");
1452 break;
1453 case HTTP_STATUS_ACCEPTED :
1454 s = _("Accepted");
1455 break;
1456 case HTTP_STATUS_NO_CONTENT :
1457 s = _("No Content");
1458 break;
1459 case HTTP_STATUS_MOVED_PERMANENTLY :
1460 s = _("Moved Permanently");
1461 break;
1462 case HTTP_STATUS_FOUND :
1463 s = _("Found");
1464 break;
1465 case HTTP_STATUS_SEE_OTHER :
1466 s = _("See Other");
1467 break;
1468 case HTTP_STATUS_NOT_MODIFIED :
1469 s = _("Not Modified");
1470 break;
1471 case HTTP_STATUS_BAD_REQUEST :
1472 s = _("Bad Request");
1473 break;
1474 case HTTP_STATUS_UNAUTHORIZED :
1475 case HTTP_STATUS_CUPS_AUTHORIZATION_CANCELED :
1476 s = _("Unauthorized");
1477 break;
1478 case HTTP_STATUS_FORBIDDEN :
1479 s = _("Forbidden");
1480 break;
1481 case HTTP_STATUS_NOT_FOUND :
1482 s = _("Not Found");
1483 break;
1484 case HTTP_STATUS_REQUEST_TOO_LARGE :
1485 s = _("Request Entity Too Large");
1486 break;
1487 case HTTP_STATUS_URI_TOO_LONG :
1488 s = _("URI Too Long");
1489 break;
1490 case HTTP_STATUS_UPGRADE_REQUIRED :
1491 s = _("Upgrade Required");
1492 break;
1493 case HTTP_STATUS_NOT_IMPLEMENTED :
1494 s = _("Not Implemented");
1495 break;
1496 case HTTP_STATUS_NOT_SUPPORTED :
1497 s = _("Not Supported");
1498 break;
1499 case HTTP_STATUS_EXPECTATION_FAILED :
1500 s = _("Expectation Failed");
1501 break;
1502 case HTTP_STATUS_SERVICE_UNAVAILABLE :
1503 s = _("Service Unavailable");
1504 break;
1505 case HTTP_STATUS_SERVER_ERROR :
1506 s = _("Internal Server Error");
1507 break;
1508 case HTTP_STATUS_CUPS_PKI_ERROR :
1509 s = _("SSL/TLS Negotiation Error");
1510 break;
1511 case HTTP_STATUS_CUPS_WEBIF_DISABLED :
1512 s = _("Web Interface is Disabled");
1513 break;
1514
1515 default :
1516 s = _("Unknown");
1517 break;
1518 }
1519
1520 return (_cupsLangString(lang, s));
1521 }
1522
1523
1524 /*
1525 * 'httpStatus()' - Return a short string describing a HTTP status code.
1526 *
1527 * The returned string is localized to the current POSIX locale and is based
1528 * on the status strings defined in RFC 7231.
1529 */
1530
1531 const char * /* O - Localized status string */
1532 httpStatus(http_status_t status) /* I - HTTP status code */
1533 {
1534 _cups_globals_t *cg = _cupsGlobals(); /* Global data */
1535
1536
1537 if (!cg->lang_default)
1538 cg->lang_default = cupsLangDefault();
1539
1540 return (_httpStatus(cg->lang_default, status));
1541 }
1542
1543 /*
1544 * 'httpURIStatusString()' - Return a string describing a URI status code.
1545 *
1546 * @since CUPS 2.0/OS 10.10@
1547 */
1548
1549 const char * /* O - Localized status string */
1550 httpURIStatusString(
1551 http_uri_status_t status) /* I - URI status code */
1552 {
1553 const char *s; /* Status string */
1554 _cups_globals_t *cg = _cupsGlobals(); /* Global data */
1555
1556
1557 if (!cg->lang_default)
1558 cg->lang_default = cupsLangDefault();
1559
1560 switch (status)
1561 {
1562 case HTTP_URI_STATUS_OVERFLOW :
1563 s = _("URI too large");
1564 break;
1565 case HTTP_URI_STATUS_BAD_ARGUMENTS :
1566 s = _("Bad arguments to function");
1567 break;
1568 case HTTP_URI_STATUS_BAD_RESOURCE :
1569 s = _("Bad resource in URI");
1570 break;
1571 case HTTP_URI_STATUS_BAD_PORT :
1572 s = _("Bad port number in URI");
1573 break;
1574 case HTTP_URI_STATUS_BAD_HOSTNAME :
1575 s = _("Bad hostname/address in URI");
1576 break;
1577 case HTTP_URI_STATUS_BAD_USERNAME :
1578 s = _("Bad username in URI");
1579 break;
1580 case HTTP_URI_STATUS_BAD_SCHEME :
1581 s = _("Bad scheme in URI");
1582 break;
1583 case HTTP_URI_STATUS_BAD_URI :
1584 s = _("Bad/empty URI");
1585 break;
1586 case HTTP_URI_STATUS_OK :
1587 s = _("OK");
1588 break;
1589 case HTTP_URI_STATUS_MISSING_SCHEME :
1590 s = _("Missing scheme in URI");
1591 break;
1592 case HTTP_URI_STATUS_UNKNOWN_SCHEME :
1593 s = _("Unknown scheme in URI");
1594 break;
1595 case HTTP_URI_STATUS_MISSING_RESOURCE :
1596 s = _("Missing resource in URI");
1597 break;
1598
1599 default:
1600 s = _("Unknown");
1601 break;
1602 }
1603
1604 return (_cupsLangString(cg->lang_default, s));
1605 }
1606
1607
1608 #ifndef HAVE_HSTRERROR
1609 /*
1610 * '_cups_hstrerror()' - hstrerror() emulation function for Solaris and others.
1611 */
1612
1613 const char * /* O - Error string */
1614 _cups_hstrerror(int error) /* I - Error number */
1615 {
1616 static const char * const errors[] = /* Error strings */
1617 {
1618 "OK",
1619 "Host not found.",
1620 "Try again.",
1621 "Unrecoverable lookup error.",
1622 "No data associated with name."
1623 };
1624
1625
1626 if (error < 0 || error > 4)
1627 return ("Unknown hostname lookup error.");
1628 else
1629 return (errors[error]);
1630 }
1631 #endif /* !HAVE_HSTRERROR */
1632
1633
1634 /*
1635 * '_httpDecodeURI()' - Percent-decode a HTTP request URI.
1636 */
1637
1638 char * /* O - Decoded URI or NULL on error */
1639 _httpDecodeURI(char *dst, /* I - Destination buffer */
1640 const char *src, /* I - Source URI */
1641 size_t dstsize) /* I - Size of destination buffer */
1642 {
1643 if (http_copy_decode(dst, src, (int)dstsize, NULL, 1))
1644 return (dst);
1645 else
1646 return (NULL);
1647 }
1648
1649
1650 /*
1651 * '_httpEncodeURI()' - Percent-encode a HTTP request URI.
1652 */
1653
1654 char * /* O - Encoded URI */
1655 _httpEncodeURI(char *dst, /* I - Destination buffer */
1656 const char *src, /* I - Source URI */
1657 size_t dstsize) /* I - Size of destination buffer */
1658 {
1659 http_copy_encode(dst, src, dst + dstsize - 1, NULL, NULL, 1);
1660 return (dst);
1661 }
1662
1663
1664 /*
1665 * '_httpResolveURI()' - Resolve a DNS-SD URI.
1666 */
1667
1668 const char * /* O - Resolved URI */
1669 _httpResolveURI(
1670 const char *uri, /* I - DNS-SD URI */
1671 char *resolved_uri, /* I - Buffer for resolved URI */
1672 size_t resolved_size, /* I - Size of URI buffer */
1673 int options, /* I - Resolve options */
1674 int (*cb)(void *context), /* I - Continue callback function */
1675 void *context) /* I - Context pointer for callback */
1676 {
1677 char scheme[32], /* URI components... */
1678 userpass[256],
1679 hostname[1024],
1680 resource[1024];
1681 int port;
1682 #ifdef DEBUG
1683 http_uri_status_t status; /* URI decode status */
1684 #endif /* DEBUG */
1685
1686
1687 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));
1688
1689 /*
1690 * Get the device URI...
1691 */
1692
1693 #ifdef DEBUG
1694 if ((status = httpSeparateURI(HTTP_URI_CODING_ALL, uri, scheme,
1695 sizeof(scheme), userpass, sizeof(userpass),
1696 hostname, sizeof(hostname), &port, resource,
1697 sizeof(resource))) < HTTP_URI_STATUS_OK)
1698 #else
1699 if (httpSeparateURI(HTTP_URI_CODING_ALL, uri, scheme,
1700 sizeof(scheme), userpass, sizeof(userpass),
1701 hostname, sizeof(hostname), &port, resource,
1702 sizeof(resource)) < HTTP_URI_STATUS_OK)
1703 #endif /* DEBUG */
1704 {
1705 if (options & _HTTP_RESOLVE_STDERR)
1706 _cupsLangPrintFilter(stderr, "ERROR", _("Bad device-uri \"%s\"."), uri);
1707
1708 DEBUG_printf(("2_httpResolveURI: httpSeparateURI returned %d!", status));
1709 DEBUG_puts("2_httpResolveURI: Returning NULL");
1710 return (NULL);
1711 }
1712
1713 /*
1714 * Resolve it as needed...
1715 */
1716
1717 if (strstr(hostname, "._tcp"))
1718 {
1719 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
1720 char *regtype, /* Pointer to type in hostname */
1721 *domain, /* Pointer to domain in hostname */
1722 *uuid, /* Pointer to UUID in URI */
1723 *uuidend; /* Pointer to end of UUID in URI */
1724 _http_uribuf_t uribuf; /* URI buffer */
1725 int offline = 0; /* offline-report state set? */
1726 # ifdef HAVE_DNSSD
1727 # ifdef WIN32
1728 # pragma comment(lib, "dnssd.lib")
1729 # endif /* WIN32 */
1730 DNSServiceRef ref, /* DNS-SD master service reference */
1731 domainref = NULL,/* DNS-SD service reference for domain */
1732 ippref = NULL, /* DNS-SD service reference for network IPP */
1733 ippsref = NULL, /* DNS-SD service reference for network IPPS */
1734 localref; /* DNS-SD service reference for .local */
1735 int extrasent = 0; /* Send the domain/IPP/IPPS resolves? */
1736 # ifdef HAVE_POLL
1737 struct pollfd polldata; /* Polling data */
1738 # else /* select() */
1739 fd_set input_set; /* Input set for select() */
1740 struct timeval stimeout; /* Timeout value for select() */
1741 # endif /* HAVE_POLL */
1742 # elif defined(HAVE_AVAHI)
1743 AvahiClient *client; /* Client information */
1744 int error; /* Status */
1745 # endif /* HAVE_DNSSD */
1746
1747 if (options & _HTTP_RESOLVE_STDERR)
1748 fprintf(stderr, "DEBUG: Resolving \"%s\"...\n", hostname);
1749
1750 /*
1751 * Separate the hostname into service name, registration type, and domain...
1752 */
1753
1754 for (regtype = strstr(hostname, "._tcp") - 2;
1755 regtype > hostname;
1756 regtype --)
1757 if (regtype[0] == '.' && regtype[1] == '_')
1758 {
1759 /*
1760 * Found ._servicetype in front of ._tcp...
1761 */
1762
1763 *regtype++ = '\0';
1764 break;
1765 }
1766
1767 if (regtype <= hostname)
1768 {
1769 DEBUG_puts("2_httpResolveURI: Bad hostname, returning NULL");
1770 return (NULL);
1771 }
1772
1773 for (domain = strchr(regtype, '.');
1774 domain;
1775 domain = strchr(domain + 1, '.'))
1776 if (domain[1] != '_')
1777 break;
1778
1779 if (domain)
1780 *domain++ = '\0';
1781
1782 if ((uuid = strstr(resource, "?uuid=")) != NULL)
1783 {
1784 *uuid = '\0';
1785 uuid += 6;
1786 if ((uuidend = strchr(uuid, '&')) != NULL)
1787 *uuidend = '\0';
1788 }
1789
1790 resolved_uri[0] = '\0';
1791
1792 uribuf.buffer = resolved_uri;
1793 uribuf.bufsize = resolved_size;
1794 uribuf.options = options;
1795 uribuf.resource = resource;
1796 uribuf.uuid = uuid;
1797
1798 DEBUG_printf(("2_httpResolveURI: Resolving hostname=\"%s\", regtype=\"%s\", "
1799 "domain=\"%s\"\n", hostname, regtype, domain));
1800 if (options & _HTTP_RESOLVE_STDERR)
1801 {
1802 fputs("STATE: +connecting-to-device\n", stderr);
1803 fprintf(stderr, "DEBUG: Resolving \"%s\", regtype=\"%s\", "
1804 "domain=\"local.\"...\n", hostname, regtype);
1805 }
1806
1807 uri = NULL;
1808
1809 # ifdef HAVE_DNSSD
1810 if (DNSServiceCreateConnection(&ref) == kDNSServiceErr_NoError)
1811 {
1812 uint32_t myinterface = kDNSServiceInterfaceIndexAny;
1813 /* Lookup on any interface */
1814
1815 if (!strcmp(scheme, "ippusb"))
1816 myinterface = kDNSServiceInterfaceIndexLocalOnly;
1817
1818 localref = ref;
1819 if (DNSServiceResolve(&localref,
1820 kDNSServiceFlagsShareConnection, myinterface,
1821 hostname, regtype, "local.", http_resolve_cb,
1822 &uribuf) == kDNSServiceErr_NoError)
1823 {
1824 int fds; /* Number of ready descriptors */
1825 time_t timeout, /* Poll timeout */
1826 start_time = time(NULL),/* Start time */
1827 end_time = start_time + 90;
1828 /* End time */
1829
1830 while (time(NULL) < end_time)
1831 {
1832 if (options & _HTTP_RESOLVE_STDERR)
1833 _cupsLangPrintFilter(stderr, "INFO", _("Looking for printer."));
1834
1835 if (cb && !(*cb)(context))
1836 {
1837 DEBUG_puts("2_httpResolveURI: callback returned 0 (stop)");
1838 break;
1839 }
1840
1841 /*
1842 * Wakeup every 2 seconds to emit a "looking for printer" message...
1843 */
1844
1845 if ((timeout = end_time - time(NULL)) > 2)
1846 timeout = 2;
1847
1848 # ifdef HAVE_POLL
1849 polldata.fd = DNSServiceRefSockFD(ref);
1850 polldata.events = POLLIN;
1851
1852 fds = poll(&polldata, 1, (int)(1000 * timeout));
1853
1854 # else /* select() */
1855 FD_ZERO(&input_set);
1856 FD_SET(DNSServiceRefSockFD(ref), &input_set);
1857
1858 # ifdef WIN32
1859 stimeout.tv_sec = (long)timeout;
1860 # else
1861 stimeout.tv_sec = timeout;
1862 # endif /* WIN32 */
1863 stimeout.tv_usec = 0;
1864
1865 fds = select(DNSServiceRefSockFD(ref)+1, &input_set, NULL, NULL,
1866 &stimeout);
1867 # endif /* HAVE_POLL */
1868
1869 if (fds < 0)
1870 {
1871 if (errno != EINTR && errno != EAGAIN)
1872 {
1873 DEBUG_printf(("2_httpResolveURI: poll error: %s", strerror(errno)));
1874 break;
1875 }
1876 }
1877 else if (fds == 0)
1878 {
1879 /*
1880 * Wait 2 seconds for a response to the local resolve; if nothing
1881 * comes in, do an additional domain resolution...
1882 */
1883
1884 if (extrasent == 0 && domain && _cups_strcasecmp(domain, "local."))
1885 {
1886 if (options & _HTTP_RESOLVE_STDERR)
1887 fprintf(stderr,
1888 "DEBUG: Resolving \"%s\", regtype=\"%s\", "
1889 "domain=\"%s\"...\n", hostname, regtype,
1890 domain ? domain : "");
1891
1892 domainref = ref;
1893 if (DNSServiceResolve(&domainref,
1894 kDNSServiceFlagsShareConnection,
1895 myinterface, hostname, regtype, domain,
1896 http_resolve_cb,
1897 &uribuf) == kDNSServiceErr_NoError)
1898 extrasent = 1;
1899 }
1900 else if (extrasent == 0 && !strcmp(scheme, "ippusb"))
1901 {
1902 if (options & _HTTP_RESOLVE_STDERR)
1903 fprintf(stderr, "DEBUG: Resolving \"%s\", regtype=\"_ipps._tcp\", domain=\"local.\"...\n", hostname);
1904
1905 ippsref = ref;
1906 if (DNSServiceResolve(&ippsref,
1907 kDNSServiceFlagsShareConnection,
1908 kDNSServiceInterfaceIndexAny, hostname,
1909 "_ipps._tcp", domain, http_resolve_cb,
1910 &uribuf) == kDNSServiceErr_NoError)
1911 extrasent = 1;
1912 }
1913 else if (extrasent == 1 && !strcmp(scheme, "ippusb"))
1914 {
1915 if (options & _HTTP_RESOLVE_STDERR)
1916 fprintf(stderr, "DEBUG: Resolving \"%s\", regtype=\"_ipp._tcp\", domain=\"local.\"...\n", hostname);
1917
1918 ippref = ref;
1919 if (DNSServiceResolve(&ippref,
1920 kDNSServiceFlagsShareConnection,
1921 kDNSServiceInterfaceIndexAny, hostname,
1922 "_ipp._tcp", domain, http_resolve_cb,
1923 &uribuf) == kDNSServiceErr_NoError)
1924 extrasent = 2;
1925 }
1926
1927 /*
1928 * If it hasn't resolved within 5 seconds set the offline-report
1929 * printer-state-reason...
1930 */
1931
1932 if ((options & _HTTP_RESOLVE_STDERR) && offline == 0 &&
1933 time(NULL) > (start_time + 5))
1934 {
1935 fputs("STATE: +offline-report\n", stderr);
1936 offline = 1;
1937 }
1938 }
1939 else
1940 {
1941 if (DNSServiceProcessResult(ref) == kDNSServiceErr_NoError &&
1942 resolved_uri[0])
1943 {
1944 uri = resolved_uri;
1945 break;
1946 }
1947 }
1948 }
1949
1950 if (extrasent)
1951 {
1952 if (domainref)
1953 DNSServiceRefDeallocate(domainref);
1954 if (ippref)
1955 DNSServiceRefDeallocate(ippref);
1956 if (ippsref)
1957 DNSServiceRefDeallocate(ippsref);
1958 }
1959
1960 DNSServiceRefDeallocate(localref);
1961 }
1962
1963 DNSServiceRefDeallocate(ref);
1964 }
1965 # else /* HAVE_AVAHI */
1966 if ((uribuf.poll = avahi_simple_poll_new()) != NULL)
1967 {
1968 avahi_simple_poll_set_func(uribuf.poll, http_poll_cb, NULL);
1969
1970 if ((client = avahi_client_new(avahi_simple_poll_get(uribuf.poll),
1971 0, http_client_cb,
1972 &uribuf, &error)) != NULL)
1973 {
1974 if (avahi_service_resolver_new(client, AVAHI_IF_UNSPEC,
1975 AVAHI_PROTO_UNSPEC, hostname,
1976 regtype, "local.", AVAHI_PROTO_UNSPEC, 0,
1977 http_resolve_cb, &uribuf) != NULL)
1978 {
1979 time_t start_time = time(NULL),
1980 /* Start time */
1981 end_time = start_time + 90;
1982 /* End time */
1983 int pstatus; /* Poll status */
1984
1985 pstatus = avahi_simple_poll_iterate(uribuf.poll, 2000);
1986
1987 if (pstatus == 0 && !resolved_uri[0] && domain &&
1988 _cups_strcasecmp(domain, "local."))
1989 {
1990 /*
1991 * Resolve for .local hasn't returned anything, try the listed
1992 * domain...
1993 */
1994
1995 avahi_service_resolver_new(client, AVAHI_IF_UNSPEC,
1996 AVAHI_PROTO_UNSPEC, hostname,
1997 regtype, domain, AVAHI_PROTO_UNSPEC, 0,
1998 http_resolve_cb, &uribuf);
1999 }
2000
2001 while (!pstatus && !resolved_uri[0] && time(NULL) < end_time)
2002 {
2003 if ((pstatus = avahi_simple_poll_iterate(uribuf.poll, 2000)) != 0)
2004 break;
2005
2006 /*
2007 * If it hasn't resolved within 5 seconds set the offline-report
2008 * printer-state-reason...
2009 */
2010
2011 if ((options & _HTTP_RESOLVE_STDERR) && offline == 0 &&
2012 time(NULL) > (start_time + 5))
2013 {
2014 fputs("STATE: +offline-report\n", stderr);
2015 offline = 1;
2016 }
2017 }
2018
2019 /*
2020 * Collect the result (if we got one).
2021 */
2022
2023 if (resolved_uri[0])
2024 uri = resolved_uri;
2025 }
2026
2027 avahi_client_free(client);
2028 }
2029
2030 avahi_simple_poll_free(uribuf.poll);
2031 }
2032 # endif /* HAVE_DNSSD */
2033
2034 if (options & _HTTP_RESOLVE_STDERR)
2035 {
2036 if (uri)
2037 {
2038 fprintf(stderr, "DEBUG: Resolved as \"%s\"...\n", uri);
2039 fputs("STATE: -connecting-to-device,offline-report\n", stderr);
2040 }
2041 else
2042 {
2043 fputs("DEBUG: Unable to resolve URI\n", stderr);
2044 fputs("STATE: -connecting-to-device\n", stderr);
2045 }
2046 }
2047
2048 #else /* HAVE_DNSSD || HAVE_AVAHI */
2049 /*
2050 * No DNS-SD support...
2051 */
2052
2053 uri = NULL;
2054 #endif /* HAVE_DNSSD || HAVE_AVAHI */
2055
2056 if ((options & _HTTP_RESOLVE_STDERR) && !uri)
2057 _cupsLangPrintFilter(stderr, "INFO", _("Unable to find printer."));
2058 }
2059 else
2060 {
2061 /*
2062 * Nothing more to do...
2063 */
2064
2065 strlcpy(resolved_uri, uri, resolved_size);
2066 uri = resolved_uri;
2067 }
2068
2069 DEBUG_printf(("2_httpResolveURI: Returning \"%s\"", uri));
2070
2071 return (uri);
2072 }
2073
2074
2075 #ifdef HAVE_AVAHI
2076 /*
2077 * 'http_client_cb()' - Client callback for resolving URI.
2078 */
2079
2080 static void
2081 http_client_cb(
2082 AvahiClient *client, /* I - Client information */
2083 AvahiClientState state, /* I - Current state */
2084 void *context) /* I - Pointer to URI buffer */
2085 {
2086 DEBUG_printf(("7http_client_cb(client=%p, state=%d, context=%p)", client,
2087 state, context));
2088
2089 /*
2090 * If the connection drops, quit.
2091 */
2092
2093 if (state == AVAHI_CLIENT_FAILURE)
2094 {
2095 _http_uribuf_t *uribuf = (_http_uribuf_t *)context;
2096 /* URI buffer */
2097
2098 avahi_simple_poll_quit(uribuf->poll);
2099 }
2100 }
2101 #endif /* HAVE_AVAHI */
2102
2103
2104 /*
2105 * 'http_copy_decode()' - Copy and decode a URI.
2106 */
2107
2108 static const char * /* O - New source pointer or NULL on error */
2109 http_copy_decode(char *dst, /* O - Destination buffer */
2110 const char *src, /* I - Source pointer */
2111 int dstsize, /* I - Destination size */
2112 const char *term, /* I - Terminating characters */
2113 int decode) /* I - Decode %-encoded values */
2114 {
2115 char *ptr, /* Pointer into buffer */
2116 *end; /* End of buffer */
2117 int quoted; /* Quoted character */
2118
2119
2120 /*
2121 * Copy the src to the destination until we hit a terminating character
2122 * or the end of the string.
2123 */
2124
2125 for (ptr = dst, end = dst + dstsize - 1;
2126 *src && (!term || !strchr(term, *src));
2127 src ++)
2128 if (ptr < end)
2129 {
2130 if (*src == '%' && decode)
2131 {
2132 if (isxdigit(src[1] & 255) && isxdigit(src[2] & 255))
2133 {
2134 /*
2135 * Grab a hex-encoded character...
2136 */
2137
2138 src ++;
2139 if (isalpha(*src))
2140 quoted = (tolower(*src) - 'a' + 10) << 4;
2141 else
2142 quoted = (*src - '0') << 4;
2143
2144 src ++;
2145 if (isalpha(*src))
2146 quoted |= tolower(*src) - 'a' + 10;
2147 else
2148 quoted |= *src - '0';
2149
2150 *ptr++ = (char)quoted;
2151 }
2152 else
2153 {
2154 /*
2155 * Bad hex-encoded character...
2156 */
2157
2158 *ptr = '\0';
2159 return (NULL);
2160 }
2161 }
2162 else if ((*src & 255) <= 0x20 || (*src & 255) >= 0x7f)
2163 {
2164 *ptr = '\0';
2165 return (NULL);
2166 }
2167 else
2168 *ptr++ = *src;
2169 }
2170
2171 *ptr = '\0';
2172
2173 return (src);
2174 }
2175
2176
2177 /*
2178 * 'http_copy_encode()' - Copy and encode a URI.
2179 */
2180
2181 static char * /* O - End of current URI */
2182 http_copy_encode(char *dst, /* O - Destination buffer */
2183 const char *src, /* I - Source pointer */
2184 char *dstend, /* I - End of destination buffer */
2185 const char *reserved, /* I - Extra reserved characters */
2186 const char *term, /* I - Terminating characters */
2187 int encode) /* I - %-encode reserved chars? */
2188 {
2189 static const char hex[] = "0123456789ABCDEF";
2190
2191
2192 while (*src && dst < dstend)
2193 {
2194 if (term && *src == *term)
2195 return (dst);
2196
2197 if (encode && (*src == '%' || *src <= ' ' || *src & 128 ||
2198 (reserved && strchr(reserved, *src))))
2199 {
2200 /*
2201 * Hex encode reserved characters...
2202 */
2203
2204 if ((dst + 2) >= dstend)
2205 break;
2206
2207 *dst++ = '%';
2208 *dst++ = hex[(*src >> 4) & 15];
2209 *dst++ = hex[*src & 15];
2210
2211 src ++;
2212 }
2213 else
2214 *dst++ = *src++;
2215 }
2216
2217 *dst = '\0';
2218
2219 if (*src)
2220 return (NULL);
2221 else
2222 return (dst);
2223 }
2224
2225
2226 #ifdef HAVE_DNSSD
2227 /*
2228 * 'http_resolve_cb()' - Build a device URI for the given service name.
2229 */
2230
2231 static void DNSSD_API
2232 http_resolve_cb(
2233 DNSServiceRef sdRef, /* I - Service reference */
2234 DNSServiceFlags flags, /* I - Results flags */
2235 uint32_t interfaceIndex, /* I - Interface number */
2236 DNSServiceErrorType errorCode, /* I - Error, if any */
2237 const char *fullName, /* I - Full service name */
2238 const char *hostTarget, /* I - Hostname */
2239 uint16_t port, /* I - Port number */
2240 uint16_t txtLen, /* I - Length of TXT record */
2241 const unsigned char *txtRecord, /* I - TXT record data */
2242 void *context) /* I - Pointer to URI buffer */
2243 {
2244 _http_uribuf_t *uribuf = (_http_uribuf_t *)context;
2245 /* URI buffer */
2246 const char *scheme, /* URI scheme */
2247 *hostptr, /* Pointer into hostTarget */
2248 *reskey, /* "rp" or "rfo" */
2249 *resdefault; /* Default path */
2250 char resource[257], /* Remote path */
2251 fqdn[256]; /* FQDN of the .local name */
2252 const void *value; /* Value from TXT record */
2253 uint8_t valueLen; /* Length of value */
2254
2255
2256 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));
2257
2258 /*
2259 * If we have a UUID, compare it...
2260 */
2261
2262 if (uribuf->uuid &&
2263 (value = TXTRecordGetValuePtr(txtLen, txtRecord, "UUID",
2264 &valueLen)) != NULL)
2265 {
2266 char uuid[256]; /* UUID value */
2267
2268 memcpy(uuid, value, valueLen);
2269 uuid[valueLen] = '\0';
2270
2271 if (_cups_strcasecmp(uuid, uribuf->uuid))
2272 {
2273 if (uribuf->options & _HTTP_RESOLVE_STDERR)
2274 fprintf(stderr, "DEBUG: Found UUID %s, looking for %s.", uuid,
2275 uribuf->uuid);
2276
2277 DEBUG_printf(("5http_resolve_cb: Found UUID %s, looking for %s.", uuid,
2278 uribuf->uuid));
2279 return;
2280 }
2281 }
2282
2283 /*
2284 * Figure out the scheme from the full name...
2285 */
2286
2287 if (strstr(fullName, "._ipps") || strstr(fullName, "._ipp-tls"))
2288 scheme = "ipps";
2289 else if (strstr(fullName, "._ipp") || strstr(fullName, "._fax-ipp"))
2290 scheme = "ipp";
2291 else if (strstr(fullName, "._http."))
2292 scheme = "http";
2293 else if (strstr(fullName, "._https."))
2294 scheme = "https";
2295 else if (strstr(fullName, "._printer."))
2296 scheme = "lpd";
2297 else if (strstr(fullName, "._pdl-datastream."))
2298 scheme = "socket";
2299 else
2300 scheme = "riousbprint";
2301
2302 /*
2303 * Extract the "remote printer" key from the TXT record...
2304 */
2305
2306 if ((uribuf->options & _HTTP_RESOLVE_FAXOUT) &&
2307 (!strcmp(scheme, "ipp") || !strcmp(scheme, "ipps")) &&
2308 !TXTRecordGetValuePtr(txtLen, txtRecord, "printer-type", &valueLen))
2309 {
2310 reskey = "rfo";
2311 resdefault = "/ipp/faxout";
2312 }
2313 else
2314 {
2315 reskey = "rp";
2316 resdefault = "/";
2317 }
2318
2319 if ((value = TXTRecordGetValuePtr(txtLen, txtRecord, reskey,
2320 &valueLen)) != NULL)
2321 {
2322 if (((char *)value)[0] == '/')
2323 {
2324 /*
2325 * Value (incorrectly) has a leading slash already...
2326 */
2327
2328 memcpy(resource, value, valueLen);
2329 resource[valueLen] = '\0';
2330 }
2331 else
2332 {
2333 /*
2334 * Convert to resource by concatenating with a leading "/"...
2335 */
2336
2337 resource[0] = '/';
2338 memcpy(resource + 1, value, valueLen);
2339 resource[valueLen + 1] = '\0';
2340 }
2341 }
2342 else
2343 {
2344 /*
2345 * Use the default value...
2346 */
2347
2348 strlcpy(resource, resdefault, sizeof(resource));
2349 }
2350
2351 /*
2352 * Lookup the FQDN if needed...
2353 */
2354
2355 if ((uribuf->options & _HTTP_RESOLVE_FQDN) &&
2356 (hostptr = hostTarget + strlen(hostTarget) - 7) > hostTarget &&
2357 !_cups_strcasecmp(hostptr, ".local."))
2358 {
2359 /*
2360 * OK, we got a .local name but the caller needs a real domain. Start by
2361 * getting the IP address of the .local name and then do reverse-lookups...
2362 */
2363
2364 http_addrlist_t *addrlist, /* List of addresses */
2365 *addr; /* Current address */
2366
2367 DEBUG_printf(("5http_resolve_cb: Looking up \"%s\".", hostTarget));
2368
2369 snprintf(fqdn, sizeof(fqdn), "%d", ntohs(port));
2370 if ((addrlist = httpAddrGetList(hostTarget, AF_UNSPEC, fqdn)) != NULL)
2371 {
2372 for (addr = addrlist; addr; addr = addr->next)
2373 {
2374 int error = getnameinfo(&(addr->addr.addr), (socklen_t)httpAddrLength(&(addr->addr)), fqdn, sizeof(fqdn), NULL, 0, NI_NAMEREQD);
2375
2376 if (!error)
2377 {
2378 DEBUG_printf(("5http_resolve_cb: Found \"%s\".", fqdn));
2379
2380 if ((hostptr = fqdn + strlen(fqdn) - 6) <= fqdn ||
2381 _cups_strcasecmp(hostptr, ".local"))
2382 {
2383 hostTarget = fqdn;
2384 break;
2385 }
2386 }
2387 #ifdef DEBUG
2388 else
2389 DEBUG_printf(("5http_resolve_cb: \"%s\" did not resolve: %d",
2390 httpAddrString(&(addr->addr), fqdn, sizeof(fqdn)),
2391 error));
2392 #endif /* DEBUG */
2393 }
2394
2395 httpAddrFreeList(addrlist);
2396 }
2397 }
2398
2399 /*
2400 * Assemble the final device URI...
2401 */
2402
2403 if ((!strcmp(scheme, "ipp") || !strcmp(scheme, "ipps")) &&
2404 !strcmp(uribuf->resource, "/cups"))
2405 httpAssembleURIf(HTTP_URI_CODING_ALL, uribuf->buffer, (int)uribuf->bufsize, scheme, NULL, hostTarget, ntohs(port), "%s?snmp=false", resource);
2406 else
2407 httpAssembleURI(HTTP_URI_CODING_ALL, uribuf->buffer, (int)uribuf->bufsize, scheme, NULL, hostTarget, ntohs(port), resource);
2408
2409 DEBUG_printf(("5http_resolve_cb: Resolved URI is \"%s\"...", uribuf->buffer));
2410 }
2411
2412 #elif defined(HAVE_AVAHI)
2413 /*
2414 * 'http_poll_cb()' - Wait for input on the specified file descriptors.
2415 *
2416 * Note: This function is needed because avahi_simple_poll_iterate is broken
2417 * and always uses a timeout of 0 (!) milliseconds.
2418 * (Avahi Ticket #364)
2419 *
2420 * @private@
2421 */
2422
2423 static int /* O - Number of file descriptors matching */
2424 http_poll_cb(
2425 struct pollfd *pollfds, /* I - File descriptors */
2426 unsigned int num_pollfds, /* I - Number of file descriptors */
2427 int timeout, /* I - Timeout in milliseconds (used) */
2428 void *context) /* I - User data (unused) */
2429 {
2430 (void)timeout;
2431 (void)context;
2432
2433 return (poll(pollfds, num_pollfds, 2000));
2434 }
2435
2436
2437 /*
2438 * 'http_resolve_cb()' - Build a device URI for the given service name.
2439 */
2440
2441 static void
2442 http_resolve_cb(
2443 AvahiServiceResolver *resolver, /* I - Resolver (unused) */
2444 AvahiIfIndex interface, /* I - Interface index (unused) */
2445 AvahiProtocol protocol, /* I - Network protocol (unused) */
2446 AvahiResolverEvent event, /* I - Event (found, etc.) */
2447 const char *name, /* I - Service name */
2448 const char *type, /* I - Registration type */
2449 const char *domain, /* I - Domain (unused) */
2450 const char *hostTarget, /* I - Hostname */
2451 const AvahiAddress *address, /* I - Address (unused) */
2452 uint16_t port, /* I - Port number */
2453 AvahiStringList *txt, /* I - TXT record */
2454 AvahiLookupResultFlags flags, /* I - Lookup flags (unused) */
2455 void *context) /* I - Pointer to URI buffer */
2456 {
2457 _http_uribuf_t *uribuf = (_http_uribuf_t *)context;
2458 /* URI buffer */
2459 const char *scheme, /* URI scheme */
2460 *hostptr, /* Pointer into hostTarget */
2461 *reskey, /* "rp" or "rfo" */
2462 *resdefault; /* Default path */
2463 char resource[257], /* Remote path */
2464 fqdn[256]; /* FQDN of the .local name */
2465 AvahiStringList *pair; /* Current TXT record key/value pair */
2466 char *value; /* Value for "rp" key */
2467 size_t valueLen = 0; /* Length of "rp" key */
2468
2469
2470 DEBUG_printf(("4http_resolve_cb(resolver=%p, "
2471 "interface=%d, protocol=%d, event=%d, name=\"%s\", "
2472 "type=\"%s\", domain=\"%s\", hostTarget=\"%s\", address=%p, "
2473 "port=%d, txt=%p, flags=%d, context=%p)",
2474 resolver, interface, protocol, event, name, type, domain,
2475 hostTarget, address, port, txt, flags, context));
2476
2477 if (event != AVAHI_RESOLVER_FOUND)
2478 {
2479 avahi_service_resolver_free(resolver);
2480 avahi_simple_poll_quit(uribuf->poll);
2481 return;
2482 }
2483
2484 /*
2485 * If we have a UUID, compare it...
2486 */
2487
2488 if (uribuf->uuid && (pair = avahi_string_list_find(txt, "UUID")) != NULL)
2489 {
2490 char uuid[256]; /* UUID value */
2491
2492 avahi_string_list_get_pair(pair, NULL, &value, &valueLen);
2493
2494 memcpy(uuid, value, valueLen);
2495 uuid[valueLen] = '\0';
2496
2497 if (_cups_strcasecmp(uuid, uribuf->uuid))
2498 {
2499 if (uribuf->options & _HTTP_RESOLVE_STDERR)
2500 fprintf(stderr, "DEBUG: Found UUID %s, looking for %s.", uuid,
2501 uribuf->uuid);
2502
2503 DEBUG_printf(("5http_resolve_cb: Found UUID %s, looking for %s.", uuid,
2504 uribuf->uuid));
2505 return;
2506 }
2507 }
2508
2509 /*
2510 * Figure out the scheme from the full name...
2511 */
2512
2513 if (strstr(type, "_ipp."))
2514 scheme = "ipp";
2515 else if (strstr(type, "_printer."))
2516 scheme = "lpd";
2517 else if (strstr(type, "_pdl-datastream."))
2518 scheme = "socket";
2519 else
2520 scheme = "riousbprint";
2521
2522 if (!strncmp(type, "_ipps.", 6) || !strncmp(type, "_ipp-tls.", 9))
2523 scheme = "ipps";
2524 else if (!strncmp(type, "_ipp.", 5) || !strncmp(type, "_fax-ipp.", 9))
2525 scheme = "ipp";
2526 else if (!strncmp(type, "_http.", 6))
2527 scheme = "http";
2528 else if (!strncmp(type, "_https.", 7))
2529 scheme = "https";
2530 else if (!strncmp(type, "_printer.", 9))
2531 scheme = "lpd";
2532 else if (!strncmp(type, "_pdl-datastream.", 16))
2533 scheme = "socket";
2534 else
2535 {
2536 avahi_service_resolver_free(resolver);
2537 avahi_simple_poll_quit(uribuf->poll);
2538 return;
2539 }
2540
2541 /*
2542 * Extract the remote resource key from the TXT record...
2543 */
2544
2545 if ((uribuf->options & _HTTP_RESOLVE_FAXOUT) &&
2546 (!strcmp(scheme, "ipp") || !strcmp(scheme, "ipps")) &&
2547 !avahi_string_list_find(txt, "printer-type"))
2548 {
2549 reskey = "rfo";
2550 resdefault = "/ipp/faxout";
2551 }
2552 else
2553 {
2554 reskey = "rp";
2555 resdefault = "/";
2556 }
2557
2558 if ((pair = avahi_string_list_find(txt, reskey)) != NULL)
2559 {
2560 avahi_string_list_get_pair(pair, NULL, &value, &valueLen);
2561
2562 if (value[0] == '/')
2563 {
2564 /*
2565 * Value (incorrectly) has a leading slash already...
2566 */
2567
2568 memcpy(resource, value, valueLen);
2569 resource[valueLen] = '\0';
2570 }
2571 else
2572 {
2573 /*
2574 * Convert to resource by concatenating with a leading "/"...
2575 */
2576
2577 resource[0] = '/';
2578 memcpy(resource + 1, value, valueLen);
2579 resource[valueLen + 1] = '\0';
2580 }
2581 }
2582 else
2583 {
2584 /*
2585 * Use the default value...
2586 */
2587
2588 strlcpy(resource, resdefault, sizeof(resource));
2589 }
2590
2591 /*
2592 * Lookup the FQDN if needed...
2593 */
2594
2595 if ((uribuf->options & _HTTP_RESOLVE_FQDN) &&
2596 (hostptr = hostTarget + strlen(hostTarget) - 6) > hostTarget &&
2597 !_cups_strcasecmp(hostptr, ".local"))
2598 {
2599 /*
2600 * OK, we got a .local name but the caller needs a real domain. Start by
2601 * getting the IP address of the .local name and then do reverse-lookups...
2602 */
2603
2604 http_addrlist_t *addrlist, /* List of addresses */
2605 *addr; /* Current address */
2606
2607 DEBUG_printf(("5http_resolve_cb: Looking up \"%s\".", hostTarget));
2608
2609 snprintf(fqdn, sizeof(fqdn), "%d", ntohs(port));
2610 if ((addrlist = httpAddrGetList(hostTarget, AF_UNSPEC, fqdn)) != NULL)
2611 {
2612 for (addr = addrlist; addr; addr = addr->next)
2613 {
2614 int error = getnameinfo(&(addr->addr.addr), (socklen_t)httpAddrLength(&(addr->addr)), fqdn, sizeof(fqdn), NULL, 0, NI_NAMEREQD);
2615
2616 if (!error)
2617 {
2618 DEBUG_printf(("5http_resolve_cb: Found \"%s\".", fqdn));
2619
2620 if ((hostptr = fqdn + strlen(fqdn) - 6) <= fqdn ||
2621 _cups_strcasecmp(hostptr, ".local"))
2622 {
2623 hostTarget = fqdn;
2624 break;
2625 }
2626 }
2627 #ifdef DEBUG
2628 else
2629 DEBUG_printf(("5http_resolve_cb: \"%s\" did not resolve: %d",
2630 httpAddrString(&(addr->addr), fqdn, sizeof(fqdn)),
2631 error));
2632 #endif /* DEBUG */
2633 }
2634
2635 httpAddrFreeList(addrlist);
2636 }
2637 }
2638
2639 /*
2640 * Assemble the final device URI using the resolved hostname...
2641 */
2642
2643 httpAssembleURI(HTTP_URI_CODING_ALL, uribuf->buffer, (int)uribuf->bufsize, scheme,
2644 NULL, hostTarget, port, resource);
2645 DEBUG_printf(("5http_resolve_cb: Resolved URI is \"%s\".", uribuf->buffer));
2646
2647 avahi_simple_poll_quit(uribuf->poll);
2648 }
2649 #endif /* HAVE_DNSSD */