Coverage Report

Created: 2026-07-24 06:12

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