Coverage Report

Created: 2026-12-01 07:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libcups/cups/http.c
Line
Count
Source
1
//
2
// HTTP routines for CUPS.
3
//
4
// Copyright © 2021-2026 by OpenPrinting.
5
// Copyright © 2007-2021 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 <fcntl.h>
14
#include <math.h>
15
#ifdef _WIN32
16
#  include <tchar.h>
17
#else
18
#  include <poll.h>
19
#  include <signal.h>
20
#  include <sys/time.h>
21
#  include <sys/resource.h>
22
#endif // _WIN32
23
#include <zlib.h>
24
25
26
//
27
// Local functions...
28
//
29
30
static void   http_add_field(http_t *http, http_field_t field, const char *value, bool append);
31
static void   http_advance_state(http_t *http);
32
static void   http_content_coding_finish(http_t *http);
33
static void   http_content_coding_start(http_t *http, const char *value);
34
static http_t   *http_create(const char *host, int port, http_addrlist_t *addrlist, int family, http_encryption_t encryption, bool blocking, _http_mode_t mode);
35
#ifdef DEBUG
36
static void   http_debug_hex(const char *prefix, const char *buffer, int bytes);
37
#endif // DEBUG
38
static ssize_t    http_read(http_t *http, char *buffer, size_t length, int timeout);
39
static ssize_t    http_read_buffered(http_t *http, char *buffer, size_t length);
40
static ssize_t    http_read_chunk(http_t *http, char *buffer, size_t length);
41
static bool   http_send(http_t *http, http_state_t request, const char *uri);
42
static off_t    http_set_length(http_t *http);
43
static void   http_set_timeout(int fd, double timeout);
44
static void   http_set_wait(http_t *http);
45
static bool   http_tls_upgrade(http_t *http);
46
static ssize_t    http_write(http_t *http, const char *buffer, size_t length);
47
static ssize_t    http_write_chunk(http_t *http, const char *buffer, size_t length);
48
static bool   http_write_header(http_t *http, http_field_t field, const char *value);
49
50
51
//
52
// Local globals...
53
//
54
55
static const char * const http_fields[HTTP_FIELD_MAX] =
56
{
57
  "Accept",
58
  "Accept-CH",
59
  "Accept-Encoding",
60
  "Accept-Language",
61
  "Accept-Ranges",
62
  "Access-Control-Allow-Credentials",
63
  "Access-Control-Allow-Headers",
64
  "Access-Control-Allow-Methods",
65
  "Access-Control-Allow-Origin",
66
  "Access-Control-Expose-Headers",
67
  "Access-Control-Max-Age",
68
  "Access-Control-Request-Headers",
69
  "Access-Control-Request-Method",
70
  "Age",
71
  "Allow",
72
  "Authentication-Control",
73
  "Authentication-Info",
74
  "Authorization",
75
  "Cache-Control",
76
  "Cache-Status",
77
  "Cert-Not-After",
78
  "Cert-Not-Before",
79
  "Connection",
80
  "Content-Disposition",
81
  "Content-Encoding",
82
  "Content-Language",
83
  "Content-Length",
84
  "Content-Location",
85
  "Content-Range",
86
  "Content-Security-Policy",
87
  "Content-Security-Policy-Report-Only",
88
  "Content-Type",
89
  "Cross-Origin-Embedder-Policy",
90
  "Cross-Origin-Embedder-Policy-Report-Only",
91
  "Cross-Origin-Opener-Policy",
92
  "Cross-Origin-Opener-Policy-Report-Only",
93
  "Cross-Origin-Resource-Policy",
94
  "DASL",
95
  "Date",
96
  "DAV",
97
  "Depth",
98
  "Destination",
99
  "ETag",
100
  "Expires",
101
  "Forwarded",
102
  "From",
103
  "Host",
104
  "If",
105
  "If-Match",
106
  "If-Modified-Since",
107
  "If-None-Match",
108
  "If-Range",
109
  "If-Schedule-Tag-Match",
110
  "If-Unmodified-since",
111
  "Keep-Alive",
112
  "Last-Modified",
113
  "Link",
114
  "Location",
115
  "Lock-Token",
116
  "Max-Forwards",
117
  "Optional-WWW-Authenticate",
118
  "Origin",
119
  "OSCORE",
120
  "Overwrite",
121
  "Pragma",
122
  "Proxy-Authenticate",
123
  "Proxy-Authentication-Info",
124
  "Proxy-Authorization",
125
  "Proxy-Status",
126
  "Public",
127
  "Range",
128
  "Referer",
129
  "Refresh",
130
  "Replay-Nonce",
131
  "Retry-After",
132
  "Schedule-Reply",
133
  "Schedule-Tag",
134
  "Server",
135
  "Strict-Transport-Security",
136
  "TE",
137
  "Timeout",
138
  "Trailer",
139
  "Transfer-Encoding",
140
  "Upgrade",
141
  "User-Agent",
142
  "Vary",
143
  "Via",
144
  "WWW-Authenticate",
145
  "X-Content-Options",
146
  "X-Frame-Options"
147
};
148
149
150
//
151
// 'httpAcceptConnection()' - Accept a new HTTP client connection.
152
//
153
// This function accepts a new HTTP client connection from the specified
154
// listening socket "fd".  The "blocking" argument specifies whether the new
155
// HTTP connection is blocking.
156
//
157
158
http_t *        // O - HTTP connection or `NULL`
159
httpAcceptConnection(int  fd,   // I - Listen socket file descriptor
160
                     bool blocking) // I - `true` if the connection should be blocking, `false` otherwise
161
0
{
162
0
  http_t    *http;    // HTTP connection
163
0
  http_addrlist_t addrlist; // Dummy address list
164
0
  socklen_t   addrlen;  // Length of address
165
0
  int     val;    // Socket option value
166
167
168
  // Range check input...
169
0
  if (fd < 0)
170
0
    return (NULL);
171
172
  // Create the client connection...
173
0
  memset(&addrlist, 0, sizeof(addrlist));
174
175
0
  if ((http = http_create(NULL, 0, &addrlist, AF_UNSPEC, HTTP_ENCRYPTION_IF_REQUESTED, blocking, _HTTP_MODE_SERVER)) == NULL)
176
0
    return (NULL);
177
178
  // Accept the client and get the remote address...
179
0
  addrlen = sizeof(http_addr_t);
180
181
0
  if ((http->fd = accept(fd, (struct sockaddr *)&(http->hostlist->addr), &addrlen)) < 0)
182
0
  {
183
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(errno), false);
184
0
    httpClose(http);
185
186
0
    return (NULL);
187
0
  }
188
189
0
  http->hostaddr = &(http->hostlist->addr);
190
191
0
  if (httpAddrIsLocalhost(http->hostaddr))
192
0
    cupsCopyString(http->hostname, "localhost", sizeof(http->hostname));
193
0
  else
194
0
    httpAddrGetString(http->hostaddr, http->hostname, sizeof(http->hostname));
195
196
#ifdef SO_NOSIGPIPE
197
  // Disable SIGPIPE for this socket.
198
  val = 1;
199
  if (setsockopt(http->fd, SOL_SOCKET, SO_NOSIGPIPE, CUPS_SOCAST &val, sizeof(val)))
200
    DEBUG_printf("httpAcceptConnection: setsockopt(SO_NOSIGPIPE) failed - %s", strerror(errno));
201
#endif // SO_NOSIGPIPE
202
203
  // Using TCP_NODELAY improves responsiveness, especially on systems with a
204
  // slow loopback interface.  Since we write large buffers when sending print
205
  // files and requests, there shouldn't be any performance penalty for this...
206
0
  val = 1;
207
0
  if (setsockopt(http->fd, IPPROTO_TCP, TCP_NODELAY, CUPS_SOCAST &val, sizeof(val)))
208
0
    DEBUG_printf("httpAcceptConnection: setsockopt(TCP_NODELAY) failed - %s", strerror(errno));
209
210
0
#ifdef FD_CLOEXEC
211
  // Close this socket when starting another process...
212
0
  if (fcntl(http->fd, F_SETFD, FD_CLOEXEC))
213
0
    DEBUG_printf("httpAcceptConnection: fcntl(F_SETFD, FD_CLOEXEC) failed - %s", strerror(errno));
214
0
#endif // FD_CLOEXEC
215
216
0
  return (http);
217
0
}
218
219
220
//
221
// 'httpClearCookie()' - Clear the cookie value(s).
222
//
223
224
void
225
httpClearCookie(http_t *http)   // I - HTTP connection
226
0
{
227
0
  if (!http)
228
0
    return;
229
230
0
  free(http->cookie);
231
0
  http->cookie = NULL;
232
233
0
  free(http->set_cookie);
234
0
  http->set_cookie = NULL;
235
0
}
236
237
238
//
239
// 'httpClearFields()' - Clear HTTP request/response fields.
240
//
241
242
void
243
httpClearFields(http_t *http)   // I - HTTP connection
244
0
{
245
0
  http_field_t  field;      // Current field
246
247
248
0
  DEBUG_printf("httpClearFields(http=%p)", (void *)http);
249
250
0
  if (http)
251
0
  {
252
0
    for (field = HTTP_FIELD_ACCEPT; field < HTTP_FIELD_MAX; field ++)
253
0
    {
254
0
      free(http->fields[field]);
255
0
      http->fields[field] = NULL;
256
0
    }
257
258
0
    if (http->mode == _HTTP_MODE_CLIENT)
259
0
    {
260
0
      if (http->hostname[0] == '/')
261
0
  httpSetField(http, HTTP_FIELD_HOST, "localhost");
262
0
      else
263
0
  httpSetField(http, HTTP_FIELD_HOST, http->hostname);
264
0
    }
265
266
0
    http->expect = (http_status_t)0;
267
0
  }
268
0
}
269
270
271
//
272
// 'httpClose()' - Close a HTTP connection.
273
//
274
275
void
276
httpClose(http_t *http)     // I - HTTP connection
277
0
{
278
0
  http_field_t  field;      // Current field
279
280
281
0
  DEBUG_printf("httpClose(http=%p)", (void *)http);
282
283
  // Range check input...
284
0
  if (!http)
285
0
    return;
286
287
  // Close any open connection...
288
0
  _httpDisconnect(http);
289
290
  // Free memory used...
291
0
  httpAddrFreeList(http->hostlist);
292
293
0
  for (field = HTTP_FIELD_ACCEPT; field < HTTP_FIELD_MAX; field ++)
294
0
  {
295
0
    free(http->default_fields[field]);
296
0
    free(http->fields[field]);
297
0
  }
298
299
0
  if (http->stream)
300
0
  {
301
0
    if (http->coding == _HTTP_CODING_DEFLATE || http->coding == _HTTP_CODING_GZIP)
302
0
      deflateEnd((z_stream *)http->stream);
303
0
    else
304
0
      inflateEnd((z_stream *)http->stream);
305
306
0
    free(http->stream);
307
0
  }
308
309
0
  free(http->authstring);
310
0
  free(http->cookie);
311
0
  free(http->set_cookie);
312
0
  free(http->fbuffer);
313
0
  free(http->sbuffer);
314
315
0
  _httpFreeCredentials(http->tls_credentials);
316
317
0
  free(http);
318
0
}
319
320
321
//
322
// 'httpConnect()' - Connect to a HTTP server.
323
//
324
// This function creates a connection to a HTTP server.  The "host" and "port"
325
// arguments specify a hostname or IP address and port number to use while the
326
// "addrlist" argument specifies a list of addresses to use or `NULL` to do a
327
// fresh lookup.  The "family" argument specifies the address family to use -
328
// `AF_UNSPEC` to try both IPv4 and IPv6, `AF_INET` for IPv4, or `AF_INET6` for
329
// IPv6.
330
//
331
// The "encryption" argument specifies whether to encrypt the connection and the
332
// "blocking" argument specifies whether to use blocking behavior when reading
333
// or writing data.
334
//
335
// The "msec" argument specifies how long to try to connect to the server or `0`
336
// to just create an unconnected `http_t` object.  The "cancel" argument
337
// specifies an integer variable that can be set to a non-zero value to cancel
338
// the connection process.
339
//
340
341
http_t *        // O - New HTTP connection
342
httpConnect(
343
    const char        *host,    // I - Host to connect to
344
    int               port,   // I - Port number
345
    http_addrlist_t   *addrlist,  // I - List of addresses or `NULL` to lookup
346
    int               family,   // I - Address family to use or `AF_UNSPEC` for any
347
    http_encryption_t encryption, // I - Type of encryption to use
348
    bool              blocking,   // I - `true` for blocking connection, `false` for non-blocking
349
    int               msec,   // I - Connection timeout in milliseconds, `0` means don't connect
350
    int               *cancel)    // I - Pointer to "cancel" variable or `NULL` for none
351
0
{
352
0
  http_t  *http;      // New HTTP connection
353
354
355
0
  DEBUG_printf("httpConnect(host=\"%s\", port=%d, addrlist=%p, family=%d, encryption=%d, blocking=%d, msec=%d, cancel=%p)", host, port, (void *)addrlist, family, encryption, blocking, msec, (void *)cancel);
356
357
  // Create the HTTP structure...
358
0
  if ((http = http_create(host, port, addrlist, family, encryption, blocking, _HTTP_MODE_CLIENT)) == NULL)
359
0
    return (NULL);
360
361
  // Optionally connect to the remote system...
362
0
  if (msec == 0 || httpConnectAgain(http, msec, cancel))
363
0
    return (http);
364
365
  // Could not connect to any known address - bail out!
366
0
  httpClose(http);
367
368
0
  return (NULL);
369
0
}
370
371
372
//
373
// 'httpConnectAgain()' - Reconnect to a HTTP server with timeout and optional cancel variable.
374
//
375
376
bool          // O - `true` on success, `false` on failure
377
httpConnectAgain(http_t *http,    // I - HTTP connection
378
           int    msec,   // I - Timeout in milliseconds
379
           int    *cancel)  // I - Pointer to "cancel" variable
380
0
{
381
0
  http_addrlist_t *addr;    // Connected address
382
0
  char      *orig_creds;  // Original peer credentials
383
#ifdef DEBUG
384
  http_addrlist_t *current; // Current address
385
  char      temp[256];  // Temporary address string
386
#endif // DEBUG
387
388
389
0
  DEBUG_printf("httpConnectAgain(http=%p, msec=%d, cancel=%p)", (void *)http, msec, (void *)cancel);
390
391
  // Range check input...
392
0
  if (!http)
393
0
  {
394
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0);
395
0
    return (false);
396
0
  }
397
398
0
  orig_creds = httpCopyPeerCredentials(http);
399
400
0
  if (http->tls)
401
0
  {
402
0
    DEBUG_puts("2httpConnectAgain: Shutting down SSL/TLS...");
403
0
    _httpTLSStop(http);
404
0
  }
405
406
  // Close any previously open socket...
407
0
  if (http->fd >= 0)
408
0
  {
409
0
    DEBUG_printf("2httpConnectAgain: Closing socket %d...", http->fd);
410
411
0
    httpAddrClose(NULL, http->fd);
412
413
0
    http->fd = -1;
414
0
  }
415
416
  // Reset all state (except fields, which may be reused)...
417
0
  http->state           = HTTP_STATE_WAITING;
418
0
  http->version         = HTTP_VERSION_1_1;
419
0
  http->keep_alive      = HTTP_KEEPALIVE_OFF;
420
0
  http->data_encoding   = HTTP_ENCODING_FIELDS;
421
0
  http->used            = 0;
422
0
  http->data_remaining  = 0;
423
0
  http->hostaddr        = NULL;
424
0
  http->wused           = 0;
425
426
  // Connect to the server...
427
#ifdef DEBUG
428
  for (current = http->hostlist; current; current = current->next)
429
    DEBUG_printf("2httpConnectAgain: Address %s:%d", httpAddrGetString(&(current->addr), temp, sizeof(temp)), httpAddrGetPort(&(current->addr)));
430
#endif // DEBUG
431
432
0
  if ((addr = httpAddrConnect(http->hostlist, &(http->fd), msec, cancel)) == NULL)
433
0
  {
434
    // Unable to connect...
435
#ifdef _WIN32
436
    http->error  = WSAGetLastError();
437
#else
438
0
    http->error  = errno;
439
0
#endif // _WIN32
440
0
    http->status = HTTP_STATUS_ERROR;
441
442
0
    DEBUG_printf("1httpConnectAgain: httpAddrConnect failed: %s", strerror(http->error));
443
444
0
    free(orig_creds);
445
446
0
    return (false);
447
0
  }
448
449
0
  DEBUG_printf("2httpConnectAgain: New socket=%d", http->fd);
450
451
0
  if (http->timeout_value > 0)
452
0
    http_set_timeout(http->fd, http->timeout_value);
453
454
0
  http->hostaddr = &(addr->addr);
455
0
  http->error    = 0;
456
457
0
  if (http->encryption == HTTP_ENCRYPTION_ALWAYS)
458
0
  {
459
    // Always do encryption via SSL.
460
0
    if (!_httpTLSStart(http))
461
0
    {
462
0
      httpAddrClose(NULL, http->fd);
463
0
      http->fd = -1;
464
465
0
      free(orig_creds);
466
467
0
      return (false);
468
0
    }
469
0
  }
470
0
  else if (http->encryption == HTTP_ENCRYPTION_REQUIRED && !http->tls_upgrade)
471
0
  {
472
0
    if (!http_tls_upgrade(http))
473
0
    {
474
0
      free(orig_creds);
475
476
0
      return (false);
477
0
    }
478
0
  }
479
480
0
  DEBUG_printf("1httpConnectAgain: Connected to %s:%d...", httpAddrGetString(http->hostaddr, temp, sizeof(temp)), httpAddrGetPort(http->hostaddr));
481
482
0
  if (orig_creds)
483
0
  {
484
0
    char *new_creds = httpCopyPeerCredentials(http);
485
          // New peer credentials
486
487
0
    if (!new_creds || (strcmp(orig_creds, new_creds) && cupsGetCredentialsTrust(/*path*/NULL, http->hostname, new_creds, /*require_ca*/true) != HTTP_TRUST_OK))
488
0
    {
489
      // New and old credentials don't match and the new cert doesn't validate...
490
0
      _httpDisconnect(http);
491
492
0
      free(orig_creds);
493
0
      free(new_creds);
494
495
0
      return (false);
496
0
    }
497
498
0
    free(new_creds);
499
0
  }
500
501
0
  free(orig_creds);
502
503
0
  return (true);
504
0
}
505
506
507
//
508
// 'httpConnectURI()' - Connect to a HTTP service using a URI.
509
//
510
// This function creates a connection to a HTTP server.  The "uri" argument
511
// specifies a "http", "https", "ipp", or "ipps" URI for the service.
512
//
513
// The resource path for the service is returned in the buffer pointed to by
514
// the "resource" argument of size "rsize".
515
//
516
// The "msec" argument specifies how long to try to connect to the server or `0`
517
// to just create an unconnected `http_t` object.  The "cancel" argument
518
// specifies an integer variable that can be set to a non-zero value to cancel
519
// the connection process.
520
//
521
// The "require_ca" argument specifies whether to verify that the service
522
// connection is using a CA-signed X.509 certificate.
523
//
524
525
http_t *        // O - New HTTP connection
526
httpConnectURI(const char *uri,   // I - Service to connect to
527
               char       *host,  // I - Host name buffer (`NULL` for don't care)
528
               size_t     hsize,  // I - Size of host name buffer
529
               int        *port,  // O - Port number (`NULL` for don't care)
530
               char       *resource,  // I - Resource path buffer (`NULL` for don't care)
531
               size_t     rsize,  // I - Size of resource path buffer
532
               bool       blocking, // I - `true` for blocking connection, `false` for non-blocking
533
               int        msec,   // I - Connection timeout in milliseconds, `0` means don't connect
534
               int        *cancel,  // I - Pointer to "cancel" variable or `NULL` for none
535
               bool       require_ca) // I - `true` to require a CA-signed X.509 certificate
536
0
{
537
0
  http_t  *http;      // New HTTP connection
538
0
  char    scheme[32],   // URI scheme
539
0
    userpass[32],   // URI username:password
540
0
    lhost[256],   // URI host (local copy)
541
0
    lresource[256];   // URI resource (local copy)
542
0
  int   lport;      // URI port (local copy)
543
0
  http_encryption_t encryption;   // Type of encryption to use
544
0
  http_uri_status_t uri_status;   // URI separation status
545
546
547
0
  DEBUG_printf("httpConnectURI(uri=\"%s\", host=%p, hsize=%u, port=%p, resource=%p, rsize=%u, blocking=%d, msec=%d, cancel=%p, require_ca=%s)", uri, (void *)host, (unsigned)hsize, (void *)port, (void *)resource, (unsigned)rsize, blocking, msec, (void *)cancel, require_ca ? "true" : "false");
548
549
  // Range check input...
550
0
  if (!uri)
551
0
  {
552
0
    if (host)
553
0
      *host = '\0';
554
555
0
    if (port)
556
0
      *port = 0;
557
558
0
    if (resource)
559
0
      *resource = '\0';
560
561
0
    return (NULL);
562
0
  }
563
564
0
  if (!host)
565
0
  {
566
0
    host  = lhost;
567
0
    hsize = sizeof(lhost);
568
0
  }
569
570
0
  if (!port)
571
0
    port = &lport;
572
573
0
  if (!resource)
574
0
  {
575
0
    resource = lresource;
576
0
    rsize    = sizeof(lresource);
577
0
  }
578
579
  // Get the URI components...
580
0
  if ((uri_status = httpSeparateURI(HTTP_URI_CODING_ALL, uri, scheme, sizeof(scheme), userpass, sizeof(userpass), host, hsize, port, resource, rsize)) < HTTP_URI_STATUS_OK)
581
0
  {
582
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, httpURIStatusString(uri_status), 0);
583
0
    return (NULL);
584
0
  }
585
586
0
  DEBUG_printf("1httpConnectURI: scheme=\"%s\", host=\"%s\", port=%d, resource=\"%s\"", scheme, host, *port, resource);
587
588
0
  if (!strcmp(scheme, "https") || !strcmp(scheme, "ipps") || *port == 443)
589
0
    encryption = HTTP_ENCRYPTION_ALWAYS;
590
0
  else
591
0
    encryption = HTTP_ENCRYPTION_IF_REQUESTED;
592
593
0
  http = httpConnect(host, *port, /*addrlist*/NULL, AF_UNSPEC, encryption, blocking, msec, cancel);
594
595
0
  if (httpIsEncrypted(http))
