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