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