596
0
  {
597
    // Validate trust with service...
598
0
    char  *creds;     // Peer credentials...
599
0
    http_trust_t trust;     // Trust in credentials...
600
601
0
    creds = httpCopyPeerCredentials(http);
602
0
    trust = cupsGetCredentialsTrust(/*path*/NULL, host, creds, require_ca);
603
604
0
    if (trust == HTTP_TRUST_OK)
605
0
    {
606
      // Pin the trusted credentials (for TOFU)...
607
0
      cupsSaveCredentials(/*path*/NULL, host, creds, /*key*/NULL);
608
0
    }
609
0
    else if (trust != HTTP_TRUST_RENEWED)
610
0
    {
611
      // Don't allow the connection...
612
0
      httpClose(http);
613
0
      http = NULL;
614
0
    }
615
616
0
    free(creds);
617
0
  }
618
619
0
  return (http);
620
0
}
621
622
623
//
624
// '_httpDisconnect()' - Disconnect a HTTP connection.
625
//
626
627
void
628
_httpDisconnect(http_t *http)   // I - HTTP connection
629
0
{
630
0
  if (http->tls)
631
0
    _httpTLSStop(http);
632
633
0
  httpAddrClose(NULL, http->fd);
634
635
0
  http->fd = -1;
636
0
}
637
638
639
//
640
// 'httpFieldValue()' - Return the HTTP field enumeration value for a field
641
//                      name.
642
//
643
644
http_field_t        // O - Field index
645
httpFieldValue(const char *name)  // I - String name
646
0
{
647
0
  int i;        // Looping var
648
649
650
0
  for (i = 0; i < HTTP_FIELD_MAX; i ++)
651
0
  {
652
0
    if (!_cups_strcasecmp(name, http_fields[i]))
653
0
      return ((http_field_t)i);
654
0
  }
655
656
0
  return (HTTP_FIELD_UNKNOWN);
657
0
}
658
659
660
//
661
// 'httpFlush()' - Flush data read from a HTTP connection.
662
//
663
664
void
665
httpFlush(http_t *http)     // I - HTTP connection
666
0
{
667
0
  char    buffer[8192];   // Junk buffer
668
0
  bool    blocking;   // To block or not to block
669
0
  http_state_t  oldstate;   // Old state
670
671
672
0
  DEBUG_printf("httpFlush(http=%p), state=%s", (void *)http, httpStateString(http->state));
673
674
  // Nothing to do if we are in the "waiting" state...
675
0
  if (http->state == HTTP_STATE_WAITING)
676
0
    return;
677
678
  // Temporarily set non-blocking mode so we don't get stuck in httpRead()...
679
0
  blocking = http->blocking;
680
0
  http->blocking = false;
681
682
  // Read any data we can...
683
0
  oldstate = http->state;
684
0
  while (httpRead(http, buffer, sizeof(buffer)) > 0);
685
686
  // Restore blocking and reset the connection if we didn't get all of the remaining data...
687
0
  http->blocking = blocking;
688
689
0
  if (http->state == oldstate && http->state != HTTP_STATE_WAITING && http->fd >= 0)
690
0
  {
691
    // Didn't get the data back, so close the current connection.
692
0
    if (http->coding)
693
0
      http_content_coding_finish(http);
694
695
0
    DEBUG_puts("1httpFlush: Setting state to HTTP_STATE_WAITING and closing.");
696
697
0
    http->state = HTTP_STATE_WAITING;
698
699
0
    if (http->tls)
700
0
      _httpTLSStop(http);
701
702
0
    httpAddrClose(NULL, http->fd);
703
704
0
    http->fd = -1;
705
0
  }
706
0
}
707
708
709
//
710
// 'httpFlushWrite()' - Flush data written to a HTTP connection.
711
//
712
713
int         // O - Bytes written or -1 on error
714
httpFlushWrite(http_t *http)    // I - HTTP connection
715
0
{
716
0
  ssize_t bytes;      // Bytes written
717
718
719
0
  DEBUG_printf("httpFlushWrite(http=%p) data_encoding=%d", (void *)http, http ? http->data_encoding : 100);
720
721
0
  if (!http || !http->wused)
722
0
  {
723
0
    DEBUG_puts(http ? "1httpFlushWrite: Write buffer is empty." : "1httpFlushWrite: No connection.");
724
0
    return (0);
725
0
  }
726
727
0
  if (http->data_encoding == HTTP_ENCODING_CHUNKED)
728
0
    bytes = http_write_chunk(http, http->wbuffer, (size_t)http->wused);
729
0
  else
730
0
    bytes = http_write(http, http->wbuffer, (size_t)http->wused);
731
732
0
  http->wused = 0;
733
734
0
  DEBUG_printf("1httpFlushWrite: Returning %d, errno=%d.", (int)bytes, errno);
735
736
0
  return ((int)bytes);
737
0
}
738
739
740
//
741
// 'httpGetActivity()' - Get the most recent activity for a connection.
742
//
743
// The return value is the time in seconds of the last read or write.
744
//
745
746
time_t          // O - Time of last read or write
747
httpGetActivity(http_t *http)   // I - HTTP connection
748
0
{
749
0
  return (http ? http->activity : 0);
750
0
}
751
752
753
//
754
// 'httpGetAuthString()' - Get the current authorization string.
755
//
756
// The authorization string is set by @link cupsDoAuthentication@ and
757
// @link httpSetAuthString@.  Use @link httpGetAuthString@ to retrieve the
758
// string to use with @link httpSetField@ for the
759
// `HTTP_FIELD_AUTHORIZATION` value.
760
//
761
762
const char *        // O - Authorization string
763
httpGetAuthString(http_t *http)   // I - HTTP connection
764
0
{
765
0
  if (http)
766
0
    return (http->authstring);
767
0
  else
768
0
    return (NULL);
769
0
}
770
771
772
//
773
// 'httpGetBlocking()' - Get the blocking/non-blocking state of a connection.
774
//
775
776
bool          // O - `true` if blocking, `false` if non-blocking
777
httpGetBlocking(http_t *http)   // I - HTTP connection
778
0
{
779
0
  return (http ? http->blocking : false);
780
0
}
781
782
783
//
784
// 'httpGetContentEncoding()' - Get a common content encoding, if any, between
785
//                              the client and server.
786
//
787
// This function uses the value of the Accepts-Encoding HTTP header and must be
788
// called after receiving a response from the server or a request from the
789
// client.  The value returned can be use in subsequent requests (for clients)
790
// or in the response (for servers) in order to compress the content stream.
791
//
792
793
const char *        // O - Content-Coding value or `NULL` for the identity coding.
794
httpGetContentEncoding(http_t *http)  // I - HTTP connection
795
0
{
796
0
  if (http && http->fields[HTTP_FIELD_ACCEPT_ENCODING])
797
0
  {
798
0
    int   i;      // Looping var
799
0
    char  temp[_HTTP_MAX_VALUE],  // Copy of Accepts-Encoding value
800
0
    *start,     // Start of coding value
801
0
    *end;     // End of coding value
802
0
    double  qvalue;     // "qvalue" for coding
803
0
    struct lconv *loc = localeconv(); // Locale data
804
0
    static const char * const codings[] =
805
0
    {         // Supported content codings
806
0
      "deflate",
807
0
      "gzip",
808
0
      "x-deflate",
809
0
      "x-gzip"
810
0
    };
811
812
0
    cupsCopyString(temp, http->fields[HTTP_FIELD_ACCEPT_ENCODING], sizeof(temp));
813
814
0
    for (start = temp; *start; start = end)
815
0
    {
816
      // Find the end of the coding name...
817
0
      qvalue = 1.0;
818
0
      end    = start;
819
0
      while (*end && *end != ';' && *end != ',' && !_cups_isspace(*end))
820
0
        end ++;
821
822
0
      if (*end == ';')
823
0
      {
824
        // Grab the qvalue as needed...
825
0
        if (!strncmp(end, ";q=", 3))
826
0
          qvalue = _cupsStrScand(end + 3, NULL, loc);
827
828
        // Skip past all attributes...
829
0
        *end++ = '\0';
830
0
        while (*end && *end != ',' && !_cups_isspace(*end))
831
0
          end ++;
832
0
      }
833
0
      else if (*end)
834
0
      {
835
0
        *end++ = '\0';
836
0
      }
837
838
0
      while (*end && _cups_isspace(*end))
839
0
  end ++;
840
841
      // Check value if it matches something we support...
842
0
      if (qvalue <= 0.0)
843
0
        continue;
844
845
0
      for (i = 0; i < (int)(sizeof(codings) / sizeof(codings[0])); i ++)
846
0
      {
847
0
        if (!strcmp(start, codings[i]))
848
0
          return (codings[i]);
849
0
      }
850
0
    }
851
0
  }
852
853
0
  return (NULL);
854
0
}
855
856
857
//
858
// 'httpGetCookie()' - Get cookie data from the HTTP connection.
859
//
860
// This function returns any HTTP "Set-Cookie:" or "Cookie:" header data for the
861
// given HTTP connection as described in RFC 6265.  Use the
862
// @link httpGetCookieValue@ to get the value of a named "Cookie:" value.
863
//
864
865
const char *        // O - Cookie data or `NULL`
866
httpGetCookie(http_t *http)   // I - HTTP connection
867
0
{
868
0
  return (http ? http->cookie : NULL);
869
0
}
870
871
872
//
873
// 'httpGetCookieValue()' - Get the value of a named cookie from the HTTP connection.
874
//
875
// This function copies the value of a named cookie in the HTTP "Cookie:" header
876
// for the given HTTP connection as described in RFC 6265.  Use the
877
// @link httpGetCookie@ function to get the original "Cookie:" string.
878
//
879
880
char *          // O - Cookie value or `NULL` if not present
881
httpGetCookieValue(http_t     *http,  // I - HTTP connection
882
                   const char *name,  // I - Cookie name
883
                   char       *buffer,  // I - Value buffer
884
                   size_t     bufsize)  // I - Size of value buffer
885
0
{
886
0
  const char  *cookie;    // Cookie: header value
887
0
  char    current[128],   // Current name string
888
0
    *ptr,     // Pointer into name/buffer
889
0
    *end;     // End of name/buffer
890
0
  bool    match;      // Does the current name match?
891
892
893
  // Range check input...
894
0
  if (buffer)
895
0
    *buffer = '\0';
896
897
0
  if (!http || !http->cookie || !name || !buffer || bufsize < 2)
898
0
    return (NULL);
899
900
  // Loop through the cookie string...
901
0
  for (cookie = http->cookie; *cookie;)
902
0
  {
903
    // Skip leading whitespace...
904
0
    while (_cups_isspace(*cookie))
905
0
      cookie ++;
906
0
    if (!*cookie)
907
0
      break;
908
909
    // Copy the name...
910
0
    for (ptr = current, end = current + sizeof(current) - 1; *cookie && *cookie != '=';)
911
0
    {
912
0
      if (ptr < end)
913
0
        *ptr++ = *cookie++;
914
0
      else
915
0
  cookie ++;
916
0
    }
917
918
0
    if (*cookie != '=')
919
0
      break;
920
921
0
    *ptr = '\0';
922
0
    match = !strcmp(current, name);
923
0
    cookie ++;
924
925
    // Then the value...
926
0
    if (*cookie == '\"')
927
0
    {
928
      // Copy quoted value...
929
0
      for (cookie ++, ptr = buffer, end = buffer + bufsize - 1; *cookie && *cookie != '\"';)
930
0
      {
931
0
        if (match && ptr < end)
932
0
    *ptr++ = *cookie++;
933
0
  else
934
0
    cookie ++;
935
0
      }
936
937
0
      if (*cookie == '\"')
938
0
        cookie ++;
939
0
      else
940
0
        match = false;
941
0
    }
942
0
    else
943
0
    {
944
      // Copy unquoted value...
945
0
      for (ptr = buffer, end = buffer + bufsize - 1; *cookie && *cookie != ';';)
946
0
      {
947
0
        if (match && ptr < end)
948
0
    *ptr++ = *cookie++;
949
0
  else
950
0
    cookie ++;
951
0
      }
952
0
    }
953
954
0
    if (match)
955
0
    {
956
      // Got the value we were looking for, nul-terminate and return...
957
0
      *ptr = '\0';
958
0
      return (buffer);
959
0
    }
960
961
    // Skip over separator...
962
0
    if (*cookie == ';')
963
0
      cookie ++;
964
0
  }
965
966
  // If we get here then we never found the cookie...
967
0
  return (NULL);
968
0
}
969
970
971
//
972
// 'httpGetEncryption()' - Get the current encryption mode of a connection.
973
//
974
// This function returns the encryption mode for the connection. Use the
975
// @link httpIsEncrypted@ function to determine whether a TLS session has
976
// been established.
977
//
978
979
http_encryption_t     // O - Current encryption mode
980
httpGetEncryption(http_t *http)   // I - HTTP connection
981
0
{
982
0
  return (http ? http->encryption : HTTP_ENCRYPTION_IF_REQUESTED);
983
0
}
984
985
986
//
987
// 'httpGetError()' - Get the last error on a connection.
988
//
989
990
int         // O - Error code (errno) value
991
httpGetError(http_t *http)    // I - HTTP connection
992
0
{
993
0
  if (http)
994
0
    return (http->error);
995
0
  else
996
0
    return (EINVAL);
997
0
}
998
999
1000
//
1001
// 'httpGetExpect()' - Get the value of the Expect header, if any.
1002
//
1003
// Returns `HTTP_STATUS_NONE` if there is no Expect header, otherwise
1004
// returns the expected HTTP status code, typically `HTTP_STATUS_CONTINUE`.
1005
//
1006
1007
http_status_t       // O - Expect: status, if any
1008
httpGetExpect(http_t *http)   // I - HTTP connection
1009
0
{
1010
0
  if (!http)
1011
0
    return (HTTP_STATUS_ERROR);
1012
0
  else
1013
0
    return (http->expect);
1014
0
}
1015
1016
1017
//
1018
// 'httpGetFd()' - Get the file descriptor associated with a connection.
1019
//
1020
1021
int         // O - File descriptor or -1 if none
1022
httpGetFd(http_t *http)     // I - HTTP connection
1023
0
{
1024
0
  return (http ? http->fd : -1);
1025
0
}
1026
1027
1028
//
1029
// 'httpGetField()' - Get a field value from a request/response.
1030
//
1031
1032
const char *        // O - Field value
1033
httpGetField(http_t       *http,  // I - HTTP connection
1034
             http_field_t field)  // I - Field to get
1035
0
{
1036
0
  if (!http || field <= HTTP_FIELD_UNKNOWN || field >= HTTP_FIELD_MAX)
1037
0
    return (NULL);
1038
0
  else if (http->fields[field])
1039
0
    return (http->fields[field]);
1040
0
  else
1041
0
    return ("");
1042
0
}
1043
1044
1045
//
1046
// 'httpGetKeepAlive()' - Get the current Keep-Alive state of the connection.
1047
//
1048
1049
http_keepalive_t      // O - Keep-Alive state
1050
httpGetKeepAlive(http_t *http)    // I - HTTP connection
1051
0
{
1052
0
  return (http ? http->keep_alive : HTTP_KEEPALIVE_OFF);
1053
0
}
1054
1055
1056
//
1057
// 'httpGetLength()' - Get the amount of data remaining from the content-length
1058
//                     or transfer-encoding fields.
1059
//
1060
// This function returns the complete content length, even for content larger
1061
// than 2^31 - 1.
1062
//
1063
1064
off_t         // O - Content length
1065
httpGetLength(http_t *http)   // I - HTTP connection
1066
0
{
1067
0
  off_t     remaining;  // Remaining length
1068
1069
1070
0
  DEBUG_printf("2httpGetLength(http=%p), state=%s", (void *)http, http ? httpStateString(http->state) : "NONE");
1071
1072
0
  if (!http)
1073
0
  {
1074
0
    remaining = -1;
1075
0
  }
1076
0
  else if (http->fields[HTTP_FIELD_TRANSFER_ENCODING])
1077
0
  {
1078
    // Chunked content?
1079
0
    if (!_cups_strcasecmp(http->fields[HTTP_FIELD_TRANSFER_ENCODING], "chunked"))
1080
0
    {
1081
0
      DEBUG_puts("4httpGetLength: chunked request.");
1082
0
      remaining = 0;
1083
0
    }
1084
0
    else
1085
0
    {
1086
0
      DEBUG_printf("4httpGetLength: Unknown Transfer-Encoding '%s'.", http->fields[HTTP_FIELD_TRANSFER_ENCODING]);
1087
0
      remaining = -1;
1088
0
    }
1089
0
  }
1090
0
  else if (http->fields[HTTP_FIELD_CONTENT_LENGTH] && http->fields[HTTP_FIELD_CONTENT_LENGTH][0])
1091
0
  {
1092
    // Fixed length content...
1093
0
    char *end;        // Pointer to end of value
1094
1095
0
    if ((remaining = strtoll(http->fields[HTTP_FIELD_CONTENT_LENGTH], &end, 10)) < 0 || (remaining == 0 && errno == ERANGE) || *end)
1096
0
    {
1097
0
      DEBUG_printf("4httpGetLength: Bad Content-Length '%s'.", http->fields[HTTP_FIELD_CONTENT_LENGTH]);
1098
0
      remaining = -1;
1099
0
    }
1100
0
  }
1101
0
  else
1102
0
  {
1103
    // The following is a hack for HTTP servers that don't send a Content-Length
1104
    // or Transfer-Encoding field.  If there is no Content-Length then the
1105
    // connection must close after the transfer is complete.  The default
1106
    // content length is 0 for errors and certain types of operations, and
1107
    // 2^31-1 for other successful requests...
1108
0
    if (http->status >= HTTP_STATUS_MULTIPLE_CHOICES || http->state == HTTP_STATE_OPTIONS || (http->state == HTTP_STATE_GET && http->mode == _HTTP_MODE_SERVER) || http->state == HTTP_STATE_HEAD || (http->state == HTTP_STATE_PUT && http->mode == _HTTP_MODE_CLIENT) || http->state == HTTP_STATE_DELETE || http->state == HTTP_STATE_TRACE || http->state == HTTP_STATE_CONNECT)
1109
0
      remaining = 0;
1110
0
    else
1111
0
      remaining = 2147483647;
1112
0
  }
1113
1114
0
  DEBUG_printf("4httpGetLength: Returning " CUPS_LLFMT ".", CUPS_LLCAST remaining);
1115
1116
0
  return (remaining);
1117
0
}
1118
1119
1120
//
1121
// 'httpGetPending()' - Get the number of bytes that are buffered for writing.
1122
//
1123
1124
size_t          // O - Number of bytes buffered
1125
httpGetPending(http_t *http)    // I - HTTP connection
1126
0
{
1127
0
  return (http ? (size_t)http->wused : 0);
1128
0
}
1129
1130
1131
//
1132
// 'httpGetReady()' - Get the number of bytes that can be read without blocking.
1133
//
1134
1135
size_t          // O - Number of bytes available
1136
httpGetReady(http_t *http)    // I - HTTP connection
1137
0
{
1138
0
  if (!http)
1139
0
    return (0);
1140
0
  else if (http->used > 0)
1141
0
    return ((size_t)http->used);
1142
0
  else if (http->tls)
1143
0
    return (_httpTLSPending(http));
1144
1145
0
  return (0);
1146
0
}
1147
1148
1149
//
1150
// 'httpGetRemaining()' - Get the number of remaining bytes in the message
1151
//                        body or current chunk.
1152
//
1153
// The @link httpIsChunked@ function can be used to determine whether the
1154
// message body is chunked or fixed-length.
1155
//
1156
1157
size_t          // O - Remaining bytes
1158
httpGetRemaining(http_t *http)    // I - HTTP connection
1159
0
{
1160
0
  return (http ? (size_t)http->data_remaining : 0);
1161
0
}
1162
1163
1164
//
1165
// 'httpGets()' - Get a line of text from a HTTP connection.
1166
//
1167
1168
char *          // O - Line or `NULL`
1169
httpGets(http_t *http,      // I - HTTP connection
1170
         char   *line,      // I - Line to read into
1171
         size_t length)     // I - Max length of buffer
