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