Coverage Report

Created: 2026-11-27 06:48

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
1.81k
{
162
1.81k
  http_t    *http;    // HTTP connection
163
1.81k
  http_addrlist_t addrlist; // Dummy address list
164
1.81k
  socklen_t   addrlen;  // Length of address
165
1.81k
  int     val;    // Socket option value
166
167
168
  // Range check input...
169
1.81k
  if (fd < 0)
170
0
    return (NULL);
171
172
  // Create the client connection...
173
1.81k
  memset(&addrlist, 0, sizeof(addrlist));
174
175
1.81k
  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
1.81k
  addrlen = sizeof(http_addr_t);
180
181
1.81k
  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
1.81k
  http->hostaddr = &(http->hostlist->addr);
190
191
1.81k
  if (httpAddrIsLocalhost(http->hostaddr))
192
1.81k
    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
1.81k
  val = 1;
207
1.81k
  if (setsockopt(http->fd, IPPROTO_TCP, TCP_NODELAY, CUPS_SOCAST &val, sizeof(val)))
208
1.81k
    DEBUG_printf("httpAcceptConnection: setsockopt(TCP_NODELAY) failed - %s", strerror(errno));
209
210
1.81k
#ifdef FD_CLOEXEC
211
  // Close this socket when starting another process...
212
1.81k
  if (fcntl(http->fd, F_SETFD, FD_CLOEXEC))
213
0
    DEBUG_printf("httpAcceptConnection: fcntl(F_SETFD, FD_CLOEXEC) failed - %s", strerror(errno));
214
1.81k
#endif // FD_CLOEXEC
215
216
1.81k
  return (http);
217
1.81k
}
218
219
220
//
221
// 'httpClearCookie()' - Clear the cookie value(s).
222
//
223
224
void
225
httpClearCookie(http_t *http)   // I - HTTP connection
226
3.46k
{
227
3.46k
  if (!http)
228
0
    return;
229
230
3.46k
  free(http->cookie);
231
3.46k
  http->cookie = NULL;
232
233
3.46k
  free(http->set_cookie);
234
3.46k
  http->set_cookie = NULL;
235
3.46k
}
236
237
238
//
239
// 'httpClearFields()' - Clear HTTP request/response fields.
240
//
241
242
void
243
httpClearFields(http_t *http)   // I - HTTP connection
244
18.3k
{
245
18.3k
  http_field_t  field;      // Current field
246
247
248
18.3k
  DEBUG_printf("httpClearFields(http=%p)", (void *)http);
249
250
18.3k
  if (http)
251
18.3k
  {
252
1.66M
    for (field = HTTP_FIELD_ACCEPT; field < HTTP_FIELD_MAX; field ++)
253
1.64M
    {
254
1.64M
      free(http->fields[field]);
255
1.64M
      http->fields[field] = NULL;
256
1.64M
    }
257
258
18.3k
    if (http->mode == _HTTP_MODE_CLIENT)
259
7.74k
    {
260
7.74k
      if (http->hostname[0] == '/')
261
7.74k
  httpSetField(http, HTTP_FIELD_HOST, "localhost");
262
0
      else
263
0
  httpSetField(http, HTTP_FIELD_HOST, http->hostname);
264
7.74k
    }
265
266
18.3k
    http->expect = (http_status_t)0;
267
18.3k
  }
268
18.3k
}
269
270
271
//
272
// 'httpClose()' - Close a HTTP connection.
273
//
274
275
void
276
httpClose(http_t *http)     // I - HTTP connection
277
5.71k
{
278
5.71k
  http_field_t  field;      // Current field
279
280
281
5.71k
  DEBUG_printf("httpClose(http=%p)", (void *)http);
282
283
  // Range check input...
284
5.71k
  if (!http)
285
0
    return;
286
287
  // Close any open connection...
288
5.71k
  _httpDisconnect(http);
289
290
  // Free memory used...
291
5.71k
  httpAddrFreeList(http->hostlist);
292
293
519k
  for (field = HTTP_FIELD_ACCEPT; field < HTTP_FIELD_MAX; field ++)
294
513k
  {
295
513k
    free(http->default_fields[field]);
296
513k
    free(http->fields[field]);
297
513k
  }
298
299
5.71k
  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
5.71k
  free(http->authstring);
310
5.71k
  free(http->cookie);
311
5.71k
  free(http->set_cookie);
312
5.71k
  free(http->fbuffer);
313
5.71k
  free(http->sbuffer);
314
315
5.71k
  _httpFreeCredentials(http->tls_credentials);
316
317
5.71k
  free(http);
318
5.71k
}
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
3.89k
{
352
3.89k
  http_t  *http;      // New HTTP connection
353
354
355
3.89k
  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
3.89k
  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
3.89k
  if (msec == 0 || httpConnectAgain(http, msec, cancel))
363
3.89k
    return (http);
364
365
  // Could not connect to any known address - bail out!
366
0
  httpClose(http);
367
368
0
  return (NULL);
369
3.89k
}
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
3.89k
{
381
3.89k
  http_addrlist_t *addr;    // Connected address
382
3.89k
  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
3.89k
  DEBUG_printf("httpConnectAgain(http=%p, msec=%d, cancel=%p)", (void *)http, msec, (void *)cancel);
390
391
  // Range check input...
392
3.89k
  if (!http)
393
0
  {
394
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0);
395
0
    return (false);
396
0
  }
397
398
3.89k
  orig_creds = httpCopyPeerCredentials(http);
399
400
3.89k
  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
3.89k
  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
3.89k
  http->state           = HTTP_STATE_WAITING;
418
3.89k
  http->version         = HTTP_VERSION_1_1;
419
3.89k
  http->keep_alive      = HTTP_KEEPALIVE_OFF;
420
3.89k
  http->data_encoding   = HTTP_ENCODING_FIELDS;
421
3.89k
  http->used            = 0;
422
3.89k
  http->data_remaining  = 0;
423
3.89k
  http->hostaddr        = NULL;
424
3.89k
  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
3.89k
  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
3.89k
  DEBUG_printf("2httpConnectAgain: New socket=%d", http->fd);
450
451
3.89k
  if (http->timeout_value > 0)
452
0
    http_set_timeout(http->fd, http->timeout_value);
453
454
3.89k
  http->hostaddr = &(addr->addr);
455
3.89k
  http->error    = 0;
456
457
3.89k
  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
3.89k
  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
3.89k
  DEBUG_printf("1httpConnectAgain: Connected to %s:%d...", httpAddrGetString(http->hostaddr, temp, sizeof(temp)), httpAddrGetPort(http->hostaddr));
481
482
3.89k
  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
3.89k
  free(orig_creds);
502
503
3.89k
  return (true);