1172
0
{
1173
0
  char    *lineptr,   // Pointer into line
1174
0
    *lineend,   // End of line
1175
0
    *bufptr,    // Pointer into input buffer
1176
0
          *bufend;    // Pointer to end of buffer
1177
0
  ssize_t bytes;      // Number of bytes read
1178
0
  int   eol;      // End-of-line?
1179
1180
1181
0
  DEBUG_printf("2httpGets(http=%p, line=%p, length=%u)", (void *)http, (void *)line, (unsigned)length);
1182
1183
0
  if (!http || !line || length <= 1)
1184
0
    return (NULL);
1185
1186
  // Read a line from the buffer...
1187
0
  http->error = 0;
1188
0
  lineptr     = line;
1189
0
  lineend     = line + length - 1;
1190
0
  eol         = 0;
1191
1192
0
  while (lineptr < lineend)
1193
0
  {
1194
    // Pre-load the buffer as needed...
1195
#ifdef _WIN32
1196
    WSASetLastError(0);
1197
#else
1198
0
    errno = 0;
1199
0
#endif // _WIN32
1200
1201
0
    while (http->used == 0)
1202
0
    {
1203
      // No newline; see if there is more data to be read...
1204
0
      while (!_httpWait(http, http->wait_value, 1))
1205
0
      {
1206
0
  if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
1207
0
    continue;
1208
1209
0
        DEBUG_puts("3httpGets: Timed out!");
1210
#ifdef _WIN32
1211
        http->error = WSAETIMEDOUT;
1212
#else
1213
0
        http->error = ETIMEDOUT;
1214
0
#endif // _WIN32
1215
0
        return (NULL);
1216
0
      }
1217
1218
0
      bytes = http_read(http, http->buffer + http->used, (size_t)(_HTTP_MAX_BUFFER - http->used), http->wait_value);
1219
1220
0
      DEBUG_printf("4httpGets: read " CUPS_LLFMT " bytes.", CUPS_LLCAST bytes);
1221
1222
0
      if (bytes < 0)
1223
0
      {
1224
        // Nope, can't get a line this time...
1225
#ifdef _WIN32
1226
        DEBUG_printf("3httpGets: recv() error %d!", WSAGetLastError());
1227
1228
        if (WSAGetLastError() == WSAEINTR)
1229
        {
1230
    continue;
1231
  }
1232
  else if (WSAGetLastError() == WSAEWOULDBLOCK)
1233
  {
1234
    if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
1235
      continue;
1236
1237
    http->error = WSAGetLastError();
1238
  }
1239
  else if (WSAGetLastError() != http->error)
1240
  {
1241
    http->error = WSAGetLastError();
1242
    continue;
1243
  }
1244
1245
#else
1246
0
        DEBUG_printf("3httpGets: recv() error %d!", errno);
1247
1248
0
        if (errno == EINTR)
1249
0
        {
1250
0
    continue;
1251
0
  }
1252
0
  else if (errno == EWOULDBLOCK || errno == EAGAIN)
1253
0
  {
1254
0
    if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
1255
0
      continue;
1256
0
    else if (!http->timeout_cb && errno == EAGAIN)
1257
0
      continue;
1258
1259
0
    http->error = errno;
1260
0
  }
1261
0
  else if (errno != http->error)
1262
0
  {
1263
0
    http->error = errno;
1264
0
    continue;
1265
0
  }
1266
0
#endif // _WIN32
1267
1268
0
        return (NULL);
1269
0
      }
1270
0
      else if (bytes == 0)
1271
0
      {
1272
0
  http->error = EPIPE;
1273
1274
0
        return (NULL);
1275
0
      }
1276
1277
      // Yup, update the amount used...
1278
0
      http->used += (int)bytes;
1279
0
    }
1280
1281
    // Now copy as much of the current line as possible...
1282
0
    for (bufptr = http->buffer, bufend = http->buffer + http->used; lineptr < lineend && bufptr < bufend;)
1283
0
    {
1284
0
      if (*bufptr == 0x0a)
1285
0
      {
1286
0
        eol = 1;
1287
0
  bufptr ++;
1288
0
  break;
1289
0
      }
1290
0
      else if (*bufptr == 0x0d)
1291
0
      {
1292
0
  bufptr ++;
1293
0
      }
1294
0
      else
1295
0
      {
1296
0
  *lineptr++ = *bufptr++;
1297
0
      }
1298
0
    }
1299
1300
0
    http->used -= (int)(bufptr - http->buffer);
1301
0
    if (http->used > 0)
1302
0
      memmove(http->buffer, bufptr, (size_t)http->used);
1303
1304
0
    if (eol)
1305
0
    {
1306
      // End of line...
1307
0
      http->activity = time(NULL);
1308
1309
0
      *lineptr = '\0';
1310
1311
0
      DEBUG_printf("3httpGets: Returning \"%s\"", line);
1312
1313
0
      return (line);
1314
0
    }
1315
0
  }
1316
1317
0
  DEBUG_puts("3httpGets: No new line available!");
1318
1319
0
  return (NULL);
1320
0
}
1321
1322
1323
//
1324
// 'httpGetState()' - Get the current state of the HTTP request.
1325
//
1326
1327
http_state_t        // O - HTTP state
1328
httpGetState(http_t *http)    // I - HTTP connection
1329
0
{
1330
0
  return (http ? http->state : HTTP_STATE_ERROR);
1331
0
}
1332
1333
1334
//
1335
// 'httpGetStatus()' - Get the status of the last HTTP request.
1336
//
1337
//
1338
//
1339
1340
http_status_t       // O - HTTP status
1341
httpGetStatus(http_t *http)   // I - HTTP connection
1342
0
{
1343
0
  return (http ? http->status : HTTP_STATUS_ERROR);
1344
0
}
1345
1346
1347
//
1348
// 'httpGetSubField()' - Get a sub-field value.
1349
//
1350
1351
char *          // O - Value or `NULL`
1352
httpGetSubField(http_t       *http, // I - HTTP connection
1353
                http_field_t field, // I - Field index
1354
                const char   *name, // I - Name of sub-field
1355
    char         *value,  // O - Value string
1356
    size_t       valuelen)  // I - Size of value buffer
1357
0
{
1358
0
  const char  *fptr;      // Pointer into field
1359
0
  char    temp[_HTTP_MAX_VALUE],  // Temporary buffer for name
1360
0
    *ptr,     // Pointer into string buffer
1361
0
    *end;     // End of value buffer
1362
1363
1364
0
  DEBUG_printf("2httpGetSubField(http=%p, field=%d, name=\"%s\", value=%p, valuelen=%u)", (void *)http, field, name, (void *)value, (unsigned)valuelen);
1365
1366
0
  if (value)
1367
0
    *value = '\0';
1368
1369
0
  if (!http || !name || !value || valuelen < 2 || field <= HTTP_FIELD_UNKNOWN || field >= HTTP_FIELD_MAX || !http->fields[field])
1370
0
    return (NULL);
1371
1372
0
  end = value + valuelen - 1;
1373
1374
0
  for (fptr = http->fields[field]; *fptr;)
1375
0
  {
1376
    // Skip leading whitespace...
1377
0
    while (_cups_isspace(*fptr))
1378
0
      fptr ++;
1379
1380
0
    if (*fptr == ',')
1381
0
    {
1382
0
      fptr ++;
1383
0
      continue;
1384
0
    }
1385
1386
    // Get the sub-field name...
1387
0
    for (ptr = temp; *fptr && *fptr != '=' && !_cups_isspace(*fptr) && ptr < (temp + sizeof(temp) - 1); *ptr++ = *fptr++);
1388
1389
0
    *ptr = '\0';
1390
1391
0
    DEBUG_printf("4httpGetSubField: name=\"%s\"", temp);
1392
1393
    // Skip trailing chars up to the '='...
1394
0
    while (_cups_isspace(*fptr))
1395
0
      fptr ++;
1396
1397
0
    if (!*fptr)
1398
0
      break;
1399
1400
0
    if (*fptr != '=')
1401
0
      continue;
1402
1403
    // Skip = and leading whitespace...
1404
0
    fptr ++;
1405
1406
0
    while (_cups_isspace(*fptr))
1407
0
      fptr ++;
1408
1409
0
    if (*fptr == '\"')
1410
0
    {
1411
      // Read quoted string...
1412
0
      for (ptr = value, fptr ++; *fptr && *fptr != '\"' && ptr < end; *ptr++ = *fptr++);
1413
1414
0
      *ptr = '\0';
1415
1416
0
      while (*fptr && *fptr != '\"')
1417
0
        fptr ++;
1418
1419
0
      if (*fptr)
1420
0
        fptr ++;
1421
0
    }
1422
0
    else
1423
0
    {
1424
      // Read unquoted string...
1425
0
      for (ptr = value; *fptr && !_cups_isspace(*fptr) && *fptr != ',' && ptr < end; *ptr++ = *fptr++);
1426
1427
0
      *ptr = '\0';
1428
1429
0
      while (*fptr && !_cups_isspace(*fptr) && *fptr != ',')
1430
0
        fptr ++;
1431
0
    }
1432
1433
0
    DEBUG_printf("4httpGetSubField: value=\"%s\"", value);
1434
1435
    // See if this is the one...
1436
0
    if (!strcmp(name, temp))
1437
0
    {
1438
0
      DEBUG_printf("3httpGetSubField: Returning \"%s\"", value);
1439
0
      return (value);
1440
0
    }
1441
0
  }
1442
1443
0
  value[0] = '\0';
1444
1445
0
  DEBUG_puts("3httpGetSubField: Returning NULL");
1446
1447
0
  return (NULL);
1448
0
}
1449
1450
1451
//
1452
// 'httpGetVersion()' - Get the HTTP version at the other end.
1453
//
1454
1455
http_version_t        // O - Version number
1456
httpGetVersion(http_t *http)    // I - HTTP connection
1457
0
{
1458
0
  return (http ? http->version : HTTP_VERSION_1_0);
1459
0
}
1460
1461
1462
//
1463
// 'httpInitialize()' - Initialize the HTTP interface library and set the default HTTP proxy (if any).
1464
//
1465
1466
void
1467
httpInitialize(void)
1468
0
{
1469
0
  static int  initialized = 0;  // Have we been called before?
1470
#ifdef _WIN32
1471
  WSADATA winsockdata;    // WinSock data
1472
#endif // _WIN32
1473
1474
1475
0
  _cupsGlobalLock();
1476
0
  if (initialized)
1477
0
  {
1478
0
    _cupsGlobalUnlock();
1479
0
    return;
1480
0
  }
1481
1482
#ifdef _WIN32
1483
  WSAStartup(MAKEWORD(2,2), &winsockdata);
1484
1485
#elif !defined(SO_NOSIGPIPE)
1486
  // Ignore SIGPIPE signals...
1487
0
  struct sigaction  action;   // POSIX sigaction data
1488
1489
0
  memset(&action, 0, sizeof(action));
1490
0
  action.sa_handler = SIG_IGN;
1491
0
  sigaction(SIGPIPE, &action, NULL);
1492
0
#endif // _WIN32
1493
1494
0
  _httpTLSInitialize();
1495
1496
0
  initialized = 1;
1497
0
  _cupsGlobalUnlock();
1498
0
}
1499
1500
1501
//
1502
// 'httpIsChunked()' - Report whether a message body is chunked.
1503
//
1504
// This function returns `true` if the message body is composed of
1505
// variable-length chunks.
1506
//
1507
1508
bool          // O - `true` if chunked, `false` if not
1509
httpIsChunked(http_t *http)   // I - HTTP connection
1510
0
{
1511
0
  return (http ? http->data_encoding == HTTP_ENCODING_CHUNKED : 0);
1512
0
}
1513
1514
1515
//
1516
// 'httpIsEncrypted()' - Report whether a connection is encrypted.
1517
//
1518
// This function returns `true` if the connection is currently encrypted.
1519
//
1520
1521
bool          // O - `true` if encrypted, `false` if not
1522
httpIsEncrypted(http_t *http)   // I - HTTP connection
1523
0
{
1524
0
  return (http ? http->tls != NULL : 0);
1525
0
}
1526
1527
1528
//
1529
// 'httpPeek()' - Peek at data from a HTTP connection.
1530
//
1531
// This function copies available data from the given HTTP connection, reading
1532
// a buffer as needed.  The data is still available for reading using
1533
// @link httpRead@.
1534
//
1535
// For non-blocking connections the usual timeouts apply.
1536
//
1537
1538
ssize_t         // O - Number of bytes copied
1539
httpPeek(http_t *http,      // I - HTTP connection
1540
         char   *buffer,    // I - Buffer for data
1541
   size_t length)     // I - Maximum number of bytes
1542
0
{
1543
0
  ssize_t bytes;      // Bytes read
1544
0
  char    len[32];    // Length string
1545
1546
1547
0
  DEBUG_printf("httpPeek(http=%p, buffer=%p, length=" CUPS_LLFMT ")", (void *)http, (void *)buffer, CUPS_LLCAST length);
1548
1549
0
  if (http == NULL || buffer == NULL)
1550
0
    return (-1);
1551
1552
0
  http->activity = time(NULL);
1553
0
  http->error    = 0;
1554
1555
0
  if (length <= 0)
1556
0
    return (0);
1557
1558
0
  if (http->data_encoding == HTTP_ENCODING_CHUNKED && http->data_remaining <= 0)
1559
0
  {
1560
0
    DEBUG_puts("2httpPeek: Getting chunk length...");
1561
1562
0
    if (httpGets(http, len, sizeof(len)) == NULL)
1563
0
    {
1564
0
      DEBUG_puts("1httpPeek: Could not get length!");
1565
0
      return (0);
1566
0
    }
1567
1568
0
    if (!len[0])
1569
0
    {
1570
0
      DEBUG_puts("1httpPeek: Blank chunk length, trying again...");
1571
0
      if (!httpGets(http, len, sizeof(len)))
1572
0
      {
1573
0
  DEBUG_puts("1httpPeek: Could not get chunk length.");
1574
0
  return (0);
1575
0
      }
1576
0
    }
1577
1578
0
    http->data_remaining = strtoll(len, NULL, 16);
1579
1580
0
    if (http->data_remaining < 0)
1581
0
    {
1582
0
      DEBUG_puts("1httpPeek: Negative chunk length!");
1583
0
      return (0);
1584
0
    }
1585
0
  }
1586
1587
0
  DEBUG_printf("2httpPeek: data_remaining=" CUPS_LLFMT, CUPS_LLCAST http->data_remaining);
1588
1589
0
  if (http->data_remaining <= 0 && http->data_encoding != HTTP_ENCODING_FIELDS)
1590
0
  {
1591
    // A zero-length chunk ends a transfer; unless we are reading POST data, go idle...
1592
0
    if (http->coding >= _HTTP_CODING_GUNZIP)
1593
0
      http_content_coding_finish(http);
1594
1595
0
    if (http->data_encoding == HTTP_ENCODING_CHUNKED)
1596
0
      httpGets(http, len, sizeof(len));
1597
1598
0
    if (http->state == HTTP_STATE_LOCK_RECV || http->state == HTTP_STATE_POST_RECV || http->state == HTTP_STATE_PROPFIND_RECV || http->state == HTTP_STATE_PROPPATCH_RECV)
1599
0
      http->state ++;
1600
0
    else
1601
0
      http->state = HTTP_STATE_STATUS;
1602
1603
0
    DEBUG_printf("1httpPeek: 0-length chunk, set state to %s.", httpStateString(http->state));
1604
1605
    // Prevent future reads for this request...
1606
0
    http->data_encoding = HTTP_ENCODING_FIELDS;
1607
1608
0
    return (0);
1609
0
  }
1610
0
  else if (length > (size_t)http->data_remaining)
1611
0
  {
1612
0
    length = (size_t)http->data_remaining;
1613
0
  }
1614
1615
0
  if (http->used == 0 && (http->coding == _HTTP_CODING_IDENTITY || (http->coding >= _HTTP_CODING_GUNZIP && ((z_stream *)http->stream)->avail_in == 0)))
1616
0
  {
1617
    // Buffer small reads for better performance...
1618
0
    ssize_t buflen;     // Length of read for buffer
1619
1620
0
    if (!http->blocking)
1621
0
    {
1622
0
      while (!httpWait(http, http->wait_value))
1623
0
      {
1624
0
  if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
1625
0
    continue;
1626
1627
0
  return (0);
1628
0
      }
1629
0
    }
1630
1631
0
    if ((size_t)http->data_remaining > sizeof(http->buffer))
1632
0
      buflen = sizeof(http->buffer);
1633
0
    else
1634
0
      buflen = (ssize_t)http->data_remaining;
1635
1636
0
    DEBUG_printf("2httpPeek: Reading %d bytes into buffer.", (int)buflen);
1637
0
    bytes = http_read(http, http->buffer, (size_t)buflen, http->wait_value);
1638
1639
0
    DEBUG_printf("2httpPeek: Read " CUPS_LLFMT " bytes into buffer.", CUPS_LLCAST bytes);
1640
0
    if (bytes > 0)
1641
0
    {
1642
#ifdef DEBUG
1643
      http_debug_hex("httpPeek", http->buffer, (int)bytes);
1644
#endif // DEBUG
1645
1646
0
      http->used = (int)bytes;
1647
0
    }
1648
0
  }
1649
1650
0
  if (http->coding >= _HTTP_CODING_GUNZIP)
1651
0
  {
1652
0
    int   zerr;     // Decompressor error
1653
0
    z_stream  stream;     // Copy of decompressor stream
1654
1655
0
    memset(&stream, 0, sizeof(stream));
1656
1657
0
    if (http->used > 0 && ((z_stream *)http->stream)->avail_in < _HTTP_MAX_BUFFER)
1658
0
    {
1659
0
      size_t buflen = _HTTP_MAX_BUFFER - ((z_stream *)http->stream)->avail_in;
1660
          // Number of bytes to copy
1661
1662
0
      if (((z_stream *)http->stream)->avail_in > 0 && ((z_stream *)http->stream)->next_in > http->sbuffer)
1663
0
        memmove(http->sbuffer, ((z_stream *)http->stream)->next_in, ((z_stream *)http->stream)->avail_in);
1664
1665
0
      ((z_stream *)http->stream)->next_in = http->sbuffer;
1666
1667
0
      if (buflen > (size_t)http->data_remaining)
1668
0
        buflen = (size_t)http->data_remaining;
1669
1670
0
      if (buflen > (size_t)http->used)
1671
0
        buflen = (size_t)http->used;
1672
1673
0
      DEBUG_printf("1httpPeek: Copying %d more bytes of data into decompression buffer.", (int)buflen);
1674
1675
0
      memcpy(http->sbuffer + ((z_stream *)http->stream)->avail_in, http->buffer, buflen);
1676
0
      ((z_stream *)http->stream)->avail_in += buflen;
1677
0
      http->used            -= (int)buflen;
1678
0
      http->data_remaining  -= (off_t)buflen;
1679
1680
0
      if (http->used > 0)
1681
0
        memmove(http->buffer, http->buffer + buflen, (size_t)http->used);
1682
0
    }
1683
1684
0
    DEBUG_printf("2httpPeek: length=%d, avail_in=%d", (int)length, (int)((z_stream *)http->stream)->avail_in);
1685
1686
0
    if (inflateCopy(&stream, (z_stream *)http->stream) != Z_OK)
1687
0
    {
1688
0
      DEBUG_puts("2httpPeek: Unable to copy decompressor stream.");
1689
0
      http->error = ENOMEM;
1690
0
      return (-1);
1691
0
    }
1692
1693
0
    stream.next_out  = (Bytef *)buffer;
1694
0
    stream.avail_out = (uInt)length;
1695
1696
0
    zerr  = inflate(&stream, Z_SYNC_FLUSH);
1697
0
    bytes = (ssize_t)(length - stream.avail_out);
1698
1699
0
    inflateEnd(&stream);
1700
1701
0
    if (zerr < Z_OK)
1702
0
    {
1703
0
      DEBUG_printf("2httpPeek: zerr=%d", zerr);
1704
#ifdef DEBUG
1705
      http_debug_hex("2httpPeek", (char *)http->sbuffer, (int)stream.avail_in);
1706
#endif // DEBUG
1707
1708
0
      http->error = EIO;
1709
0
      return (-1);
1710
0
    }
1711
0
  }
1712
0
  else if (http->used > 0)
1713
0
  {
1714
0
    if (length > (size_t)http->used)
1715
0
      length = (size_t)http->used;
1716
1717
0
    bytes = (ssize_t)length;
1718
1719
0
    DEBUG_printf("2httpPeek: grabbing %d bytes from input buffer...", (int)bytes);
1720
1721
0
    memcpy(buffer, http->buffer, length);
1722
0
  }
1723
0
  else
1724
0
  {
1725
0
    bytes = 0;
1726
0
  }
1727
1728
0
  if (bytes < 0)
1729
0
  {
1730
#ifdef _WIN32
1731
    if (WSAGetLastError() == WSAEINTR || WSAGetLastError() == WSAEWOULDBLOCK)
1732
      bytes = 0;
1733
    else
1734
      http->error = WSAGetLastError();
1735
1736
#else
1737
0
    if (errno == EINTR || errno == EAGAIN)
1738
0
      bytes = 0;
1739
0
    else
1740
0
      http->error = errno;
1741
0
#endif // _WIN32
1742
0
  }
1743
0
  else if (bytes == 0)
1744
0
  {
1745
0
    http->error = EPIPE;
1746
0
    return (0);
1747
0
  }
1748
1749
0
  return (bytes);
1750
0
}
1751
1752
1753
//
1754
// 'httpPrintf()' - Print a formatted string to a HTTP connection.
1755
//
1756
1757
ssize_t         // O - Number of bytes written or `-1` on error
1758
httpPrintf(http_t     *http,    // I - HTTP connection
1759
           const char *format,    // I - printf-style format string
1760
     ...)       // I - Additional args as needed
1761
0
{
1762
0
  ssize_t bytes;      // Number of bytes to write
1763
0
  va_list ap, ap2;    // Variable argument pointers
1764
0
  char    *temp;      // Temporary buffer pointer
1765
1766
1767
0
  DEBUG_printf("2httpPrintf(http=%p, format=\"%s\", ...)", (void *)http, format);
1768
1769
0
  va_start(ap, format);
1770
0
  while (true)
1771
0
  {
1772
0
    va_copy(ap2, ap);
1773
0
    bytes = vsnprintf(http->fbuffer, http->fbufsize, format, ap2);
1774
1775
0
    if (bytes < (ssize_t)http->fbufsize || bytes >= _HTTP_MAX_PRINTF)
1776
0
      break;
1777
1778
0
    if ((temp = realloc(http->fbuffer, (size_t)bytes + 1)) == NULL)
1779
0
      break;
1780
1781
0
    http->fbuffer  = temp;
1782
0
    http->fbufsize = (size_t)bytes + 1;
1783
0
  }
1784
0
  va_end(ap);
1785
1786
0
  DEBUG_printf("3httpPrintf: (" CUPS_LLFMT " bytes) %s", CUPS_LLCAST bytes, http->fbuffer);
1787
1788
0
  if (bytes < 0 || bytes >= (ssize_t)http->fbufsize)
1789
0
  {
1790
0
    http->error = ENOMEM;
1791
0
    return (-1);
1792
0
  }
1793
0
  else if (http->data_encoding == HTTP_ENCODING_FIELDS)
1794
0
  {
1795
0
    return (httpWrite(http, http->fbuffer, (size_t)bytes));
1796
0
  }
1797
0
  else
1798
0
  {
1799
0
    if (http->wused)
1800
0
    {
1801
0
      DEBUG_puts("4httpPrintf: flushing existing data...");
1802
1803
0
      if (httpFlushWrite(http) < 0)
1804
0
  return (-1);
1805
0
    }
1806
1807
0
    return (http_write(http, http->fbuffer, (size_t)bytes));
1808
0
  }
1809
0
}
1810
1811
1812
//
1813
// 'httpRead()' - Read data from a HTTP connection.
1814
//
1815
1816
ssize_t         // O - Number of bytes read
1817
httpRead(http_t *http,      // I - HTTP connection
1818
         char   *buffer,    // I - Buffer for data
1819
   size_t length)     // I - Maximum number of bytes
