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