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