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