1820
0
{
1821
0
  ssize_t bytes;      // Bytes read
1822
1823
1824
0
  DEBUG_printf("httpRead(http=%p, buffer=%p, length=" CUPS_LLFMT ") coding=%d data_encoding=%d data_remaining=" CUPS_LLFMT, (void *)http, (void *)buffer, CUPS_LLCAST length, http ? http->coding : 0, http ? http->data_encoding : 0, CUPS_LLCAST (http ? http->data_remaining : -1));
1825
1826
0
  if (http == NULL || buffer == NULL)
1827
0
    return (-1);
1828
1829
0
  http->activity = time(NULL);
1830
0
  http->error    = 0;
1831
1832
0
  if (length <= 0)
1833
0
    return (0);
1834
1835
0
  if (http->coding >= _HTTP_CODING_GUNZIP)
1836
0
  {
1837
0
    do
1838
0
    {
1839
0
      if (((z_stream *)http->stream)->avail_in > 0)
1840
0
      {
1841
0
  int zerr;     // Decompressor error
1842
1843
0
  DEBUG_printf("2httpRead: avail_in=%d, avail_out=%d", (int)((z_stream *)http->stream)->avail_in, (int)length);
1844
1845
0
  ((z_stream *)http->stream)->next_out  = (Bytef *)buffer;
1846
0
  ((z_stream *)http->stream)->avail_out = (uInt)length;
1847
1848
0
  if ((zerr = inflate((z_stream *)http->stream, Z_SYNC_FLUSH)) < Z_OK)
1849
0
  {
1850
0
    DEBUG_printf("2httpRead: zerr=%d", zerr);
1851
#ifdef DEBUG
1852
          http_debug_hex("2httpRead", (char *)http->sbuffer, (int)((z_stream *)http->stream)->avail_in);
1853
#endif // DEBUG
1854
1855
0
    http->error = EIO;
1856
0
    return (-1);
1857
0
  }
1858
1859
0
  bytes = (ssize_t)(length - ((z_stream *)http->stream)->avail_out);
1860
1861
0
  DEBUG_printf("2httpRead: avail_in=%d, avail_out=%d, bytes=%d", ((z_stream *)http->stream)->avail_in, ((z_stream *)http->stream)->avail_out, (int)bytes);
1862
0
      }
1863
0
      else
1864
0
      {
1865
0
        bytes = 0;
1866
0
      }
1867
1868
0
      if (bytes == 0)
1869
0
      {
1870
0
        ssize_t buflen = _HTTP_MAX_BUFFER - (ssize_t)((z_stream *)http->stream)->avail_in;
1871
          // Additional bytes for buffer
1872
1873
0
        if (buflen > 0)
1874
0
        {
1875
0
          if (((z_stream *)http->stream)->avail_in > 0 && ((z_stream *)http->stream)->next_in > http->sbuffer)
1876
0
            memmove(http->sbuffer, ((z_stream *)http->stream)->next_in, ((z_stream *)http->stream)->avail_in);
1877
1878
0
    ((z_stream *)http->stream)->next_in = http->sbuffer;
1879
1880
0
          DEBUG_printf("1httpRead: Reading up to %d more bytes of data into decompression buffer.", (int)buflen);
1881
1882
0
          if (http->data_remaining > 0)
1883
0
          {
1884
0
      if (buflen > http->data_remaining)
1885
0
        buflen = (ssize_t)http->data_remaining;
1886
1887
0
      bytes = http_read_buffered(http, (char *)http->sbuffer + ((z_stream *)http->stream)->avail_in, (size_t)buflen);
1888
0
          }
1889
0
          else if (http->data_encoding == HTTP_ENCODING_CHUNKED)
1890
0
          {
1891
0
            bytes = http_read_chunk(http, (char *)http->sbuffer + ((z_stream *)http->stream)->avail_in, (size_t)buflen);
1892
0
          }
1893
0
          else
1894
0
          {
1895
0
            bytes = 0;
1896
0
          }
1897
1898
0
          if (bytes < 0)
1899
0
            return (bytes);
1900
0
          else if (bytes == 0)
1901
0
            break;
1902
1903
0
          DEBUG_printf("1httpRead: Adding " CUPS_LLFMT " bytes to decompression buffer.", CUPS_LLCAST bytes);
1904
1905
0
          http->data_remaining -= bytes;
1906
0
          ((z_stream *)http->stream)->avail_in += (uInt)bytes;
1907
1908
0
    if (http->data_remaining <= 0 && http->data_encoding == HTTP_ENCODING_CHUNKED)
1909
0
    {
1910
      // Read the trailing blank line now...
1911
0
      char  len[32];    // Length string
1912
1913
0
      httpGets(http, len, sizeof(len));
1914
0
    }
1915
1916
0
          bytes = 0;
1917
0
        }
1918
0
        else
1919
0
        {
1920
0
          return (0);
1921
0
        }
1922
0
      }
1923
0
    }
1924
0
    while (bytes == 0);
1925
0
  }
1926
0
  else if (http->data_remaining == 0 && http->data_encoding == HTTP_ENCODING_CHUNKED)
1927
0
  {
1928
0
    if ((bytes = http_read_chunk(http, buffer, length)) > 0)
1929
0
    {
1930
0
      http->data_remaining -= bytes;
1931
1932
0
      if (http->data_remaining <= 0)
1933
0
      {
1934
        // Read the trailing blank line now...
1935
0
        char  len[32];    // Length string
1936
1937
0
        httpGets(http, len, sizeof(len));
1938
0
      }
1939
0
    }
1940
0
  }
1941
0
  else if (http->data_remaining <= 0)
1942
0
  {
1943
    // No more data to read...
1944
0
    return (0);
1945
0
  }
1946
0
  else
1947
0
  {
1948
0
    DEBUG_printf("1httpRead: Reading up to %d bytes into buffer.", (int)length);
1949
1950
0
    if (length > (size_t)http->data_remaining)
1951
0
      length = (size_t)http->data_remaining;
1952
1953
0
    if ((bytes = http_read_buffered(http, buffer, length)) > 0)
1954
0
    {
1955
0
      http->data_remaining -= bytes;
1956
1957
0
      if (http->data_remaining <= 0 && http->data_encoding == HTTP_ENCODING_CHUNKED)
1958
0
      {
1959
        // Read the trailing blank line now...
1960
0
        char  len[32];    // Length string
1961
1962
0
        httpGets(http, len, sizeof(len));
1963
0
      }
1964
0
    }
1965
0
  }
1966
1967
0
  if ((http->coding == _HTTP_CODING_IDENTITY ||
1968
0
       (http->coding >= _HTTP_CODING_GUNZIP && ((z_stream *)http->stream)->avail_in == 0)) &&
1969
0
      ((http->data_remaining <= 0 && http->data_encoding == HTTP_ENCODING_LENGTH) ||
1970
0
       (http->data_encoding == HTTP_ENCODING_CHUNKED && bytes == 0)))
1971
0
  {
1972
0
    if (http->coding >= _HTTP_CODING_GUNZIP)
1973
0
      http_content_coding_finish(http);
1974
1975
0
    http_advance_state(http);
1976
1977
0
    DEBUG_printf("1httpRead: End of content, set state to %s.", httpStateString(http->state));
1978
0
  }
1979
1980
0
  return (bytes);
1981
0
}
1982
1983
1984
//
1985
// 'httpReadRequest()' - Read a HTTP request from a connection.
1986
//
1987
1988
http_state_t        // O - New state of connection
1989
httpReadRequest(http_t *http,   // I - HTTP connection
1990
                char   *uri,    // I - URI buffer
1991
    size_t urilen)    // I - Size of URI buffer
1992
0
{
1993
0
  char  line[4096],     // HTTP request line
1994
0
  *req_method,      // HTTP request method
1995
0
  *req_uri,     // HTTP request URI
1996
0
  *req_version;     // HTTP request version number string
1997
1998
1999
  // Range check input...
2000
0
  DEBUG_printf("httpReadRequest(http=%p, uri=%p, urilen=" CUPS_LLFMT ")", (void *)http, (void *)uri, CUPS_LLCAST urilen);
2001
2002
0
  if (uri)
2003
0
    *uri = '\0';
2004
2005
0
  if (!http || !uri || urilen < 1)
2006
0
  {
2007
0
    DEBUG_puts("1httpReadRequest: Bad arguments, returning HTTP_STATE_ERROR.");
2008
0
    return (HTTP_STATE_ERROR);
2009
0
  }
2010
0
  else if (http->state != HTTP_STATE_WAITING)
2011
0
  {
2012
0
    DEBUG_printf("1httpReadRequest: Bad state %s, returning HTTP_STATE_ERROR.", httpStateString(http->state));
2013
0
    return (HTTP_STATE_ERROR);
2014
0
  }
2015
2016
  // Reset state...
2017
0
  httpClearFields(http);
2018
2019
0
  http->activity       = time(NULL);
2020
0
  http->data_encoding  = HTTP_ENCODING_FIELDS;
2021
0
  http->data_remaining = 0;
2022
0
  http->keep_alive     = HTTP_KEEPALIVE_OFF;
2023
0
  http->status         = HTTP_STATUS_OK;
2024
0
  http->version        = HTTP_VERSION_1_1;
2025
2026
  // Read a line from the socket...
2027
0
  if (!httpGets(http, line, sizeof(line)))
2028
0
  {
2029
0
    DEBUG_puts("1httpReadRequest: Unable to read, returning HTTP_STATE_ERROR");
2030
0
    return (HTTP_STATE_ERROR);
2031
0
  }
2032
2033
0
  if (!line[0])
2034
0
  {
2035
0
    DEBUG_puts("1httpReadRequest: Blank line, returning HTTP_STATE_WAITING");
2036
0
    return (HTTP_STATE_WAITING);
2037
0
  }
2038
2039
0
  DEBUG_printf("1httpReadRequest: %s", line);
2040
2041
  // Parse it...
2042
0
  req_method = line;
2043
0
  req_uri    = line;
2044
2045
0
  while (*req_uri && !_cups_isspace(*req_uri))
2046
0
    req_uri ++;
2047
2048
0
  if (!*req_uri)
2049
0
  {
2050
0
    DEBUG_puts("1httpReadRequest: No request URI.");
2051
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("No request URI."), 1);
2052
0
    return (HTTP_STATE_ERROR);
2053
0
  }
2054
2055
0
  *req_uri++ = '\0';
2056
2057
0
  while (*req_uri && _cups_isspace(*req_uri))
2058
0
    req_uri ++;
2059
2060
0
  req_version = req_uri;
2061
2062
0
  while (*req_version && !_cups_isspace(*req_version))
2063
0
    req_version ++;
2064
2065
0
  if (!*req_version)
2066
0
  {
2067
0
    DEBUG_puts("1httpReadRequest: No request protocol version.");
2068
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("No request protocol version."), 1);
2069
0
    return (HTTP_STATE_ERROR);
2070
0
  }
2071
2072
0
  *req_version++ = '\0';
2073
2074
0
  while (*req_version && _cups_isspace(*req_version))
2075
0
    req_version ++;
2076
2077
  // Validate...
2078
0
  if (!strcmp(req_method, "CONNECT"))
2079
0
  {
2080
0
    http->state = HTTP_STATE_CONNECT;
2081
0
  }
2082
0
  else if (!strcmp(req_method, "COPY"))
2083
0
  {
2084
0
    http->state = HTTP_STATE_COPY;
2085
0
  }
2086
0
  else if (!strcmp(req_method, "DELETE"))
2087
0
  {
2088
0
    http->state = HTTP_STATE_DELETE;
2089
0
  }
2090
0
  else if (!strcmp(req_method, "GET"))
2091
0
  {
2092
0
    http->state = HTTP_STATE_GET;
2093
0
  }
2094
0
  else if (!strcmp(req_method, "HEAD"))
2095
0
  {
2096
0
    http->state = HTTP_STATE_HEAD;
2097
0
  }
2098
0
  else if (!strcmp(req_method, "LOCK"))
2099
0
  {
2100
0
    http->state = HTTP_STATE_LOCK;
2101
0
  }
2102
0
  else if (!strcmp(req_method, "MKCOL"))
2103
0
  {
2104
0
    http->state = HTTP_STATE_MKCOL;
2105
0
  }
2106
0
  else if (!strcmp(req_method, "MOVE"))
2107
0
  {
2108
0
    http->state = HTTP_STATE_MOVE;
2109
0
  }
2110
0
  else if (!strcmp(req_method, "OPTIONS"))
2111
0
  {
2112
0
    http->state = HTTP_STATE_OPTIONS;
2113
0
  }
2114
0
  else if (!strcmp(req_method, "POST"))
2115
0
  {
2116
0
    http->state = HTTP_STATE_POST;
2117
0
  }
2118
0
  else if (!strcmp(req_method, "PROPFIND"))
2119
0
  {
2120
0
    http->state = HTTP_STATE_PROPFIND;
2121
0
  }
2122
0
  else if (!strcmp(req_method, "PROPPATCH"))
2123
0
  {
2124
0
    http->state = HTTP_STATE_PROPPATCH;
2125
0
  }
2126
0
  else if (!strcmp(req_method, "PUT"))
2127
0
  {
2128
0
    http->state = HTTP_STATE_PUT;
2129
0
  }
2130
0
  else if (!strcmp(req_method, "TRACE"))
2131
0
  {
2132
0
    http->state = HTTP_STATE_TRACE;
2133
0
  }
2134
0
  else if (!strcmp(req_method, "UNLOCK"))
2135
0
  {
2136
0
    http->state = HTTP_STATE_UNLOCK;
2137
0
  }
2138
0
  else
2139
0
  {
2140
0
    DEBUG_printf("1httpReadRequest: Unknown method \"%s\".", req_method);
2141
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unknown request method."), 1);
2142
0
    return (HTTP_STATE_UNKNOWN_METHOD);
2143
0
  }
2144
2145
0
  DEBUG_printf("1httpReadRequest: Set state to %s.", httpStateString(http->state));
2146
2147
0
  if (!strcmp(req_version, "HTTP/1.0"))
2148
0
  {
2149
0
    http->version    = HTTP_VERSION_1_0;
2150
0
    http->keep_alive = HTTP_KEEPALIVE_OFF;
2151
0
  }
2152
0
  else if (!strcmp(req_version, "HTTP/1.1"))
2153
0
  {
2154
0
    http->version    = HTTP_VERSION_1_1;
2155
0
    http->keep_alive = HTTP_KEEPALIVE_ON;
2156
0
  }
2157
0
  else
2158
0
  {
2159
0
    DEBUG_printf("1httpReadRequest: Unknown version \"%s\".", req_version);
2160
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unknown request version."), 1);
2161
0
    return (HTTP_STATE_UNKNOWN_VERSION);
2162
0
  }
2163
2164
0
  DEBUG_printf("1httpReadRequest: URI is \"%s\".", req_uri);
2165
0
  cupsCopyString(uri, req_uri, urilen);
2166
2167
0
  return (http->state);
2168
0
}
2169
2170
2171
//
2172
// 'httpSetAuthString()' - Set the current authorization string.
2173
//
2174
// This function stores a copy of the current authorization string in the HTTP
2175
// connection object.  You must still call @link httpSetField@ to set
2176
// `HTTP_FIELD_AUTHORIZATION` prior to issuing a HTTP request using
2177
// @link httpWriteRequest@.
2178
//
2179
2180
void
2181
httpSetAuthString(http_t     *http, // I - HTTP connection
2182
                  const char *scheme, // I - Auth scheme (`NULL` to clear it)
2183
      const char *data) // I - Auth data (`NULL` for none)
2184
0
{
2185
  // Range check input...
2186
0
  DEBUG_printf("httpSetAuthString(http=%p, scheme=\"%s\", data=\"%s\")", (void *)http, scheme, data);
2187
2188
0
  if (!http)
2189
0
    return;
2190
2191
0
  free(http->authstring);
2192
2193
0
  if (scheme)
2194
0
  {
2195
    // Set the current authorization string...
2196
0
    size_t len = strlen(scheme) + (data ? strlen(data) + 1 : 0) + 1;
2197
2198
0
    if ((http->authstring = malloc(len)) != NULL)
2199
0
    {
2200
0
      if (data)
2201
0
  snprintf(http->authstring, len, "%s %s", scheme, data);
2202
0
      else
2203
0
  cupsCopyString(http->authstring, scheme, len);
2204
0
    }
2205
0
  }
2206
0
  else
2207
0
  {
2208
    // Clear the current authorization string...
2209
0
    http->authstring = NULL;
2210
0
  }
2211
2212
0
  DEBUG_printf("1httpSetAuthString: authstring=\"%s\"", http->authstring);
2213
0
}
2214
2215
2216
//
2217
// 'httpSetBlocking()' - Set blocking/non-blocking behavior on a connection.
2218
//
2219
// This function sets whether a connection uses blocking behavior when reading
2220
// or writing data.  The "http" argument specifies the HTTP connection and the
2221
// "blocking" argument specifies whether to use blocking behavior.
2222
//
2223
2224
void
2225
httpSetBlocking(http_t *http,   // I - HTTP connection
2226
                bool   blocking)  // I - `true` = blocking, `false` = non-blocking
2227
0
{
2228
0
  if (http)
2229
0
  {
2230
0
    http->blocking = blocking;
2231
0
    http_set_wait(http);
2232
0
  }
2233
0
}
2234
2235
2236
//
2237
// 'httpSetCookie()' - Add Set-Cookie value(s).
2238
//
2239
// This function adds one or more Set-Cookie header values that will be sent to
2240
// the client with the @link httpWriteResponse@ function.  Each value conforms
2241
// to the format defined in RFC 6265.  Multiple values can be passed in the
2242
// "cookie" string separated by a newline character.
2243
//
2244
// Call the @link httpClearCookies@ function to clear all Set-Cookie values.
2245
//
2246
2247
void
2248
httpSetCookie(http_t     *http,   // I - Connection
2249
              const char *cookie) // I - Cookie string
2250
0
{
2251
  // Range check input...
2252
0
  if (!http || !cookie)
2253
0
    return;
2254
2255
  // Set or append the Set-Cookie value....
2256
0
  if (http->set_cookie)
2257
0
  {
2258
    // Append with a newline between values...
2259
0
    size_t  clen,     // Length of cookie string
2260
0
    ctotal;     // Total length of cookies
2261
0
    char  *temp;      // Temporary value
2262
2263
0
    clen   = strlen(http->set_cookie);
2264
0
    ctotal = clen + strlen(cookie) + 2;
2265
2266
0
    if ((temp = realloc(http->set_cookie, ctotal)) == NULL)
2267
0
      return;
2268
2269
0
    http->set_cookie = temp;
2270
0
    temp[clen]       = '\n';
2271
0
    cupsCopyString(temp + clen + 1, cookie, ctotal - clen - 1);
2272
0
  }
2273
0
  else
2274
0
  {
2275
    // Just copy/set this cookie...
2276
0
    http->set_cookie = strdup(cookie);
2277
0
  }
2278
0
}
2279
2280
2281
//
2282
// 'httpSetDefaultField()' - Set the default value of a HTTP header.
2283
//
2284
// This function sets the default value for a HTTP header.
2285
//
2286
// > *Note:* Currently only the `HTTP_FIELD_ACCEPT_ENCODING`,
2287
// > `HTTP_FIELD_SERVER`, and `HTTP_FIELD_USER_AGENT` fields can be set.
2288
//
2289
2290
void
2291
httpSetDefaultField(http_t       *http, // I - HTTP connection
2292
                    http_field_t field, // I - Field index
2293
              const char   *value)// I - Value
2294
0
{
2295
0
  DEBUG_printf("httpSetDefaultField(http=%p, field=%d(%s), value=\"%s\")", (void *)http, field, field >= HTTP_FIELD_ACCEPT_LANGUAGE && field < HTTP_FIELD_MAX ? http_fields[field] : "unknown", value);
2296
2297
0
  if (!http || field <= HTTP_FIELD_UNKNOWN || field >= HTTP_FIELD_MAX)
2298
0
    return;
2299
2300
0
  free(http->default_fields[field]);
2301
2302
0
  http->default_fields[field] = value ? strdup(value) : NULL;
2303
0
}
2304
2305
2306
//
2307
// 'httpSetEncryption()' - Set the required encryption on a HTTP connection.
2308
//
2309
2310
bool          // O - `true` on success, `false` on error
2311
httpSetEncryption(
2312
    http_t            *http,    // I - HTTP connection
2313
    http_encryption_t e)    // I - New encryption preference
2314
0
{
2315
0
  DEBUG_printf("httpSetEncryption(http=%p, e=%d)", (void *)http, e);
2316
2317
0
  if (!http)
2318
0
    return (false);
2319
2320
0
  if (http->mode == _HTTP_MODE_CLIENT)
2321
0
  {
2322
0
    http->encryption = e;
2323
2324
0
    if ((http->encryption == HTTP_ENCRYPTION_ALWAYS && !http->tls) || (http->encryption == HTTP_ENCRYPTION_NEVER && http->tls))
2325
0
      return (httpConnectAgain(http, 30000, NULL));
2326
0
    else if (http->encryption == HTTP_ENCRYPTION_REQUIRED && !http->tls)
2327
0
      return (http_tls_upgrade(http));
2328
0
    else
2329
0
      return (true);
2330
0
  }
2331
0
  else
2332
0
  {
2333
0
    if (e == HTTP_ENCRYPTION_NEVER && http->tls)
2334
0
      return (false);
2335
2336
0
    http->encryption = e;
2337
0
    if (e != HTTP_ENCRYPTION_IF_REQUESTED && !http->tls)
2338
0
      return (_httpTLSStart(http));
2339
0
    else
2340
0
      return (true);
2341
0
  }
2342
0
}
2343
2344
2345
//
2346
// 'httpSetExpect()' - Set the Expect: header in a request.
2347
//
2348
// This function sets the `Expect:` header in a request.  Currently only
2349
// `HTTP_STATUS_NONE` or `HTTP_STATUS_CONTINUE` is supported for the "expect"
2350
// argument.
2351
//
2352
2353
void
2354
httpSetExpect(http_t        *http,  // I - HTTP connection
2355
              http_status_t expect) // I - HTTP status to expect (`HTTP_STATUS_NONE` or `HTTP_STATUS_CONTINUE`)
2356
0
{
2357
0
  DEBUG_printf("httpSetExpect(http=%p, expect=%d)", (void *)http, expect);
2358
2359
0
  if (http)
2360
0
    http->expect = expect;
2361
0
}
2362
2363
2364
//
2365
// 'httpSetField()' - Set the value of a HTTP header.
2366
//
2367
2368
void
2369
httpSetField(http_t       *http,  // I - HTTP connection
2370
             http_field_t field,  // I - Field index
2371
       const char   *value) // I - Value
