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