504
3.89k
}
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
5.71k
{
630
5.71k
  if (http->tls)
631
0
    _httpTLSStop(http);
632
633
5.71k
  httpAddrClose(NULL, http->fd);
634
635
5.71k
  http->fd = -1;
636
5.71k
}
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
15.9k
{
647
15.9k
  int i;        // Looping var
648
649
650
863k
  for (i = 0; i < HTTP_FIELD_MAX; i ++)
651
860k
  {
652
860k
    if (!_cups_strcasecmp(name, http_fields[i]))
653
13.3k
      return ((http_field_t)i);
654
860k
  }
655
656
2.64k
  return (HTTP_FIELD_UNKNOWN);
657
15.9k
}
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
8.88k
{
716
8.88k
  ssize_t bytes;      // Bytes written
717
718
719
8.88k
  DEBUG_printf("httpFlushWrite(http=%p) data_encoding=%d", (void *)http, http ? http->data_encoding : 100);
720
721
8.88k
  if (!http || !http->wused)
722
54
  {
723
54
    DEBUG_puts(http ? "1httpFlushWrite: Write buffer is empty." : "1httpFlushWrite: No connection.");
724
54
    return (0);
725
54
  }
726
727
8.83k
  if (http->data_encoding == HTTP_ENCODING_CHUNKED)
728
1.78k
    bytes = http_write_chunk(http, http->wbuffer, (size_t)http->wused);
729
7.04k
  else
730
7.04k
    bytes = http_write(http, http->wbuffer, (size_t)http->wused);
731
732
8.83k
  http->wused = 0;
733
734
8.83k
  DEBUG_printf("1httpFlushWrite: Returning %d, errno=%d.", (int)bytes, errno);
735
736
8.83k
  return ((int)bytes);
737
8.88k
}
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
2.32k
{
796
2.32k
  if (http && http->fields[HTTP_FIELD_ACCEPT_ENCODING])
797
818
  {
798
818
    int   i;      // Looping var
799
818
    char  temp[_HTTP_MAX_VALUE],  // Copy of Accepts-Encoding value
800
818
    *start,     // Start of coding value
801
818
    *end;     // End of coding value
802
818
    double  qvalue;     // "qvalue" for coding
803
818
    struct lconv *loc = localeconv(); // Locale data
804
818
    static const char * const codings[] =
805
818
    {         // Supported content codings
806
818
      "deflate",
807
818
      "gzip",
808
818
      "x-deflate",
809
818
      "x-gzip"
810
818
    };
811
812
818
    cupsCopyString(temp, http->fields[HTTP_FIELD_ACCEPT_ENCODING], sizeof(temp));
813
814
6.85k
    for (start = temp; *start; start = end)
815
6.25k
    {
816
      // Find the end of the coding name...
817
6.25k
      qvalue = 1.0;
818
6.25k
      end    = start;
819
15.0k
      while (*end && *end != ';' && *end != ',' && !_cups_isspace(*end))
820
8.84k
        end ++;
821
822
6.25k
      if (*end == ';')
823
3.89k
      {
824
        // Grab the qvalue as needed...
825
3.89k
        if (!strncmp(end, ";q=", 3))
826
3.49k
          qvalue = _cupsStrScand(end + 3, NULL, loc);
827
828
        // Skip past all attributes...
829
3.89k
        *end++ = '\0';
830
19.9k
        while (*end && *end != ',' && !_cups_isspace(*end))
831
16.0k
          end ++;
832
3.89k
      }
833
2.35k
      else if (*end)
834
2.02k
      {
835
2.02k
        *end++ = '\0';
836
2.02k
      }
837
838
12.2k
      while (*end && _cups_isspace(*end))
839
6.00k
  end ++;
840
841
      // Check value if it matches something we support...
842
6.25k
      if (qvalue <= 0.0)
843
3.24k
        continue;
844
845
14.3k
      for (i = 0; i < (int)(sizeof(codings) / sizeof(codings[0])); i ++)
846
11.5k
      {
847
11.5k
        if (!strcmp(start, codings[i]))
848
213
          return (codings[i]);
849
11.5k
      }
850
3.01k
    }
851
818
  }
852
853
2.11k
  return (NULL);
854
2.32k
}
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
12.4k
{
886
12.4k
  const char  *cookie;    // Cookie: header value
887
12.4k
  char    current[128],   // Current name string
888
12.4k
    *ptr,     // Pointer into name/buffer
889
12.4k
    *end;     // End of name/buffer
890
12.4k
  bool    match;      // Does the current name match?
891
892
893
  // Range check input...
894
12.4k
  if (buffer)
895
12.4k
    *buffer = '\0';
896
897
12.4k
  if (!http || !http->cookie || !name || !buffer || bufsize < 2)
898
11.5k
    return (NULL);
899
900
  // Loop through the cookie string...
901
2.10k
  for (cookie = http->cookie; *cookie;)
902
1.54k
  {
903
    // Skip leading whitespace...
904
2.22k
    while (_cups_isspace(*cookie))
905
680
      cookie ++;
906
1.54k
    if (!*cookie)
907
0
      break;
908
909
    // Copy the name...
910
17.4k
    for (ptr = current, end = current + sizeof(current) - 1; *cookie && *cookie != '=';)
911
15.9k
    {
912
15.9k
      if (ptr < end)
913
12.1k
        *ptr++ = *cookie++;
914
3.75k
      else
915
3.75k
  cookie ++;
916
15.9k
    }
917
918
1.54k
    if (*cookie != '=')
919
198
      break;
920
921
1.34k
    *ptr = '\0';
922
1.34k
    match = !strcmp(current, name);
923
1.34k
    cookie ++;
924
925
    // Then the value...
926
1.34k
    if (*cookie == '\"')
927
537
    {
928
      // Copy quoted value...
929
22.3k
      for (cookie ++, ptr = buffer, end = buffer + bufsize - 1; *cookie && *cookie != '\"';)
930
21.8k
      {
931
21.8k
        if (match && ptr < end)
932
2.23k
    *ptr++ = *cookie++;
933
19.6k
  else
934
19.6k
    cookie ++;
935
21.8k
      }
936
937
537
      if (*cookie == '\"')
938
385
        cookie ++;
939
152
      else
940
152
        match = false;
941
537
    }
942
805
    else
943
805
    {
944
      // Copy unquoted value...
945
22.1k
      for (ptr = buffer, end = buffer + bufsize - 1; *cookie && *cookie != ';';)
946
21.3k
      {
947
21.3k
        if (match && ptr < end)
948
2.33k
    *ptr++ = *cookie++;
949
18.9k
  else
950
18.9k
    cookie ++;
951
21.3k
      }
952
805
    }
953
954
1.34k
    if (match)
955
117
    {
956
      // Got the value we were looking for, nul-terminate and return...
957
117
      *ptr = '\0';
958
117
      return (buffer);
959
117
    }
960
961
    // Skip over separator...
962
1.22k
    if (*cookie == ';')
963
391
      cookie ++;
964
1.22k
  }
965
966
  // If we get here then we never found the cookie...
967
765
  return (NULL);
968
882
}
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
878
{
1010
878
  if (!http)
1011
0
    return (HTTP_STATUS_ERROR);
1012
878
  else
1013
878
    return (http->expect);
1014
878
}
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
642k
{
1036
642k
  if (!http || field <= HTTP_FIELD_UNKNOWN || field >= HTTP_FIELD_MAX)
1037
0
    return (NULL);
1038
642k
  else if (http->fields[field])
1039
30.1k
    return (http->fields[field]);
1040
612k
  else
1041
612k
    return ("");
1042
642k
}
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
9.62k
{
1067
9.62k
  off_t     remaining;  // Remaining length
1068
1069
1070
9.62k
  DEBUG_printf("2httpGetLength(http=%p), state=%s", (void *)http, http ? httpStateString(http->state) : "NONE");
1071
1072
9.62k
  if (!http)
1073
0
  {
1074
0
    remaining = -1;
1075
0
  }
1076
9.62k
  else if (http->fields[HTTP_FIELD_TRANSFER_ENCODING])
1077
4.44k
  {
1078
    // Chunked content?
1079
4.44k
    if (!_cups_strcasecmp(http->fields[HTTP_FIELD_TRANSFER_ENCODING], "chunked"))
1080
4.44k
    {
1081
4.44k
      DEBUG_puts("4httpGetLength: chunked request.");
1082
4.44k
      remaining = 0;
1083
4.44k
    }
1084
2
    else
1085
2
    {
1086
2
      DEBUG_printf("4httpGetLength: Unknown Transfer-Encoding '%s'.", http->fields[HTTP_FIELD_TRANSFER_ENCODING]);
1087
2
      remaining = -1;
1088
2
    }
1089
4.44k
  }
1090
5.17k
  else if (http->fields[HTTP_FIELD_CONTENT_LENGTH] && http->fields[HTTP_FIELD_CONTENT_LENGTH][0])
1091
823
  {
1092
    // Fixed length content...
1093
823
    char *end;        // Pointer to end of value
1094
1095
823
    if ((remaining = strtoll(http->fields[HTTP_FIELD_CONTENT_LENGTH], &end, 10)) < 0 || (remaining == 0 && errno == ERANGE) || *end)
1096
93
    {
1097
93
      DEBUG_printf("4httpGetLength: Bad Content-Length '%s'.", http->fields[HTTP_FIELD_CONTENT_LENGTH]);
1098
93
      remaining = -1;
1099
93
    }
1100
823
  }
1101
4.35k
  else
1102
4.35k
  {
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
4.35k
    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
694
      remaining = 0;
1110
3.66k
    else
1111
3.66k
      remaining = 2147483647;
1112
4.35k
  }
1113
1114
9.62k
  DEBUG_printf("4httpGetLength: Returning " CUPS_LLFMT ".", CUPS_LLCAST remaining);
1115
1116
9.62k
  return (remaining);
1117
9.62k
}
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
47.5k
{
1173
47.5k
  char    *lineptr,   // Pointer into line
1174
47.5k
    *lineend,   // End of line
1175
47.5k
    *bufptr,    // Pointer into input buffer
1176
47.5k
          *bufend;    // Pointer to end of buffer
1177
47.5k
  ssize_t bytes;      // Number of bytes read
1178
47.5k
  int   eol;      // End-of-line?
1179
1180
1181
47.5k
  DEBUG_printf("2httpGets(http=%p, line=%p, length=%u)", (void *)http, (void *)line, (unsigned)length);
1182
1183
47.5k
  if (!http || !line || length <= 1)
1184
0
    return (NULL);
1185
1186
  // Read a line from the buffer...
1187
47.5k
  http->error = 0;
1188
47.5k
  lineptr     = line;
1189
47.5k
  lineend     = line + length - 1;
1190
47.5k
  eol         = 0;
1191
1192
47.9k
  while (lineptr < lineend)
1193
47.6k
  {
1194
    // Pre-load the buffer as needed...
1195
#ifdef _WIN32
1196
    WSASetLastError(0);
1197
#else
1198
47.6k
    errno = 0;
1199
47.6k
#endif // _WIN32
1200
1201
53.3k
    while (http->used == 0)
1202
9.24k
    {
1203
      // No newline; see if there is more data to be read...
1204
9.24k
      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
9.24k
      bytes = http_read(http, http->buffer + http->used, (size_t)(_HTTP_MAX_BUFFER - http->used), http->wait_value);
1219
1220
9.24k
      DEBUG_printf("4httpGets: read " CUPS_LLFMT " bytes.", CUPS_LLCAST bytes);
1221
1222
9.24k
      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
9.24k
      else if (bytes == 0)
1271
3.52k
      {
1272
3.52k
  http->error = EPIPE;
1273
1274
3.52k
        return (NULL);
1275
3.52k
      }
1276
1277
      // Yup, update the amount used...
1278
5.72k
      http->used += (int)bytes;
1279
5.72k
    }
1280
1281
    // Now copy as much of the current line as possible...
1282
2.13M
    for (bufptr = http->buffer, bufend = http->buffer + http->used; lineptr < lineend && bufptr < bufend;)
1283
2.13M
    {
1284
2.13M
      if (*bufptr == 0x0a)
1285
43.7k
      {
1286
43.7k
        eol = 1;
1287
43.7k
  bufptr ++;
1288
43.7k
  break;
1289
43.7k
      }
1290
2.09M
      else if (*bufptr == 0x0d)
1291
3.97k
      {
1292
3.97k
  bufptr ++;
1293
3.97k
      }
1294
2.09M
      else
1295
2.09M
      {
1296
2.09M
  *lineptr++ = *bufptr++;
1297
2.09M
      }
1298
2.13M
    }
1299
1300
44.1k
    http->used -= (int)(bufptr - http->buffer);
1301
44.1k
    if (http->used > 0)
1302
39.0k
      memmove(http->buffer, bufptr, (size_t)http->used);
1303
1304
44.1k
    if (eol)
1305
43.7k
    {
1306
      // End of line...
1307
43.7k
      http->activity = time(NULL);
1308
1309
43.7k
      *lineptr = '\0';
1310
1311
43.7k
      DEBUG_printf("3httpGets: Returning \"%s\"", line);
1312
1313
43.7k
      return (line);
1314
43.7k
    }
1315
44.1k
  }
1316
1317
284
  DEBUG_puts("3httpGets: No new line available!");
1318
1319
284
  return (NULL);
1320
47.5k
}
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
7.73k
{
1330
7.73k
  return (http ? http->state : HTTP_STATE_ERROR);
1331
7.73k
}
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
26.2k
{
1358
26.2k
  const char  *fptr;      // Pointer into field
1359
26.2k
  char    temp[_HTTP_MAX_VALUE],  // Temporary buffer for name
1360
26.2k
    *ptr,     // Pointer into string buffer
1361
26.2k
    *end;     // End of value buffer
1362
1363
1364
26.2k
  DEBUG_printf("2httpGetSubField(http=%p, field=%d, name=\"%s\", value=%p, valuelen=%u)", (void *)http, field, name, (void *)value, (unsigned)valuelen);
1365
1366
26.2k
  if (value)
1367
26.2k
    *value = '\0';
1368
1369
26.2k
  if (!http || !name || !value || valuelen < 2 || field <= HTTP_FIELD_UNKNOWN || field >= HTTP_FIELD_MAX || !http->fields[field])
1370
23.6k
    return (NULL);
1371
1372
2.58k
  end = value + valuelen - 1;
1373
1374
15.5k
  for (fptr = http->fields[field]; *fptr;)
1375
14.0k
  {
1376
    // Skip leading whitespace...
1377
18.0k
    while (_cups_isspace(*fptr))
1378
3.99k
      fptr ++;
1379
1380
14.0k
    if (*fptr == ',')
1381
1.90k
    {
1382
1.90k
      fptr ++;
1383
1.90k
      continue;
1384
1.90k
    }
1385
1386
    // Get the sub-field name...
1387
331k
    for (ptr = temp; *fptr && *fptr != '=' && !_cups_isspace(*fptr) && ptr < (temp + sizeof(temp) - 1); *ptr++ = *fptr++);
1388
1389
12.1k
    *ptr = '\0';
1390
1391
12.1k
    DEBUG_printf("4httpGetSubField: name=\"%s\"", temp);
1392
1393
    // Skip trailing chars up to the '='...
1394
20.0k
    while (_cups_isspace(*fptr))
1395
7.93k
      fptr ++;
1396
1397
12.1k
    if (!*fptr)
1398
871
      break;
1399
1400
11.2k
    if (*fptr != '=')
1401
5.94k
      continue;
1402
1403
    // Skip = and leading whitespace...
1404
5.29k
    fptr ++;
1405
1406
6.61k
    while (_cups_isspace(*fptr))
1407
1.32k
      fptr ++;
1408
1409
5.29k
    if (*fptr == '\"')
1410
1.70k
    {
1411
      // Read quoted string...
1412
99.3k
      for (ptr = value, fptr ++; *fptr && *fptr != '\"' && ptr < end; *ptr++ = *fptr++);
1413
1414
1.70k
      *ptr = '\0';
1415
1416
17.9k
      while (*fptr && *fptr != '\"')
1417
16.2k
        fptr ++;
1418
1419
1.70k
      if (*fptr)
1420
764
        fptr ++;
1421
1.70k
    }
1422
3.59k
    else
1423
3.59k
    {
1424
      // Read unquoted string...
1425
52.6k
      for (ptr = value; *fptr && !_cups_isspace(*fptr) && *fptr != ',' && ptr < end; *ptr++ = *fptr++);
1426
1427
3.59k
      *ptr = '\0';
1428
1429
8.03k
      while (*fptr && !_cups_isspace(*fptr) && *fptr != ',')
1430
4.44k
        fptr ++;
1431
3.59k
    }
1432
1433
5.29k
    DEBUG_printf("4httpGetSubField: value=\"%s\"", value);
1434
1435
    // See if this is the one...
1436
5.29k
    if (!strcmp(name, temp))
1437
223
    {
1438
223
      DEBUG_printf("3httpGetSubField: Returning \"%s\"", value);
1439
223
      return (value);
1440
223
    }
1441
5.29k
  }
1442
1443
2.36k
  value[0] = '\0';
1444
1445
2.36k
  DEBUG_puts("3httpGetSubField: Returning NULL");
1446
1447
2.36k
  return (NULL);
1448
2.58k
}
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
13.5k
{
1469
13.5k
  static int  initialized = 0;  // Have we been called before?
1470
#ifdef _WIN32
1471
  WSADATA winsockdata;    // WinSock data
1472
#endif // _WIN32
1473
1474
1475
13.5k
  _cupsGlobalLock();
1476
13.5k
  if (initialized)
1477
13.5k
  {
1478
13.5k
    _cupsGlobalUnlock();
1479
13.5k
    return;
1480
13.5k
  }
1481
1482
#ifdef _WIN32
1483
  WSAStartup(MAKEWORD(2,2), &winsockdata);
1484
1485
#elif !defined(SO_NOSIGPIPE)
1486
  // Ignore SIGPIPE signals...
1487
1
  struct sigaction  action;   // POSIX sigaction data
1488
1489
1
  memset(&action, 0, sizeof(action));
1490
1
  action.sa_handler = SIG_IGN;
1491
1
  sigaction(SIGPIPE, &action, NULL);
1492
1
#endif // _WIN32
1493
1494
1
  _httpTLSInitialize();
1495
1496
1
  initialized = 1;
1497
1
  _cupsGlobalUnlock();
1498
1
}
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
4.77k
{
1543
4.77k
  ssize_t bytes;      // Bytes read
1544
4.77k
  char    len[32];    // Length string
1545
1546
1547
4.77k
  DEBUG_printf("httpPeek(http=%p, buffer=%p, length=" CUPS_LLFMT ")", (void *)http, (void *)buffer, CUPS_LLCAST length);
1548
1549
4.77k
  if (http == NULL || buffer == NULL)
1550
0
    return (-1);
1551
1552
4.77k
  http->activity = time(NULL);
1553
4.77k
  http->error    = 0;
1554
1555
4.77k
  if (length <= 0)
1556
0
    return (0);
1557
1558
4.77k
  if (http->data_encoding == HTTP_ENCODING_CHUNKED && http->data_remaining <= 0)
1559
1.12k
  {
1560
1.12k
    DEBUG_puts("2httpPeek: Getting chunk length...");
1561
1562
1.12k
    if (httpGets(http, len, sizeof(len)) == NULL)
1563
48
    {
1564
48
      DEBUG_puts("1httpPeek: Could not get length!");
1565
48
      return (0);
1566
48
    }
1567
1568
1.08k
    if (!len[0])
1569
165
    {
1570
165
      DEBUG_puts("1httpPeek: Blank chunk length, trying again...");
1571
165
      if (!httpGets(http, len, sizeof(len)))
1572
19
      {
1573
19
  DEBUG_puts("1httpPeek: Could not get chunk length.");
1574
19
  return (0);
1575
19
      }
1576
165
    }
1577
1578
1.06k
    http->data_remaining = strtoll(len, NULL, 16);
1579
1580
1.06k
    if (http->data_remaining < 0)
1581
294
    {
1582
294
      DEBUG_puts("1httpPeek: Negative chunk length!");
1583
294
      return (0);
1584
294
    }
1585
1.06k
  }
1586
1587
4.41k
  DEBUG_printf("2httpPeek: data_remaining=" CUPS_LLFMT, CUPS_LLCAST http->data_remaining);
1588
1589
4.41k
  if (http->data_remaining <= 0 && http->data_encoding != HTTP_ENCODING_FIELDS)
1590
273
  {
1591
    // A zero-length chunk ends a transfer; unless we are reading POST data, go idle...
1592
273
    if (http->coding >= _HTTP_CODING_GUNZIP)
1593
38
      http_content_coding_finish(http);
1594
1595
273
    if (http->data_encoding == HTTP_ENCODING_CHUNKED)
1596
243
      httpGets(http, len, sizeof(len));
1597
1598
273
    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
184
      http->state ++;
1600
89
    else
1601
89
      http->state = HTTP_STATE_STATUS;
1602
1603
273
    DEBUG_printf("1httpPeek: 0-length chunk, set state to %s.", httpStateString(http->state));
1604
1605
    // Prevent future reads for this request...
1606
273
    http->data_encoding = HTTP_ENCODING_FIELDS;
1607
1608
273
    return (0);
1609
273
  }
1610
4.14k
  else if (length > (size_t)http->data_remaining)
1611
1.52k
  {
1612
1.52k
    length = (size_t)http->data_remaining;
1613
1.52k
  }
1614
1615
4.14k
  if (http->used == 0 && (http->coding == _HTTP_CODING_IDENTITY || (http->coding >= _HTTP_CODING_GUNZIP && ((z_stream *)http->stream)->avail_in == 0)))
1616
3.01k
  {
1617
    // Buffer small reads for better performance...
1618
3.01k
    ssize_t buflen;     // Length of read for buffer
1619
1620
3.01k
    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
3.01k
    if ((size_t)http->data_remaining > sizeof(http->buffer))
1632
2.26k
      buflen = sizeof(http->buffer);
1633
750
    else
1634
750
      buflen = (ssize_t)http->data_remaining;
1635
1636
3.01k
    DEBUG_printf("2httpPeek: Reading %d bytes into buffer.", (int)buflen);
1637
3.01k
    bytes = http_read(http, http->buffer, (size_t)buflen, http->wait_value);
1638
1639
3.01k
    DEBUG_printf("2httpPeek: Read " CUPS_LLFMT " bytes into buffer.", CUPS_LLCAST bytes);
1640
3.01k
    if (bytes > 0)
1641
16
    {
1642
#ifdef DEBUG
1643
      http_debug_hex("httpPeek", http->buffer, (int)bytes);
1644
#endif // DEBUG
1645
1646
16
      http->used = (int)bytes;
1647
16
    }
1648
3.01k
  }
1649
1650
4.14k
  if (http->coding >= _HTTP_CODING_GUNZIP)
1651
485
  {
1652
485
    int   zerr;     // Decompressor error
1653
485
    z_stream  stream;     // Copy of decompressor stream
1654
1655
485
    memset(&stream, 0, sizeof(stream));
1656
1657
485
    if (http->used > 0 && ((z_stream *)http->stream)->avail_in < _HTTP_MAX_BUFFER)
1658
383
    {
1659
383
      size_t buflen = _HTTP_MAX_BUFFER - ((z_stream *)http->stream)->avail_in;
1660
          // Number of bytes to copy
1661
1662
383
      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
383
      ((z_stream *)http->stream)->next_in = http->sbuffer;
1666
1667
383
      if (buflen > (size_t)http->data_remaining)
1668
180
        buflen = (size_t)http->data_remaining;
1669
1670
383
      if (buflen > (size_t)http->used)
1671
234
        buflen = (size_t)http->used;
1672
1673
383
      DEBUG_printf("1httpPeek: Copying %d more bytes of data into decompression buffer.", (int)buflen);
1674
1675
383
      memcpy(http->sbuffer + ((z_stream *)http->stream)->avail_in, http->buffer, buflen);
1676
383
      ((z_stream *)http->stream)->avail_in += buflen;
1677
383
      http->used            -= (int)buflen;
1678
383
      http->data_remaining  -= (off_t)buflen;
1679
1680
383
      if (http->used > 0)
1681
141
        memmove(http->buffer, http->buffer + buflen, (size_t)http->used);
1682
383
    }
1683
1684
485
    DEBUG_printf("2httpPeek: length=%d, avail_in=%d", (int)length, (int)((z_stream *)http->stream)->avail_in);
1685
1686
485
    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
485
    stream.next_out  = (Bytef *)buffer;
1694
485
    stream.avail_out = (uInt)length;
1695
1696
485
    zerr  = inflate(&stream, Z_SYNC_FLUSH);
1697
485
    bytes = (ssize_t)(length - stream.avail_out);
1698
1699
485
    inflateEnd(&stream);
1700
1701
485
    if (zerr < Z_OK)
1702
116
    {
1703
116
      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
116
      http->error = EIO;
1709
116
      return (-1);
1710
116
    }
1711
485
  }
1712
3.65k
  else if (http->used > 0)
1713
761
  {
1714
761
    if (length > (size_t)http->used)
1715
131
      length = (size_t)http->used;
1716
1717
761
    bytes = (ssize_t)length;
1718
1719
761
    DEBUG_printf("2httpPeek: grabbing %d bytes from input buffer...", (int)bytes);
1720
1721
761
    memcpy(buffer, http->buffer, length);
1722
761
  }
1723
2.89k
  else
1724
2.89k
  {
1725
2.89k
    bytes = 0;
1726
2.89k
  }
1727
1728
4.02k
  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
4.02k
  else if (bytes == 0)
1744
3.15k
  {
1745
3.15k
    http->error = EPIPE;
1746
3.15k
    return (0);
1747
3.15k
  }
1748
1749
873
  return (bytes);
1750
4.02k
}
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
13.6k
{
1821
13.6k
  ssize_t bytes;      // Bytes read
1822
1823
1824
13.6k
  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
13.6k
  if (http == NULL || buffer == NULL)
1827
0
    return (-1);
1828
1829
13.6k
  http->activity = time(NULL);
1830
13.6k
  http->error    = 0;
1831
1832
13.6k
  if (length <= 0)
1833
0
    return (0);
1834
1835
13.6k
  if (http->coding >= _HTTP_CODING_GUNZIP)
1836
3.45k
  {
1837
3.45k
    do
1838
4.40k
    {
1839
4.40k
      if (((z_stream *)http->stream)->avail_in > 0)
1840
3.62k
      {
1841
3.62k
  int zerr;     // Decompressor error
1842
1843
3.62k
  DEBUG_printf("2httpRead: avail_in=%d, avail_out=%d", (int)((z_stream *)http->stream)->avail_in, (int)length);
1844
1845
3.62k
  ((z_stream *)http->stream)->next_out  = (Bytef *)buffer;
1846
3.62k
  ((z_stream *)http->stream)->avail_out = (uInt)length;
1847
1848
3.62k
  if ((zerr = inflate((z_stream *)http->stream, Z_SYNC_FLUSH)) < Z_OK)
1849
31
  {
1850
31
    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
31
    http->error = EIO;
1856
31
    return (-1);
1857
31
  }
1858
1859
3.59k
  bytes = (ssize_t)(length - ((z_stream *)http->stream)->avail_out);
1860
1861
3.59k
  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
3.59k
      }
1863
778
      else
1864
778
      {
1865
778
        bytes = 0;
1866
778
      }
1867
1868
4.37k
      if (bytes == 0)
1869
1.59k
      {
1870
1.59k
        ssize_t buflen = _HTTP_MAX_BUFFER - (ssize_t)((z_stream *)http->stream)->avail_in;
1871
          // Additional bytes for buffer
1872
1873
1.59k
        if (buflen > 0)
1874
1.59k
        {
1875
1.59k
          if (((z_stream *)http->stream)->avail_in > 0 && ((z_stream *)http->stream)->next_in > http->sbuffer)
1876
58
            memmove(http->sbuffer, ((z_stream *)http->stream)->next_in, ((z_stream *)http->stream)->avail_in);
1877
1878
1.59k
    ((z_stream *)http->stream)->next_in = http->sbuffer;
1879
1880
1.59k
          DEBUG_printf("1httpRead: Reading up to %d more bytes of data into decompression buffer.", (int)buflen);
1881
1882
1.59k
          if (http->data_remaining > 0)
1883
401
          {
1884
401
      if (buflen > http->data_remaining)
1885
74
        buflen = (ssize_t)http->data_remaining;
1886
1887
401
      bytes = http_read_buffered(http, (char *)http->sbuffer + ((z_stream *)http->stream)->avail_in, (size_t)buflen);
1888
401
          }
1889
1.19k
          else if (http->data_encoding == HTTP_ENCODING_CHUNKED)
1890
1.09k
          {
1891
1.09k
            bytes = http_read_chunk(http, (char *)http->sbuffer + ((z_stream *)http->stream)->avail_in, (size_t)buflen);
1892
1.09k
          }
1893
91
          else
1894
91
          {
1895
91
            bytes = 0;
1896
91
          }
1897
1898
1.59k
          if (bytes < 0)
1899
0
            return (bytes);
1900
1.59k
          else if (bytes == 0)
1901
640
            break;
1902
1903
951
          DEBUG_printf("1httpRead: Adding " CUPS_LLFMT " bytes to decompression buffer.", CUPS_LLCAST bytes);
1904
1905
951
          http->data_remaining -= bytes;
1906
951
          ((z_stream *)http->stream)->avail_in += (uInt)bytes;
1907
1908
951
    if (http->data_remaining <= 0 && http->data_encoding == HTTP_ENCODING_CHUNKED)
1909
857
    {
1910
      // Read the trailing blank line now...
1911
857
      char  len[32];    // Length string
1912
1913
857
      httpGets(http, len, sizeof(len));
1914
857
    }
1915
1916
951
          bytes = 0;
1917
951
        }
1918
2
        else
1919
2
        {
1920
2
          return (0);
1921
2
        }
1922
1.59k
      }
1923
4.37k
    }
1924
3.73k
    while (bytes == 0);
1925
3.45k
  }
1926
10.1k
  else if (http->data_remaining == 0 && http->data_encoding == HTTP_ENCODING_CHUNKED)
1927
5.66k
  {
1928
5.66k
    if ((bytes = http_read_chunk(http, buffer, length)) > 0)
1929
5.22k
    {
1930
5.22k
      http->data_remaining -= bytes;
1931
1932
5.22k
      if (http->data_remaining <= 0)
1933
5.12k
      {
1934
        // Read the trailing blank line now...
1935
5.12k
        char  len[32];    // Length string
1936
1937
5.12k
        httpGets(http, len, sizeof(len));
1938
5.12k
      }
1939
5.22k
    }
1940
5.66k
  }
1941
4.53k
  else if (http->data_remaining <= 0)
1942
1.22k
  {
1943
    // No more data to read...
1944
1.22k
    return (0);
1945
1.22k
  }
1946
3.30k
  else
1947
3.30k
  {
1948
3.30k
    DEBUG_printf("1httpRead: Reading up to %d bytes into buffer.", (int)length);
1949
1950
3.30k
    if (length > (size_t)http->data_remaining)
1951
746
      length = (size_t)http->data_remaining;
1952
1953
3.30k
    if ((bytes = http_read_buffered(http, buffer, length)) > 0)
1954
869
    {
1955
869
      http->data_remaining -= bytes;
1956
1957
869
      if (http->data_remaining <= 0 && http->data_encoding == HTTP_ENCODING_CHUNKED)
1958
476
      {
1959
        // Read the trailing blank line now...
1960
476
        char  len[32];    // Length string
1961
1962
476
        httpGets(http, len, sizeof(len));
1963
476
      }
1964
869
    }
1965
3.30k
  }
1966
1967
12.3k
  if ((http->coding == _HTTP_CODING_IDENTITY ||
1968
3.42k
       (http->coding >= _HTTP_CODING_GUNZIP && ((z_stream *)http->stream)->avail_in == 0)) &&
1969
10.0k
      ((http->data_remaining <= 0 && http->data_encoding == HTTP_ENCODING_LENGTH) ||
1970
9.76k
       (http->data_encoding == HTTP_ENCODING_CHUNKED && bytes == 0)))
1971
1.01k
  {
1972
1.01k
    if (http->coding >= _HTTP_CODING_GUNZIP)
1973
318
      http_content_coding_finish(http);
1974
1975
1.01k
    http_advance_state(http);
1976
1977
1.01k
    DEBUG_printf("1httpRead: End of content, set state to %s.", httpStateString(http->state));
1978
1.01k
  }
1979
1980
12.3k
  return (bytes);
1981
13.6k
}
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
4.04k
{
1993
4.04k
  char  line[4096],     // HTTP request line
1994
4.04k
  *req_method,      // HTTP request method
1995
4.04k
  *req_uri,     // HTTP request URI
1996
4.04k
  *req_version;     // HTTP request version number string
1997
1998
1999
  // Range check input...
2000
4.04k
  DEBUG_printf("httpReadRequest(http=%p, uri=%p, urilen=" CUPS_LLFMT ")", (void *)http, (void *)uri, CUPS_LLCAST urilen);
2001
2002
4.04k
  if (uri)
2003
4.04k
    *uri = '\0';
2004
2005
4.04k
  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
4.04k
  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
4.04k
  httpClearFields(http);
2018
2019
4.04k
  http->activity       = time(NULL);
2020
4.04k
  http->data_encoding  = HTTP_ENCODING_FIELDS;
2021
4.04k
  http->data_remaining = 0;
2022
4.04k
  http->keep_alive     = HTTP_KEEPALIVE_OFF;
2023
4.04k
  http->status         = HTTP_STATUS_OK;
2024
4.04k
  http->version        = HTTP_VERSION_1_1;
2025
2026
  // Read a line from the socket...
2027
4.04k
  if (!httpGets(http, line, sizeof(line)))
2028
253
  {
2029
253
    DEBUG_puts("1httpReadRequest: Unable to read, returning HTTP_STATE_ERROR");
2030
253
    return (HTTP_STATE_ERROR);
2031
253
  }
2032
2033
3.78k
  if (!line[0])
2034
582
  {
2035
582
    DEBUG_puts("1httpReadRequest: Blank line, returning HTTP_STATE_WAITING");
2036
582
    return (HTTP_STATE_WAITING);
2037
582
  }
2038
2039
3.20k
  DEBUG_printf("1httpReadRequest: %s", line);
2040
2041
  // Parse it...
2042
3.20k
  req_method = line;
2043
3.20k
  req_uri    = line;
2044
2045
15.8k
  while (*req_uri && !_cups_isspace(*req_uri))
2046
12.6k
    req_uri ++;
2047
2048
3.20k
  if (!*req_uri)
2049
37
  {
2050
37
    DEBUG_puts("1httpReadRequest: No request URI.");
2051
37
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("No request URI."), 1);
2052
37
    return (HTTP_STATE_ERROR);
2053
37
  }
