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