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