2054
2055
3.17k
  *req_uri++ = '\0';
2056
2057
4.14k
  while (*req_uri && _cups_isspace(*req_uri))
2058
978
    req_uri ++;
2059
2060
3.17k
  req_version = req_uri;
2061
2062
9.76k
  while (*req_version && !_cups_isspace(*req_version))
2063
6.59k
    req_version ++;
2064
2065
3.17k
  if (!*req_version)
2066
89
  {
2067
89
    DEBUG_puts("1httpReadRequest: No request protocol version.");
2068
89
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("No request protocol version."), 1);
2069
89
    return (HTTP_STATE_ERROR);
2070
89
  }
2071
2072
3.08k
  *req_version++ = '\0';
2073
2074
3.87k
  while (*req_version && _cups_isspace(*req_version))
2075
797
    req_version ++;
2076
2077
  // Validate...
2078
3.08k
  if (!strcmp(req_method, "CONNECT"))
2079
37
  {
2080
37
    http->state = HTTP_STATE_CONNECT;
2081
37
  }
2082
3.04k
  else if (!strcmp(req_method, "COPY"))
2083
117
  {
2084
117
    http->state = HTTP_STATE_COPY;
2085
117
  }
2086
2.92k
  else if (!strcmp(req_method, "DELETE"))
