Coverage Report

Created: 2026-09-03 06:16

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