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