2087
39
  {
2088
39
    http->state = HTTP_STATE_DELETE;
2089
39
  }
2090
2.88k
  else if (!strcmp(req_method, "GET"))
2091
889
  {
2092
889
    http->state = HTTP_STATE_GET;
2093
889
  }
2094
1.99k
  else if (!strcmp(req_method, "HEAD"))
2095
149
  {
2096
149
    http->state = HTTP_STATE_HEAD;
2097
149
  }
2098
1.85k
  else if (!strcmp(req_method, "LOCK"))
2099
128
  {
2100
128
    http->state = HTTP_STATE_LOCK;
2101
128
  }
2102
1.72k
  else if (!strcmp(req_method, "MKCOL"))
2103
2
  {
2104
2
    http->state = HTTP_STATE_MKCOL;
2105
2
  }
2106
1.72k
  else if (!strcmp(req_method, "MOVE"))
2107
54
  {
2108
54
    http->state = HTTP_STATE_MOVE;
2109
54
  }
2110
1.66k
  else if (!strcmp(req_method, "OPTIONS"))
2111
47
  {
2112
47
    http->state = HTTP_STATE_OPTIONS;
2113
47
  }
2114
1.61k
  else if (!strcmp(req_method, "POST"))
2115
420
  {
2116
420
    http->state = HTTP_STATE_POST;
2117
420
  }
2118
1.19k
  else if (!strcmp(req_method, "PROPFIND"))
2119
99
  {
2120
99
    http->state = HTTP_STATE_PROPFIND;
2121
99
  }
2122
1.10k
  else if (!strcmp(req_method, "PROPPATCH"))
2123
79
  {
2124
79
    http->state = HTTP_STATE_PROPPATCH;
2125
79
  }
2126
1.02k
  else if (!strcmp(req_method, "PUT"))
2127
383
  {
2128
383
    http->state = HTTP_STATE_PUT;
2129
383
  }
2130
638
  else if (!strcmp(req_method, "TRACE"))
2131
37
  {
2132
37
    http->state = HTTP_STATE_TRACE;
2133
37
  }
2134
601
  else if (!strcmp(req_method, "UNLOCK"))
2135
4
  {
2136
4
    http->state = HTTP_STATE_UNLOCK;
2137
4
  }
2138
597
  else
2139
597
  {
2140
597
    DEBUG_printf("1httpReadRequest: Unknown method \"%s\".", req_method);
2141
597
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unknown request method."), 1);
2142
597
    return (HTTP_STATE_UNKNOWN_METHOD);
2143
597
  }
2144
2145
2.48k
  DEBUG_printf("1httpReadRequest: Set state to %s.", httpStateString(http->state));
2146
2147
2.48k
  if (!strcmp(req_version, "HTTP/1.0"))
2148
917
  {
2149
917
    http->version    = HTTP_VERSION_1_0;
2150
917
    http->keep_alive = HTTP_KEEPALIVE_OFF;
2151
917
  }
2152
1.56k
  else if (!strcmp(req_version, "HTTP/1.1"))
2153
1.42k
  {
2154
1.42k
    http->version    = HTTP_VERSION_1_1;
2155
1.42k
    http->keep_alive = HTTP_KEEPALIVE_ON;
2156
1.42k
  }
2157
144
  else
2158
144
  {
2159
144
    DEBUG_printf("1httpReadRequest: Unknown version \"%s\".", req_version);
2160
144
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unknown request version."), 1);
2161
144
    return (HTTP_STATE_UNKNOWN_VERSION);
2162
144
  }
2163
2164
2.34k
  DEBUG_printf("1httpReadRequest: URI is \"%s\".", req_uri);
2165
2.34k
  cupsCopyString(uri, req_uri, urilen);
2166
2167
2.34k
  return (http->state);