2372
0
{
2373
0
  DEBUG_printf("httpSetField(http=%p, field=%d(%s), value=\"%s\")", (void *)http, field, field >= HTTP_FIELD_ACCEPT_LANGUAGE && field < HTTP_FIELD_MAX ? http_fields[field] : "unknown", value);
2374
2375
0
  if (!http || field <= HTTP_FIELD_UNKNOWN || field >= HTTP_FIELD_MAX || !value)
2376
0
    return;
2377
2378
0
  http_add_field(http, field, value, false);
2379
0
}
2380
2381
2382
//
2383
// 'httpSetKeepAlive()' - Set the current Keep-Alive state of a connection.
2384
//
2385
2386
void
2387
httpSetKeepAlive(
2388
    http_t           *http,   // I - HTTP connection
2389
    http_keepalive_t keep_alive)  // I - New Keep-Alive value
2390
0
{
2391
0
  if (http)
2392
0
    http->keep_alive = keep_alive;
2393
0
}
2394
2395
2396
//
2397
// 'httpSetLength()' - Set the `Content-Length` and `Transfer-Encoding` fields.
2398
//
2399
// This function sets the `Content-Length` and `Transfer-Encoding` fields.
2400
// Passing `0` to the "length" argument specifies a chunked transfer encoding
2401
// while other values specify a fixed `Content-Length`.
2402
//
2403
2404
void
2405
httpSetLength(http_t *http,   // I - HTTP connection
2406
              size_t length)    // I - Length (`0` for chunked)
2407
0
{
2408
0
  DEBUG_printf("httpSetLength(http=%p, length=" CUPS_LLFMT ")", (void *)http, CUPS_LLCAST length);
2409
2410
0
  if (!http)
2411
0
    return;
2412
2413
0
  if (!length)
2414
0
  {
2415
0
    httpSetField(http, HTTP_FIELD_TRANSFER_ENCODING, "chunked");
2416
0
    httpSetField(http, HTTP_FIELD_CONTENT_LENGTH, "");
2417
0
  }
2418
0
  else
2419
0
  {
2420
0
    char len[32];     // Length string
2421
2422
0
    snprintf(len, sizeof(len), CUPS_LLFMT, CUPS_LLCAST length);
2423
0
    httpSetField(http, HTTP_FIELD_TRANSFER_ENCODING, "");
2424
0
    httpSetField(http, HTTP_FIELD_CONTENT_LENGTH, len);
2425
0
  }
2426
0
}
2427
2428
2429
//
2430
// 'httpSetTimeout()' - Set read/write timeouts and an optional callback.
2431
//
2432
// This function sets the read/write timeouts for a HTTP connection with an
2433
// optional timeout callback.  The timeout callback receives both the HTTP
2434
// connection pointer and a user data pointer, and returns `true` to continue or
2435
// `false` to error (time) out.
2436
//
2437
// ```
2438
// bool // true to continue, false to stop
2439
// timeout_cb(http_t *http, void *user_data)
2440
// {
2441
//   ... "http" contains the HTTP connection, "user_data" contains the callback pointer
2442
// }
2443
// ```
2444
//
2445
2446
void
2447
httpSetTimeout(
2448
    http_t            *http,    // I - HTTP connection
2449
    double            timeout,    // I - Number of seconds for timeout, must be greater than `0`
2450
    http_timeout_cb_t cb,   // I - Callback function or `NULL` for none
2451
    void              *cb_data)   // I - Callback data pointer
2452
0
{
2453
0
  if (!http || timeout <= 0.0)
2454
0
    return;
2455
2456
0
  http->timeout_cb    = cb;
2457
0
  http->timeout_data  = cb_data;
2458
0
  http->timeout_value = timeout;
2459
2460
0
  if (http->fd >= 0)
2461
0
    http_set_timeout(http->fd, timeout);
2462
2463
0
  http_set_wait(http);
2464
0
}
2465
2466
2467
//
2468
// 'httpShutdown()' - Shutdown one side of a HTTP connection.
2469
//
2470
2471
void
2472
httpShutdown(http_t *http)    // I - HTTP connection
2473
0
{
2474
0
  if (!http || http->fd < 0)
2475
0
    return;
2476
2477
0
  if (http->tls)
2478
0
    _httpTLSStop(http);
2479
2480
#ifdef _WIN32
2481
  shutdown(http->fd, SD_RECEIVE); // Microsoft-ism...
2482
#else
2483
0
  shutdown(http->fd, SHUT_RD);
2484
0
#endif // _WIN32
2485
0
}
2486
2487
2488
//
2489
// '_httpUpdate()' - Update the current HTTP status for incoming data.
2490
//
2491
// Note: Unlike httpUpdate(), this function does not flush pending write data
2492
// and only retrieves a single status line from the HTTP connection.
2493
//
2494
2495
bool          // O - `true` to continue, `false` to stop
2496
_httpUpdate(http_t        *http,  // I - HTTP connection
2497
            http_status_t *status)  // O - Current HTTP status
2498
0
{
2499
0
  char    *value,     // Pointer to value on line
2500
0
    *valend;    // Pointer to end of value
2501
0
  http_field_t  field;      // Field index
2502
0
  int   major, minor;   // HTTP version numbers
2503
2504
2505
0
  DEBUG_printf("_httpUpdate(http=%p, status=%p), state=%s", (void *)http, (void *)status, httpStateString(http->state));
2506
2507
  // When doing non-blocking I/O, make sure we have a whole line...
2508
0
  if (!http->blocking)
2509
0
  {
2510
0
    ssize_t bytes;      // Bytes "peeked" from connection
2511
2512
    // See whether our read buffer is full...
2513
0
    DEBUG_printf("2_httpUpdate: used=%d", http->used);
2514
2515
0
    if ((size_t)http->used < sizeof(http->buffer))
2516
0
    {
2517
      // No, try filling in more data...
2518
0
      if ((bytes = http_read(http, http->buffer + http->used, sizeof(http->buffer) - (size_t)http->used, 0)) > 0)
2519
0
      {
2520
0
        DEBUG_printf("2_httpUpdate: Read %d bytes.", (int)bytes);
2521
0
        http->used += (int)bytes;
2522
0
      }
2523
0
    }
2524
2525
    // Peek at the incoming data...
2526
0
    if (!http->used || !memchr(http->buffer, '\n', (size_t)http->used))
2527
0
    {
2528
      // Don't have a full line, tell the reader to try again when there is more data...
2529
0
      DEBUG_puts("1_htttpUpdate: No newline in buffer yet.");
2530
0
      if ((size_t)http->used == sizeof(http->buffer))
2531
0
        *status = HTTP_STATUS_ERROR;
2532
0
      else
2533
0
        *status = HTTP_STATUS_CONTINUE;
2534
0
      return (0);
2535
0
    }
2536
2537
0
    DEBUG_puts("2_httpUpdate: Found newline in buffer.");
2538
0
  }
2539
2540
  // Grab a single line from the connection...
2541
0
  if (!httpGets(http, http->line, sizeof(http->line)))
2542
0
  {
2543
0
    DEBUG_puts("1_httpUpdate: Error reading request line.");
2544
0
    *status = HTTP_STATUS_ERROR;
2545
0
    return (false);
2546
0
  }
2547
2548
0
  DEBUG_printf("2_httpUpdate: Got \"%s\"", http->line);
2549
2550
0
  if (http->line[0] == '\0')
2551
0
  {
2552
    // Blank line means the start of the data section (if any).  Return
2553
    // the result code, too...
2554
    //
2555
    // If we get status 100 (HTTP_STATUS_CONTINUE), then we *don't* change
2556
    // states.  Instead, we just return HTTP_STATUS_CONTINUE to the caller and
2557
    // keep on trying.
2558
0
    if (http->status == HTTP_STATUS_CONTINUE)
2559
0
    {
2560
0
      *status = http->status;
2561
0
      return (false);
2562
0
    }
2563
2564
0
    if (http->status < HTTP_STATUS_BAD_REQUEST)
2565
0
      http->digest_tries = 0;
2566
2567
0
    if (http->status == HTTP_STATUS_SWITCHING_PROTOCOLS && !http->tls)
2568
0
    {
2569
0
      if (!_httpTLSStart(http))
2570
0
      {
2571
0
        httpAddrClose(NULL, http->fd);
2572
0
        http->fd = -1;
2573
2574
0
  *status = http->status = HTTP_STATUS_ERROR;
2575
0
  return (false);
2576
0
      }
2577
2578
0
      *status = HTTP_STATUS_CONTINUE;
2579
0
      return (false);
2580
0
    }
2581
2582
0
    if (http_set_length(http) < 0)
2583
0
    {
2584
0
      DEBUG_puts("1_httpUpdate: Bad Content-Length.");
2585
0
      http->error  = EINVAL;
2586
0
      http->status = *status = HTTP_STATUS_ERROR;
2587
0
      return (false);
2588
0
    }
2589
2590
0
    switch (http->state)
2591
0
    {
2592
0
      case HTTP_STATE_COPY :
2593
0
      case HTTP_STATE_DELETE :
2594
0
      case HTTP_STATE_GET :
2595
0
      case HTTP_STATE_LOCK :
2596
0
      case HTTP_STATE_LOCK_RECV :
2597
0
      case HTTP_STATE_POST :
2598
0
      case HTTP_STATE_POST_RECV :
2599
0
      case HTTP_STATE_PROPFIND :
2600
0
      case HTTP_STATE_PROPFIND_RECV :
2601
0
      case HTTP_STATE_PROPPATCH :
2602
0
      case HTTP_STATE_PROPPATCH_RECV :
2603
0
      case HTTP_STATE_PUT :
2604
0
    http->state ++;
2605
2606
0
    DEBUG_printf("1_httpUpdate: Set state to %s.", httpStateString(http->state));
2607
0
    break;
2608
2609
0
      case HTTP_STATE_CONNECT :
2610
0
      case HTTP_STATE_HEAD :
2611
0
      case HTTP_STATE_LOCK_SEND :
2612
0
      case HTTP_STATE_MKCOL :
2613
0
      case HTTP_STATE_POST_SEND :
2614
0
      case HTTP_STATE_PROPFIND_SEND :
2615
0
      case HTTP_STATE_PROPPATCH_SEND :
2616
0
      case HTTP_STATE_TRACE :
2617
0
      case HTTP_STATE_UNLOCK :
2618
0
    break;
2619
2620
0
      default :
2621
0
    http->state = HTTP_STATE_WAITING;
2622
2623
0
    DEBUG_puts("1_httpUpdate: Reset state to HTTP_STATE_WAITING.");
2624
0
    break;
2625
0
    }
2626
2627
0
    if (http->data_encoding == HTTP_ENCODING_LENGTH && http->data_remaining == 0)
2628
0
    {
2629
      // POST/PUT/etc. with empty message body...
2630
0
      http_advance_state(http);
2631
0
    }
2632
0
    else
2633
0
    {
2634
      // Non-empty message body...
2635
0
      DEBUG_puts("1_httpUpdate: Calling http_content_coding_start.");
2636
0
      http_content_coding_start(http, httpGetField(http, HTTP_FIELD_CONTENT_ENCODING));
2637
0
    }
2638
2639
0
    *status = http->status;
2640
0
    return (false);
2641
0
  }
2642
0
  else if (!strncmp(http->line, "HTTP/", 5) && http->mode == _HTTP_MODE_CLIENT)
2643
0
  {
2644
    // Got the beginning of a response...
2645
0
    int intstatus;      // Status value as an integer
2646
2647
0
    if (sscanf(http->line, "HTTP/%d.%d%d", &major, &minor, &intstatus) != 3)
2648
0
    {
2649
0
      *status = http->status = HTTP_STATUS_ERROR;
2650
0
      return (false);
2651
0
    }
2652
2653
0
    httpClearFields(http);
2654
2655
0
    http->version = (http_version_t)(major * 100 + minor);
2656
0
    *status       = http->status = (http_status_t)intstatus;
2657
0
  }
2658
0
  else if ((value = (char *)strchr(http->line, ':')) != NULL)
2659
0
  {
2660
    // Got a value...
2661
0
    *value++ = '\0';
2662
0
    while (_cups_isspace(*value))
2663
0
      value ++;
2664
2665
    // Strip trailing whitespace...
2666
0
    for (valend = value + strlen(value) - 1; valend > value; valend --)
2667
0
    {
2668
0
      if (!_cups_isspace(*valend))
2669
0
        break;
2670
0
    }
2671
0
    if (valend >= value)
2672
0
      valend[1] = '\0';
2673
2674
0
    DEBUG_printf("1_httpUpdate: Header %s: %s", http->line, value);
2675
2676
    // Be tolerants of servers that send unknown attribute fields...
2677
0
    if (!_cups_strcasecmp(http->line, "expect"))
2678
0
    {
2679
      // "Expect: 100-continue" or similar...
2680
0
      http->expect = (http_status_t)atoi(value);
2681
0
    }
2682
0
    else if (!_cups_strcasecmp(http->line, "cookie"))
2683
0
    {
2684
      // "Cookie: name=value[; name=value ...]" - replaces previous cookies...
2685
0
      free(http->cookie);
2686
0
      http->cookie = strdup(value);
2687
0
    }
2688
0
    else if ((field = httpFieldValue(http->line)) != HTTP_FIELD_UNKNOWN)
2689
0
    {
2690
0
      http_add_field(http, field, value, true);
2691
2692
0
      if (field == HTTP_FIELD_AUTHENTICATION_INFO)
2693
0
        httpGetSubField(http, HTTP_FIELD_AUTHENTICATION_INFO, "nextnonce", http->nextnonce, (int)sizeof(http->nextnonce));
2694
0
    }
2695
#ifdef DEBUG
2696
    else
2697
    {
2698
      DEBUG_printf("1_httpUpdate: unknown field %s seen!", http->line);
2699
    }
2700
#endif // DEBUG
2701
0
  }
2702
0
  else
2703
0
  {
2704
0
    DEBUG_printf("1_httpUpdate: Bad response line \"%s\"!", http->line);
2705
0
    http->error  = EINVAL;
2706
0
    http->status = *status = HTTP_STATUS_ERROR;
2707
0
    return (false);
2708
0
  }
2709
2710
0
  return (true);
2711
0
}
2712
2713
2714
//
2715
// 'httpUpdate()' - Update the current HTTP state for incoming data.
2716
//
2717
2718
http_status_t       // O - HTTP status
2719
httpUpdate(http_t *http)    // I - HTTP connection
2720
0
{
2721
0
  http_status_t status;     // Request status
2722
2723
2724
0
  DEBUG_printf("httpUpdate(http=%p), state=%s", (void *)http, httpStateString(http->state));
2725
2726
  // Flush pending data, if any...
2727
0
  if (http->wused)
2728
0
  {
2729
0
    DEBUG_puts("2httpUpdate: flushing buffer...");
2730
2731
0
    if (httpFlushWrite(http) < 0)
2732
0
      return (HTTP_STATUS_ERROR);
2733
0
  }
2734
2735
  // If we haven't issued any commands, then there is nothing to "update"...
2736
0
  if (http->state == HTTP_STATE_WAITING)
2737
0
    return (HTTP_STATUS_CONTINUE);
2738
2739
  // Grab all of the lines we can from the connection...
2740
0
  while (_httpUpdate(http, &status));
2741
2742
  // See if there was an error...
2743
0
  if (http->error == EPIPE && http->status > HTTP_STATUS_CONTINUE)
2744
0
  {
2745
0
    DEBUG_printf("1httpUpdate: Returning status %d...", http->status);
2746
0
    return (http->status);
2747
0
  }
2748
2749
0
  if (http->error)
2750
0
  {
2751
0
    DEBUG_printf("1httpUpdate: socket error %d - %s", http->error, strerror(http->error));
2752
0
    http->status = HTTP_STATUS_ERROR;
2753
0
    return (HTTP_STATUS_ERROR);
2754
0
  }
2755
2756
  // Return the current status...
2757
0
  return (status);
2758
0
}
2759
2760
2761
//
2762
// '_httpWait()' - Wait for data available on a connection (no flush).
2763
//
2764
2765
bool          // O - `true` if data is available, `false` otherwise
2766
_httpWait(http_t *http,     // I - HTTP connection
2767
          int    msec,      // I - Milliseconds to wait
2768
    bool   usessl)    // I - Use SSL context?
2769
0
{
2770
0
  struct pollfd   pfd;    // Polled file descriptor
2771
0
  int     nfds;   // Result from select()/poll()
2772
2773
2774
0
  DEBUG_printf("4_httpWait(http=%p, msec=%d, usessl=%d)", (void *)http, msec, usessl);
2775
2776
0
  if (http->fd < 0)
2777
0
  {
2778
0
    DEBUG_printf("5_httpWait: Returning 0 since fd=%d", http->fd);
2779
0
    return (false);
2780
0
  }
2781
2782
  // Check the SSL/TLS buffers for data first...
2783
0
  if (usessl && http->tls && _httpTLSPending(http))
2784
0
  {
2785
0
    DEBUG_puts("5_httpWait: Return 1 since there is pending TLS data.");
2786
0
    return (true);
2787
0
  }
2788
2789
  // Then try polling the socket...
2790
0
  pfd.fd     = http->fd;
2791
0
  pfd.events = POLLIN;
2792
2793
0
  do
2794
0
  {
2795
0
    nfds = poll(&pfd, 1, msec);
2796
0
  }
2797
#ifdef _WIN32
2798
  while (nfds < 0 && (WSAGetLastError() == WSAEINTR || WSAGetLastError() == WSAEWOULDBLOCK));
2799
#else
2800
0
  while (nfds < 0 && (errno == EINTR || errno == EAGAIN));
2801
0
#endif // _WIN32
2802
2803
0
  DEBUG_printf("5_httpWait: returning with nfds=%d, errno=%d...", nfds, errno);
2804
2805
0
  return (nfds > 0);
2806
0
}
2807
2808
2809
//
2810
// 'httpWait()' - Wait for data available on a connection.
2811
//
2812
2813
bool          // O - `true` when data is available, `false` otherwise
2814
httpWait(http_t *http,      // I - HTTP connection
2815
         int    msec)     // I - Milliseconds to wait
2816
0
{
2817
  // First see if there is data in the buffer...
2818
0
  DEBUG_printf("2httpWait(http=%p, msec=%d)", (void *)http, msec);
2819
2820
0
  if (http == NULL)
2821
0
    return (false);
2822
2823
0
  if (http->used)
2824
0
  {
2825
0
    DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
2826
0
    return (true);
2827
0
  }
2828
2829
0
  if (http->coding >= _HTTP_CODING_GUNZIP && ((z_stream *)http->stream)->avail_in > 0)
2830
0
  {
2831
0
    DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
2832
0
    return (true);
2833
0
  }
2834
2835
  // Flush pending data, if any...
2836
0
  if (http->wused)
2837
0
  {
2838
0
    DEBUG_puts("3httpWait: Flushing write buffer.");
2839
2840
0
    if (httpFlushWrite(http) < 0)
2841
0
      return (false);
2842
0
  }
2843
2844
  // If not, check the SSL/TLS buffers and do a select() on the connection...
2845
0
  return (_httpWait(http, msec, 1));
2846
0
}
2847
2848
2849
//
2850
// 'httpWrite()' - Write data to a HTTP connection.
2851
//
2852
// This function writes data to a HTTP connection. When using chunking or
2853
// content coding, specifying a "length" of `0` will complete the current HTTP
2854
// request/response message.
2855
//
2856
2857
ssize_t         // O - Number of bytes written
2858
httpWrite(http_t     *http,   // I - HTTP connection
2859
          const char *buffer,   // I - Buffer for data
2860
    size_t     length)    // I - Number of bytes to write
