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