2168
2.48k
}
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
1.37k
{
2185
  // Range check input...
2186
1.37k
  DEBUG_printf("httpSetAuthString(http=%p, scheme=\"%s\", data=\"%s\")", (void *)http, scheme, data);
2187
2188
1.37k
  if (!http)
2189
0
    return;
2190
2191
1.37k
  free(http->authstring);
2192
2193
1.37k
  if (scheme)
2194
357
  {
2195
    // Set the current authorization string...
2196
357
    size_t len = strlen(scheme) + (data ? strlen(data) + 1 : 0) + 1;
2197
2198
357
    if ((http->authstring = malloc(len)) != NULL)
2199
357
    {
2200
357
      if (data)
2201
357
  snprintf(http->authstring, len, "%s %s", scheme, data);
2202
0
      else
2203
0
  cupsCopyString(http->authstring, scheme, len);
2204
357
    }
2205
357
  }
2206
1.02k
  else
2207
1.02k
  {
2208
    // Clear the current authorization string...
2209
1.02k
    http->authstring = NULL;
2210
1.02k
  }
2211
2212
1.37k
  DEBUG_printf("1httpSetAuthString: authstring=\"%s\"", http->authstring);
2213
1.37k
}
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
36.6k
{
2373
36.6k
  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
36.6k
  if (!http || field <= HTTP_FIELD_UNKNOWN || field >= HTTP_FIELD_MAX || !value)
2376
0
    return;
2377
2378
36.6k
  http_add_field(http, field, value, false);
2379
36.6k
}
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
3.84k
{
2408
3.84k
  DEBUG_printf("httpSetLength(http=%p, length=" CUPS_LLFMT ")", (void *)http, CUPS_LLCAST length);
2409
2410
3.84k
  if (!http)
2411
0
    return;
2412
2413
3.84k
  if (!length)
2414
3.84k
  {
2415
3.84k
    httpSetField(http, HTTP_FIELD_TRANSFER_ENCODING, "chunked");
2416
3.84k
    httpSetField(http, HTTP_FIELD_CONTENT_LENGTH, "");
2417
3.84k
  }
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
3.84k
}
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
27.4k
{
2499
27.4k
  char    *value,     // Pointer to value on line
2500
27.4k
    *valend;    // Pointer to end of value
2501
27.4k
  http_field_t  field;      // Field index
2502
27.4k
  int   major, minor;   // HTTP version numbers
2503
2504
2505
27.4k
  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
27.4k
  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
27.4k
  if (!httpGets(http, http->line, sizeof(http->line)))
2542
2.95k
  {
2543
2.95k
    DEBUG_puts("1_httpUpdate: Error reading request line.");
2544
2.95k
    *status = HTTP_STATUS_ERROR;
2545
2.95k
    return (false);
2546
2.95k
  }
2547
2548
24.5k
  DEBUG_printf("2_httpUpdate: Got \"%s\"", http->line);
2549
2550
24.5k
  if (http->line[0] == '\0')
2551
3.60k
  {
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
3.60k
    if (http->status == HTTP_STATUS_CONTINUE)
2559
421
    {
2560
421
      *status = http->status;
2561
421
      return (false);
2562
421
    }
2563
2564
3.18k
    if (http->status < HTTP_STATUS_BAD_REQUEST)
2565
3.14k
      http->digest_tries = 0;
2566
2567
3.18k
    if (http->status == HTTP_STATUS_SWITCHING_PROTOCOLS && !http->tls)
2568
12
    {
2569
12
      if (!_httpTLSStart(http))
2570
12
      {
2571
12
        httpAddrClose(NULL, http->fd);
2572
12
        http->fd = -1;
2573
2574
12
  *status = http->status = HTTP_STATUS_ERROR;
2575
12
  return (false);
2576
12
      }
2577
2578
0
      *status = HTTP_STATUS_CONTINUE;
2579
0
      return (false);
2580
12
    }
2581
2582
3.17k
    if (http_set_length(http) < 0)
2583
95
    {
2584
95
      DEBUG_puts("1_httpUpdate: Bad Content-Length.");
2585
95
      http->error  = EINVAL;
2586
95
      http->status = *status = HTTP_STATUS_ERROR;
2587
95
      return (false);
2588
95
    }
2589
2590
3.07k
    switch (http->state)
2591
3.07k
    {
2592
95
      case HTTP_STATE_COPY :
2593
128
      case HTTP_STATE_DELETE :
2594
1.76k
      case HTTP_STATE_GET :
2595
1.88k
      case HTTP_STATE_LOCK :
2596
1.88k
      case HTTP_STATE_LOCK_RECV :
2597
2.25k
      case HTTP_STATE_POST :
2598
2.25k
      case HTTP_STATE_POST_RECV :
2599
2.35k
      case HTTP_STATE_PROPFIND :
2600
2.35k
      case HTTP_STATE_PROPFIND_RECV :
2601
2.42k
      case HTTP_STATE_PROPPATCH :
2602
2.42k
      case HTTP_STATE_PROPPATCH_RECV :
2603
2.74k
      case HTTP_STATE_PUT :
2604
2.74k
    http->state ++;
2605
2606
2.74k
    DEBUG_printf("1_httpUpdate: Set state to %s.", httpStateString(http->state));
2607
2.74k
    break;
2608
2609
31
      case HTTP_STATE_CONNECT :
2610
140
      case HTTP_STATE_HEAD :
2611
140
      case HTTP_STATE_LOCK_SEND :
2612
141
      case HTTP_STATE_MKCOL :
2613
214
      case HTTP_STATE_POST_SEND :
2614
214
      case HTTP_STATE_PROPFIND_SEND :
2615
214
      case HTTP_STATE_PROPPATCH_SEND :
2616
245
      case HTTP_STATE_TRACE :
2617
247
      case HTTP_STATE_UNLOCK :
2618
247
    break;
2619
2620
86
      default :
2621
86
    http->state = HTTP_STATE_WAITING;
2622
2623
86
    DEBUG_puts("1_httpUpdate: Reset state to HTTP_STATE_WAITING.");
2624
86
    break;
2625
3.07k
    }
2626
2627
3.07k
    if (http->data_encoding == HTTP_ENCODING_LENGTH && http->data_remaining == 0)
2628
131
    {
2629
      // POST/PUT/etc. with empty message body...
2630
131
      http_advance_state(http);
2631
131
    }
2632
2.94k
    else
2633
2.94k
    {
2634
      // Non-empty message body...
2635
2.94k
      DEBUG_puts("1_httpUpdate: Calling http_content_coding_start.");
2636
2.94k
      http_content_coding_start(http, httpGetField(http, HTTP_FIELD_CONTENT_ENCODING));
2637
2.94k
    }
2638
2639
3.07k
    *status = http->status;
2640
3.07k
    return (false);
2641
3.07k
  }
2642
20.9k
  else if (!strncmp(http->line, "HTTP/", 5) && http->mode == _HTTP_MODE_CLIENT)
2643
3.85k
  {
2644
    // Got the beginning of a response...
2645
3.85k
    int intstatus;      // Status value as an integer
2646
2647
3.85k
    if (sscanf(http->line, "HTTP/%d.%d%d", &major, &minor, &intstatus) != 3)
2648
3
    {
2649
3
      *status = http->status = HTTP_STATUS_ERROR;
2650
3
      return (false);
2651
3
    }
2652
2653
3.85k
    httpClearFields(http);
2654
2655
3.85k
    http->version = (http_version_t)(major * 100 + minor);
2656
3.85k
    *status       = http->status = (http_status_t)intstatus;
2657
3.85k
  }
2658
17.0k
  else if ((value = (char *)strchr(http->line, ':')) != NULL)
2659
16.9k
  {
2660
    // Got a value...
2661
16.9k
    *value++ = '\0';
2662
18.6k
    while (_cups_isspace(*value))
2663
1.67k
      value ++;
2664
2665
    // Strip trailing whitespace...
2666
18.1k
    for (valend = value + strlen(value) - 1; valend > value; valend --)
2667
10.4k
    {
2668
10.4k
      if (!_cups_isspace(*valend))
2669
9.29k
        break;
2670
10.4k
    }
2671
16.9k
    if (valend >= value)
2672
12.8k
      valend[1] = '\0';
2673
2674
16.9k
    DEBUG_printf("1_httpUpdate: Header %s: %s", http->line, value);
2675
2676
    // Be tolerants of servers that send unknown attribute fields...
2677
16.9k
    if (!_cups_strcasecmp(http->line, "expect"))
2678
378
    {
2679
      // "Expect: 100-continue" or similar...
2680
378
      http->expect = (http_status_t)atoi(value);
2681
378
    }
2682
16.6k
    else if (!_cups_strcasecmp(http->line, "cookie"))
2683
627
    {
2684
      // "Cookie: name=value[; name=value ...]" - replaces previous cookies...
2685
627
      free(http->cookie);
2686
627
      http->cookie = strdup(value);
2687
627
    }
2688
15.9k
    else if ((field = httpFieldValue(http->line)) != HTTP_FIELD_UNKNOWN)
2689
13.3k
    {
2690
13.3k
      http_add_field(http, field, value, true);
2691
2692
13.3k
      if (field == HTTP_FIELD_AUTHENTICATION_INFO)
2693
1.37k
        httpGetSubField(http, HTTP_FIELD_AUTHENTICATION_INFO, "nextnonce", http->nextnonce, (int)sizeof(http->nextnonce));
2694
13.3k
    }
2695
#ifdef DEBUG
2696
    else
2697
    {
2698
      DEBUG_printf("1_httpUpdate: unknown field %s seen!", http->line);
2699
    }
2700
#endif // DEBUG
2701
16.9k
  }
2702
90
  else
2703
90
  {
2704
90
    DEBUG_printf("1_httpUpdate: Bad response line \"%s\"!", http->line);
2705
90
    http->error  = EINVAL;
2706
90
    http->status = *status = HTTP_STATUS_ERROR;
2707
90
    return (false);
2708
90
  }
2709
2710
20.8k
  return (true);
2711
24.5k
}
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
6.65k
{
2721
6.65k
  http_status_t status;     // Request status
2722
2723
2724
6.65k
  DEBUG_printf("httpUpdate(http=%p), state=%s", (void *)http, httpStateString(http->state));
2725
2726
  // Flush pending data, if any...
2727
6.65k
  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
6.65k
  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
27.4k
  while (_httpUpdate(http, &status));
2741
2742
  // See if there was an error...
2743
6.65k
  if (http->error == EPIPE && http->status > HTTP_STATUS_CONTINUE)
2744
1.57k
  {
2745
1.57k
    DEBUG_printf("1httpUpdate: Returning status %d...", http->status);
2746
1.57k
    return (http->status);
2747
1.57k
  }
2748
2749
5.08k
  if (http->error)
2750
1.56k
  {
2751
1.56k
    DEBUG_printf("1httpUpdate: socket error %d - %s", http->error, strerror(http->error));
2752
1.56k
    http->status = HTTP_STATUS_ERROR;
2753
1.56k
    return (HTTP_STATUS_ERROR);
2754
1.56k
  }
2755
2756
  // Return the current status...
2757
3.51k
  return (status);
2758
5.08k
}
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
24.4k
{
2770
24.4k
  struct pollfd   pfd;    // Polled file descriptor
2771
24.4k
  int     nfds;   // Result from select()/poll()
2772
2773
2774
24.4k
  DEBUG_printf("4_httpWait(http=%p, msec=%d, usessl=%d)", (void *)http, msec, usessl);
2775
2776
24.4k
  if (http->fd < 0)
2777
14
  {
2778
14
    DEBUG_printf("5_httpWait: Returning 0 since fd=%d", http->fd);
2779
14
    return (false);
2780
14
  }
2781
2782
  // Check the SSL/TLS buffers for data first...
2783
24.4k
  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
24.4k
  pfd.fd     = http->fd;
2791
24.4k
  pfd.events = POLLIN;
2792
2793
24.4k
  do
2794
24.4k
  {
2795
24.4k
    nfds = poll(&pfd, 1, msec);
2796
24.4k
  }
2797
#ifdef _WIN32
2798
  while (nfds < 0 && (WSAGetLastError() == WSAEINTR || WSAGetLastError() == WSAEWOULDBLOCK));
2799
#else
2800
24.4k
  while (nfds < 0 && (errno == EINTR || errno == EAGAIN));
2801
24.4k
#endif // _WIN32
2802
2803
24.4k
  DEBUG_printf("5_httpWait: returning with nfds=%d, errno=%d...", nfds, errno);
2804
2805
24.4k
  return (nfds > 0);
2806
24.4k
}
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
123k
{
2862
123k
  ssize_t bytes;      // Bytes written
2863
2864
2865
123k
  DEBUG_printf("httpWrite(http=%p, buffer=%p, length=" CUPS_LLFMT ")", (void *)http, (void *)buffer, CUPS_LLCAST length);
2866
2867
  // Range check input...
2868
123k
  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
123k
  http->activity = time(NULL);
2876
2877
  // Buffer small writes for better performance...
2878
123k
  if (http->coding == _HTTP_CODING_GZIP || http->coding == _HTTP_CODING_DEFLATE)
2879
1.96k
  {
2880
1.96k
    DEBUG_printf("1httpWrite: http->coding=%d", http->coding);
2881
2882
1.96k
    if (length == 0)
2883
185
    {
2884
185
      http_content_coding_finish(http);
2885
185
      bytes = 0;
2886
185
    }
2887
1.78k
    else
2888
1.78k
    {
2889
1.78k
      size_t  slen;     // Bytes to write
2890
1.78k
      ssize_t sret;     // Bytes written
2891
2892
1.78k
      ((z_stream *)http->stream)->next_in   = (Bytef *)buffer;
2893
1.78k
      ((z_stream *)http->stream)->avail_in  = (uInt)length;
2894
2895
3.56k
      while (deflate((z_stream *)http->stream, Z_NO_FLUSH) == Z_OK)
2896
1.78k
      {
2897
1.78k
        DEBUG_printf("1httpWrite: avail_out=%d", ((z_stream *)http->stream)->avail_out);
2898
2899
1.78k
        if (((z_stream *)http->stream)->avail_out > 0)
2900
1.78k
    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
1.78k
      bytes = (ssize_t)length;
2924
1.78k
    }
2925
1.96k
  }
2926
121k
  else if (length > 0)
2927
119k
  {
2928
119k
    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
119k
    if ((length + (size_t)http->wused) <= sizeof(http->wbuffer) && length < sizeof(http->wbuffer))
2936
119k
    {
2937
      // Write to buffer...
2938
119k
      DEBUG_printf("2httpWrite: Copying " CUPS_LLFMT " bytes to wbuffer...", CUPS_LLCAST length);
2939
2940
119k
      memcpy(http->wbuffer + http->wused, buffer, length);
2941
119k
      http->wused += (int)length;
2942
119k
      bytes = (ssize_t)length;
2943
119k
    }
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
119k
    if (http->data_encoding == HTTP_ENCODING_LENGTH)
2958
0
      http->data_remaining -= bytes;
2959
119k
  }
2960
2.44k
  else
2961
2.44k
  {
2962
2.44k
    bytes = 0;
2963
2.44k
  }
2964
2965
  // Handle end-of-request processing...
2966
123k
  if ((http->data_encoding == HTTP_ENCODING_CHUNKED && length == 0) ||
2967
121k
      (http->data_encoding == HTTP_ENCODING_LENGTH && http->data_remaining == 0))
2968
1.95k
  {
2969
    // Finished with the transfer; unless we are sending POST or PUT data, go idle...
2970
1.95k
    if (http->coding == _HTTP_CODING_GZIP || http->coding == _HTTP_CODING_DEFLATE)
2971
0
      http_content_coding_finish(http);
2972
2973
1.95k
    if (http->wused)
2974
1.78k
    {
2975
1.78k
      if (httpFlushWrite(http) < 0)
2976
0
        return (-1);
2977
1.78k
    }
2978
2979
1.95k
    if (http->data_encoding == HTTP_ENCODING_CHUNKED)
2980
1.95k
    {
2981
      // Send a 0-length chunk at the end of the request...
2982
1.95k
      http_write(http, "0\r\n\r\n", 5);
2983
2984
      // Reset the data state...
2985
1.95k
      http->data_encoding  = HTTP_ENCODING_FIELDS;
2986
1.95k
      http->data_remaining = 0;
2987
1.95k
    }
2988
2989
1.95k
    http_advance_state(http);
2990
1.95k
    DEBUG_printf("2httpWrite: Changed state to %s.", httpStateString(http->state));
2991
1.95k
  }
2992
2993
123k
  DEBUG_printf("1httpWrite: Returning " CUPS_LLFMT ".", CUPS_LLCAST bytes);
2994
2995
123k
  return (bytes);
2996
123k
}
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
3.89k
{
3014
3.89k
  DEBUG_printf("httpWriteRequest(http=%p, method=\"%s\", uri=\"%s\")", (void *)http, method, uri);
3015
3016
3.89k
  if (!strcasecmp(method, "COPY"))
3017
0
    return (http_send(http, HTTP_STATE_COPY, uri));
3018
3.89k
  else if (!strcasecmp(method, "DELETE"))
3019
0
    return (http_send(http, HTTP_STATE_DELETE, uri));
3020
3.89k
  else if (!strcasecmp(method, "GET"))
3021
3.13k
    return (http_send(http, HTTP_STATE_GET, uri));
3022
760
  else if (!strcasecmp(method, "HEAD"))
3023
0
    return (http_send(http, HTTP_STATE_HEAD, uri));
3024
760
  else if (!strcasecmp(method, "LOCK"))
3025
0
    return (http_send(http, HTTP_STATE_LOCK, uri));
3026
760
  else if (!strcasecmp(method, "MKCOL"))
3027
0
    return (http_send(http, HTTP_STATE_MKCOL, uri));
3028
760
  else if (!strcasecmp(method, "MOVE"))
3029
0
    return (http_send(http, HTTP_STATE_MOVE, uri));
3030
760
  else if (!strcasecmp(method, "OPTIONS"))
3031
0
    return (http_send(http, HTTP_STATE_OPTIONS, uri));
3032
760
  else if (!strcasecmp(method, "POST"))
3033
760
    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
3.89k
}
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
3.20k
{
3059
3.20k
  http_encoding_t old_encoding; // Old data_encoding value
3060
3.20k
  off_t     old_remaining;  // Old data_remaining value
3061
3.20k
  cups_lang_t   *lang;    // Response language
3062
3.20k
  char      buf[1024];  // Response header
3063
3064
3065
  // Range check input...
3066
3.20k
  DEBUG_printf("httpWriteResponse(http=%p, status=%d)", (void *)http, status);
3067
3068
3.20k
  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
3.20k
  if (!http->fields[HTTP_FIELD_DATE])
3076
3.18k
  {
3077
3.18k
    char  buffer[256];    // Date value
3078
3079
3.18k
    httpSetField(http, HTTP_FIELD_DATE, httpGetDateString(time(NULL), buffer, sizeof(buffer)));
3080
3.18k
  }
3081
3082
3.20k
  if (status >= HTTP_STATUS_BAD_REQUEST && http->keep_alive)
3083
7
  {
3084
7
    http->keep_alive = HTTP_KEEPALIVE_OFF;
3085
7
    httpSetField(http, HTTP_FIELD_KEEP_ALIVE, "");
3086
7
  }
3087
3088
3.20k
  if (http->version == HTTP_VERSION_1_1)
3089
2.24k
  {
3090
2.24k
    if (!http->fields[HTTP_FIELD_CONNECTION])
3091
2.22k
    {
3092
2.22k
      if (http->keep_alive)
3093
1.47k
  httpSetField(http, HTTP_FIELD_CONNECTION, "Keep-Alive");
3094
748
      else
3095
748
  httpSetField(http, HTTP_FIELD_CONNECTION, "close");
3096
2.22k
    }
3097
3098
2.24k
    if (http->keep_alive && !http->fields[HTTP_FIELD_KEEP_ALIVE])
3099
1.47k
      httpSetField(http, HTTP_FIELD_KEEP_ALIVE, "timeout=10");
3100
2.24k
  }
3101
3102
3.20k
  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
3.20k
  if (!http->fields[HTTP_FIELD_SERVER])
3115
3.20k
    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
3.20k
  if (!http->fields[HTTP_FIELD_ACCEPT_ENCODING])
3119
3.18k
    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
3.20k
  lang = cupsLangFind(http->fields[HTTP_FIELD_CONTENT_LANGUAGE]);
3123
3124
  // Send the response header...
3125
3.20k
  old_encoding        = http->data_encoding;
3126
3.20k
  old_remaining       = http->data_remaining;
3127
3.20k
  http->data_encoding = HTTP_ENCODING_FIELDS;
3128
3129
3.20k
  snprintf(buf, sizeof(buf), "HTTP/%d.%d %d %s\r\n", http->version / 100, http->version % 100, (int)status, _httpStatusString(lang, status));
3130
3131
3.20k
  if (httpWrite(http, buf, strlen(buf)) < 0)
3132
0
  {
3133
0
    http->status = HTTP_STATUS_ERROR;
3134
0
    return (false);
3135
0
  }
3136
3137
3.20k
  if (status != HTTP_STATUS_CONTINUE)
3138
3.08k
  {
3139
    // 100 Continue doesn't have the rest of the response headers...
3140
3.08k
    int   i;      // Looping var
3141
3.08k
    const char  *value;     // Field value
3142
3143
280k
    for (i = 0; i < HTTP_FIELD_MAX; i ++)
3144
277k
    {
3145
277k
      if ((value = httpGetField(http, i)) != NULL && *value)
3146
19.1k
      {
3147
19.1k
        if (!http_write_header(http, i, value))
3148
0
  {
3149
0
    http->status = HTTP_STATUS_ERROR;
3150
0
    return (false);
3151
0
  }
3152
19.1k
      }
3153
277k
    }
3154
3155
3.08k
    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
3.08k
  }
3195
3196
3.20k
  if (httpWrite(http, "\r\n", 2) < 2)
3197
0
  {
3198
0
    http->status = HTTP_STATUS_ERROR;
3199
0
    return (false);
3200
0
  }
3201
3202
3.20k
  if (httpFlushWrite(http) < 0)
3203
0
  {
3204
0
    http->status = HTTP_STATUS_ERROR;
3205
0
    return (false);
3206
0
  }
3207
3208
3.20k
  if (status == HTTP_STATUS_CONTINUE || status == HTTP_STATUS_SWITCHING_PROTOCOLS)
3209
125
  {
3210
    // Restore the old data_encoding and data_length values...
3211
125
    http->data_encoding  = old_encoding;
3212
125
    http->data_remaining = old_remaining;
3213
125
  }
3214
3.08k
  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
526
  {
3216
526
    DEBUG_printf("1httpWriteResponse: Resetting state to HTTP_STATE_WAITING, was %s.", httpStateString(http->state));
3217
526
    http->state = HTTP_STATE_WAITING;
3218
526
  }
3219
2.55k
  else
3220
2.55k
  {
3221
    // Force data_encoding and data_length to be set according to the response
3222
    // headers...
3223
2.55k
    http_set_length(http);
3224
3225
2.55k
    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
2.55k
    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
585
      http->state ++;
3234
3235
    // Then start any content encoding...
3236
2.55k
    DEBUG_puts("1httpWriteResponse: Calling http_content_coding_start.");
3237
2.55k
    http_content_coding_start(http, httpGetField(http, HTTP_FIELD_CONTENT_ENCODING));
3238
2.55k
  }
3239
3240
3.20k
  return (true);
3241
3.20k
}
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
50.0k
{
3254
50.0k
  char    temp[1024];   // Temporary value string
3255
50.0k
  size_t  fieldlen,   // Length of existing value
3256
50.0k
    valuelen,   // Length of value string
3257
50.0k
    total;      // Total length of string
3258
3259
3260
50.0k
  if (field == HTTP_FIELD_HOST)
3261
9.47k
  {
3262
    // Special-case for Host: as we don't want a trailing "." on the hostname
3263
    // and need to bracket IPv6 numeric addresses.
3264
9.47k
    char *ptr = (char *)strchr(value, ':');
3265
3266
9.47k
    if (value[0] != '[' && ptr && strchr(ptr + 1, ':'))
3267
196
    {
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
196
      snprintf(temp, sizeof(temp), "[%s]", value);
3273
196
      value = temp;
3274
196
    }
3275
9.27k
    else if (*value)
3276
8.82k
    {
3277
      // Check for a trailing dot on the hostname...
3278
8.82k
      cupsCopyString(temp, value, sizeof(temp));
3279
8.82k
      value = temp;
3280
8.82k
      ptr   = temp + strlen(temp) - 1;
3281
3282
8.82k
      if (*ptr == '.')
3283
453
  *ptr = '\0';
3284
8.82k
    }
3285
9.47k
  }
3286
3287
50.0k
  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
7.38k
    append = false;
3289
3290
50.0k
  if (!append && http->fields[field])
3291
4.06k
  {
3292
4.06k
    free(http->fields[field]);
3293
3294
4.06k
    http->fields[field] = NULL;
3295
4.06k
  }
3296
3297
50.0k
  valuelen = strlen(value);
3298
3299
50.0k
  if (!valuelen)
3300
7.47k
    return;
3301
3302
42.5k
  if (http->fields[field])
3303
997
  {
3304
997
    fieldlen = strlen(http->fields[field]);
3305
997
    total    = fieldlen + 2 + valuelen;
3306
997
  }
3307
41.5k
  else
3308
41.5k
  {
3309
41.5k
    fieldlen = 0;
3310
41.5k
    total    = valuelen;
3311
41.5k
  }
3312
3313
42.5k
  if (fieldlen)
3314
997
  {
3315
    // Expand the field value...
3316
997
    char *mcombined;      // New value string
3317
3318
997
    if ((mcombined = realloc(http->fields[field], total + 1)) != NULL)
3319
997
    {
3320
997
      http->fields[field] = mcombined;
3321
997
      cupsConcatString(mcombined, ", ", total + 1);
3322
997
      cupsConcatString(mcombined, value, total + 1);
3323
997
    }
3324
997
  }
3325
41.5k
  else
3326
41.5k
  {
3327
    // Allocate the field value...
3328
41.5k
    http->fields[field] = strdup(value);
3329
41.5k
  }
3330
3331
42.5k
  DEBUG_printf("1http_add_field: append=%s, field=%d(%s), value=\"%s\".", append ? "true" : "false", field, http_fields[field], http->fields[field]);
3332
3333
42.5k
  if (field == HTTP_FIELD_CONTENT_ENCODING && http->data_encoding != HTTP_ENCODING_FIELDS)
3334
2.17k
  {
3335
2.17k
    DEBUG_puts("1http_add_field: Calling http_content_coding_start.");
3336
2.17k
    http_content_coding_start(http, value);
3337
2.17k
  }
3338
42.5k
}
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
3.09k
{
3348
3.09k
  DEBUG_printf("4http_advance_state(http=%p(%s)", http, httpStateString(http->state));
3349
3350
3.09k
  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
1.15k
    http->state ++;
3352
1.94k
  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
1.69k
    http->state = HTTP_STATE_WAITING;
3354
254
  else
3355
254
    http->state = HTTP_STATE_STATUS;
3356
3357
3.09k
  DEBUG_printf("5http_advance_state: Set state to %s.", httpStateString(http->state));
3358
3.09k
}
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
541
{
3369
541
  int   zerr;     // Compression status
3370
541
  Byte    dummy[1];   // Dummy read buffer
3371
541
  size_t  bytes;      // Number of bytes to write
3372
3373
3374
541
  DEBUG_printf("http_content_coding_finish(http=%p)", (void *)http);
3375
541
  DEBUG_printf("1http_content_coding_finishing: http->coding=%d", http->coding);
3376
3377
541
  switch (http->coding)
3378
541
  {
3379
52
    case _HTTP_CODING_DEFLATE :
3380
185
    case _HTTP_CODING_GZIP :
3381
185
        ((z_stream *)http->stream)->next_in  = dummy;
3382
185
        ((z_stream *)http->stream)->avail_in = 0;
3383
3384
185
        do
3385
185
        {
3386
185
          zerr  = deflate((z_stream *)http->stream, Z_FINISH);
3387
185
    bytes = _HTTP_MAX_SBUFFER - ((z_stream *)http->stream)->avail_out;
3388
3389
185
          if (bytes > 0)
3390
185
    {
3391
185
      DEBUG_printf("1http_content_coding_finish: Writing trailing chunk, len=%d", (int)bytes);
3392
3393
185
      if (http->data_encoding == HTTP_ENCODING_CHUNKED)
3394
173
        http_write_chunk(http, (char *)http->sbuffer, bytes);
3395
12
      else
3396
12
        http_write(http, (char *)http->sbuffer, bytes);
3397
185
          }
3398
3399
185
          ((z_stream *)http->stream)->next_out  = (Bytef *)http->sbuffer;
3400
185
          ((z_stream *)http->stream)->avail_out = (uInt)_HTTP_MAX_SBUFFER;
3401
185
  }
3402
185
        while (zerr == Z_OK);
3403
3404
185
        deflateEnd((z_stream *)http->stream);
3405
3406
185
        free(http->sbuffer);
3407
185
        free(http->stream);
3408
3409
185
        http->sbuffer = NULL;
3410
185
        http->stream  = NULL;
3411
3412
185
        if (http->wused)
3413
0
          httpFlushWrite(http);
3414
185
        break;
3415
3416
86
    case _HTTP_CODING_INFLATE :
3417
356
    case _HTTP_CODING_GUNZIP :
3418
356
        inflateEnd((z_stream *)http->stream);
3419
3420
356
        free(http->sbuffer);
3421
356
        free(http->stream);
3422
3423
356
        http->sbuffer = NULL;
3424
356
        http->stream  = NULL;
3425
356
        break;
3426
3427
0
    default :
3428
0
        break;
3429
541
  }
3430
3431
541
  http->coding = _HTTP_CODING_IDENTITY;
3432
541
}
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
7.67k
{
3444
7.67k
  int     zerr;   // Error/status
3445
7.67k
  _http_coding_t  coding;   // Content coding value
3446
3447
3448
7.67k
  DEBUG_printf("http_content_coding_start(http=%p, value=\"%s\")", (void *)http, value);
3449
3450
7.67k
  if (http->coding != _HTTP_CODING_IDENTITY)
3451
104
  {
3452
104
    DEBUG_printf("1http_content_coding_start: http->coding already %d.", http->coding);
3453
104
    return;
3454
104
  }
3455
7.57k
  else if (!strcmp(value, "x-gzip") || !strcmp(value, "gzip"))
3456
1.71k
  {
3457
1.71k
    if (http->state == HTTP_STATE_GET_SEND ||
3458
1.27k
        http->state == HTTP_STATE_POST_SEND)
3459
517
      coding = http->mode == _HTTP_MODE_SERVER ? _HTTP_CODING_GZIP :
3460
517
                                                 _HTTP_CODING_GUNZIP;
3461
1.19k
    else if (http->state == HTTP_STATE_POST_RECV ||
3462
1.11k
             http->state == HTTP_STATE_PUT_RECV)
3463
138
      coding = http->mode == _HTTP_MODE_CLIENT ? _HTTP_CODING_GZIP :
3464
138
                                                 _HTTP_CODING_GUNZIP;
3465
1.05k
    else
3466
1.05k
    {
3467
1.05k
      DEBUG_puts("1http_content_coding_start: Not doing content coding.");
3468
1.05k
      return;
3469
1.05k
    }
3470
1.71k
  }
3471
5.86k
  else if (!strcmp(value, "x-deflate") || !strcmp(value, "deflate"))
3472
966
  {
3473
966
    if (http->state == HTTP_STATE_GET_SEND ||
3474
788
        http->state == HTTP_STATE_POST_SEND)
3475
201
      coding = http->mode == _HTTP_MODE_SERVER ? _HTTP_CODING_DEFLATE :
3476
201
                                                 _HTTP_CODING_INFLATE;
3477
765
    else if (http->state == HTTP_STATE_POST_RECV ||
3478
725
             http->state == HTTP_STATE_PUT_RECV)
3479
67
      coding = http->mode == _HTTP_MODE_CLIENT ? _HTTP_CODING_DEFLATE :
3480
67
                                                 _HTTP_CODING_INFLATE;
3481
698
    else
3482
698
    {
3483
698
      DEBUG_puts("1http_content_coding_start: Not doing content coding.");
3484
698
      return;
3485
698
    }
3486
966
  }
3487
4.89k
  else
3488
4.89k
  {
3489
4.89k
    DEBUG_puts("1http_content_coding_start: Not doing content coding.");
3490
4.89k
    return;
3491
4.89k
  }
3492
3493
923
  switch (coding)
3494
923
  {
3495
52
    case _HTTP_CODING_DEFLATE :
3496
185
    case _HTTP_CODING_GZIP :
3497
185
        if (http->wused)
3498
0
          httpFlushWrite(http);
3499
3500
185
        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
185
  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
185
        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
185
  ((z_stream *)http->stream)->next_out  = (Bytef *)http->sbuffer;
3533
185
  ((z_stream *)http->stream)->avail_out = (uInt)_HTTP_MAX_SBUFFER;
3534
185
        break;
3535
3536
216
    case _HTTP_CODING_INFLATE :
3537
738
    case _HTTP_CODING_GUNZIP :
3538
738
        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
738
  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
738
        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
738
        ((z_stream *)http->stream)->avail_in = 0;
3570
738
        ((z_stream *)http->stream)->next_in  = http->sbuffer;
3571
738
        break;
3572
3573
0
    default :
3574
0
        break;
3575
923
  }
3576
3577
923
  http->coding = coding;
3578
3579
923
  DEBUG_printf("1http_content_coding_start: http->coding now %d.", http->coding);
3580
923
}
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
5.71k
{
3597
5.71k
  http_t  *http;      // New HTTP connection
3598
5.71k
  char    service[255];   // Service name
3599
5.71k
  http_addrlist_t *myaddrlist = NULL; // My address list
3600
5.71k
  _cups_globals_t *cg = _cupsGlobals(); // Thread global data
3601
3602
3603
5.71k
  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
5.71k
  if (!host && mode == _HTTP_MODE_CLIENT)
3606
0
    return (NULL);
3607
3608
5.71k
  httpInitialize();
3609
3610
  // Lookup the host...
3611
5.71k
  if (addrlist)
3612
1.81k
  {
3613
1.81k
    myaddrlist = httpAddrCopyList(addrlist);
3614
1.81k
  }
3615
3.89k
  else
3616
3.89k
  {
3617
3.89k
    snprintf(service, sizeof(service), "%d", port);
3618
3619
3.89k
    myaddrlist = httpAddrGetList(host, family, service);
3620
3.89k
  }
3621
3622
5.71k
  if (!myaddrlist)
3623
0
    return (NULL);
3624
3625
  // Allocate memory for the structure...
3626
5.71k
  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
5.71k
  http->mode     = mode;
3635
5.71k
  http->activity = time(NULL);
3636
5.71k
  http->hostlist = myaddrlist;
3637
5.71k
  http->blocking = blocking;
3638
5.71k
  http->fd       = -1;
3639
5.71k
  http->status   = HTTP_STATUS_CONTINUE;
3640
5.71k
  http->version  = HTTP_VERSION_1_1;
3641
3642
5.71k
  if (host)
3643
3.89k
  {
3644
3.89k
    DEBUG_printf("5http_create: host=\"%s\"", host);
3645
3646
3.89k
    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
3.89k
    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
3.89k
    else
3661
3.89k
    {
3662
      // Not an IPv6 numeric address...
3663
3.89k
      cupsCopyString(http->hostname, host, sizeof(http->hostname));
3664
3.89k
    }
3665
3666
3.89k
    DEBUG_printf("5http_create: http->hostname=\"%s\"", http->hostname);
3667
3.89k
  }
3668
3669
5.71k
  if (port == 443)      // Always use encryption for https
3670
0
    http->encryption = HTTP_ENCRYPTION_ALWAYS;
3671
5.71k
  else
3672
5.71k
    http->encryption = encryption;
3673
3674
5.71k
  http_set_wait(http);
3675
3676
  // Set client credentials...
3677
5.71k
  http->tls_credentials = _httpUseCredentials(cg->credentials);
3678
3679
  // Return the new structure...
3680
5.71k
  return (http);
3681
5.71k
}
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
15.2k
{
3754
15.2k
  ssize_t bytes;      // Bytes read
3755
3756
3757
15.2k
  DEBUG_printf("7http_read(http=%p, buffer=%p, length=" CUPS_LLFMT ", timeout=%d)", (void *)http, (void *)buffer, CUPS_LLCAST length, timeout);
3758
3759
15.2k
  if (!http->blocking || timeout > 0)
3760
15.2k
  {
3761
15.2k
    while (!_httpWait(http, timeout, true))
3762
14
    {
3763
14
      if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
3764
0
  continue;
3765
3766
14
      DEBUG_puts("8http_read: Timeout.");
3767
14
      return (0);
3768
14
    }
3769
15.2k
  }
3770
3771
15.2k
  DEBUG_printf("8http_read: Reading %d bytes into buffer.", (int)length);
3772
3773
15.2k
  do
3774
15.2k
  {
3775
15.2k
    if (http->tls)
3776
0
      bytes = _httpTLSRead(http, buffer, (int)length);
3777
15.2k
    else
3778
15.2k
      bytes = recv(http->fd, buffer, length, 0);
3779
3780
15.2k
    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
15.2k
  }
3821
15.2k
  while (bytes < 0);
3822
3823
15.2k
  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
15.2k
  if (bytes == 0)
3830
9.46k
  {
3831
9.46k
    http->error = EPIPE;
3832
9.46k
    return (0);
3833
9.46k
  }
3834
3835
5.77k
  return (bytes);
3836
15.2k
}
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
10.0k
{
3850
10.0k
  ssize_t bytes;      // Bytes read
3851
3852
3853
10.0k
  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
10.0k
  if (http->used > 0)
3856
7.01k
  {
3857
7.01k
    if (length > (size_t)http->used)
3858
319
      bytes = (ssize_t)http->used;
3859
6.69k
    else
3860
6.69k
      bytes = (ssize_t)length;
3861
3862
7.01k
    DEBUG_printf("8http_read_buffered: Grabbing %d bytes from input buffer.", (int)bytes);
3863
3864
7.01k
    memcpy(buffer, http->buffer, (size_t)bytes);
3865
7.01k
    http->used -= (int)bytes;
3866
3867
7.01k
    if (http->used > 0)
3868
6.63k
      memmove(http->buffer, http->buffer + bytes, (size_t)http->used);
3869
7.01k
  }
3870
2.99k
  else
3871
2.99k
  {
3872
2.99k
    bytes = http_read(http, buffer, length, http->wait_value);
3873
2.99k
  }
3874
3875
10.0k
  return (bytes);
3876
10.0k
}
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
6.75k
{
3891
6.75k
  DEBUG_printf("7http_read_chunk(http=%p, buffer=%p, length=" CUPS_LLFMT ")", (void *)http, (void *)buffer, CUPS_LLCAST length);
3892
3893
6.75k
  if (http->data_remaining <= 0)
3894
6.75k
  {
3895
    // Read the CR LR at the end of the chunk...
3896
6.75k
    char  *lineptr;   // Pointer into line
3897
3898
6.75k
    if (!httpGets(http, http->line, sizeof(http->line)))
3899
196
    {
3900
196
      DEBUG_puts("8http_read_chunk: Could not get end of chunk.");
3901
196
      return (0);
3902
196
    }
3903
3904
    // Read the chunk header as needed...
3905
6.56k
    if (!http->line[0])
3906
1.02k
    {
3907
1.02k
      if (!httpGets(http, http->line, sizeof(http->line)))
3908
1
      {
3909
1
  DEBUG_puts("8http_read_chunk: Could not get chunk header.");
3910
1
  return (0);
3911
1
      }
3912
1.02k
    }
3913
3914
6.56k
    if (!_cups_isxdigit(http->line[0]))
3915
171
    {
3916
171
      DEBUG_printf("8http_read_chunk: Bad chunk header '%s'.", http->line);
3917
171
      return (0);
3918
171
    }
3919
3920
6.39k
    http->data_remaining = strtoll(http->line, &lineptr, 16);
3921
3922
6.39k
    if (lineptr && *lineptr && *lineptr != ';' && !_cups_isspace(*lineptr))
3923
58
    {
3924
58
      DEBUG_printf("8http_read_chunk: Bad chunk header '%s'.", http->line);
3925
58
      return (0);
3926
58
    }
3927
3928
6.33k
    DEBUG_printf("8http_read_chunk: Got chunk header '%s' (length=" CUPS_LLFMT ")", http->line, CUPS_LLCAST http->data_remaining);
3929
3930
6.33k
    if (http->data_remaining == 0)
3931
33
    {
3932
      // 0-length chunk, grab trailing headers and blank line...
3933
227
      while (httpGets(http, http->line, sizeof(http->line)))
3934
212
      {
3935
212
        DEBUG_printf("8http_read_chunk: Got chunk trailer '%s'.", http->line);
3936
3937
212
        if (!http->line[0])
3938
18
          break;
3939
212
      }
3940
33
    }
3941
6.33k
  }
3942
3943
6.33k
  DEBUG_printf("8http_read_chunk: data_remaining=" CUPS_LLFMT, CUPS_LLCAST http->data_remaining);
3944
3945
6.33k
  if (http->data_remaining <= 0)
3946
33
    return (0);
3947
6.30k
  else if (length > (size_t)http->data_remaining)
3948
6.10k
    length = (size_t)http->data_remaining;
3949
3950
6.30k
  return (http_read_buffered(http, buffer, length));
3951
6.33k
}
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
3.89k
{
3963
3.89k
  int   i;      // Looping var
3964
3.89k
  char    buf[1024];    // Encoded URI buffer
3965
3.89k
  const char  *value;     // Field value
3966
3.89k
  static const char * const codes[HTTP_STATE_MAX] =
3967
3.89k
  {         // Request code strings
3968
3.89k
    NULL, // WAITING
3969
3.89k
    "CONNECT ",
3970
3.89k
    "COPY ",
3971
3.89k
    NULL,
3972
3.89k
    "DELETE ",
3973
3.89k
    NULL,
3974
3.89k
    "GET ",
3975
3.89k
    NULL,
3976
3.89k
    "HEAD ",
3977
3.89k
    "LOCK ",
3978
3.89k
    NULL,
3979
3.89k
    NULL,
3980
3.89k
    "MKCOL ",
3981
3.89k
    "MOVE ",
3982
3.89k
    NULL,
3983
3.89k
    "OPTIONS ",
3984
3.89k
    "POST ",
3985
3.89k
    NULL,
3986
3.89k
    NULL,
3987
3.89k
    "PROPFIND ",
3988
3.89k
    NULL,
3989
3.89k
    NULL,
3990
3.89k
    "PROPPATCH ",
3991
3.89k
    NULL,
3992
3.89k
    NULL,
3993
3.89k
    "PUT ",
3994
3.89k
    NULL,
3995
3.89k
    "TRACE ",
3996
3.89k
    "UNLOCK ",
3997
3.89k
    NULL,
3998
3.89k
    NULL,
3999
3.89k
    NULL
4000
3.89k
  };
4001
4002
4003
3.89k
  DEBUG_printf("4http_send(http=%p, request=HTTP_%s, uri=\"%s\")", (void *)http, codes[request], uri);
4004
4005
3.89k
  if (http == NULL || uri == NULL)
4006
0
    return (false);
4007
4008
  // Set the User-Agent field if it isn't already...
4009
3.89k
  if (!http->fields[HTTP_FIELD_USER_AGENT])
4010
3.89k
  {
4011
3.89k
    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
3.89k
    else
4017
3.89k
    {
4018
3.89k
      DEBUG_puts("5http_send: Using client.conf User-Agent.");
4019
3.89k
      httpSetField(http, HTTP_FIELD_USER_AGENT, cupsGetUserAgent());
4020
3.89k
    }
4021
3.89k
  }
4022
4023
  // Set the Accept-Encoding field if it isn't already...
4024
3.89k
  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
3.89k
  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
3.89k
  _httpEncodeURI(buf, uri, sizeof(buf));
4033
4034
  // See if we had an error the last time around; if so, reconnect...
4035
3.89k
  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
3.89k
  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
3.89k
  http->state         = request;
4055
3.89k
  http->data_encoding = HTTP_ENCODING_FIELDS;
4056
4057
3.89k
  if (request == HTTP_STATE_LOCK || request == HTTP_STATE_POST || request == HTTP_STATE_PROPFIND || request == HTTP_STATE_PROPPATCH || request == HTTP_STATE_PUT)
4058
760
    http->state ++;
4059
4060
3.89k
  http->status = HTTP_STATUS_CONTINUE;
4061
4062
3.89k
  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
3.89k
  if (httpWrite(http, codes[request], strlen(codes[request])) < 1 ||
4069
3.89k
      httpWrite(http, buf, strlen(buf)) < 1 ||
4070
3.89k
      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
354k
  for (i = 0; i < HTTP_FIELD_MAX; i ++)
4077
350k
  {
4078
350k
    if ((value = httpGetField(http, i)) != NULL && *value)
4079
4.89k
    {
4080
4.89k
      DEBUG_printf("5http_send: %s: %s", http_fields[i], value);
4081
4082
4.89k
      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
4.89k
      else if (!http_write_header(http, i, value))
4093
0
      {
4094
0
  http->status = HTTP_STATUS_ERROR;
4095
0
  return (false);
4096
0
      }
4097
4.89k
    }
4098
350k
  }
4099
4100
3.89k
  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
3.89k
  DEBUG_printf("5http_send: expect=%d, mode=%d, state=%s", http->expect, http->mode, httpStateString(http->state));
4112
4113
3.89k
  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
3.89k
  if (httpWrite(http, "\r\n", 2) < 1)
4123
0
  {
4124
0
    http->status = HTTP_STATUS_ERROR;
4125
0
    return (false);
4126
0
  }
4127
4128
3.89k
  if (httpFlushWrite(http) < 0)
4129
0
    return (false);
4130
4131
3.89k
  http_set_length(http);
4132
3.89k
  httpClearFields(http);
4133
4134
  // Some authentication strings can only be used once...
4135
3.89k
  if (http->fields[HTTP_FIELD_AUTHORIZATION] && http->authstring)
4136
0
  {
4137
0
    free(http->authstring);
4138
0
    http->authstring = NULL;
4139
0
  }
4140
4141
3.89k
  return (true);
4142
3.89k
}
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
9.62k
{
4152
9.62k
  off_t remaining;      // Remainder
4153
4154
4155
9.62k
  DEBUG_printf("4http_set_length(http=%p) mode=%d state=%s", (void *)http, http->mode, httpStateString(http->state));
4156
4157
9.62k
  if ((remaining = httpGetLength(http)) >= 0)
4158
9.52k
  {
4159
9.52k
    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
2.16k
    {
4161
2.16k
      DEBUG_puts("5http_set_length: Not setting data_encoding/remaining.");
4162
2.16k
      return (remaining);
4163
2.16k
    }
4164
4165
7.36k
    if (!_cups_strcasecmp(httpGetField(http, HTTP_FIELD_TRANSFER_ENCODING), "chunked"))
4166
3.08k
    {
4167
3.08k
      DEBUG_puts("5http_set_length: Setting data_encoding to HTTP_ENCODING_CHUNKED.");
4168
3.08k
      http->data_encoding = HTTP_ENCODING_CHUNKED;
4169
3.08k
    }
4170
4.27k
    else
4171
4.27k
    {
4172
4.27k
      DEBUG_puts("5http_set_length: Setting data_encoding to HTTP_ENCODING_LENGTH.");
4173
4.27k
      http->data_encoding = HTTP_ENCODING_LENGTH;
4174
4.27k
    }
4175
4176
7.36k
    DEBUG_printf("5http_set_length: Setting data_remaining to " CUPS_LLFMT ".", CUPS_LLCAST remaining);
4177
7.36k
    http->data_remaining = remaining;
4178
7.36k
  }
4179
4180
7.45k
  return (remaining);
4181
9.62k
}
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
5.71k
{
4222
5.71k
  http->wait_value = (int)(http->timeout_value * 1000);
4223
4224
5.71k
  if (http->wait_value <= 0)
4225
5.71k
  {
4226
5.71k
    if (http->blocking)
4227
5.71k
      http->wait_value = 60000;
4228
0
    else
4229
0
      http->wait_value = 1000;
4230
5.71k
  }
4231
5.71k
}
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
14.8k
{
4312
14.8k
  ssize_t tbytes,     // Total bytes sent
4313
14.8k
    bytes;      // Bytes sent
4314
4315
4316
14.8k
  DEBUG_printf("7http_write(http=%p, buffer=%p, length=" CUPS_LLFMT ")", (void *)http, (void *)buffer, CUPS_LLCAST length);
4317
14.8k
  http->error = 0;
4318
14.8k
  tbytes      = 0;
4319
4320
29.7k
  while (length > 0)
4321
14.8k
  {
4322
14.8k
    DEBUG_printf("8http_write: About to write %d bytes.", (int)length);
4323
4324
14.8k
    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
14.8k
    if (http->tls)
4364
0
      bytes = _httpTLSWrite(http, buffer, (int)length);
4365
14.8k
    else
4366
14.8k
      bytes = send(http->fd, buffer, length, 0);
4367
4368
14.8k
    DEBUG_printf("8http_write: Write of " CUPS_LLFMT " bytes returned " CUPS_LLFMT ".", CUPS_LLCAST length, CUPS_LLCAST bytes);
4369
4370
14.8k
    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
14.8k
    buffer += bytes;
4414
14.8k
    tbytes += bytes;
4415
14.8k
    length -= (size_t)bytes;
4416
14.8k
  }
4417
4418
#ifdef DEBUG
4419
  http_debug_hex("http_write", buffer - tbytes, (int)tbytes);
4420
#endif // DEBUG
4421
4422
14.8k
  DEBUG_printf("8http_write: Returning " CUPS_LLFMT ".", CUPS_LLCAST tbytes);
4423
4424
14.8k
  return (tbytes);
4425
14.8k
}
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
1.95k
{
4437
1.95k
  char    header[16];   // Chunk header
4438
1.95k
  ssize_t bytes;      // Bytes written
4439
4440
4441
1.95k
  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
1.95k
  snprintf(header, sizeof(header), "%x\r\n", (unsigned)length);
4445
1.95k
  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
1.95k
  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
1.95k
  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
1.95k
  return (bytes);
4464
1.95k
}
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
24.0k
{
4476
24.0k
  return (httpWrite(http, http_fields[field], strlen(http_fields[field])) > 0 &&
4477
24.0k
          httpWrite(http, ": ", 2) > 0 &&
4478
24.0k
          httpWrite(http, value, strlen(value)) > 0 &&
4479
24.0k
          httpWrite(http, "\r\n", 2) > 0);
4480
24.0k
}