2861
0
{
2862
0
  ssize_t bytes;      // Bytes written
2863
2864
2865
0
  DEBUG_printf("httpWrite(http=%p, buffer=%p, length=" CUPS_LLFMT ")", (void *)http, (void *)buffer, CUPS_LLCAST length);
2866
2867
  // Range check input...
2868
0
  if (!http || !buffer)
2869
0
  {
2870
0
    DEBUG_puts("1httpWrite: Returning -1 due to bad input.");
2871
0
    return (-1);
2872
0
  }
2873
2874
  // Mark activity on the connection...
2875
0
  http->activity = time(NULL);
2876
2877
  // Buffer small writes for better performance...
2878
0
  if (http->coding == _HTTP_CODING_GZIP || http->coding == _HTTP_CODING_DEFLATE)
2879
0
  {
2880
0
    DEBUG_printf("1httpWrite: http->coding=%d", http->coding);
2881
2882
0
    if (length == 0)
2883
0
    {
2884
0
      http_content_coding_finish(http);
2885
0
      bytes = 0;
2886
0
    }
2887
0
    else
2888
0
    {
2889
0
      size_t  slen;     // Bytes to write
2890
0
      ssize_t sret;     // Bytes written
2891
2892
0
      ((z_stream *)http->stream)->next_in   = (Bytef *)buffer;
2893
0
      ((z_stream *)http->stream)->avail_in  = (uInt)length;
2894
2895
0
      while (deflate((z_stream *)http->stream, Z_NO_FLUSH) == Z_OK)
2896
0
      {
2897
0
        DEBUG_printf("1httpWrite: avail_out=%d", ((z_stream *)http->stream)->avail_out);
2898
2899
0
        if (((z_stream *)http->stream)->avail_out > 0)
2900
0
    continue;
2901
2902
0
  slen = _HTTP_MAX_SBUFFER - ((z_stream *)http->stream)->avail_out;
2903
2904
0
        DEBUG_printf("1httpWrite: Writing intermediate chunk, len=%d", (int)slen);
2905
2906
0
  if (slen > 0 && http->data_encoding == HTTP_ENCODING_CHUNKED)
2907
0
    sret = http_write_chunk(http, (char *)http->sbuffer, slen);
2908
0
  else if (slen > 0)
2909
0
    sret = http_write(http, (char *)http->sbuffer, slen);
2910
0
  else
2911
0
    sret = 0;
2912
2913
0
        if (sret < 0)
2914
0
  {
2915
0
    DEBUG_puts("1httpWrite: Unable to write, returning -1.");
2916
0
    return (-1);
2917
0
  }
2918
2919
0
  ((z_stream *)http->stream)->next_out  = (Bytef *)http->sbuffer;
2920
0
  ((z_stream *)http->stream)->avail_out = (uInt)_HTTP_MAX_SBUFFER;
2921
0
      }
2922
2923
0
      bytes = (ssize_t)length;
2924
0
    }
2925
0
  }
2926
0
  else if (length > 0)
2927
0
  {
2928
0
    if (http->wused && (length + (size_t)http->wused) > sizeof(http->wbuffer))
2929
0
    {
2930
0
      DEBUG_printf("2httpWrite: Flushing buffer (wused=%d, length=" CUPS_LLFMT ")", http->wused, CUPS_LLCAST length);
2931
2932
0
      httpFlushWrite(http);
2933
0
    }
2934
2935
0
    if ((length + (size_t)http->wused) <= sizeof(http->wbuffer) && length < sizeof(http->wbuffer))
2936
0
    {
2937
      // Write to buffer...
2938
0
      DEBUG_printf("2httpWrite: Copying " CUPS_LLFMT " bytes to wbuffer...", CUPS_LLCAST length);
2939
2940
0
      memcpy(http->wbuffer + http->wused, buffer, length);
2941
0
      http->wused += (int)length;
2942
0
      bytes = (ssize_t)length;
2943
0
    }
2944
0
    else
2945
0
    {
2946
      // Otherwise write the data directly...
2947
0
      DEBUG_printf("2httpWrite: Writing " CUPS_LLFMT " bytes to socket...", CUPS_LLCAST length);
2948
2949
0
      if (http->data_encoding == HTTP_ENCODING_CHUNKED)
2950
0
  bytes = (ssize_t)http_write_chunk(http, buffer, length);
2951
0
      else
2952
0
  bytes = (ssize_t)http_write(http, buffer, length);
2953
2954
0
      DEBUG_printf("2httpWrite: Wrote " CUPS_LLFMT " bytes...", CUPS_LLCAST bytes);
2955
0
    }
2956
2957
0
    if (http->data_encoding == HTTP_ENCODING_LENGTH)
2958
0
      http->data_remaining -= bytes;
2959
0
  }
2960
0
  else
2961
0
  {
2962
0
    bytes = 0;
2963
0
  }
2964
2965
  // Handle end-of-request processing...
2966
0
  if ((http->data_encoding == HTTP_ENCODING_CHUNKED && length == 0) ||
2967
0
      (http->data_encoding == HTTP_ENCODING_LENGTH && http->data_remaining == 0))
2968
0
  {
2969
    // Finished with the transfer; unless we are sending POST or PUT data, go idle...
2970
0
    if (http->coding == _HTTP_CODING_GZIP || http->coding == _HTTP_CODING_DEFLATE)
2971
0
      http_content_coding_finish(http);
2972
2973
0
    if (http->wused)
2974
0
    {
2975
0
      if (httpFlushWrite(http) < 0)
2976
0
        return (-1);
2977
0
    }
2978
2979
0
    if (http->data_encoding == HTTP_ENCODING_CHUNKED)
2980
0
    {
2981
      // Send a 0-length chunk at the end of the request...
2982
0
      http_write(http, "0\r\n\r\n", 5);
2983
2984
      // Reset the data state...
2985
0
      http->data_encoding  = HTTP_ENCODING_FIELDS;
2986
0
      http->data_remaining = 0;
2987
0
    }
2988
2989
0
    http_advance_state(http);
2990
0
    DEBUG_printf("2httpWrite: Changed state to %s.", httpStateString(http->state));
2991
0
  }
2992
2993
0
  DEBUG_printf("1httpWrite: Returning " CUPS_LLFMT ".", CUPS_LLCAST bytes);
2994
2995
0
  return (bytes);
2996
0
}
2997
2998
2999
//
3000
// 'httpWriteRequest()' - Write a HTTP request.
3001
//
3002
// This function writes a HTTP request to the specified connection.  The
3003
// "method" argument specifies the HTTP method ("GET", "POST", "PUT", etc)
3004
// while the "uri" argument specifies the request URI.  All fields must be
3005
// set using the @link httpSetCookie@, @link httpSetField@, and
3006
// @link httpSetLength@ functions prior to writing the request.
3007
//
3008
3009
bool          // O - `true` on success, `false` on failure
3010
httpWriteRequest(http_t     *http,  // I - HTTP connection
3011
                 const char *method,  // I - Request method ("GET", "POST", "PUT", etc.)
3012
                 const char *uri) // I - Request URI
3013
0
{
3014
0
  DEBUG_printf("httpWriteRequest(http=%p, method=\"%s\", uri=\"%s\")", (void *)http, method, uri);
3015
3016
0
  if (!strcasecmp(method, "COPY"))
3017
0
    return (http_send(http, HTTP_STATE_COPY, uri));
3018
0
  else if (!strcasecmp(method, "DELETE"))
3019
0
    return (http_send(http, HTTP_STATE_DELETE, uri));
3020
0
  else if (!strcasecmp(method, "GET"))
3021
0
    return (http_send(http, HTTP_STATE_GET, uri));
3022
0
  else if (!strcasecmp(method, "HEAD"))
3023
0
    return (http_send(http, HTTP_STATE_HEAD, uri));
3024
0
  else if (!strcasecmp(method, "LOCK"))
3025
0
    return (http_send(http, HTTP_STATE_LOCK, uri));
3026
0
  else if (!strcasecmp(method, "MKCOL"))
3027
0
    return (http_send(http, HTTP_STATE_MKCOL, uri));
3028
0
  else if (!strcasecmp(method, "MOVE"))
3029
0
    return (http_send(http, HTTP_STATE_MOVE, uri));
3030
0
  else if (!strcasecmp(method, "OPTIONS"))
3031
0
    return (http_send(http, HTTP_STATE_OPTIONS, uri));
3032
0
  else if (!strcasecmp(method, "POST"))
3033
0
    return (http_send(http, HTTP_STATE_POST, uri));
3034
0
  else if (!strcasecmp(method, "PROPFIND"))
3035
0
    return (http_send(http, HTTP_STATE_PROPFIND, uri));
3036
0
  else if (!strcasecmp(method, "PROPPATCH"))
3037
0
    return (http_send(http, HTTP_STATE_PROPPATCH, uri));
3038
0
  else if (!strcasecmp(method, "PUT"))
3039
0
    return (http_send(http, HTTP_STATE_PUT, uri));
3040
0
  else if (!strcasecmp(method, "TRACE"))
3041
0
    return (http_send(http, HTTP_STATE_TRACE, uri));
3042
0
  else if (!strcasecmp(method, "UNLOCK"))
3043
0
    return (http_send(http, HTTP_STATE_UNLOCK, uri));
3044
3045
0
  DEBUG_printf("httpWriteRequest: Unknown method, returning false.");
3046
3047
0
  return (false);
3048
0
}
3049
3050
3051
//
3052
// 'httpWriteResponse()' - Write a HTTP response to a client connection.
3053
//
3054
3055
bool          // O - `true` on success, `false` on error
3056
httpWriteResponse(http_t        *http,  // I - HTTP connection
3057
      http_status_t status) // I - Status code
3058
0
{
3059
0
  http_encoding_t old_encoding; // Old data_encoding value
3060
0
  off_t     old_remaining;  // Old data_remaining value
3061
0
  cups_lang_t   *lang;    // Response language
3062
0
  char      buf[1024];  // Response header
3063
3064
3065
  // Range check input...
3066
0
  DEBUG_printf("httpWriteResponse(http=%p, status=%d)", (void *)http, status);
3067
3068
0
  if (!http || status < HTTP_STATUS_CONTINUE)
3069
0
  {
3070
0
    DEBUG_puts("1httpWriteResponse: Bad input.");
3071
0
    return (false);
3072
0
  }
3073
3074
  // Set the various standard fields if they aren't already...
3075
0
  if (!http->fields[HTTP_FIELD_DATE])
3076
0
  {
3077
0
    char  buffer[256];    // Date value
3078
3079
0
    httpSetField(http, HTTP_FIELD_DATE, httpGetDateString(time(NULL), buffer, sizeof(buffer)));
3080
0
  }
3081
3082
0
  if (status >= HTTP_STATUS_BAD_REQUEST && http->keep_alive)
3083
0
  {
3084
0
    http->keep_alive = HTTP_KEEPALIVE_OFF;
3085
0
    httpSetField(http, HTTP_FIELD_KEEP_ALIVE, "");
3086
0
  }
3087
3088
0
  if (http->version == HTTP_VERSION_1_1)
3089
0
  {
3090
0
    if (!http->fields[HTTP_FIELD_CONNECTION])
3091
0
    {
3092
0
      if (http->keep_alive)
3093
0
  httpSetField(http, HTTP_FIELD_CONNECTION, "Keep-Alive");
3094
0
      else
3095
0
  httpSetField(http, HTTP_FIELD_CONNECTION, "close");
3096
0
    }
3097
3098
0
    if (http->keep_alive && !http->fields[HTTP_FIELD_KEEP_ALIVE])
3099
0
      httpSetField(http, HTTP_FIELD_KEEP_ALIVE, "timeout=10");
3100
0
  }
3101
3102
0
  if (status == HTTP_STATUS_UPGRADE_REQUIRED || status == HTTP_STATUS_SWITCHING_PROTOCOLS)
3103
0
  {
3104
0
    if (!http->fields[HTTP_FIELD_CONNECTION])
3105
0
      httpSetField(http, HTTP_FIELD_CONNECTION, "Upgrade");
3106
3107
0
    if (!http->fields[HTTP_FIELD_UPGRADE])
3108
0
      httpSetField(http, HTTP_FIELD_UPGRADE, "TLS/1.3,TLS/1.2");
3109
3110
0
    if (!http->fields[HTTP_FIELD_CONTENT_LENGTH])
3111
0
      httpSetField(http, HTTP_FIELD_CONTENT_LENGTH, "0");
3112
0
  }
3113
3114
0
  if (!http->fields[HTTP_FIELD_SERVER])
3115
0
    httpSetField(http, HTTP_FIELD_SERVER, http->default_fields[HTTP_FIELD_SERVER] ? http->default_fields[HTTP_FIELD_SERVER] : "CUPS/" LIBCUPS_VERSION " IPP/2.0");
3116
3117
  // Set the Accept-Encoding field if it isn't already...
3118
0
  if (!http->fields[HTTP_FIELD_ACCEPT_ENCODING])
3119
0
    httpSetField(http, HTTP_FIELD_ACCEPT_ENCODING, http->default_fields[HTTP_FIELD_ACCEPT_ENCODING] ? http->default_fields[HTTP_FIELD_ACCEPT_ENCODING] : "gzip, deflate, identity");
3120
3121
  // Get the response language, if any...
3122
0
  lang = cupsLangFind(http->fields[HTTP_FIELD_CONTENT_LANGUAGE]);
3123
3124
  // Send the response header...
3125
0
  old_encoding        = http->data_encoding;
3126
0
  old_remaining       = http->data_remaining;
3127
0
  http->data_encoding = HTTP_ENCODING_FIELDS;
3128
3129
0
  snprintf(buf, sizeof(buf), "HTTP/%d.%d %d %s\r\n", http->version / 100, http->version % 100, (int)status, _httpStatusString(lang, status));
3130
3131
0
  if (httpWrite(http, buf, strlen(buf)) < 0)
3132
0
  {
3133
0
    http->status = HTTP_STATUS_ERROR;
3134
0
    return (false);
3135
0
  }
3136
3137
0
  if (status != HTTP_STATUS_CONTINUE)
3138
0
  {
3139
    // 100 Continue doesn't have the rest of the response headers...
3140
0
    int   i;      // Looping var
3141
0
    const char  *value;     // Field value
3142
3143
0
    for (i = 0; i < HTTP_FIELD_MAX; i ++)
3144
0
    {
3145
0
      if ((value = httpGetField(http, i)) != NULL && *value)
3146
0
      {
3147
0
        if (!http_write_header(http, i, value))
3148
0
  {
3149
0
    http->status = HTTP_STATUS_ERROR;
3150
0
    return (false);
3151
0
  }
3152
0
      }
3153
0
    }
3154
3155
0
    if (http->set_cookie)
3156
0
    {
3157
0
      char  *start,     // Start of cookie
3158
0
    *end,     // Pointer into cookie
3159
0
    *semi;      // Pointer to semicolon in cookie
3160
3161
0
      for (start = http->set_cookie; start && *start; start = end)
3162
0
      {
3163
0
        if ((end = (char *)strchr(start, '\n')) == NULL)
3164
0
          end = start + strlen(start);
3165
3166
0
  if ((semi = (char *)strchr(start, ';')) != NULL && semi < end)
3167
0
  {
3168
0
    if (httpWrite(http, "Set-Cookie: ", 12) < 0 ||
3169
0
        httpWrite(http, start, (size_t)(end - start)) < 0 ||
3170
0
        httpWrite(http, "\r\n", 2) < 0)
3171
0
    {
3172
0
      http->status = HTTP_STATUS_ERROR;
3173
0
      return (false);
3174
0
    }
3175
0
  }
3176
0
  else
3177
0
  {
3178
0
    const char *foot = http->tls ? "; path=/; httponly; secure;\r\n" : "; path=/; httponly;\r\n";
3179
          // End of cookie header
3180
3181
0
    if (httpWrite(http, "Set-Cookie: ", 12) < 0 ||
3182
0
        httpWrite(http, start, (size_t)(end - start)) < 0 ||
3183
0
        httpWrite(http, foot, strlen(foot)) < 0)
3184
0
    {
3185
0
      http->status = HTTP_STATUS_ERROR;
3186
0
      return (false);
3187
0
    }
3188
0
        }
3189
3190
0
  if (*end)
3191
0
    end ++;
3192
0
      }
3193
0
    }
3194
0
  }
3195
3196
0
  if (httpWrite(http, "\r\n", 2) < 2)
3197
0
  {
3198
0
    http->status = HTTP_STATUS_ERROR;
3199
0
    return (false);
3200
0
  }
3201
3202
0
  if (httpFlushWrite(http) < 0)
3203
0
  {
3204
0
    http->status = HTTP_STATUS_ERROR;
3205
0
    return (false);
3206
0
  }
3207
3208
0
  if (status == HTTP_STATUS_CONTINUE || status == HTTP_STATUS_SWITCHING_PROTOCOLS)
3209
0
  {
3210
    // Restore the old data_encoding and data_length values...
3211
0
    http->data_encoding  = old_encoding;
3212
0
    http->data_remaining = old_remaining;
3213
0
  }
3214
0
  else if (http->state == HTTP_STATE_OPTIONS || http->state == HTTP_STATE_HEAD || http->state == HTTP_STATE_PUT || http->state == HTTP_STATE_TRACE || http->state == HTTP_STATE_CONNECT || http->state == HTTP_STATE_STATUS)
3215
0
  {
3216
0
    DEBUG_printf("1httpWriteResponse: Resetting state to HTTP_STATE_WAITING, was %s.", httpStateString(http->state));
3217
0
    http->state = HTTP_STATE_WAITING;
3218
0
  }
3219
0
  else
3220
0
  {
3221
    // Force data_encoding and data_length to be set according to the response
3222
    // headers...
3223
0
    http_set_length(http);
3224
3225
0
    if (http->data_encoding == HTTP_ENCODING_LENGTH && http->data_remaining == 0)
3226
0
    {
3227
0
      DEBUG_printf("1httpWriteResponse: Resetting state to HTTP_STATE_WAITING, was %s.", httpStateString(http->state));
3228
0
      http->state = HTTP_STATE_WAITING;
3229
0
      return (true);
3230
0
    }
3231
3232
0
    if (http->state == HTTP_STATE_COPY || http->state == HTTP_STATE_DELETE || http->state == HTTP_STATE_GET || http->state == HTTP_STATE_LOCK_RECV || http->state == HTTP_STATE_MOVE || http->state == HTTP_STATE_POST_RECV || http->state == HTTP_STATE_PROPFIND_RECV || http->state == HTTP_STATE_PROPPATCH_RECV)
3233
0
      http->state ++;
3234
3235
    // Then start any content encoding...
3236
0
    DEBUG_puts("1httpWriteResponse: Calling http_content_coding_start.");
3237
0
    http_content_coding_start(http, httpGetField(http, HTTP_FIELD_CONTENT_ENCODING));
3238
0
  }
3239
3240
0
  return (true);
3241
0
}
3242
3243
3244
//
3245
// 'http_add_field()' - Add a value for a HTTP field, appending if needed.
3246
//
3247
3248
static void
3249
http_add_field(http_t       *http,  // I - HTTP connection
3250
               http_field_t field,  // I - HTTP field
3251
               const char   *value, // I - Value string
3252
               bool         append) // I - Append value?
3253
0
{
3254
0
  char    temp[1024];   // Temporary value string
3255
0
  size_t  fieldlen,   // Length of existing value
3256
0
    valuelen,   // Length of value string
3257
0
    total;      // Total length of string
3258
3259
3260
0
  if (field == HTTP_FIELD_HOST)
3261
0
  {
3262
    // Special-case for Host: as we don't want a trailing "." on the hostname
3263
    // and need to bracket IPv6 numeric addresses.
3264
0
    char *ptr = (char *)strchr(value, ':');
3265
3266
0
    if (value[0] != '[' && ptr && strchr(ptr + 1, ':'))
3267
0
    {
3268
      // Bracket IPv6 numeric addresses...
3269
      //
3270
      // This is slightly inefficient (basically copying twice), but is an edge
3271
      // case and not worth optimizing...
3272
0
      snprintf(temp, sizeof(temp), "[%s]", value);
3273
0
      value = temp;
3274
0
    }
3275
0
    else if (*value)
3276
0
    {
3277
      // Check for a trailing dot on the hostname...
3278
0
      cupsCopyString(temp, value, sizeof(temp));
3279
0
      value = temp;
3280
0
      ptr   = temp + strlen(temp) - 1;
3281
3282
0
      if (*ptr == '.')
3283
0
  *ptr = '\0';
3284
0
    }
3285
0
  }
3286
3287
0
  if (append && field != HTTP_FIELD_ACCEPT_ENCODING && field != HTTP_FIELD_ACCEPT_LANGUAGE && field != HTTP_FIELD_ACCEPT_RANGES && field != HTTP_FIELD_ALLOW && field != HTTP_FIELD_CONTENT_LENGTH && field != HTTP_FIELD_LINK && field != HTTP_FIELD_TRANSFER_ENCODING && field != HTTP_FIELD_UPGRADE && field != HTTP_FIELD_WWW_AUTHENTICATE)
3288
0
    append = false;
3289
3290
0
  if (!append && http->fields[field])
3291
0
  {
3292
0
    free(http->fields[field]);
3293
3294
0
    http->fields[field] = NULL;
3295
0
  }
3296
3297
0
  valuelen = strlen(value);
3298
3299
0
  if (!valuelen)
3300
0
    return;
3301
3302
0
  if (http->fields[field])
3303
0
  {
3304
0
    fieldlen = strlen(http->fields[field]);
3305
0
    total    = fieldlen + 2 + valuelen;
3306
0
  }
3307
0
  else
3308
0
  {
3309
0
    fieldlen = 0;
3310
0
    total    = valuelen;
3311
0
  }
3312
3313
0
  if (fieldlen)
3314
0
  {
3315
    // Expand the field value...
3316
0
    char *mcombined;      // New value string
3317
3318
0
    if ((mcombined = realloc(http->fields[field], total + 1)) != NULL)
3319
0
    {
3320
0
      http->fields[field] = mcombined;
3321
0
      cupsConcatString(mcombined, ", ", total + 1);
3322
0
      cupsConcatString(mcombined, value, total + 1);
3323
0
    }
3324
0
  }
3325
0
  else
3326
0
  {
3327
    // Allocate the field value...
3328
0
    http->fields[field] = strdup(value);
3329
0
  }
3330
3331
0
  DEBUG_printf("1http_add_field: append=%s, field=%d(%s), value=\"%s\".", append ? "true" : "false", field, http_fields[field], http->fields[field]);
3332
3333
0
  if (field == HTTP_FIELD_CONTENT_ENCODING && http->data_encoding != HTTP_ENCODING_FIELDS)
3334
0
  {
3335
0
    DEBUG_puts("1http_add_field: Calling http_content_coding_start.");
3336
0
    http_content_coding_start(http, value);
3337
0
  }
3338
0
}
3339
3340
3341
//
3342
// 'http_advance_state()' - Advance to the next HTTP state.
3343
//
3344
3345
static void
3346
http_advance_state(http_t *http)  // I - HTTP connection
3347
0
{
3348
0
  DEBUG_printf("4http_advance_state(http=%p(%s)", http, httpStateString(http->state));
3349
3350
0
  if (http->state == HTTP_STATE_LOCK_RECV || http->state == HTTP_STATE_POST_RECV || http->state == HTTP_STATE_PROPFIND_RECV || http->state == HTTP_STATE_PROPPATCH_RECV)
3351
0
    http->state ++;
3352
0
  else if (http->state == HTTP_STATE_COPY_SEND || http->state == HTTP_STATE_DELETE_SEND || http->state == HTTP_STATE_GET_SEND || http->state == HTTP_STATE_LOCK_SEND || http->state == HTTP_STATE_MOVE_SEND || http->state == HTTP_STATE_POST_SEND || http->state == HTTP_STATE_PROPFIND_SEND || http->state == HTTP_STATE_PROPPATCH_SEND)
3353
0
    http->state = HTTP_STATE_WAITING;
3354
0
  else
3355
0
    http->state = HTTP_STATE_STATUS;
3356
3357
0
  DEBUG_printf("5http_advance_state: Set state to %s.", httpStateString(http->state));
3358
0
}
3359
3360
3361
//
3362
// 'http_content_coding_finish()' - Finish doing any content encoding.
3363
//
3364
3365
static void
3366
http_content_coding_finish(
3367
    http_t *http)     // I - HTTP connection
