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