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