3368
0
{
3369
0
  int   zerr;     // Compression status
3370
0
  Byte    dummy[1];   // Dummy read buffer
3371
0
  size_t  bytes;      // Number of bytes to write
3372
3373
3374
0
  DEBUG_printf("http_content_coding_finish(http=%p)", (void *)http);
3375
0
  DEBUG_printf("1http_content_coding_finishing: http->coding=%d", http->coding);
3376
3377
0
  switch (http->coding)
3378
0
  {
3379
0
    case _HTTP_CODING_DEFLATE :
3380
0
    case _HTTP_CODING_GZIP :
3381
0
        ((z_stream *)http->stream)->next_in  = dummy;
3382
0
        ((z_stream *)http->stream)->avail_in = 0;
3383
3384
0
        do
3385
0
        {
3386
0
          zerr  = deflate((z_stream *)http->stream, Z_FINISH);
3387
0
    bytes = _HTTP_MAX_SBUFFER - ((z_stream *)http->stream)->avail_out;
3388
3389
0
          if (bytes > 0)
3390
0
    {
3391
0
      DEBUG_printf("1http_content_coding_finish: Writing trailing chunk, len=%d", (int)bytes);
3392
3393
0
      if (http->data_encoding == HTTP_ENCODING_CHUNKED)
3394
0
        http_write_chunk(http, (char *)http->sbuffer, bytes);
3395
0
      else
3396
0
        http_write(http, (char *)http->sbuffer, bytes);
3397
0
          }
3398
3399
0
          ((z_stream *)http->stream)->next_out  = (Bytef *)http->sbuffer;
3400
0
          ((z_stream *)http->stream)->avail_out = (uInt)_HTTP_MAX_SBUFFER;
3401
0
  }
3402
0
        while (zerr == Z_OK);
3403
3404
0
        deflateEnd((z_stream *)http->stream);
3405
3406
0
        free(http->sbuffer);
3407
0
        free(http->stream);
3408
3409
0
        http->sbuffer = NULL;
3410
0
        http->stream  = NULL;
3411
3412
0
        if (http->wused)
3413
0
          httpFlushWrite(http);
3414
0
        break;
3415
3416
0
    case _HTTP_CODING_INFLATE :
3417
0
    case _HTTP_CODING_GUNZIP :
3418
0
        inflateEnd((z_stream *)http->stream);
3419
3420
0
        free(http->sbuffer);
3421
0
        free(http->stream);
3422
3423
0
        http->sbuffer = NULL;
3424
0
        http->stream  = NULL;
3425
0
        break;
3426
3427
0
    default :
3428
0
        break;
3429
0
  }
3430
3431
0
  http->coding = _HTTP_CODING_IDENTITY;
3432
0
}
3433
3434
3435
//
3436
// 'http_content_coding_start()' - Start doing content encoding.
3437
//
3438
3439
static void
3440
http_content_coding_start(
3441
    http_t     *http,     // I - HTTP connection
3442
    const char *value)      // I - Value of Content-Encoding
3443
0
{
3444
0
  int     zerr;   // Error/status
3445
0
  _http_coding_t  coding;   // Content coding value
3446
3447
3448
0
  DEBUG_printf("http_content_coding_start(http=%p, value=\"%s\")", (void *)http, value);
3449
3450
0
  if (http->coding != _HTTP_CODING_IDENTITY)
3451
0
  {
3452
0
    DEBUG_printf("1http_content_coding_start: http->coding already %d.", http->coding);
3453
0
    return;
3454
0
  }
3455
0
  else if (!strcmp(value, "x-gzip") || !strcmp(value, "gzip"))
3456
0
  {
3457
0
    if (http->state == HTTP_STATE_GET_SEND ||
3458
0
        http->state == HTTP_STATE_POST_SEND)
3459
0
      coding = http->mode == _HTTP_MODE_SERVER ? _HTTP_CODING_GZIP :
3460
0
                                                 _HTTP_CODING_GUNZIP;
3461
0
    else if (http->state == HTTP_STATE_POST_RECV ||
3462
0
             http->state == HTTP_STATE_PUT_RECV)
3463
0
      coding = http->mode == _HTTP_MODE_CLIENT ? _HTTP_CODING_GZIP :
3464
0
                                                 _HTTP_CODING_GUNZIP;
3465
0
    else
3466
0
    {
3467
0
      DEBUG_puts("1http_content_coding_start: Not doing content coding.");
3468
0
      return;
3469
0
    }
3470
0
  }
3471
0
  else if (!strcmp(value, "x-deflate") || !strcmp(value, "deflate"))
3472
0
  {
3473
0
    if (http->state == HTTP_STATE_GET_SEND ||
3474
0
        http->state == HTTP_STATE_POST_SEND)
3475
0
      coding = http->mode == _HTTP_MODE_SERVER ? _HTTP_CODING_DEFLATE :
3476
0
                                                 _HTTP_CODING_INFLATE;
3477
0
    else if (http->state == HTTP_STATE_POST_RECV ||
3478
0
             http->state == HTTP_STATE_PUT_RECV)
3479
0
      coding = http->mode == _HTTP_MODE_CLIENT ? _HTTP_CODING_DEFLATE :
3480
0
                                                 _HTTP_CODING_INFLATE;
3481
0
    else
3482
0
    {
3483
0
      DEBUG_puts("1http_content_coding_start: Not doing content coding.");
3484
0
      return;
3485
0
    }
3486
0
  }
3487
0
  else
3488
0
  {
3489
0
    DEBUG_puts("1http_content_coding_start: Not doing content coding.");
3490
0
    return;
3491
0
  }
3492
3493
0
  switch (coding)
3494
0
  {
3495
0
    case _HTTP_CODING_DEFLATE :
3496
0
    case _HTTP_CODING_GZIP :
3497
0
        if (http->wused)
3498
0
          httpFlushWrite(http);
3499
3500
0
        if ((http->sbuffer = malloc(_HTTP_MAX_SBUFFER)) == NULL)
3501
0
        {
3502
0
          http->status = HTTP_STATUS_ERROR;
3503
0
          http->error  = errno;
3504
0
          return;
3505
0
        }
3506
3507
        // Window size for compression is 11 bits - optimal based on PWG Raster
3508
        // sample files on pwg.org.  -11 is raw deflate, 27 is gzip, per ZLIB
3509
        // documentation.
3510
0
  if ((http->stream = calloc(1, sizeof(z_stream))) == NULL)
3511
0
  {
3512
0
          free(http->sbuffer);
3513
3514
0
          http->sbuffer = NULL;
3515
0
          http->status  = HTTP_STATUS_ERROR;
3516
0
          http->error   = errno;
3517
0
          return;
3518
0
  }
3519
3520
0
        if ((zerr = deflateInit2((z_stream *)http->stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, coding == _HTTP_CODING_DEFLATE ? -11 : 27, 7, Z_DEFAULT_STRATEGY)) < Z_OK)
3521
0
        {
3522
0
          free(http->sbuffer);
3523
0
          free(http->stream);
3524
3525
0
          http->sbuffer = NULL;
3526
0
          http->stream  = NULL;
3527
0
          http->status  = HTTP_STATUS_ERROR;
3528
0
          http->error   = zerr == Z_MEM_ERROR ? ENOMEM : EINVAL;
3529
0
          return;
3530
0
        }
3531
3532
0
  ((z_stream *)http->stream)->next_out  = (Bytef *)http->sbuffer;
3533
0
  ((z_stream *)http->stream)->avail_out = (uInt)_HTTP_MAX_SBUFFER;
3534
0
        break;
3535
3536
0
    case _HTTP_CODING_INFLATE :
3537
0
    case _HTTP_CODING_GUNZIP :
3538
0
        if ((http->sbuffer = malloc(_HTTP_MAX_SBUFFER)) == NULL)
3539
0
        {
3540
0
          http->status = HTTP_STATUS_ERROR;
3541
0
          http->error  = errno;
3542
0
          return;
3543
0
        }
3544
3545
        // Window size for decompression is up to 15 bits (maximum supported).
3546
        // -15 is raw inflate, 31 is gunzip, per ZLIB documentation.
3547
0
  if ((http->stream = calloc(1, sizeof(z_stream))) == NULL)
3548
0
  {
3549
0
          free(http->sbuffer);
3550
3551
0
          http->sbuffer = NULL;
3552
0
          http->status  = HTTP_STATUS_ERROR;
3553
0
          http->error   = errno;
3554
0
          return;
3555
0
  }
3556
3557
0
        if ((zerr = inflateInit2((z_stream *)http->stream, coding == _HTTP_CODING_INFLATE ? -15 : 31)) < Z_OK)
3558
0
        {
3559
0
          free(http->sbuffer);
3560
0
          free(http->stream);
3561
3562
0
          http->sbuffer = NULL;
3563
0
          http->stream  = NULL;
3564
0
          http->status  = HTTP_STATUS_ERROR;
3565
0
          http->error   = zerr == Z_MEM_ERROR ? ENOMEM : EINVAL;
3566
0
          return;
3567
0
        }
3568
3569
0
        ((z_stream *)http->stream)->avail_in = 0;
3570
0
        ((z_stream *)http->stream)->next_in  = http->sbuffer;
3571
0
        break;
3572
3573
0
    default :
3574
0
        break;
3575
0
  }
3576
3577
0
  http->coding = coding;
3578
3579
0
  DEBUG_printf("1http_content_coding_start: http->coding now %d.", http->coding);
3580
0
}
3581
3582
3583
//
3584
// 'http_create()' - Create an unconnected HTTP connection.
3585
//
3586
3587
static http_t *       // O - HTTP connection
3588
http_create(
3589
    const char        *host,    // I - Hostname
3590
    int               port,   // I - Port number
3591
    http_addrlist_t   *addrlist,  // I - Address list or `NULL`
3592
    int               family,   // I - Address family or AF_UNSPEC
3593
    http_encryption_t encryption, // I - Encryption to use
3594
    bool              blocking,   // I - `true` for blocking mode
3595
    _http_mode_t      mode)   // I - _HTTP_MODE_CLIENT or _SERVER
3596
0
{
3597
0
  http_t  *http;      // New HTTP connection
3598
0
  char    service[255];   // Service name
3599
0
  http_addrlist_t *myaddrlist = NULL; // My address list
3600
0
  _cups_globals_t *cg = _cupsGlobals(); // Thread global data
3601
3602
3603
0
  DEBUG_printf("4http_create(host=\"%s\", port=%d, addrlist=%p, family=%d, encryption=%d, blocking=%s, mode=%d)", host, port, (void *)addrlist, family, encryption, blocking ? "true" : "false", mode);
3604
3605
0
  if (!host && mode == _HTTP_MODE_CLIENT)
3606
0
    return (NULL);
3607
3608
0
  httpInitialize();
3609
3610
  // Lookup the host...
3611
0
  if (addrlist)
3612
0
  {
3613
0
    myaddrlist = httpAddrCopyList(addrlist);
3614
0
  }
3615
0
  else
3616
0
  {
3617
0
    snprintf(service, sizeof(service), "%d", port);
3618
3619
0
    myaddrlist = httpAddrGetList(host, family, service);
3620
0
  }
3621
3622
0
  if (!myaddrlist)
3623
0
    return (NULL);
3624
3625
  // Allocate memory for the structure...
3626
0
  if ((http = calloc(sizeof(http_t), 1)) == NULL)
3627
0
  {
3628
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(errno), 0);
3629
0
    httpAddrFreeList(myaddrlist);
3630
0
    return (NULL);
3631
0
  }
3632
3633
  // Initialize the HTTP data...
3634
0
  http->mode     = mode;
3635
0
  http->activity = time(NULL);
3636
0
  http->hostlist = myaddrlist;
3637
0
  http->blocking = blocking;
3638
0
  http->fd       = -1;
3639
0
  http->status   = HTTP_STATUS_CONTINUE;
3640
0
  http->version  = HTTP_VERSION_1_1;
3641
3642
0
  if (host)
3643
0
  {
3644
0
    DEBUG_printf("5http_create: host=\"%s\"", host);
3645
3646
0
    if (!strncmp(host, "fe80::", 6))
3647
0
    {
3648
      // IPv6 link local address, convert to IPvFuture format...
3649
0
      char  *zoneid;    // Pointer to zoneid separator
3650
3651
0
      snprintf(http->hostname, sizeof(http->hostname), "[v1.%s]", host);
3652
0
      if ((zoneid = (char *)strchr(http->hostname, '%')) != NULL)
3653
0
        *zoneid = '+';
3654
0
    }
3655
0
    else if (isxdigit(host[0]) && isxdigit(host[1]) && isxdigit(host[2]) && isxdigit(host[3]) && host[4] == ':')
3656
0
    {
3657
      // IPv6 address, convert to URI format...
3658
0
      snprintf(http->hostname, sizeof(http->hostname), "[%s]", host);
3659
0
    }
3660
0
    else
3661
0
    {
3662
      // Not an IPv6 numeric address...
3663
0
      cupsCopyString(http->hostname, host, sizeof(http->hostname));
3664
0
    }
3665
3666
0
    DEBUG_printf("5http_create: http->hostname=\"%s\"", http->hostname);
3667
0
  }
3668
3669
0
  if (port == 443)     // Always use encryption for https
3670
0
    http->encryption = HTTP_ENCRYPTION_ALWAYS;
3671
0
  else
3672
0
    http->encryption = encryption;
3673
3674
0
  http_set_wait(http);
3675
3676
  // Set client credentials...
3677
0
  http->tls_credentials = _httpUseCredentials(cg->credentials);
3678
3679
  // Return the new structure...
3680
0
  return (http);
3681
0
}
3682
3683
3684
#ifdef DEBUG
3685
//
3686
// 'http_debug_hex()' - Do a hex dump of a buffer.
3687
//
3688
3689
static void
3690
http_debug_hex(const char *prefix,  // I - Prefix for line
3691
               const char *buffer,  // I - Buffer to dump
3692
               int        bytes)  // I - Bytes to dump
3693
{
3694
  int i, j,       // Looping vars
3695
  ch;       // Current character
3696
  char  line[255],      // Line buffer
3697
  *start,       // Start of line after prefix
3698
  *ptr;       // Pointer into line
3699
3700
3701
  if (_cups_debug_fd < 0 || _cups_debug_level < 6)
3702
    return;
3703
3704
  DEBUG_printf("9%s: %d bytes:", prefix, bytes);
3705
3706
  snprintf(line, sizeof(line), "9%s: ", prefix);
3707
  start = line + strlen(line);
3708
3709
  for (i = 0; i < bytes; i += 16)
3710
  {
3711
    for (j = 0, ptr = start; j < 16 && (i + j) < bytes; j ++, ptr += 2)
3712
      snprintf(ptr, 3, "%02X", buffer[i + j] & 255);
3713
3714
    while (j < 16)
3715
    {
3716
      memcpy(ptr, "  ", 3);
3717
      ptr += 2;
3718
      j ++;
3719
    }
3720
3721
    memcpy(ptr, "  ", 3);
3722
    ptr += 2;
3723
3724
    for (j = 0; j < 16 && (i + j) < bytes; j ++)
3725
    {
3726
      ch = buffer[i + j] & 255;
3727
3728
      if (ch < ' ' || ch >= 127)
3729
  ch = '.';
3730
3731
      *ptr++ = (char)ch;
3732
    }
3733
3734
    *ptr = '\0';
3735
    DEBUG_puts(line);
3736
  }
3737
}
3738
#endif // DEBUG
3739
3740
3741
//
3742
// 'http_read()' - Read a buffer from a HTTP connection.
3743
//
3744
// This function does the low-level read from the socket, retrying and timing
3745
// out as needed.
3746
//
3747
3748
static ssize_t        // O - Number of bytes read or -1 on error
3749
http_read(http_t *http,     // I - HTTP connection
3750
          char   *buffer,   // I - Buffer
3751
          size_t length,    // I - Maximum bytes to read
3752
          int    timeout)   // I - Timeout
3753
0
{
3754
0
  ssize_t bytes;      // Bytes read
3755
3756
3757
0
  DEBUG_printf("7http_read(http=%p, buffer=%p, length=" CUPS_LLFMT ", timeout=%d)", (void *)http, (void *)buffer, CUPS_LLCAST length, timeout);
3758
3759
0
  if (!http->blocking || timeout > 0)
3760
0
  {
3761
0
    while (!_httpWait(http, timeout, true))
3762
0
    {
3763
0
      if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
3764
0
  continue;
3765
3766
0
      DEBUG_puts("8http_read: Timeout.");
3767
0
      return (0);
3768
0
    }
3769
0
  }
3770
3771
0
  DEBUG_printf("8http_read: Reading %d bytes into buffer.", (int)length);
3772
3773
0
  do
3774
0
  {
3775
0
    if (http->tls)
3776
0
      bytes = _httpTLSRead(http, buffer, (int)length);
3777
0
    else
3778
0
      bytes = recv(http->fd, buffer, length, 0);
3779
3780
0
    if (bytes < 0)
3781
0
    {
3782
#ifdef _WIN32
3783
      if (WSAGetLastError() != WSAEINTR)
3784
      {
3785
  http->error = WSAGetLastError();
3786
  return (-1);
3787
      }
3788
      else if (WSAGetLastError() == WSAEWOULDBLOCK)
3789
      {
3790
  if (!http->timeout_cb ||
3791
      !(*http->timeout_cb)(http, http->timeout_data))
3792
  {
3793
    http->error = WSAEWOULDBLOCK;
3794
    return (-1);
3795
  }
3796
      }
3797
#else
3798
0
      DEBUG_printf("8http_read: %s", strerror(errno));
3799
3800
0
      if (errno == EWOULDBLOCK || errno == EAGAIN)
3801
0
      {
3802
0
  if (http->timeout_cb && !(*http->timeout_cb)(http, http->timeout_data))
3803
0
  {
3804
0
    http->error = errno;
3805
0
    return (-1);
3806
0
  }
3807
0
  else if (!http->timeout_cb && errno != EAGAIN)
3808
0
  {
3809
0
    http->error = errno;
3810
0
    return (-1);
3811
0
  }
3812
0
      }
3813
0
      else if (errno != EINTR)
3814
0
      {
3815
0
  http->error = errno;
3816
0
  return (-1);
3817
0
      }
3818
0
#endif // _WIN32
3819
0
    }
3820
0
  }
3821
0
  while (bytes < 0);
3822
3823
0
  DEBUG_printf("8http_read: Read " CUPS_LLFMT " bytes into buffer.", CUPS_LLCAST bytes);
3824
#ifdef DEBUG
3825
  if (bytes > 0)
3826
    http_debug_hex("http_read", buffer, (int)bytes);
3827
  else
3828
#endif // DEBUG
3829
0
  if (bytes == 0)
3830
0
  {
3831
0
    http->error = EPIPE;
3832
0
    return (0);
3833
0
  }
3834
3835
0
  return (bytes);
3836
0
}
3837
3838
3839
//
3840
// 'http_read_buffered()' - Do a buffered read from a HTTP connection.
3841
//
3842
// This function reads data from the HTTP buffer or from the socket, as needed.
3843
//
3844
3845
static ssize_t        // O - Number of bytes read or -1 on error
3846
http_read_buffered(http_t *http,  // I - HTTP connection
3847
                   char   *buffer,  // I - Buffer
3848
                   size_t length) // I - Maximum bytes to read
3849
0
{
3850
0
  ssize_t bytes;      // Bytes read
3851
3852
3853
0
  DEBUG_printf("7http_read_buffered(http=%p, buffer=%p, length=" CUPS_LLFMT ") used=%d", (void *)http, (void *)buffer, CUPS_LLCAST length, http->used);
3854
3855
0
  if (http->used > 0)
3856
0
  {
3857
0
    if (length > (size_t)http->used)
3858
0
      bytes = (ssize_t)http->used;
3859
0
    else
3860
0
      bytes = (ssize_t)length;
3861
3862
0
    DEBUG_printf("8http_read_buffered: Grabbing %d bytes from input buffer.", (int)bytes);
3863
3864
0
    memcpy(buffer, http->buffer, (size_t)bytes);
3865
0
    http->used -= (int)bytes;
3866
3867
0
    if (http->used > 0)
3868
0
      memmove(http->buffer, http->buffer + bytes, (size_t)http->used);
3869
0
  }
3870
0
  else
3871
0
  {
3872
0
    bytes = http_read(http, buffer, length, http->wait_value);
3873
0
  }
3874
3875
0
  return (bytes);
3876
0
}
3877
3878
3879
//
3880
// 'http_read_chunk()' - Read a chunk from a HTTP connection.
3881
//
3882
// This function reads and validates the chunk length, then does a buffered read
3883
// returning the number of bytes placed in the buffer.
3884
//
3885
3886
static ssize_t        // O - Number of bytes read or -1 on error
3887
http_read_chunk(http_t *http,   // I - HTTP connection
3888
    char   *buffer,   // I - Buffer
3889
    size_t length)    // I - Maximum bytes to read
3890
0
{
3891
0
  DEBUG_printf("7http_read_chunk(http=%p, buffer=%p, length=" CUPS_LLFMT ")", (void *)http, (void *)buffer, CUPS_LLCAST length);
3892
3893
0
  if (http->data_remaining <= 0)
3894
0
  {
3895
    // Read the CR LR at the end of the chunk...
3896
0
    char  *lineptr;   // Pointer into line
3897
3898
0
    if (!httpGets(http, http->line, sizeof(http->line)))
3899
0
    {
3900
0
      DEBUG_puts("8http_read_chunk: Could not get end of chunk.");
3901
0
      return (0);
3902
0
    }
3903
3904
    // Read the chunk header as needed...
3905
0
    if (!http->line[0])
3906
0
    {
3907
0
      if (!httpGets(http, http->line, sizeof(http->line)))
3908
0
      {
3909
0
  DEBUG_puts("8http_read_chunk: Could not get chunk header.");
3910
0
  return (0);
3911
0
      }
3912
0
    }
3913
3914
0
    if (!_cups_isxdigit(http->line[0]))
3915
0
    {
3916
0
      DEBUG_printf("8http_read_chunk: Bad chunk header '%s'.", http->line);
3917
0
      return (0);
3918
0
    }
3919
3920
0
    http->data_remaining = strtoll(http->line, &lineptr, 16);
3921
3922
0
    if (lineptr && *lineptr && *lineptr != ';' && !_cups_isspace(*lineptr))
3923
0
    {
3924
0
      DEBUG_printf("8http_read_chunk: Bad chunk header '%s'.", http->line);
3925
0
      return (0);
3926
0
    }
3927
3928
0
    DEBUG_printf("8http_read_chunk: Got chunk header '%s' (length=" CUPS_LLFMT ")", http->line, CUPS_LLCAST http->data_remaining);
3929
3930
0
    if (http->data_remaining == 0)
3931
0
    {
3932
      // 0-length chunk, grab trailing headers and blank line...
3933
0
      while (httpGets(http, http->line, sizeof(http->line)))
3934
0
      {
3935
0
        DEBUG_printf("8http_read_chunk: Got chunk trailer '%s'.", http->line);
3936
3937
0
        if (!http->line[0])
3938
0
          break;
3939
0
      }
3940
0
    }
3941
0
  }
3942
3943
0
  DEBUG_printf("8http_read_chunk: data_remaining=" CUPS_LLFMT, CUPS_LLCAST http->data_remaining);
3944
3945
0
  if (http->data_remaining <= 0)
3946
0
    return (0);
3947
0
  else if (length > (size_t)http->data_remaining)
3948
0
    length = (size_t)http->data_remaining;
3949
3950
0
  return (http_read_buffered(http, buffer, length));
3951
0
}
3952
3953
3954
//
3955
// 'http_send()' - Send a request with all fields and the trailing blank line.
3956
//
3957
3958
static bool       // O - `true` on success, `false` on error
3959
http_send(http_t       *http,   // I - HTTP connection
3960
          http_state_t request,   // I - Request code
3961
    const char   *uri)    // I - URI
3962
0
{
3963
0
  int   i;      // Looping var
3964
0
  char    buf[1024];    // Encoded URI buffer
3965
0
  const char  *value;     // Field value
3966
0
  static const char * const codes[HTTP_STATE_MAX] =
3967
0
  {         // Request code strings
3968
0
    NULL, // WAITING
3969
0
    "CONNECT ",
3970
0
    "COPY ",
3971
0
    NULL,
3972
0
    "DELETE ",
3973
0
    NULL,
3974
0
    "GET ",
3975
0
    NULL,
3976
0
    "HEAD ",
3977
0
    "LOCK ",
3978
0
    NULL,
3979
0
    NULL,
3980
0
    "MKCOL ",
3981
0
    "MOVE ",
3982
0
    NULL,
3983
0
    "OPTIONS ",
3984
0
    "POST ",
3985
0
    NULL,
3986
0
    NULL,
3987
0
    "PROPFIND ",
3988
0
    NULL,
3989
0
    NULL,
3990
0
    "PROPPATCH ",
3991
0
    NULL,
3992
0
    NULL,
3993
0
    "PUT ",
3994
0
    NULL,
3995
0
    "TRACE ",
3996
0
    "UNLOCK ",
3997
0
    NULL,
3998
0
    NULL,
3999
0
    NULL
4000
0
  };
4001
4002
4003
0
  DEBUG_printf("4http_send(http=%p, request=HTTP_%s, uri=\"%s\")", (void *)http, codes[request], uri);
4004
4005
0
  if (http == NULL || uri == NULL)
4006
0
    return (false);
4007
4008
  // Set the User-Agent field if it isn't already...
4009
0
  if (!http->fields[HTTP_FIELD_USER_AGENT])
4010
0
  {
4011
0
    if (http->default_fields[HTTP_FIELD_USER_AGENT])
4012
0
    {
4013
0
      DEBUG_puts("5http_send: Using default User-Agent.");
4014
0
      httpSetField(http, HTTP_FIELD_USER_AGENT, http->default_fields[HTTP_FIELD_USER_AGENT]);
4015
0
    }
4016
0
    else
4017
0
    {
4018
0
      DEBUG_puts("5http_send: Using client.conf User-Agent.");
4019
0
      httpSetField(http, HTTP_FIELD_USER_AGENT, cupsGetUserAgent());
4020
0
    }
4021
0
  }
4022
4023
  // Set the Accept-Encoding field if it isn't already...
4024
0
  if (!http->fields[HTTP_FIELD_ACCEPT_ENCODING] && http->default_fields[HTTP_FIELD_ACCEPT_ENCODING])
4025
0
    httpSetField(http, HTTP_FIELD_ACCEPT_ENCODING, http->default_fields[HTTP_FIELD_ACCEPT_ENCODING]);
4026
4027
  // Set the Authorization field if it isn't already...
4028
0
  if (!http->fields[HTTP_FIELD_AUTHORIZATION] && http->authstring)
4029
0
    httpSetField(http, HTTP_FIELD_AUTHORIZATION, http->authstring);
4030
4031
  // Encode the URI as needed...
4032
0
  _httpEncodeURI(buf, uri, sizeof(buf));
4033
4034
  // See if we had an error the last time around; if so, reconnect...
4035
0
  if (http->fd < 0 || http->status == HTTP_STATUS_ERROR || http->status >= HTTP_STATUS_BAD_REQUEST)
4036
0
  {
4037
0
    DEBUG_printf("5http_send: Reconnecting, fd=%d, status=%d, tls_upgrade=%d", http->fd, http->status, http->tls_upgrade);
4038
4039
0
    if (!httpConnectAgain(http, 30000, NULL))
4040
0
      return (false);
4041
0
  }
4042
4043
  // Flush any written data that is pending...
4044
0
  if (http->wused)
4045
0
  {
4046
0
    if (httpFlushWrite(http) < 0)
4047
0
    {
4048
0
      if (!httpConnectAgain(http, 30000, NULL))
4049
0
        return (false);
4050
0
    }
4051
0
  }
4052
4053
  // Send the request header...
4054
0
  http->state         = request;
4055
0
  http->data_encoding = HTTP_ENCODING_FIELDS;
4056
4057
0
  if (request == HTTP_STATE_LOCK || request == HTTP_STATE_POST || request == HTTP_STATE_PROPFIND || request == HTTP_STATE_PROPPATCH || request == HTTP_STATE_PUT)
4058
0
    http->state ++;
4059
4060
0
  http->status = HTTP_STATUS_CONTINUE;
4061
4062
0
  if (http->encryption == HTTP_ENCRYPTION_REQUIRED && !http->tls)
4063
0
  {
4064
0
    httpSetField(http, HTTP_FIELD_CONNECTION, "Upgrade");
4065
0
    httpSetField(http, HTTP_FIELD_UPGRADE, "TLS/1.3,TLS/1.2");
4066
0
  }
4067
4068
0
  if (httpWrite(http, codes[request], strlen(codes[request])) < 1 ||
4069
0
      httpWrite(http, buf, strlen(buf)) < 1 ||
4070
0
      httpWrite(http, " HTTP/1.1\r\n", 11) < 1)
4071
0
  {
4072
0
    http->status = HTTP_STATUS_ERROR;
4073
0
    return (false);
4074
0
  }
4075
4076
0
  for (i = 0; i < HTTP_FIELD_MAX; i ++)
4077
0
  {
4078
0
    if ((value = httpGetField(http, i)) != NULL && *value)
4079
0
    {
4080
0
      DEBUG_printf("5http_send: %s: %s", http_fields[i], value);
4081
4082
0
      if (i == HTTP_FIELD_HOST)
4083
0
      {
4084
0
        snprintf(buf, sizeof(buf), "%s:%d", value, httpAddrGetPort(http->hostaddr));
4085
4086
0
  if (!http_write_header(http, HTTP_FIELD_HOST, buf))
4087
0
  {
4088
0
    http->status = HTTP_STATUS_ERROR;
4089
0
    return (false);
4090
0
  }
4091
0
      }
4092
0
      else if (!http_write_header(http, i, value))
4093
0
      {
4094
0
  http->status = HTTP_STATUS_ERROR;
4095
0
  return (false);
4096
0
      }
4097
0
    }
4098
0
  }
4099
4100
0
  if (http->cookie)
4101
0
  {
4102
0
    if (httpWrite(http, "Cookie: $Version=0; ", 20) < 1 ||
4103
0
        httpWrite(http, http->cookie, strlen(http->cookie)) < 1 ||
4104
0
        httpWrite(http, "\r\n", 2) < 1)
4105
0
    {
4106
0
      http->status = HTTP_STATUS_ERROR;
4107
0
      return (false);
4108
0
    }
4109
0
  }
4110
4111
0
  DEBUG_printf("5http_send: expect=%d, mode=%d, state=%s", http->expect, http->mode, httpStateString(http->state));
4112
4113
0
  if (http->expect == HTTP_STATUS_CONTINUE && http->mode == _HTTP_MODE_CLIENT && (http->state == HTTP_STATE_LOCK_RECV || http->state == HTTP_STATE_POST_RECV || http->state == HTTP_STATE_PROPFIND_RECV || http->state == HTTP_STATE_PROPPATCH_RECV || http->state == HTTP_STATE_PUT_RECV))
4114
0
  {
4115
0
    if (httpWrite(http, "Expect: 100-continue\r\n", 22) < 1)
4116
0
    {
4117
0
      http->status = HTTP_STATUS_ERROR;
4118
0
      return (false);
4119
0
    }
4120
0
  }
4121
4122
0
  if (httpWrite(http, "\r\n", 2) < 1)
4123
0
  {
4124
0
    http->status = HTTP_STATUS_ERROR;
4125
0
    return (false);
4126
0
  }
4127
4128
0
  if (httpFlushWrite(http) < 0)
4129
0
    return (false);
4130
4131
0
  http_set_length(http);
4132
0
  httpClearFields(http);
4133
4134
  // Some authentication strings can only be used once...
4135
0
  if (http->fields[HTTP_FIELD_AUTHORIZATION] && http->authstring)
4136
0
  {
4137
0
    free(http->authstring);
4138
0
    http->authstring = NULL;
4139
0
  }
4140
4141
0
  return (true);
4142
0
}
4143
4144
4145
//
4146
// 'http_set_length()' - Set the data_encoding and data_remaining values.
4147
//
4148
4149
static off_t        // O - Remainder or -1 on error
4150
http_set_length(http_t *http)   // I - Connection
4151
0
{
4152
0
  off_t remaining;      // Remainder
4153
4154
4155
0
  DEBUG_printf("4http_set_length(http=%p) mode=%d state=%s", (void *)http, http->mode, httpStateString(http->state));
4156
4157
0
  if ((remaining = httpGetLength(http)) >= 0)
4158
0
  {
4159
0
    if (http->mode == _HTTP_MODE_SERVER && http->state != HTTP_STATE_COPY_SEND && http->state != HTTP_STATE_DELETE_SEND && http->state != HTTP_STATE_GET_SEND && http->state != HTTP_STATE_LOCK && http->state != HTTP_STATE_LOCK_SEND && http->state != HTTP_STATE_MOVE_SEND && http->state != HTTP_STATE_PUT && http->state != HTTP_STATE_POST && http->state != HTTP_STATE_POST_SEND && http->state != HTTP_STATE_PROPFIND && http->state != HTTP_STATE_PROPFIND_SEND && http->state != HTTP_STATE_PROPPATCH && http->state != HTTP_STATE_PROPPATCH_SEND)
4160
0
    {
4161
0
      DEBUG_puts("5http_set_length: Not setting data_encoding/remaining.");
4162
0
      return (remaining);
4163
0
    }
4164
4165
0
    if (!_cups_strcasecmp(httpGetField(http, HTTP_FIELD_TRANSFER_ENCODING), "chunked"))
4166
0
    {
4167
0
      DEBUG_puts("5http_set_length: Setting data_encoding to HTTP_ENCODING_CHUNKED.");
4168
0
      http->data_encoding = HTTP_ENCODING_CHUNKED;
4169
0
    }
4170
0
    else
4171
0
    {
4172
0
      DEBUG_puts("5http_set_length: Setting data_encoding to HTTP_ENCODING_LENGTH.");
4173
0
      http->data_encoding = HTTP_ENCODING_LENGTH;
4174
0
    }
4175
4176
0
    DEBUG_printf("5http_set_length: Setting data_remaining to " CUPS_LLFMT ".", CUPS_LLCAST remaining);
4177
0
    http->data_remaining = remaining;
4178
0
  }
4179
4180
0
  return (remaining);
4181
0
}
4182
4183
//
4184
// 'http_set_timeout()' - Set the socket timeout values.
4185
//
4186
4187
static void
4188
http_set_timeout(int    fd,   // I - File descriptor
4189
                 double timeout)  // I - Timeout in seconds
4190
0
{
4191
#ifdef _WIN32
4192
  DWORD tv = (DWORD)(timeout * 1000);
4193
              // Timeout in milliseconds
4194
4195
  if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, CUPS_SOCAST &tv, sizeof(tv)))
4196
    DEBUG_printf("http_set_timeout: setsockopt(SO_RCVTIMEO) failed - %s", strerror(errno));
4197
4198
  if (setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, CUPS_SOCAST &tv, sizeof(tv)))
4199
    DEBUG_printf("http_set_timeout: setsockopt(SO_SNDTIMEO) failed - %s", strerror(errno));
4200
4201
#else
4202
0
  struct timeval tv;      // Timeout in secs and usecs
4203
4204
0
  tv.tv_sec  = (int)timeout;
4205
0
  tv.tv_usec = (int)(1000000 * fmod(timeout, 1.0));
4206
4207
0
  if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, CUPS_SOCAST &tv, sizeof(tv)))
4208
0
    DEBUG_printf("http_set_timeout: setsockopt(SO_RCVTIMEO) failed - %s", strerror(errno));
4209
0
  if (setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, CUPS_SOCAST &tv, sizeof(tv)))
4210
0
    DEBUG_printf("http_set_timeout: setsockopt(SO_SNDTIMEO) failed - %s", strerror(errno));
4211
0
#endif // _WIN32
4212
0
}
4213
4214
4215
//
4216
// 'http_set_wait()' - Set the default wait value for reads.
4217
//
4218
4219
static void
4220
http_set_wait(http_t *http)   // I - HTTP connection
4221
0
{
4222
0
  http->wait_value = (int)(http->timeout_value * 1000);
4223
4224
0
  if (http->wait_value <= 0)
4225
0
  {
4226
0
    if (http->blocking)
4227
0
      http->wait_value = 60000;
4228
0
    else
4229
0
      http->wait_value = 1000;
4230
0
  }
4231
0
}
4232
4233
4234
//
4235
// 'http_tls_upgrade()' - Force upgrade to TLS encryption.
4236
//
4237
4238
static bool       // O - `true` on success, `false` on failure
4239
http_tls_upgrade(http_t *http)    // I - HTTP connection
4240
0
{
4241
0
  bool    ret;      // Return value
4242
0
  http_t  myhttp;     // Local copy of HTTP data
4243
4244
4245
0
  DEBUG_printf("4http_tls_upgrade(%p)", (void *)http);
4246
4247
  // Flush the connection to make sure any previous "Upgrade" message
4248
  // has been read.
4249
0
  httpFlush(http);
4250
4251
  // Copy the HTTP data to a local variable so we can do the OPTIONS
4252
  // request without interfering with the existing request data...
4253
0
  memcpy(&myhttp, http, sizeof(myhttp));
4254
4255
  // Send an OPTIONS request to the server, requiring SSL or TLS
4256
  // encryption on the link...
4257
0
  http->tls_upgrade = true;
4258
0
  memset(http->fields, 0, sizeof(http->fields));
4259
0
  http->expect = (http_status_t)0;
4260
4261
0
  if (http->hostname[0] == '/')
4262
0
    httpSetField(http, HTTP_FIELD_HOST, "localhost");
4263
0
  else
4264
0
    httpSetField(http, HTTP_FIELD_HOST, http->hostname);
4265
4266
0
  httpSetField(http, HTTP_FIELD_CONNECTION, "upgrade");
4267
0
  httpSetField(http, HTTP_FIELD_UPGRADE, "TLS/1.3,TLS/1.2");
4268
4269
0
  if ((ret = httpWriteRequest(http, "OPTIONS", "*")) == true)
4270
0
  {
4271
    // Wait for the secure connection...
4272
0
    while (httpUpdate(http) == HTTP_STATUS_CONTINUE)
4273
0
      ;
4274
0
  }
4275
4276
  // Restore the HTTP request data...
4277
0
  memcpy(http->fields, myhttp.fields, sizeof(http->fields));
4278
4279
0
  http->data_encoding   = myhttp.data_encoding;
4280
0
  http->data_remaining  = myhttp.data_remaining;
4281
0
  http->expect          = myhttp.expect;
4282
0
  http->digest_tries    = myhttp.digest_tries;
4283
0
  http->tls_upgrade     = false;
4284
4285
  // See if we actually went secure...
4286
0
  if (!http->tls)
4287
0
  {
4288
    // Server does not support HTTP upgrade...
4289
0
    DEBUG_puts("5http_tls_upgrade: Server does not support HTTP upgrade!");
4290
4291
0
    _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, _("Encryption is not supported."), 1);
4292
0
    httpAddrClose(NULL, http->fd);
4293
4294
0
    http->fd = -1;
4295
4296
0
    return (false);
4297
0
  }
4298
4299
0
  return (ret);
4300
0
}
4301
4302
4303
//
4304
// 'http_write()' - Write a buffer to a HTTP connection.
4305
//
4306
4307
static ssize_t        // O - Number of bytes written
4308
http_write(http_t     *http,    // I - HTTP connection
4309
           const char *buffer,    // I - Buffer for data
4310
     size_t     length)   // I - Number of bytes to write
4311
0
{
4312
0
  ssize_t tbytes,     // Total bytes sent
4313
0
    bytes;      // Bytes sent
4314
4315
4316
0
  DEBUG_printf("7http_write(http=%p, buffer=%p, length=" CUPS_LLFMT ")", (void *)http, (void *)buffer, CUPS_LLCAST length);
4317
0
  http->error = 0;
4318
0
  tbytes      = 0;
4319
4320
0
  while (length > 0)
4321
0
  {
4322
0
    DEBUG_printf("8http_write: About to write %d bytes.", (int)length);
4323
4324
0
    if (http->timeout_value > 0.0)
4325
0
    {
4326
0
      struct pollfd pfd;    // Polled file descriptor
4327
0
      int   nfds;   // Result from select()/poll()
4328
4329
0
      do
4330
0
      {
4331
0
  pfd.fd     = http->fd;
4332
0
  pfd.events = POLLOUT;
4333
4334
0
  while ((nfds = poll(&pfd, 1, http->wait_value)) < 0)
4335
0
  {
4336
#ifdef _WIN32
4337
          if (WSAGetLastError() == WSAEINTR || WSAGetLastError() == WSAEWOULDBLOCK)
4338
            break;
4339
#else
4340
0
    if (errno == EINTR || errno == EAGAIN)
4341
0
      break;
4342
0
#endif // _WIN32
4343
0
        }
4344
4345
0
        if (nfds < 0)
4346
0
  {
4347
0
    http->error = errno;
4348
0
    return (-1);
4349
0
  }
4350
0
  else if (nfds == 0 && (!http->timeout_cb || !(*http->timeout_cb)(http, http->timeout_data)))
4351
0
  {
4352
#ifdef _WIN32
4353
    http->error = WSAEWOULDBLOCK;
4354
#else
4355
0
    http->error = EWOULDBLOCK;
4356
0
#endif // _WIN32
4357
0
    return (-1);
4358
0
  }
4359
0
      }
4360
0
      while (nfds <= 0);
4361
0
    }
4362
4363
0
    if (http->tls)
4364
0
      bytes = _httpTLSWrite(http, buffer, (int)length);
4365
0
    else
4366
0
      bytes = send(http->fd, buffer, length, 0);
4367
4368
0
    DEBUG_printf("8http_write: Write of " CUPS_LLFMT " bytes returned " CUPS_LLFMT ".", CUPS_LLCAST length, CUPS_LLCAST bytes);
4369
4370
0
    if (bytes < 0)
4371
0
    {
4372
#ifdef _WIN32
4373
      if (WSAGetLastError() == WSAEINTR)
4374
        continue;
4375
      else if (WSAGetLastError() == WSAEWOULDBLOCK)
4376
      {
4377
        if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
4378
          continue;
4379
4380
        http->error = WSAGetLastError();
4381
      }
4382
      else if (WSAGetLastError() != http->error &&
4383
               WSAGetLastError() != WSAECONNRESET)
4384
      {
4385
        http->error = WSAGetLastError();
4386
  continue;
4387
      }
4388
4389
#else
4390
0
      if (errno == EINTR)
4391
0
        continue;
4392
0
      else if (errno == EWOULDBLOCK || errno == EAGAIN)
4393
0
      {
4394
0
  if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
4395
0
          continue;
4396
0
        else if (!http->timeout_cb && errno == EAGAIN)
4397
0
    continue;
4398
4399
0
        http->error = errno;
4400
0
      }
4401
0
      else if (errno != http->error && errno != ECONNRESET)
4402
0
      {
4403
0
        http->error = errno;
4404
0
  continue;
4405
0
      }
4406
0
#endif // _WIN32
4407
4408
0
      DEBUG_printf("8http_write: error writing data (%s).", strerror(http->error));
4409
4410
0
      return (-1);
4411
0
    }
4412
4413
0
    buffer += bytes;
4414
0
    tbytes += bytes;
4415
0
    length -= (size_t)bytes;
4416
0
  }
4417
4418
#ifdef DEBUG
4419
  http_debug_hex("http_write", buffer - tbytes, (int)tbytes);
4420
#endif // DEBUG
4421
4422
0
  DEBUG_printf("8http_write: Returning " CUPS_LLFMT ".", CUPS_LLCAST tbytes);
4423
4424
0
  return (tbytes);
4425
0
}
4426
4427
4428
//
4429
// 'http_write_chunk()' - Write a chunked buffer.
4430
//
4431
4432
static ssize_t        // O - Number bytes written
4433
http_write_chunk(http_t     *http,  // I - HTTP connection
4434
                 const char *buffer,  // I - Buffer to write
4435
     size_t     length) // I - Length of buffer
4436
0
{
4437
0
  char    header[16];   // Chunk header
4438
0
  ssize_t bytes;      // Bytes written
4439
4440
4441
0
  DEBUG_printf("7http_write_chunk(http=%p, buffer=%p, length=" CUPS_LLFMT ")", (void *)http, (void *)buffer, CUPS_LLCAST length);
4442
4443
  // Write the chunk header, data, and trailer.
4444
0
  snprintf(header, sizeof(header), "%x\r\n", (unsigned)length);
4445
0
  if (http_write(http, header, strlen(header)) < 0)
4446
0
  {
4447
0
    DEBUG_puts("8http_write_chunk: http_write of length failed.");
4448
0
    return (-1);
4449
0
  }
4450
4451
0
  if ((bytes = http_write(http, buffer, length)) < 0)
4452
0
  {
4453
0
    DEBUG_puts("8http_write_chunk: http_write of buffer failed.");
4454
0
    return (-1);
4455
0
  }
4456
4457
0
  if (http_write(http, "\r\n", 2) < 0)
4458
0
  {
4459
0
    DEBUG_puts("8http_write_chunk: http_write of CR LF failed.");
4460
0
    return (-1);
4461
0
  }
4462
4463
0
  return (bytes);
4464
0
}
4465
4466
4467
//
4468
// 'http_write_header()' - Write a HTTP request/response header.
4469
//
4470
4471
static bool       // O - `true` on success, `false` on error
4472
http_write_header(http_t       *http, // I - HTTP connection
4473
                  http_field_t field, // I - Header field
4474
                  const char   *value)  // I - Header value
4475
0
{
4476
0
  return (httpWrite(http, http_fields[field], strlen(http_fields[field])) > 0 &&
4477
0
          httpWrite(http, ": ", 2) > 0 &&
4478
0
          httpWrite(http, value, strlen(value)) > 0 &&
4479
0
          httpWrite(http, "\r\n", 2) > 0);
4480
0
}