]> git.ipfire.org Git - thirdparty/cups.git/blob - cups/http.c
Merge changes from CUPS 1.4svn-r7394.
[thirdparty/cups.git] / cups / http.c
1 /*
2 * "$Id: http.c 6724 2007-07-25 20:39:33Z mike $"
3 *
4 * HTTP routines for the Common UNIX Printing System (CUPS).
5 *
6 * Copyright 2007-2008 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 * _httpBIOMethods() - Get the OpenSSL BIO methods for HTTP connections.
23 * httpBlocking() - Set blocking/non-blocking behavior on a connection.
24 * httpCheck() - Check to see if there is a pending response from
25 * the server.
26 * httpClearCookie() - Clear the cookie value(s).
27 * httpClearFields() - Clear HTTP request fields.
28 * httpClose() - Close an HTTP connection...
29 * httpConnect() - Connect to a HTTP server.
30 * httpConnectEncrypt() - Connect to a HTTP server using encryption.
31 * httpDelete() - Send a DELETE request to the server.
32 * httpEncryption() - Set the required encryption on the link.
33 * httpError() - Get the last error on a connection.
34 * httpFlush() - Flush data from a HTTP connection.
35 * httpFlushWrite() - Flush data in write buffer.
36 * httpGet() - Send a GET request to the server.
37 * httpGetAuthString() - Get the current authorization string.
38 * httpGetBlocking() - Get the blocking/non-block state of a connection.
39 * httpGetCookie() - Get any cookie data from the response.
40 * httpGetFd() - Get the file descriptor associated with a
41 * connection.
42 * httpGetField() - Get a field value from a request/response.
43 * httpGetLength() - Get the amount of data remaining from the
44 * content-length or transfer-encoding fields.
45 * httpGetLength2() - Get the amount of data remaining from the
46 * content-length or transfer-encoding fields.
47 * httpGetStatus() - Get the status of the last HTTP request.
48 * httpGetSubField() - Get a sub-field value.
49 * httpGets() - Get a line of text from a HTTP connection.
50 * httpHead() - Send a HEAD request to the server.
51 * httpInitialize() - Initialize the HTTP interface library and set the
52 * default HTTP proxy (if any).
53 * httpOptions() - Send an OPTIONS request to the server.
54 * httpPost() - Send a POST request to the server.
55 * httpPrintf() - Print a formatted string to a HTTP connection.
56 * httpPut() - Send a PUT request to the server.
57 * httpRead() - Read data from a HTTP connection.
58 * httpRead2() - Read data from a HTTP connection.
59 * _httpReadCDSA() - Read function for the CDSA library.
60 * _httpReadGNUTLS() - Read function for the GNU TLS library.
61 * httpReconnect() - Reconnect to a HTTP server...
62 * httpSetAuthString() - Set the current authorization string.
63 * httpSetCookie() - Set the cookie value(s)...
64 * httpSetExpect() - Set the Expect: header in a request.
65 * httpSetField() - Set the value of an HTTP header.
66 * httpSetLength() - Set the content-length and transfer-encoding.
67 * httpTrace() - Send an TRACE request to the server.
68 * httpUpdate() - Update the current HTTP state for incoming data.
69 * httpWait() - Wait for data available on a connection.
70 * httpWrite() - Write data to a HTTP connection.
71 * httpWrite2() - Write data to a HTTP connection.
72 * _httpWriteCDSA() - Write function for the CDSA library.
73 * _httpWriteGNUTLS() - Write function for the GNU TLS library.
74 * http_bio_ctrl() - Control the HTTP connection.
75 * http_bio_free() - Free OpenSSL data.
76 * http_bio_new() - Initialize an OpenSSL BIO structure.
77 * http_bio_puts() - Send a string for OpenSSL.
78 * http_bio_read() - Read data for OpenSSL.
79 * http_bio_write() - Write data for OpenSSL.
80 * http_field() - Return the field index for a field name.
81 * http_read_ssl() - Read from a SSL/TLS connection.
82 * http_send() - Send a request with all fields and the trailing
83 * blank line.
84 * http_setup_ssl() - Set up SSL/TLS on a connection.
85 * http_shutdown_ssl() - Shut down SSL/TLS on a connection.
86 * http_upgrade() - Force upgrade to TLS encryption.
87 * http_wait() - Wait for data available on a connection.
88 * http_write() - Write data to a connection.
89 * http_write_ssl() - Write to a SSL/TLS connection.
90 */
91
92 /*
93 * Include necessary headers...
94 */
95
96 #include "http-private.h"
97 #include "globals.h"
98 #include "debug.h"
99 #include <stdlib.h>
100 #include <fcntl.h>
101 #include <errno.h>
102 #ifndef WIN32
103 # include <signal.h>
104 # include <sys/time.h>
105 # include <sys/resource.h>
106 #endif /* !WIN32 */
107 #ifdef HAVE_POLL
108 # include <sys/poll.h>
109 #endif /* HAVE_POLL */
110
111
112 /*
113 * Some operating systems have done away with the Fxxxx constants for
114 * the fcntl() call; this works around that "feature"...
115 */
116
117 #ifndef FNONBLK
118 # define FNONBLK O_NONBLOCK
119 #endif /* !FNONBLK */
120
121
122 /*
123 * Local functions...
124 */
125
126 static http_field_t http_field(const char *name);
127 static int http_send(http_t *http, http_state_t request,
128 const char *uri);
129 static int http_wait(http_t *http, int msec, int usessl);
130 static int http_write(http_t *http, const char *buffer,
131 int length);
132 static int http_write_chunk(http_t *http, const char *buffer,
133 int length);
134 #ifdef HAVE_SSL
135 static int http_read_ssl(http_t *http, char *buf, int len);
136 static int http_setup_ssl(http_t *http);
137 static void http_shutdown_ssl(http_t *http);
138 static int http_upgrade(http_t *http);
139 static int http_write_ssl(http_t *http, const char *buf, int len);
140 #endif /* HAVE_SSL */
141
142
143 /*
144 * Local globals...
145 */
146
147 static const char * const http_fields[] =
148 {
149 "Accept-Language",
150 "Accept-Ranges",
151 "Authorization",
152 "Connection",
153 "Content-Encoding",
154 "Content-Language",
155 "Content-Length",
156 "Content-Location",
157 "Content-MD5",
158 "Content-Range",
159 "Content-Type",
160 "Content-Version",
161 "Date",
162 "Host",
163 "If-Modified-Since",
164 "If-Unmodified-since",
165 "Keep-Alive",
166 "Last-Modified",
167 "Link",
168 "Location",
169 "Range",
170 "Referer",
171 "Retry-After",
172 "Transfer-Encoding",
173 "Upgrade",
174 "User-Agent",
175 "WWW-Authenticate"
176 };
177
178
179 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
180 /*
181 * BIO methods for OpenSSL...
182 */
183
184 static int http_bio_write(BIO *h, const char *buf, int num);
185 static int http_bio_read(BIO *h, char *buf, int size);
186 static int http_bio_puts(BIO *h, const char *str);
187 static long http_bio_ctrl(BIO *h, int cmd, long arg1, void *arg2);
188 static int http_bio_new(BIO *h);
189 static int http_bio_free(BIO *data);
190
191 static BIO_METHOD http_bio_methods =
192 {
193 BIO_TYPE_SOCKET,
194 "http",
195 http_bio_write,
196 http_bio_read,
197 http_bio_puts,
198 NULL, /* http_bio_gets, */
199 http_bio_ctrl,
200 http_bio_new,
201 http_bio_free,
202 NULL,
203 };
204
205
206 /*
207 * '_httpBIOMethods()' - Get the OpenSSL BIO methods for HTTP connections.
208 */
209
210 BIO_METHOD * /* O - BIO methods for OpenSSL */
211 _httpBIOMethods(void)
212 {
213 return (&http_bio_methods);
214 }
215 #endif /* HAVE_SSL && HAVE_LIBSSL */
216
217
218 /*
219 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
220 */
221
222 void
223 httpBlocking(http_t *http, /* I - Connection to server */
224 int b) /* I - 1 = blocking, 0 = non-blocking */
225 {
226 if (http)
227 http->blocking = b;
228 }
229
230
231 /*
232 * 'httpCheck()' - Check to see if there is a pending response from the server.
233 */
234
235 int /* O - 0 = no data, 1 = data available */
236 httpCheck(http_t *http) /* I - Connection to server */
237 {
238 return (httpWait(http, 0));
239 }
240
241
242 /*
243 * 'httpClearCookie()' - Clear the cookie value(s).
244 *
245 * @since CUPS 1.1.19@
246 */
247
248 void
249 httpClearCookie(http_t *http) /* I - Connection to server */
250 {
251 if (!http)
252 return;
253
254 if (http->cookie)
255 {
256 free(http->cookie);
257 http->cookie = NULL;
258 }
259 }
260
261
262 /*
263 * 'httpClearFields()' - Clear HTTP request fields.
264 */
265
266 void
267 httpClearFields(http_t *http) /* I - Connection to server */
268 {
269 if (http)
270 {
271 memset(http->fields, 0, sizeof(http->fields));
272 if (http->hostname[0] == '/')
273 httpSetField(http, HTTP_FIELD_HOST, "localhost");
274 else
275 httpSetField(http, HTTP_FIELD_HOST, http->hostname);
276
277 if (http->field_authorization)
278 {
279 free(http->field_authorization);
280 http->field_authorization = NULL;
281 }
282
283 http->expect = (http_status_t)0;
284 }
285 }
286
287
288 /*
289 * 'httpClose()' - Close an HTTP connection...
290 */
291
292 void
293 httpClose(http_t *http) /* I - Connection to server */
294 {
295 #ifdef HAVE_GSSAPI
296 OM_uint32 minor_status, /* Minor status code */
297 major_status; /* Major status code */
298 #endif /* HAVE_GSSAPI */
299
300
301 DEBUG_printf(("httpClose(http=%p)\n", http));
302
303 if (!http)
304 return;
305
306 httpAddrFreeList(http->addrlist);
307
308 if (http->cookie)
309 free(http->cookie);
310
311 #ifdef HAVE_SSL
312 if (http->tls)
313 http_shutdown_ssl(http);
314 #endif /* HAVE_SSL */
315
316 #ifdef WIN32
317 closesocket(http->fd);
318 #else
319 close(http->fd);
320 #endif /* WIN32 */
321
322 #ifdef HAVE_GSSAPI
323 if (http->gssctx != GSS_C_NO_CONTEXT)
324 major_status = gss_delete_sec_context(&minor_status, &http->gssctx,
325 GSS_C_NO_BUFFER);
326
327 if (http->gssname != GSS_C_NO_NAME)
328 major_status = gss_release_name(&minor_status, &http->gssname);
329 #endif /* HAVE_GSSAPI */
330
331 #ifdef HAVE_AUTHORIZATION_H
332 if (http->auth_ref)
333 AuthorizationFree(http->auth_ref, kAuthorizationFlagDefaults);
334 #endif /* HAVE_AUTHORIZATION_H */
335
336 httpClearFields(http);
337
338 if (http->authstring && http->authstring != http->_authstring)
339 free(http->authstring);
340
341 free(http);
342 }
343
344
345 /*
346 * 'httpConnect()' - Connect to a HTTP server.
347 */
348
349 http_t * /* O - New HTTP connection */
350 httpConnect(const char *host, /* I - Host to connect to */
351 int port) /* I - Port number */
352 {
353 http_encryption_t encryption; /* Type of encryption to use */
354
355
356 /*
357 * Set the default encryption status...
358 */
359
360 if (port == 443)
361 encryption = HTTP_ENCRYPT_ALWAYS;
362 else
363 encryption = HTTP_ENCRYPT_IF_REQUESTED;
364
365 return (httpConnectEncrypt(host, port, encryption));
366 }
367
368
369 /*
370 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
371 */
372
373 http_t * /* O - New HTTP connection */
374 httpConnectEncrypt(
375 const char *host, /* I - Host to connect to */
376 int port, /* I - Port number */
377 http_encryption_t encryption) /* I - Type of encryption to use */
378 {
379 http_t *http; /* New HTTP connection */
380 http_addrlist_t *addrlist; /* Host address data */
381 char service[255]; /* Service name */
382
383
384 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)\n",
385 host ? host : "(null)", port, encryption));
386
387 if (!host)
388 return (NULL);
389
390 httpInitialize();
391
392 /*
393 * Lookup the host...
394 */
395
396 sprintf(service, "%d", port);
397
398 if ((addrlist = httpAddrGetList(host, AF_UNSPEC, service)) == NULL)
399 return (NULL);
400
401 /*
402 * Allocate memory for the structure...
403 */
404
405 if ((http = calloc(sizeof(http_t), 1)) == NULL)
406 {
407 httpAddrFreeList(addrlist);
408 return (NULL);
409 }
410
411 http->version = HTTP_1_1;
412 http->blocking = 1;
413 http->activity = time(NULL);
414 http->fd = -1;
415
416 #ifdef HAVE_GSSAPI
417 http->gssctx = GSS_C_NO_CONTEXT;
418 http->gssname = GSS_C_NO_NAME;
419 #endif /* HAVE_GSSAPI */
420
421 /*
422 * Set the encryption status...
423 */
424
425 if (port == 443) /* Always use encryption for https */
426 http->encryption = HTTP_ENCRYPT_ALWAYS;
427 else
428 http->encryption = encryption;
429
430 /*
431 * Loop through the addresses we have until one of them connects...
432 */
433
434 strlcpy(http->hostname, host, sizeof(http->hostname));
435
436 /*
437 * Connect to the remote system...
438 */
439
440 http->addrlist = addrlist;
441
442 if (!httpReconnect(http))
443 return (http);
444
445 /*
446 * Could not connect to any known address - bail out!
447 */
448
449 httpAddrFreeList(addrlist);
450
451 free(http);
452
453 return (NULL);
454 }
455
456
457 /*
458 * 'httpDelete()' - Send a DELETE request to the server.
459 */
460
461 int /* O - Status of call (0 = success) */
462 httpDelete(http_t *http, /* I - Connection to server */
463 const char *uri) /* I - URI to delete */
464 {
465 return (http_send(http, HTTP_DELETE, uri));
466 }
467
468
469 /*
470 * 'httpEncryption()' - Set the required encryption on the link.
471 */
472
473 int /* O - -1 on error, 0 on success */
474 httpEncryption(http_t *http, /* I - Connection to server */
475 http_encryption_t e) /* I - New encryption preference */
476 {
477 DEBUG_printf(("httpEncryption(http=%p, e=%d)\n", http, e));
478
479 #ifdef HAVE_SSL
480 if (!http)
481 return (0);
482
483 http->encryption = e;
484
485 if ((http->encryption == HTTP_ENCRYPT_ALWAYS && !http->tls) ||
486 (http->encryption == HTTP_ENCRYPT_NEVER && http->tls))
487 return (httpReconnect(http));
488 else if (http->encryption == HTTP_ENCRYPT_REQUIRED && !http->tls)
489 return (http_upgrade(http));
490 else
491 return (0);
492 #else
493 if (e == HTTP_ENCRYPT_ALWAYS || e == HTTP_ENCRYPT_REQUIRED)
494 return (-1);
495 else
496 return (0);
497 #endif /* HAVE_SSL */
498 }
499
500
501 /*
502 * 'httpError()' - Get the last error on a connection.
503 */
504
505 int /* O - Error code (errno) value */
506 httpError(http_t *http) /* I - Connection to server */
507 {
508 if (http)
509 return (http->error);
510 else
511 return (EINVAL);
512 }
513
514
515 /*
516 * 'httpFlush()' - Flush data from a HTTP connection.
517 */
518
519 void
520 httpFlush(http_t *http) /* I - Connection to server */
521 {
522 char buffer[8192]; /* Junk buffer */
523 int blocking; /* To block or not to block */
524
525
526 DEBUG_printf(("httpFlush(http=%p), state=%d\n", http, http->state));
527
528 /*
529 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
530 */
531
532 blocking = http->blocking;
533 http->blocking = 0;
534
535 /*
536 * Read any data we can...
537 */
538
539 while (httpRead2(http, buffer, sizeof(buffer)) > 0);
540
541 /*
542 * Restore blocking and reset the connection if we didn't get all of
543 * the remaining data...
544 */
545
546 http->blocking = blocking;
547
548 if (http->state != HTTP_WAITING && http->fd >= 0)
549 {
550 /*
551 * Didn't get the data back, so close the current connection.
552 */
553
554 http->state = HTTP_WAITING;
555
556 #ifdef HAVE_SSL
557 if (http->tls)
558 http_shutdown_ssl(http);
559 #endif /* HAVE_SSL */
560
561 #ifdef WIN32
562 closesocket(http->fd);
563 #else
564 close(http->fd);
565 #endif /* WIN32 */
566
567 http->fd = -1;
568 }
569 }
570
571
572 /*
573 * 'httpFlushWrite()' - Flush data in write buffer.
574 *
575 * @since CUPS 1.2@
576 */
577
578 int /* O - Bytes written or -1 on error */
579 httpFlushWrite(http_t *http) /* I - Connection to server */
580 {
581 int bytes; /* Bytes written */
582
583
584 DEBUG_printf(("httpFlushWrite(http=%p)\n", http));
585
586 if (!http || !http->wused)
587 return (0);
588
589 if (http->data_encoding == HTTP_ENCODE_CHUNKED)
590 bytes = http_write_chunk(http, http->wbuffer, http->wused);
591 else
592 bytes = http_write(http, http->wbuffer, http->wused);
593
594 http->wused = 0;
595
596 return (bytes);
597 }
598
599
600 /*
601 * 'httpGet()' - Send a GET request to the server.
602 */
603
604 int /* O - Status of call (0 = success) */
605 httpGet(http_t *http, /* I - Connection to server */
606 const char *uri) /* I - URI to get */
607 {
608 return (http_send(http, HTTP_GET, uri));
609 }
610
611
612 /*
613 * 'httpGetAuthString()' - Get the current authorization string.
614 *
615 * The authorization string is set by cupsDoAuthentication() and
616 * httpSetAuthString(). Use httpGetAuthString() to retrieve the
617 * string to use with httpSetField() for the HTTP_FIELD_AUTHORIZATION
618 * value.
619 *
620 * @since CUPS 1.3@
621 */
622
623 char * /* O - Authorization string */
624 httpGetAuthString(http_t *http) /* I - Connection to server */
625 {
626 if (http)
627 return (http->authstring);
628 else
629 return (NULL);
630 }
631
632
633 /*
634 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
635 *
636 * @since CUPS 1.2@
637 */
638
639 int /* O - 1 if blocking, 0 if non-blocking */
640 httpGetBlocking(http_t *http) /* I - Connection to server */
641 {
642 return (http ? http->blocking : 0);
643 }
644
645
646 /*
647 * 'httpGetCookie()' - Get any cookie data from the response.
648 *
649 * @since CUPS 1.1.19@
650 */
651
652 const char * /* O - Cookie data or NULL */
653 httpGetCookie(http_t *http) /* I - HTTP connecion */
654 {
655 return (http ? http->cookie : NULL);
656 }
657
658
659 /*
660 * 'httpGetFd()' - Get the file descriptor associated with a connection.
661 *
662 * @since CUPS 1.2@
663 */
664
665 int /* O - File descriptor or -1 if none */
666 httpGetFd(http_t *http) /* I - Connection to server */
667 {
668 return (http ? http->fd : -1);
669 }
670
671
672 /*
673 * 'httpGetField()' - Get a field value from a request/response.
674 */
675
676 const char * /* O - Field value */
677 httpGetField(http_t *http, /* I - Connection to server */
678 http_field_t field) /* I - Field to get */
679 {
680 if (!http || field <= HTTP_FIELD_UNKNOWN || field >= HTTP_FIELD_MAX)
681 return (NULL);
682 else if (field == HTTP_FIELD_AUTHORIZATION &&
683 http->field_authorization)
684 {
685 /*
686 * Special case for WWW-Authenticate: as its contents can be
687 * longer than HTTP_MAX_VALUE...
688 */
689
690 return (http->field_authorization);
691 }
692 else
693 return (http->fields[field]);
694 }
695
696
697 /*
698 * 'httpGetLength()' - Get the amount of data remaining from the
699 * content-length or transfer-encoding fields.
700 *
701 * This function is deprecated and will not return lengths larger than
702 * 2^31 - 1; use httpGetLength2() instead.
703 *
704 * @deprecated@
705 */
706
707 int /* O - Content length */
708 httpGetLength(http_t *http) /* I - Connection to server */
709 {
710 /*
711 * Get the read content length and return the 32-bit value.
712 */
713
714 if (http)
715 {
716 httpGetLength2(http);
717
718 return (http->_data_remaining);
719 }
720 else
721 return (-1);
722 }
723
724
725 /*
726 * 'httpGetLength2()' - Get the amount of data remaining from the
727 * content-length or transfer-encoding fields.
728 *
729 * This function returns the complete content length, even for
730 * content larger than 2^31 - 1.
731 *
732 * @since CUPS 1.2@
733 */
734
735 off_t /* O - Content length */
736 httpGetLength2(http_t *http) /* I - Connection to server */
737 {
738 DEBUG_printf(("httpGetLength2(http=%p), state=%d\n", http, http->state));
739
740 if (!http)
741 return (-1);
742
743 if (!strcasecmp(http->fields[HTTP_FIELD_TRANSFER_ENCODING], "chunked"))
744 {
745 DEBUG_puts("httpGetLength2: chunked request!");
746
747 http->data_encoding = HTTP_ENCODE_CHUNKED;
748 http->data_remaining = 0;
749 }
750 else
751 {
752 http->data_encoding = HTTP_ENCODE_LENGTH;
753
754 /*
755 * The following is a hack for HTTP servers that don't send a
756 * content-length or transfer-encoding field...
757 *
758 * If there is no content-length then the connection must close
759 * after the transfer is complete...
760 */
761
762 if (!http->fields[HTTP_FIELD_CONTENT_LENGTH][0])
763 {
764 /*
765 * Default content length is 0 for errors and 2^31-1 for other
766 * successful requests...
767 */
768
769 if (http->status >= HTTP_MULTIPLE_CHOICES)
770 http->data_remaining = 0;
771 else
772 http->data_remaining = 2147483647;
773 }
774 else
775 http->data_remaining = strtoll(http->fields[HTTP_FIELD_CONTENT_LENGTH],
776 NULL, 10);
777
778 DEBUG_printf(("httpGetLength2: content_length=" CUPS_LLFMT "\n",
779 CUPS_LLCAST http->data_remaining));
780 }
781
782 if (http->data_remaining <= INT_MAX)
783 http->_data_remaining = (int)http->data_remaining;
784 else
785 http->_data_remaining = INT_MAX;
786
787 return (http->data_remaining);
788 }
789
790
791 /*
792 * 'httpGetStatus()' - Get the status of the last HTTP request.
793 *
794 * @since CUPS 1.2@
795 */
796
797 http_status_t /* O - HTTP status */
798 httpGetStatus(http_t *http) /* I - Connection to server */
799 {
800 return (http ? http->status : HTTP_ERROR);
801 }
802
803
804 /*
805 * 'httpGetSubField()' - Get a sub-field value.
806 *
807 * @deprecated@
808 */
809
810 char * /* O - Value or NULL */
811 httpGetSubField(http_t *http, /* I - Connection to server */
812 http_field_t field, /* I - Field index */
813 const char *name, /* I - Name of sub-field */
814 char *value) /* O - Value string */
815 {
816 return (httpGetSubField2(http, field, name, value, HTTP_MAX_VALUE));
817 }
818
819
820 /*
821 * 'httpGetSubField2()' - Get a sub-field value.
822 *
823 * @since CUPS 1.2@
824 */
825
826 char * /* O - Value or NULL */
827 httpGetSubField2(http_t *http, /* I - Connection to server */
828 http_field_t field, /* I - Field index */
829 const char *name, /* I - Name of sub-field */
830 char *value, /* O - Value string */
831 int valuelen) /* I - Size of value buffer */
832 {
833 const char *fptr; /* Pointer into field */
834 char temp[HTTP_MAX_VALUE], /* Temporary buffer for name */
835 *ptr, /* Pointer into string buffer */
836 *end; /* End of value buffer */
837
838 DEBUG_printf(("httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, valuelen=%d)\n",
839 http, field, name, value, valuelen));
840
841 if (!http || !name || !value || valuelen < 2 ||
842 field <= HTTP_FIELD_UNKNOWN || field >= HTTP_FIELD_MAX)
843 return (NULL);
844
845 end = value + valuelen - 1;
846
847 for (fptr = http->fields[field]; *fptr;)
848 {
849 /*
850 * Skip leading whitespace...
851 */
852
853 while (isspace(*fptr & 255))
854 fptr ++;
855
856 if (*fptr == ',')
857 {
858 fptr ++;
859 continue;
860 }
861
862 /*
863 * Get the sub-field name...
864 */
865
866 for (ptr = temp;
867 *fptr && *fptr != '=' && !isspace(*fptr & 255) &&
868 ptr < (temp + sizeof(temp) - 1);
869 *ptr++ = *fptr++);
870
871 *ptr = '\0';
872
873 DEBUG_printf(("httpGetSubField: name=\"%s\"\n", temp));
874
875 /*
876 * Skip trailing chars up to the '='...
877 */
878
879 while (isspace(*fptr & 255))
880 fptr ++;
881
882 if (!*fptr)
883 break;
884
885 if (*fptr != '=')
886 continue;
887
888 /*
889 * Skip = and leading whitespace...
890 */
891
892 fptr ++;
893
894 while (isspace(*fptr & 255))
895 fptr ++;
896
897 if (*fptr == '\"')
898 {
899 /*
900 * Read quoted string...
901 */
902
903 for (ptr = value, fptr ++;
904 *fptr && *fptr != '\"' && ptr < end;
905 *ptr++ = *fptr++);
906
907 *ptr = '\0';
908
909 while (*fptr && *fptr != '\"')
910 fptr ++;
911
912 if (*fptr)
913 fptr ++;
914 }
915 else
916 {
917 /*
918 * Read unquoted string...
919 */
920
921 for (ptr = value;
922 *fptr && !isspace(*fptr & 255) && *fptr != ',' && ptr < end;
923 *ptr++ = *fptr++);
924
925 *ptr = '\0';
926
927 while (*fptr && !isspace(*fptr & 255) && *fptr != ',')
928 fptr ++;
929 }
930
931 DEBUG_printf(("httpGetSubField: value=\"%s\"\n", value));
932
933 /*
934 * See if this is the one...
935 */
936
937 if (!strcmp(name, temp))
938 return (value);
939 }
940
941 value[0] = '\0';
942
943 return (NULL);
944 }
945
946
947 /*
948 * 'httpGets()' - Get a line of text from a HTTP connection.
949 */
950
951 char * /* O - Line or NULL */
952 httpGets(char *line, /* I - Line to read into */
953 int length, /* I - Max length of buffer */
954 http_t *http) /* I - Connection to server */
955 {
956 char *lineptr, /* Pointer into line */
957 *lineend, /* End of line */
958 *bufptr, /* Pointer into input buffer */
959 *bufend; /* Pointer to end of buffer */
960 int bytes, /* Number of bytes read */
961 eol; /* End-of-line? */
962
963
964 DEBUG_printf(("httpGets(line=%p, length=%d, http=%p)\n", line, length, http));
965
966 if (http == NULL || line == NULL)
967 return (NULL);
968
969 /*
970 * Read a line from the buffer...
971 */
972
973 lineptr = line;
974 lineend = line + length - 1;
975 eol = 0;
976
977 while (lineptr < lineend)
978 {
979 /*
980 * Pre-load the buffer as needed...
981 */
982
983 #ifdef WIN32
984 WSASetLastError(0);
985 #else
986 errno = 0;
987 #endif /* WIN32 */
988
989 while (http->used == 0)
990 {
991 /*
992 * No newline; see if there is more data to be read...
993 */
994
995 if (!http->blocking && !http_wait(http, 10000, 1))
996 {
997 DEBUG_puts("httpGets: Timed out!");
998 #ifdef WIN32
999 http->error = WSAETIMEDOUT;
1000 #else
1001 http->error = ETIMEDOUT;
1002 #endif /* WIN32 */
1003 return (NULL);
1004 }
1005
1006 #ifdef HAVE_SSL
1007 if (http->tls)
1008 bytes = http_read_ssl(http, http->buffer + http->used,
1009 HTTP_MAX_BUFFER - http->used);
1010 else
1011 #endif /* HAVE_SSL */
1012 bytes = recv(http->fd, http->buffer + http->used,
1013 HTTP_MAX_BUFFER - http->used, 0);
1014
1015 DEBUG_printf(("httpGets: read %d bytes...\n", bytes));
1016
1017 if (bytes < 0)
1018 {
1019 /*
1020 * Nope, can't get a line this time...
1021 */
1022
1023 #ifdef WIN32
1024 if (WSAGetLastError() != http->error)
1025 {
1026 http->error = WSAGetLastError();
1027 continue;
1028 }
1029
1030 DEBUG_printf(("httpGets: recv() error %d!\n", WSAGetLastError()));
1031 #else
1032 DEBUG_printf(("httpGets: recv() error %d!\n", errno));
1033
1034 if (errno == EINTR)
1035 continue;
1036 else if (errno != http->error)
1037 {
1038 http->error = errno;
1039 continue;
1040 }
1041 #endif /* WIN32 */
1042
1043 return (NULL);
1044 }
1045 else if (bytes == 0)
1046 {
1047 http->error = EPIPE;
1048
1049 return (NULL);
1050 }
1051
1052 /*
1053 * Yup, update the amount used...
1054 */
1055
1056 http->used += bytes;
1057 }
1058
1059 /*
1060 * Now copy as much of the current line as possible...
1061 */
1062
1063 for (bufptr = http->buffer, bufend = http->buffer + http->used;
1064 lineptr < lineend && bufptr < bufend;)
1065 {
1066 if (*bufptr == 0x0a)
1067 {
1068 eol = 1;
1069 bufptr ++;
1070 break;
1071 }
1072 else if (*bufptr == 0x0d)
1073 bufptr ++;
1074 else
1075 *lineptr++ = *bufptr++;
1076 }
1077
1078 http->used -= (int)(bufptr - http->buffer);
1079 if (http->used > 0)
1080 memmove(http->buffer, bufptr, http->used);
1081
1082 if (eol)
1083 {
1084 /*
1085 * End of line...
1086 */
1087
1088 http->activity = time(NULL);
1089
1090 *lineptr = '\0';
1091
1092 DEBUG_printf(("httpGets: Returning \"%s\"\n", line));
1093
1094 return (line);
1095 }
1096 }
1097
1098 DEBUG_puts("httpGets: No new line available!");
1099
1100 return (NULL);
1101 }
1102
1103
1104 /*
1105 * 'httpHead()' - Send a HEAD request to the server.
1106 */
1107
1108 int /* O - Status of call (0 = success) */
1109 httpHead(http_t *http, /* I - Connection to server */
1110 const char *uri) /* I - URI for head */
1111 {
1112 return (http_send(http, HTTP_HEAD, uri));
1113 }
1114
1115
1116 /*
1117 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1118 * default HTTP proxy (if any).
1119 */
1120
1121 void
1122 httpInitialize(void)
1123 {
1124 #ifdef HAVE_LIBSSL
1125 # ifndef WIN32
1126 struct timeval curtime; /* Current time in microseconds */
1127 # endif /* !WIN32 */
1128 int i; /* Looping var */
1129 unsigned char data[1024]; /* Seed data */
1130 #endif /* HAVE_LIBSSL */
1131
1132 #ifdef WIN32
1133 WSADATA winsockdata; /* WinSock data */
1134 static int initialized = 0; /* Has WinSock been initialized? */
1135
1136
1137 if (!initialized)
1138 WSAStartup(MAKEWORD(1,1), &winsockdata);
1139 #elif !defined(SO_NOSIGPIPE)
1140 /*
1141 * Ignore SIGPIPE signals...
1142 */
1143
1144 # ifdef HAVE_SIGSET
1145 sigset(SIGPIPE, SIG_IGN);
1146 # elif defined(HAVE_SIGACTION)
1147 struct sigaction action; /* POSIX sigaction data */
1148
1149
1150 memset(&action, 0, sizeof(action));
1151 action.sa_handler = SIG_IGN;
1152 sigaction(SIGPIPE, &action, NULL);
1153 # else
1154 signal(SIGPIPE, SIG_IGN);
1155 # endif /* !SO_NOSIGPIPE */
1156 #endif /* WIN32 */
1157
1158 #ifdef HAVE_GNUTLS
1159 gnutls_global_init();
1160 #endif /* HAVE_GNUTLS */
1161
1162 #ifdef HAVE_LIBSSL
1163 SSL_load_error_strings();
1164 SSL_library_init();
1165
1166 /*
1167 * Using the current time is a dubious random seed, but on some systems
1168 * it is the best we can do (on others, this seed isn't even used...)
1169 */
1170
1171 #ifdef WIN32
1172 #else
1173 gettimeofday(&curtime, NULL);
1174 srand(curtime.tv_sec + curtime.tv_usec);
1175 #endif /* WIN32 */
1176
1177 for (i = 0; i < sizeof(data); i ++)
1178 data[i] = rand(); /* Yes, this is a poor source of random data... */
1179
1180 RAND_seed(&data, sizeof(data));
1181 #endif /* HAVE_LIBSSL */
1182 }
1183
1184
1185 /*
1186 * 'httpOptions()' - Send an OPTIONS request to the server.
1187 */
1188
1189 int /* O - Status of call (0 = success) */
1190 httpOptions(http_t *http, /* I - Connection to server */
1191 const char *uri) /* I - URI for options */
1192 {
1193 return (http_send(http, HTTP_OPTIONS, uri));
1194 }
1195
1196
1197 /*
1198 * 'httpPost()' - Send a POST request to the server.
1199 */
1200
1201 int /* O - Status of call (0 = success) */
1202 httpPost(http_t *http, /* I - Connection to server */
1203 const char *uri) /* I - URI for post */
1204 {
1205 return (http_send(http, HTTP_POST, uri));
1206 }
1207
1208
1209 /*
1210 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1211 *
1212 * @private@
1213 */
1214
1215 int /* O - Number of bytes written */
1216 httpPrintf(http_t *http, /* I - Connection to server */
1217 const char *format, /* I - printf-style format string */
1218 ...) /* I - Additional args as needed */
1219 {
1220 int bytes; /* Number of bytes to write */
1221 char buf[16384]; /* Buffer for formatted string */
1222 va_list ap; /* Variable argument pointer */
1223
1224
1225 DEBUG_printf(("httpPrintf(http=%p, format=\"%s\", ...)\n", http, format));
1226
1227 va_start(ap, format);
1228 bytes = vsnprintf(buf, sizeof(buf), format, ap);
1229 va_end(ap);
1230
1231 DEBUG_printf(("httpPrintf: %s", buf));
1232
1233 if (http->data_encoding == HTTP_ENCODE_FIELDS)
1234 return (httpWrite2(http, buf, bytes));
1235 else
1236 {
1237 if (http->wused)
1238 {
1239 DEBUG_puts(" flushing existing data...");
1240
1241 if (httpFlushWrite(http) < 0)
1242 return (-1);
1243 }
1244
1245 return (http_write(http, buf, bytes));
1246 }
1247 }
1248
1249
1250 /*
1251 * 'httpPut()' - Send a PUT request to the server.
1252 */
1253
1254 int /* O - Status of call (0 = success) */
1255 httpPut(http_t *http, /* I - Connection to server */
1256 const char *uri) /* I - URI to put */
1257 {
1258 return (http_send(http, HTTP_PUT, uri));
1259 }
1260
1261
1262 /*
1263 * 'httpRead()' - Read data from a HTTP connection.
1264 *
1265 * This function is deprecated. Use the httpRead2() function which can
1266 * read more than 2GB of data.
1267 *
1268 * @deprecated@
1269 */
1270
1271 int /* O - Number of bytes read */
1272 httpRead(http_t *http, /* I - Connection to server */
1273 char *buffer, /* I - Buffer for data */
1274 int length) /* I - Maximum number of bytes */
1275 {
1276 return ((int)httpRead2(http, buffer, length));
1277 }
1278
1279
1280 /*
1281 * 'httpRead2()' - Read data from a HTTP connection.
1282 *
1283 * @since CUPS 1.2@
1284 */
1285
1286 ssize_t /* O - Number of bytes read */
1287 httpRead2(http_t *http, /* I - Connection to server */
1288 char *buffer, /* I - Buffer for data */
1289 size_t length) /* I - Maximum number of bytes */
1290 {
1291 ssize_t bytes; /* Bytes read */
1292 char len[32]; /* Length string */
1293
1294
1295 DEBUG_printf(("httpRead(http=%p, buffer=%p, length=" CUPS_LLFMT ")\n",
1296 http, buffer, CUPS_LLCAST length));
1297
1298 if (http == NULL || buffer == NULL)
1299 return (-1);
1300
1301 http->activity = time(NULL);
1302
1303 if (length <= 0)
1304 return (0);
1305
1306 if (http->data_encoding == HTTP_ENCODE_CHUNKED &&
1307 http->data_remaining <= 0)
1308 {
1309 DEBUG_puts("httpRead2: Getting chunk length...");
1310
1311 if (httpGets(len, sizeof(len), http) == NULL)
1312 {
1313 DEBUG_puts("httpRead2: Could not get length!");
1314 return (0);
1315 }
1316
1317 http->data_remaining = strtoll(len, NULL, 16);
1318 if (http->data_remaining < 0)
1319 {
1320 DEBUG_puts("httpRead2: Negative chunk length!");
1321 return (0);
1322 }
1323 }
1324
1325 DEBUG_printf(("httpRead2: data_remaining=" CUPS_LLFMT "\n",
1326 CUPS_LLCAST http->data_remaining));
1327
1328 if (http->data_remaining <= 0)
1329 {
1330 /*
1331 * A zero-length chunk ends a transfer; unless we are reading POST
1332 * data, go idle...
1333 */
1334
1335 if (http->data_encoding == HTTP_ENCODE_CHUNKED)
1336 httpGets(len, sizeof(len), http);
1337
1338 if (http->state == HTTP_POST_RECV)
1339 http->state ++;
1340 else
1341 http->state = HTTP_WAITING;
1342
1343 /*
1344 * Prevent future reads for this request...
1345 */
1346
1347 http->data_encoding = HTTP_ENCODE_LENGTH;
1348
1349 return (0);
1350 }
1351 else if (length > (size_t)http->data_remaining)
1352 length = (size_t)http->data_remaining;
1353
1354 if (http->used == 0 && length <= 256)
1355 {
1356 /*
1357 * Buffer small reads for better performance...
1358 */
1359
1360 if (!http->blocking && !httpWait(http, 10000))
1361 return (0);
1362
1363 if (http->data_remaining > sizeof(http->buffer))
1364 bytes = sizeof(http->buffer);
1365 else
1366 bytes = http->data_remaining;
1367
1368 #ifdef HAVE_SSL
1369 if (http->tls)
1370 bytes = http_read_ssl(http, http->buffer, bytes);
1371 else
1372 #endif /* HAVE_SSL */
1373 {
1374 DEBUG_printf(("httpRead2: reading %d bytes from socket into buffer...\n",
1375 (int)bytes));
1376
1377 bytes = recv(http->fd, http->buffer, bytes, 0);
1378
1379 DEBUG_printf(("httpRead2: read %d bytes from socket into buffer...\n",
1380 (int)bytes));
1381 }
1382
1383 if (bytes > 0)
1384 http->used = bytes;
1385 else if (bytes < 0)
1386 {
1387 #ifdef WIN32
1388 http->error = WSAGetLastError();
1389 return (-1);
1390 #else
1391 if (errno != EINTR)
1392 {
1393 http->error = errno;
1394 return (-1);
1395 }
1396 #endif /* WIN32 */
1397 }
1398 else
1399 {
1400 http->error = EPIPE;
1401 return (0);
1402 }
1403 }
1404
1405 if (http->used > 0)
1406 {
1407 if (length > (size_t)http->used)
1408 length = (size_t)http->used;
1409
1410 bytes = (ssize_t)length;
1411
1412 DEBUG_printf(("httpRead2: grabbing %d bytes from input buffer...\n",
1413 (int)bytes));
1414
1415 memcpy(buffer, http->buffer, length);
1416 http->used -= (int)length;
1417
1418 if (http->used > 0)
1419 memmove(http->buffer, http->buffer + length, http->used);
1420 }
1421 #ifdef HAVE_SSL
1422 else if (http->tls)
1423 {
1424 if (!http->blocking && !httpWait(http, 10000))
1425 return (0);
1426
1427 bytes = (ssize_t)http_read_ssl(http, buffer, (int)length);
1428 }
1429 #endif /* HAVE_SSL */
1430 else
1431 {
1432 if (!http->blocking && !httpWait(http, 10000))
1433 return (0);
1434
1435 DEBUG_printf(("httpRead2: reading " CUPS_LLFMT " bytes from socket...\n",
1436 CUPS_LLCAST length));
1437
1438 #ifdef WIN32
1439 bytes = (ssize_t)recv(http->fd, buffer, (int)length, 0);
1440 #else
1441 while ((bytes = recv(http->fd, buffer, length, 0)) < 0)
1442 if (errno != EINTR)
1443 break;
1444 #endif /* WIN32 */
1445
1446 DEBUG_printf(("httpRead2: read " CUPS_LLFMT " bytes from socket...\n",
1447 CUPS_LLCAST bytes));
1448 }
1449
1450 if (bytes > 0)
1451 {
1452 http->data_remaining -= bytes;
1453
1454 if (http->data_remaining <= INT_MAX)
1455 http->_data_remaining = (int)http->data_remaining;
1456 else
1457 http->_data_remaining = INT_MAX;
1458 }
1459 else if (bytes < 0)
1460 {
1461 #ifdef WIN32
1462 http->error = WSAGetLastError();
1463 #else
1464 if (errno == EINTR)
1465 bytes = 0;
1466 else
1467 http->error = errno;
1468 #endif /* WIN32 */
1469 }
1470 else
1471 {
1472 http->error = EPIPE;
1473 return (0);
1474 }
1475
1476 if (http->data_remaining == 0)
1477 {
1478 if (http->data_encoding == HTTP_ENCODE_CHUNKED)
1479 httpGets(len, sizeof(len), http);
1480
1481 if (http->data_encoding != HTTP_ENCODE_CHUNKED)
1482 {
1483 if (http->state == HTTP_POST_RECV)
1484 http->state ++;
1485 else
1486 http->state = HTTP_WAITING;
1487 }
1488 }
1489
1490 #ifdef DEBUG
1491 {
1492 int i, j, ch;
1493 printf("httpRead2: Read " CUPS_LLFMT " bytes:\n", CUPS_LLCAST bytes);
1494 for (i = 0; i < bytes; i += 16)
1495 {
1496 printf(" ");
1497
1498 for (j = 0; j < 16 && (i + j) < bytes; j ++)
1499 printf(" %02X", buffer[i + j] & 255);
1500
1501 while (j < 16)
1502 {
1503 printf(" ");
1504 j ++;
1505 }
1506
1507 printf(" ");
1508 for (j = 0; j < 16 && (i + j) < bytes; j ++)
1509 {
1510 ch = buffer[i + j] & 255;
1511
1512 if (ch < ' ' || ch >= 127)
1513 ch = '.';
1514
1515 putchar(ch);
1516 }
1517 putchar('\n');
1518 }
1519 }
1520 #endif /* DEBUG */
1521
1522 return (bytes);
1523 }
1524
1525
1526 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
1527 /*
1528 * '_httpReadCDSA()' - Read function for the CDSA library.
1529 */
1530
1531 OSStatus /* O - -1 on error, 0 on success */
1532 _httpReadCDSA(
1533 SSLConnectionRef connection, /* I - SSL/TLS connection */
1534 void *data, /* I - Data buffer */
1535 size_t *dataLength) /* IO - Number of bytes */
1536 {
1537 OSStatus result; /* Return value */
1538 ssize_t bytes; /* Number of bytes read */
1539 http_t *http; /* HTTP connection */
1540
1541
1542 http = (http_t *)connection;
1543
1544 if (!http->blocking)
1545 {
1546 /*
1547 * Make sure we have data before we read...
1548 */
1549
1550 if (!http_wait(http, 10000, 0))
1551 {
1552 http->error = ETIMEDOUT;
1553 return (-1);
1554 }
1555 }
1556
1557 do
1558 {
1559 bytes = recv(http->fd, data, *dataLength, 0);
1560 }
1561 while (bytes == -1 && errno == EINTR);
1562
1563 if (bytes == *dataLength)
1564 {
1565 result = 0;
1566 }
1567 else if (bytes > 0)
1568 {
1569 *dataLength = bytes;
1570 result = errSSLWouldBlock;
1571 }
1572 else
1573 {
1574 *dataLength = 0;
1575
1576 if (bytes == 0)
1577 result = errSSLClosedGraceful;
1578 else if (errno == EAGAIN)
1579 result = errSSLWouldBlock;
1580 else
1581 result = errSSLClosedAbort;
1582 }
1583
1584 return (result);
1585 }
1586 #endif /* HAVE_SSL && HAVE_CDSASSL */
1587
1588
1589 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
1590 /*
1591 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
1592 */
1593
1594 ssize_t /* O - Number of bytes read or -1 on error */
1595 _httpReadGNUTLS(
1596 gnutls_transport_ptr ptr, /* I - Connection to server */
1597 void *data, /* I - Buffer */
1598 size_t length) /* I - Number of bytes to read */
1599 {
1600 http_t *http; /* HTTP connection */
1601
1602
1603 http = (http_t *)ptr;
1604
1605 if (!http->blocking)
1606 {
1607 /*
1608 * Make sure we have data before we read...
1609 */
1610
1611 if (!http_wait(http, 10000, 0))
1612 {
1613 http->error = ETIMEDOUT;
1614 return (-1);
1615 }
1616 }
1617
1618 return (recv(http->fd, data, length, 0));
1619 }
1620 #endif /* HAVE_SSL && HAVE_GNUTLS */
1621
1622
1623 /*
1624 * 'httpReconnect()' - Reconnect to a HTTP server.
1625 */
1626
1627 int /* O - 0 on success, non-zero on failure */
1628 httpReconnect(http_t *http) /* I - Connection to server */
1629 {
1630 http_addrlist_t *addr; /* Connected address */
1631
1632
1633 DEBUG_printf(("httpReconnect(http=%p)\n", http));
1634
1635 if (!http)
1636 return (-1);
1637
1638 #ifdef HAVE_SSL
1639 if (http->tls)
1640 http_shutdown_ssl(http);
1641 #endif /* HAVE_SSL */
1642
1643 /*
1644 * Close any previously open socket...
1645 */
1646
1647 if (http->fd >= 0)
1648 {
1649 #ifdef WIN32
1650 closesocket(http->fd);
1651 #else
1652 close(http->fd);
1653 #endif /* WIN32 */
1654
1655 http->fd = -1;
1656 }
1657
1658 /*
1659 * Connect to the server...
1660 */
1661
1662 if ((addr = httpAddrConnect(http->addrlist, &(http->fd))) == NULL)
1663 {
1664 /*
1665 * Unable to connect...
1666 */
1667
1668 #ifdef WIN32
1669 http->error = WSAGetLastError();
1670 #else
1671 http->error = errno;
1672 #endif /* WIN32 */
1673 http->status = HTTP_ERROR;
1674
1675 return (-1);
1676 }
1677
1678 http->hostaddr = &(addr->addr);
1679 http->error = 0;
1680 http->status = HTTP_CONTINUE;
1681
1682 #ifdef HAVE_SSL
1683 if (http->encryption == HTTP_ENCRYPT_ALWAYS)
1684 {
1685 /*
1686 * Always do encryption via SSL.
1687 */
1688
1689 if (http_setup_ssl(http) != 0)
1690 {
1691 # ifdef WIN32
1692 closesocket(http->fd);
1693 # else
1694 close(http->fd);
1695 # endif /* WIN32 */
1696
1697 return (-1);
1698 }
1699 }
1700 else if (http->encryption == HTTP_ENCRYPT_REQUIRED)
1701 return (http_upgrade(http));
1702 #endif /* HAVE_SSL */
1703
1704 return (0);
1705 }
1706
1707
1708 /*
1709 * 'httpSetAuthString()' - Set the current authorization string.
1710 *
1711 * This function just stores a copy of the current authorization string in
1712 * the HTTP connection object. You must still call httpSetField() to set
1713 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
1714 * httpHead(), httpOptions(), httpPost, or httpPut().
1715 *
1716 * @since CUPS 1.3@
1717 */
1718
1719 void
1720 httpSetAuthString(http_t *http, /* I - Connection to server */
1721 const char *scheme, /* I - Auth scheme (NULL to clear it) */
1722 const char *data) /* I - Auth data (NULL for none) */
1723 {
1724 /*
1725 * Range check input...
1726 */
1727
1728 if (!http)
1729 return;
1730
1731 if (http->authstring && http->authstring != http->_authstring)
1732 free(http->authstring);
1733
1734 http->authstring = http->_authstring;
1735
1736 if (scheme)
1737 {
1738 /*
1739 * Set the current authorization string...
1740 */
1741
1742 int len = (int)strlen(scheme) + (data ? (int)strlen(data) + 1 : 0) + 1;
1743 char *temp;
1744
1745 if (len > (int)sizeof(http->_authstring))
1746 {
1747 if ((temp = malloc(len)) == NULL)
1748 len = sizeof(http->_authstring);
1749 else
1750 http->authstring = temp;
1751 }
1752
1753 if (data)
1754 snprintf(http->authstring, len, "%s %s", scheme, data);
1755 else
1756 strlcpy(http->authstring, scheme, len);
1757 }
1758 else
1759 {
1760 /*
1761 * Clear the current authorization string...
1762 */
1763
1764 http->_authstring[0] = '\0';
1765 }
1766 }
1767
1768
1769 /*
1770 * 'httpSetCookie()' - Set the cookie value(s)...
1771 *
1772 * @since CUPS 1.1.19@
1773 */
1774
1775 void
1776 httpSetCookie(http_t *http, /* I - Connection */
1777 const char *cookie) /* I - Cookie string */
1778 {
1779 if (!http)
1780 return;
1781
1782 if (http->cookie)
1783 free(http->cookie);
1784
1785 if (cookie)
1786 http->cookie = strdup(cookie);
1787 else
1788 http->cookie = NULL;
1789 }
1790
1791
1792 /*
1793 * 'httpSetExpect()' - Set the Expect: header in a request.
1794 *
1795 * Currently only HTTP_CONTINUE is supported for the "expect" argument.
1796 *
1797 * @since CUPS 1.2@
1798 */
1799
1800 void
1801 httpSetExpect(http_t *http, /* I - Connection to server */
1802 http_status_t expect) /* I - HTTP status to expect (HTTP_CONTINUE) */
1803 {
1804 if (http)
1805 http->expect = expect;
1806 }
1807
1808
1809 /*
1810 * 'httpSetField()' - Set the value of an HTTP header.
1811 */
1812
1813 void
1814 httpSetField(http_t *http, /* I - Connection to server */
1815 http_field_t field, /* I - Field index */
1816 const char *value) /* I - Value */
1817 {
1818 if (http == NULL ||
1819 field < HTTP_FIELD_ACCEPT_LANGUAGE ||
1820 field > HTTP_FIELD_WWW_AUTHENTICATE ||
1821 value == NULL)
1822 return;
1823
1824 strlcpy(http->fields[field], value, HTTP_MAX_VALUE);
1825
1826 /*
1827 * Special case for Authorization: as its contents can be
1828 * longer than HTTP_MAX_VALUE
1829 */
1830
1831 if (field == HTTP_FIELD_AUTHORIZATION)
1832 {
1833 if (http->field_authorization)
1834 free(http->field_authorization);
1835
1836 http->field_authorization = strdup(value);
1837 }
1838 }
1839
1840
1841 /*
1842 * 'httpSetLength()' - Set the content-length and content-encoding.
1843 *
1844 * @since CUPS 1.2@
1845 */
1846
1847 void
1848 httpSetLength(http_t *http, /* I - Connection to server */
1849 size_t length) /* I - Length (0 for chunked) */
1850 {
1851 if (!http)
1852 return;
1853
1854 if (!length)
1855 {
1856 strcpy(http->fields[HTTP_FIELD_TRANSFER_ENCODING], "chunked");
1857 http->fields[HTTP_FIELD_CONTENT_LENGTH][0] = '\0';
1858 }
1859 else
1860 {
1861 http->fields[HTTP_FIELD_TRANSFER_ENCODING][0] = '\0';
1862 snprintf(http->fields[HTTP_FIELD_CONTENT_LENGTH], HTTP_MAX_VALUE,
1863 CUPS_LLFMT, CUPS_LLCAST length);
1864 }
1865 }
1866
1867
1868 /*
1869 * 'httpTrace()' - Send an TRACE request to the server.
1870 */
1871
1872 int /* O - Status of call (0 = success) */
1873 httpTrace(http_t *http, /* I - Connection to server */
1874 const char *uri) /* I - URI for trace */
1875 {
1876 return (http_send(http, HTTP_TRACE, uri));
1877 }
1878
1879
1880 /*
1881 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1882 */
1883
1884 http_status_t /* O - HTTP status */
1885 httpUpdate(http_t *http) /* I - Connection to server */
1886 {
1887 char line[32768], /* Line from connection... */
1888 *value; /* Pointer to value on line */
1889 http_field_t field; /* Field index */
1890 int major, minor, /* HTTP version numbers */
1891 status; /* Request status */
1892
1893
1894 DEBUG_printf(("httpUpdate(http=%p), state=%d\n", http, http->state));
1895
1896 /*
1897 * Flush pending data, if any...
1898 */
1899
1900 if (http->wused)
1901 {
1902 DEBUG_puts(" flushing buffer...");
1903
1904 if (httpFlushWrite(http) < 0)
1905 return (HTTP_ERROR);
1906 }
1907
1908 /*
1909 * If we haven't issued any commands, then there is nothing to "update"...
1910 */
1911
1912 if (http->state == HTTP_WAITING)
1913 return (HTTP_CONTINUE);
1914
1915 /*
1916 * Grab all of the lines we can from the connection...
1917 */
1918
1919 while (httpGets(line, sizeof(line), http) != NULL)
1920 {
1921 DEBUG_printf(("httpUpdate: Got \"%s\"\n", line));
1922
1923 if (line[0] == '\0')
1924 {
1925 /*
1926 * Blank line means the start of the data section (if any). Return
1927 * the result code, too...
1928 *
1929 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
1930 * Instead, we just return HTTP_CONTINUE to the caller and keep on
1931 * tryin'...
1932 */
1933
1934 if (http->status == HTTP_CONTINUE)
1935 return (http->status);
1936
1937 if (http->status < HTTP_BAD_REQUEST)
1938 http->digest_tries = 0;
1939
1940 #ifdef HAVE_SSL
1941 if (http->status == HTTP_SWITCHING_PROTOCOLS && !http->tls)
1942 {
1943 if (http_setup_ssl(http) != 0)
1944 {
1945 # ifdef WIN32
1946 closesocket(http->fd);
1947 # else
1948 close(http->fd);
1949 # endif /* WIN32 */
1950
1951 return (HTTP_ERROR);
1952 }
1953
1954 return (HTTP_CONTINUE);
1955 }
1956 #endif /* HAVE_SSL */
1957
1958 httpGetLength2(http);
1959
1960 switch (http->state)
1961 {
1962 case HTTP_GET :
1963 case HTTP_POST :
1964 case HTTP_POST_RECV :
1965 case HTTP_PUT :
1966 http->state ++;
1967 case HTTP_POST_SEND :
1968 case HTTP_HEAD :
1969 break;
1970
1971 default :
1972 http->state = HTTP_WAITING;
1973 break;
1974 }
1975
1976 return (http->status);
1977 }
1978 else if (strncmp(line, "HTTP/", 5) == 0)
1979 {
1980 /*
1981 * Got the beginning of a response...
1982 */
1983
1984 if (sscanf(line, "HTTP/%d.%d%d", &major, &minor, &status) != 3)
1985 return (HTTP_ERROR);
1986
1987 http->version = (http_version_t)(major * 100 + minor);
1988 http->status = (http_status_t)status;
1989 }
1990 else if ((value = strchr(line, ':')) != NULL)
1991 {
1992 /*
1993 * Got a value...
1994 */
1995
1996 *value++ = '\0';
1997 while (isspace(*value & 255))
1998 value ++;
1999
2000 /*
2001 * Be tolerants of servers that send unknown attribute fields...
2002 */
2003
2004 if (!strcasecmp(line, "expect"))
2005 {
2006 /*
2007 * "Expect: 100-continue" or similar...
2008 */
2009
2010 http->expect = (http_status_t)atoi(value);
2011 }
2012 else if (!strcasecmp(line, "cookie"))
2013 {
2014 /*
2015 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
2016 */
2017
2018 httpSetCookie(http, value);
2019 }
2020 else if ((field = http_field(line)) == HTTP_FIELD_UNKNOWN)
2021 {
2022 DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line));
2023 continue;
2024 }
2025 else
2026 httpSetField(http, field, value);
2027 }
2028 else
2029 {
2030 http->status = HTTP_ERROR;
2031 return (HTTP_ERROR);
2032 }
2033 }
2034
2035 /*
2036 * See if there was an error...
2037 */
2038
2039 if (http->error == EPIPE && http->status > HTTP_CONTINUE)
2040 return (http->status);
2041
2042 if (http->error)
2043 {
2044 DEBUG_printf(("httpUpdate: socket error %d - %s\n", http->error,
2045 strerror(http->error)));
2046 http->status = HTTP_ERROR;
2047 return (HTTP_ERROR);
2048 }
2049
2050 /*
2051 * If we haven't already returned, then there is nothing new...
2052 */
2053
2054 return (HTTP_CONTINUE);
2055 }
2056
2057
2058 /*
2059 * 'httpWait()' - Wait for data available on a connection.
2060 *
2061 * @since CUPS 1.1.19@
2062 */
2063
2064 int /* O - 1 if data is available, 0 otherwise */
2065 httpWait(http_t *http, /* I - Connection to server */
2066 int msec) /* I - Milliseconds to wait */
2067 {
2068 /*
2069 * First see if there is data in the buffer...
2070 */
2071
2072 if (http == NULL)
2073 return (0);
2074
2075 if (http->used)
2076 return (1);
2077
2078 /*
2079 * Flush pending data, if any...
2080 */
2081
2082 if (http->wused)
2083 {
2084 if (httpFlushWrite(http) < 0)
2085 return (0);
2086 }
2087
2088 /*
2089 * If not, check the SSL/TLS buffers and do a select() on the connection...
2090 */
2091
2092 return (http_wait(http, msec, 1));
2093 }
2094
2095
2096 /*
2097 * 'httpWrite()' - Write data to a HTTP connection.
2098 *
2099 * This function is deprecated. Use the httpWrite2() function which can
2100 * write more than 2GB of data.
2101 *
2102 * @deprecated@
2103 */
2104
2105 int /* O - Number of bytes written */
2106 httpWrite(http_t *http, /* I - Connection to server */
2107 const char *buffer, /* I - Buffer for data */
2108 int length) /* I - Number of bytes to write */
2109 {
2110 return ((int)httpWrite2(http, buffer, length));
2111 }
2112
2113
2114 /*
2115 * 'httpWrite2()' - Write data to a HTTP connection.
2116 *
2117 * @since CUPS 1.2@
2118 */
2119
2120 ssize_t /* O - Number of bytes written */
2121 httpWrite2(http_t *http, /* I - Connection to server */
2122 const char *buffer, /* I - Buffer for data */
2123 size_t length) /* I - Number of bytes to write */
2124 {
2125 ssize_t bytes; /* Bytes written */
2126
2127
2128 DEBUG_printf(("httpWrite(http=%p, buffer=%p, length=" CUPS_LLFMT ")\n", http,
2129 buffer, CUPS_LLCAST length));
2130
2131 /*
2132 * Range check input...
2133 */
2134
2135 if (http == NULL || buffer == NULL)
2136 return (-1);
2137
2138 /*
2139 * Mark activity on the connection...
2140 */
2141
2142 http->activity = time(NULL);
2143
2144 /*
2145 * Buffer small writes for better performance...
2146 */
2147
2148 if (length > 0)
2149 {
2150 if (http->wused && (length + http->wused) > sizeof(http->wbuffer))
2151 {
2152 DEBUG_printf((" flushing buffer (wused=%d, length=" CUPS_LLFMT ")\n",
2153 http->wused, CUPS_LLCAST length));
2154
2155 httpFlushWrite(http);
2156 }
2157
2158 if ((length + http->wused) <= sizeof(http->wbuffer))
2159 {
2160 /*
2161 * Write to buffer...
2162 */
2163
2164 DEBUG_printf((" copying " CUPS_LLFMT " bytes to wbuffer...\n",
2165 CUPS_LLCAST length));
2166
2167 memcpy(http->wbuffer + http->wused, buffer, length);
2168 http->wused += (int)length;
2169 bytes = (ssize_t)length;
2170 }
2171 else
2172 {
2173 /*
2174 * Otherwise write the data directly...
2175 */
2176
2177 DEBUG_printf((" writing " CUPS_LLFMT " bytes to socket...\n",
2178 CUPS_LLCAST length));
2179
2180 if (http->data_encoding == HTTP_ENCODE_CHUNKED)
2181 bytes = (ssize_t)http_write_chunk(http, buffer, (int)length);
2182 else
2183 bytes = (ssize_t)http_write(http, buffer, (int)length);
2184
2185 DEBUG_printf((" wrote " CUPS_LLFMT " bytes...\n", CUPS_LLCAST bytes));
2186 }
2187
2188 if (http->data_encoding == HTTP_ENCODE_LENGTH)
2189 http->data_remaining -= bytes;
2190 }
2191 else
2192 bytes = 0;
2193
2194 /*
2195 * Handle end-of-request processing...
2196 */
2197
2198 if ((http->data_encoding == HTTP_ENCODE_CHUNKED && length == 0) ||
2199 (http->data_encoding == HTTP_ENCODE_LENGTH && http->data_remaining == 0))
2200 {
2201 /*
2202 * Finished with the transfer; unless we are sending POST or PUT
2203 * data, go idle...
2204 */
2205
2206 DEBUG_puts("httpWrite: changing states...");
2207
2208 if (http->wused)
2209 httpFlushWrite(http);
2210
2211 if (http->data_encoding == HTTP_ENCODE_CHUNKED)
2212 {
2213 /*
2214 * Send a 0-length chunk at the end of the request...
2215 */
2216
2217 http_write(http, "0\r\n\r\n", 5);
2218
2219 /*
2220 * Reset the data state...
2221 */
2222
2223 http->data_encoding = HTTP_ENCODE_LENGTH;
2224 http->data_remaining = 0;
2225 }
2226
2227 if (http->state == HTTP_POST_RECV)
2228 http->state ++;
2229 else if (http->state == HTTP_PUT_RECV)
2230 http->state = HTTP_STATUS;
2231 else
2232 http->state = HTTP_WAITING;
2233 }
2234
2235 return (bytes);
2236 }
2237
2238
2239 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2240 /*
2241 * '_httpWriteCDSA()' - Write function for the CDSA library.
2242 */
2243
2244 OSStatus /* O - -1 on error, 0 on success */
2245 _httpWriteCDSA(
2246 SSLConnectionRef connection, /* I - SSL/TLS connection */
2247 const void *data, /* I - Data buffer */
2248 size_t *dataLength) /* IO - Number of bytes */
2249 {
2250 OSStatus result; /* Return value */
2251 ssize_t bytes; /* Number of bytes read */
2252 http_t *http; /* HTTP connection */
2253
2254
2255 http = (http_t *)connection;
2256
2257 do
2258 {
2259 bytes = write(http->fd, data, *dataLength);
2260 }
2261 while (bytes == -1 && errno == EINTR);
2262
2263 if (bytes == *dataLength)
2264 {
2265 result = 0;
2266 }
2267 else if (bytes >= 0)
2268 {
2269 *dataLength = bytes;
2270 result = errSSLWouldBlock;
2271 }
2272 else
2273 {
2274 *dataLength = 0;
2275
2276 if (errno == EAGAIN)
2277 result = errSSLWouldBlock;
2278 else
2279 result = errSSLClosedAbort;
2280 }
2281
2282 return (result);
2283 }
2284 #endif /* HAVE_SSL && HAVE_CDSASSL */
2285
2286
2287 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2288 /*
2289 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
2290 */
2291
2292 ssize_t /* O - Number of bytes written or -1 on error */
2293 _httpWriteGNUTLS(
2294 gnutls_transport_ptr ptr, /* I - Connection to server */
2295 const void *data, /* I - Data buffer */
2296 size_t length) /* I - Number of bytes to write */
2297 {
2298 return (send(((http_t *)ptr)->fd, data, length, 0));
2299 }
2300 #endif /* HAVE_SSL && HAVE_GNUTLS */
2301
2302
2303 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
2304 /*
2305 * 'http_bio_ctrl()' - Control the HTTP connection.
2306 */
2307
2308 static long /* O - Result/data */
2309 http_bio_ctrl(BIO *h, /* I - BIO data */
2310 int cmd, /* I - Control command */
2311 long arg1, /* I - First argument */
2312 void *arg2) /* I - Second argument */
2313 {
2314 switch (cmd)
2315 {
2316 default :
2317 return (0);
2318
2319 case BIO_CTRL_RESET :
2320 h->ptr = NULL;
2321 return (0);
2322
2323 case BIO_C_SET_FILE_PTR :
2324 h->ptr = arg2;
2325 h->init = 1;
2326 return (1);
2327
2328 case BIO_C_GET_FILE_PTR :
2329 if (arg2)
2330 {
2331 *((void **)arg2) = h->ptr;
2332 return (1);
2333 }
2334 else
2335 return (0);
2336
2337 case BIO_CTRL_DUP :
2338 case BIO_CTRL_FLUSH :
2339 return (1);
2340 }
2341 }
2342
2343
2344 /*
2345 * 'http_bio_free()' - Free OpenSSL data.
2346 */
2347
2348 static int /* O - 1 on success, 0 on failure */
2349 http_bio_free(BIO *h) /* I - BIO data */
2350 {
2351 if (!h)
2352 return (0);
2353
2354 if (h->shutdown)
2355 {
2356 h->init = 0;
2357 h->flags = 0;
2358 }
2359
2360 return (1);
2361 }
2362
2363
2364 /*
2365 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
2366 */
2367
2368 static int /* O - 1 on success, 0 on failure */
2369 http_bio_new(BIO *h) /* I - BIO data */
2370 {
2371 if (!h)
2372 return (0);
2373
2374 h->init = 0;
2375 h->num = 0;
2376 h->ptr = NULL;
2377 h->flags = 0;
2378
2379 return (1);
2380 }
2381
2382
2383 /*
2384 * 'http_bio_puts()' - Send a string for OpenSSL.
2385 */
2386
2387 static int /* O - Bytes written */
2388 http_bio_puts(BIO *h, /* I - BIO data */
2389 const char *str) /* I - String to write */
2390 {
2391 #ifdef WIN32
2392 return (send(((http_t *)h->ptr)->fd, str, (int)strlen(str), 0));
2393 #else
2394 return (send(((http_t *)h->ptr)->fd, str, strlen(str), 0));
2395 #endif /* WIN32 */
2396 }
2397
2398
2399 /*
2400 * 'http_bio_read()' - Read data for OpenSSL.
2401 */
2402
2403 static int /* O - Bytes read */
2404 http_bio_read(BIO *h, /* I - BIO data */
2405 char *buf, /* I - Buffer */
2406 int size) /* I - Number of bytes to read */
2407 {
2408 http_t *http; /* HTTP connection */
2409
2410
2411 http = (http_t *)h->ptr;
2412
2413 if (!http->blocking)
2414 {
2415 /*
2416 * Make sure we have data before we read...
2417 */
2418
2419 if (!http_wait(http, 10000, 0))
2420 {
2421 #ifdef WIN32
2422 http->error = WSAETIMEDOUT;
2423 #else
2424 http->error = ETIMEDOUT;
2425 #endif /* WIN32 */
2426
2427 return (-1);
2428 }
2429 }
2430
2431 return (recv(http->fd, buf, size, 0));
2432 }
2433
2434
2435 /*
2436 * 'http_bio_write()' - Write data for OpenSSL.
2437 */
2438
2439 static int /* O - Bytes written */
2440 http_bio_write(BIO *h, /* I - BIO data */
2441 const char *buf, /* I - Buffer to write */
2442 int num) /* I - Number of bytes to write */
2443 {
2444 return (send(((http_t *)h->ptr)->fd, buf, num, 0));
2445 }
2446 #endif /* HAVE_SSL && HAVE_LIBSSL */
2447
2448
2449 /*
2450 * 'http_field()' - Return the field index for a field name.
2451 */
2452
2453 static http_field_t /* O - Field index */
2454 http_field(const char *name) /* I - String name */
2455 {
2456 int i; /* Looping var */
2457
2458
2459 for (i = 0; i < HTTP_FIELD_MAX; i ++)
2460 if (strcasecmp(name, http_fields[i]) == 0)
2461 return ((http_field_t)i);
2462
2463 return (HTTP_FIELD_UNKNOWN);
2464 }
2465
2466
2467 #ifdef HAVE_SSL
2468 /*
2469 * 'http_read_ssl()' - Read from a SSL/TLS connection.
2470 */
2471
2472 static int /* O - Bytes read */
2473 http_read_ssl(http_t *http, /* I - Connection to server */
2474 char *buf, /* I - Buffer to store data */
2475 int len) /* I - Length of buffer */
2476 {
2477 # if defined(HAVE_LIBSSL)
2478 return (SSL_read((SSL *)(http->tls), buf, len));
2479
2480 # elif defined(HAVE_GNUTLS)
2481 return (gnutls_record_recv(((http_tls_t *)(http->tls))->session, buf, len));
2482
2483 # elif defined(HAVE_CDSASSL)
2484 int result; /* Return value */
2485 OSStatus error; /* Error info */
2486 size_t processed; /* Number of bytes processed */
2487
2488
2489 error = SSLRead(((http_tls_t *)http->tls)->session, buf, len, &processed);
2490
2491 switch (error)
2492 {
2493 case 0 :
2494 result = (int)processed;
2495 break;
2496 case errSSLClosedGraceful :
2497 result = 0;
2498 break;
2499 case errSSLWouldBlock :
2500 if (processed)
2501 result = (int)processed;
2502 else
2503 {
2504 result = -1;
2505 errno = EINTR;
2506 }
2507 break;
2508 default :
2509 errno = EPIPE;
2510 result = -1;
2511 break;
2512 }
2513
2514 return (result);
2515 # endif /* HAVE_LIBSSL */
2516 }
2517 #endif /* HAVE_SSL */
2518
2519
2520 /*
2521 * 'http_send()' - Send a request with all fields and the trailing blank line.
2522 */
2523
2524 static int /* O - 0 on success, non-zero on error */
2525 http_send(http_t *http, /* I - Connection to server */
2526 http_state_t request, /* I - Request code */
2527 const char *uri) /* I - URI */
2528 {
2529 int i; /* Looping var */
2530 char buf[1024]; /* Encoded URI buffer */
2531 static const char * const codes[] =
2532 { /* Request code strings */
2533 NULL,
2534 "OPTIONS",
2535 "GET",
2536 NULL,
2537 "HEAD",
2538 "POST",
2539 NULL,
2540 NULL,
2541 "PUT",
2542 NULL,
2543 "DELETE",
2544 "TRACE",
2545 "CLOSE"
2546 };
2547
2548
2549 DEBUG_printf(("http_send(http=%p, request=HTTP_%s, uri=\"%s\")\n",
2550 http, codes[request], uri));
2551
2552 if (http == NULL || uri == NULL)
2553 return (-1);
2554
2555 /*
2556 * Set the User-Agent field if it isn't already...
2557 */
2558
2559 if (!http->fields[HTTP_FIELD_USER_AGENT][0])
2560 httpSetField(http, HTTP_FIELD_USER_AGENT, CUPS_MINIMAL);
2561
2562 /*
2563 * Encode the URI as needed...
2564 */
2565
2566 _httpEncodeURI(buf, uri, sizeof(buf));
2567
2568 /*
2569 * See if we had an error the last time around; if so, reconnect...
2570 */
2571
2572 if (http->status == HTTP_ERROR || http->status >= HTTP_BAD_REQUEST)
2573 if (httpReconnect(http))
2574 return (-1);
2575
2576 /*
2577 * Flush any written data that is pending...
2578 */
2579
2580 if (http->wused)
2581 httpFlushWrite(http);
2582
2583 /*
2584 * Send the request header...
2585 */
2586
2587 http->state = request;
2588 http->data_encoding = HTTP_ENCODE_FIELDS;
2589
2590 if (request == HTTP_POST || request == HTTP_PUT)
2591 http->state ++;
2592
2593 http->status = HTTP_CONTINUE;
2594
2595 #ifdef HAVE_SSL
2596 if (http->encryption == HTTP_ENCRYPT_REQUIRED && !http->tls)
2597 {
2598 httpSetField(http, HTTP_FIELD_CONNECTION, "Upgrade");
2599 httpSetField(http, HTTP_FIELD_UPGRADE, "TLS/1.0,SSL/2.0,SSL/3.0");
2600 }
2601 #endif /* HAVE_SSL */
2602
2603 if (httpPrintf(http, "%s %s HTTP/1.1\r\n", codes[request], buf) < 1)
2604 {
2605 http->status = HTTP_ERROR;
2606 return (-1);
2607 }
2608
2609 for (i = 0; i < HTTP_FIELD_MAX; i ++)
2610 if (http->fields[i][0] != '\0')
2611 {
2612 DEBUG_printf(("%s: %s\n", http_fields[i], httpGetField(http, i)));
2613
2614 if (httpPrintf(http, "%s: %s\r\n", http_fields[i],
2615 httpGetField(http, i)) < 1)
2616 {
2617 http->status = HTTP_ERROR;
2618 return (-1);
2619 }
2620 }
2621
2622 if (http->cookie)
2623 if (httpPrintf(http, "Cookie: $Version=0; %s\r\n", http->cookie) < 1)
2624 {
2625 http->status = HTTP_ERROR;
2626 return (-1);
2627 }
2628
2629 if (http->expect == HTTP_CONTINUE &&
2630 (http->state == HTTP_POST_RECV || http->state == HTTP_PUT_RECV))
2631 if (httpPrintf(http, "Expect: 100-continue\r\n") < 1)
2632 {
2633 http->status = HTTP_ERROR;
2634 return (-1);
2635 }
2636
2637 if (httpPrintf(http, "\r\n") < 1)
2638 {
2639 http->status = HTTP_ERROR;
2640 return (-1);
2641 }
2642
2643 httpFlushWrite(http);
2644 httpGetLength2(http);
2645 httpClearFields(http);
2646
2647 /*
2648 * The Kerberos and AuthRef authentication strings can only be used once...
2649 */
2650
2651 if (http->field_authorization && http->authstring &&
2652 (!strncmp(http->authstring, "Negotiate", 9) ||
2653 !strncmp(http->authstring, "AuthRef", 7)))
2654 {
2655 http->_authstring[0] = '\0';
2656
2657 if (http->authstring != http->_authstring)
2658 free(http->authstring);
2659
2660 http->authstring = http->_authstring;
2661 }
2662
2663 return (0);
2664 }
2665
2666
2667 #ifdef HAVE_SSL
2668 /*
2669 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
2670 */
2671
2672 static int /* O - Status of connection */
2673 http_setup_ssl(http_t *http) /* I - Connection to server */
2674 {
2675 # ifdef HAVE_LIBSSL
2676 SSL_CTX *context; /* Context for encryption */
2677 SSL *conn; /* Connection for encryption */
2678 BIO *bio; /* BIO data */
2679 # elif defined(HAVE_GNUTLS)
2680 http_tls_t *conn; /* TLS session object */
2681 gnutls_certificate_client_credentials *credentials;
2682 /* TLS credentials */
2683 # elif defined(HAVE_CDSASSL)
2684 OSStatus error; /* Error code */
2685 http_tls_t *conn; /* CDSA connection information */
2686 # endif /* HAVE_LIBSSL */
2687
2688
2689 DEBUG_printf(("http_setup_ssl(http=%p)\n", http));
2690
2691 # ifdef HAVE_LIBSSL
2692 context = SSL_CTX_new(SSLv23_client_method());
2693
2694 SSL_CTX_set_options(context, SSL_OP_NO_SSLv2); /* Only use SSLv3 or TLS */
2695
2696 bio = BIO_new(_httpBIOMethods());
2697 BIO_ctrl(bio, BIO_C_SET_FILE_PTR, 0, (char *)http);
2698
2699 conn = SSL_new(context);
2700 SSL_set_bio(conn, bio, bio);
2701
2702 if (SSL_connect(conn) != 1)
2703 {
2704 # ifdef DEBUG
2705 unsigned long error; /* Error code */
2706
2707 while ((error = ERR_get_error()) != 0)
2708 printf("http_setup_ssl: %s\n", ERR_error_string(error, NULL));
2709 # endif /* DEBUG */
2710
2711 SSL_CTX_free(context);
2712 SSL_free(conn);
2713
2714 # ifdef WIN32
2715 http->error = WSAGetLastError();
2716 # else
2717 http->error = errno;
2718 # endif /* WIN32 */
2719 http->status = HTTP_ERROR;
2720
2721 return (HTTP_ERROR);
2722 }
2723
2724 # elif defined(HAVE_GNUTLS)
2725 if ((conn = (http_tls_t *)malloc(sizeof(http_tls_t))) == NULL)
2726 {
2727 http->error = errno;
2728 http->status = HTTP_ERROR;
2729
2730 return (-1);
2731 }
2732
2733 credentials = (gnutls_certificate_client_credentials *)
2734 malloc(sizeof(gnutls_certificate_client_credentials));
2735 if (credentials == NULL)
2736 {
2737 free(conn);
2738
2739 http->error = errno;
2740 http->status = HTTP_ERROR;
2741
2742 return (-1);
2743 }
2744
2745 gnutls_certificate_allocate_credentials(credentials);
2746
2747 gnutls_init(&(conn->session), GNUTLS_CLIENT);
2748 gnutls_set_default_priority(conn->session);
2749 gnutls_credentials_set(conn->session, GNUTLS_CRD_CERTIFICATE, *credentials);
2750 gnutls_transport_set_ptr(conn->session, (gnutls_transport_ptr)http);
2751 gnutls_transport_set_pull_function(conn->session, _httpReadGNUTLS);
2752 gnutls_transport_set_push_function(conn->session, _httpWriteGNUTLS);
2753
2754 if ((gnutls_handshake(conn->session)) != GNUTLS_E_SUCCESS)
2755 {
2756 http->error = errno;
2757 http->status = HTTP_ERROR;
2758
2759 return (-1);
2760 }
2761
2762 conn->credentials = credentials;
2763
2764 # elif defined(HAVE_CDSASSL)
2765 conn = (http_tls_t *)calloc(1, sizeof(http_tls_t));
2766
2767 if (conn == NULL)
2768 return (-1);
2769
2770 if ((error = SSLNewContext(false, &conn->session)))
2771 {
2772 http->error = error;
2773 http->status = HTTP_ERROR;
2774
2775 free(conn);
2776 return (-1);
2777 }
2778
2779 /*
2780 * Use a union to resolve warnings about int/pointer size mismatches...
2781 */
2782
2783 error = SSLSetConnection(conn->session, http);
2784
2785 if (!error)
2786 error = SSLSetIOFuncs(conn->session, _httpReadCDSA, _httpWriteCDSA);
2787
2788 if (!error)
2789 error = SSLSetAllowsExpiredCerts(conn->session, true);
2790
2791 if (!error)
2792 error = SSLSetAllowsAnyRoot(conn->session, true);
2793
2794 if (!error)
2795 error = SSLSetProtocolVersionEnabled(conn->session, kSSLProtocol2, false);
2796
2797 if (!error)
2798 {
2799 while ((error = SSLHandshake(conn->session)) == errSSLWouldBlock)
2800 usleep(1000);
2801 }
2802
2803 if (error)
2804 {
2805 http->error = error;
2806 http->status = HTTP_ERROR;
2807
2808 SSLDisposeContext(conn->session);
2809
2810 free(conn);
2811
2812 return (-1);
2813 }
2814 # endif /* HAVE_CDSASSL */
2815
2816 http->tls = conn;
2817 return (0);
2818 }
2819 #endif /* HAVE_SSL */
2820
2821
2822 #ifdef HAVE_SSL
2823 /*
2824 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
2825 */
2826
2827 static void
2828 http_shutdown_ssl(http_t *http) /* I - Connection to server */
2829 {
2830 # ifdef HAVE_LIBSSL
2831 SSL_CTX *context; /* Context for encryption */
2832 SSL *conn; /* Connection for encryption */
2833
2834
2835 conn = (SSL *)(http->tls);
2836 context = SSL_get_SSL_CTX(conn);
2837
2838 SSL_shutdown(conn);
2839 SSL_CTX_free(context);
2840 SSL_free(conn);
2841
2842 # elif defined(HAVE_GNUTLS)
2843 http_tls_t *conn; /* Encryption session */
2844 gnutls_certificate_client_credentials *credentials;
2845 /* TLS credentials */
2846
2847
2848 conn = (http_tls_t *)(http->tls);
2849 credentials = (gnutls_certificate_client_credentials *)(conn->credentials);
2850
2851 gnutls_bye(conn->session, GNUTLS_SHUT_RDWR);
2852 gnutls_deinit(conn->session);
2853 gnutls_certificate_free_credentials(*credentials);
2854 free(credentials);
2855 free(conn);
2856
2857 # elif defined(HAVE_CDSASSL)
2858 http_tls_t *conn; /* CDSA connection information */
2859
2860
2861 conn = (http_tls_t *)(http->tls);
2862
2863 while (SSLClose(conn->session) == errSSLWouldBlock)
2864 usleep(1000);
2865
2866 SSLDisposeContext(conn->session);
2867
2868 if (conn->certsArray)
2869 CFRelease(conn->certsArray);
2870
2871 free(conn);
2872 # endif /* HAVE_LIBSSL */
2873
2874 http->tls = NULL;
2875 }
2876 #endif /* HAVE_SSL */
2877
2878
2879 #ifdef HAVE_SSL
2880 /*
2881 * 'http_upgrade()' - Force upgrade to TLS encryption.
2882 */
2883
2884 static int /* O - Status of connection */
2885 http_upgrade(http_t *http) /* I - Connection to server */
2886 {
2887 int ret; /* Return value */
2888 http_t myhttp; /* Local copy of HTTP data */
2889
2890
2891 DEBUG_printf(("http_upgrade(%p)\n", http));
2892
2893 /*
2894 * Copy the HTTP data to a local variable so we can do the OPTIONS
2895 * request without interfering with the existing request data...
2896 */
2897
2898 memcpy(&myhttp, http, sizeof(myhttp));
2899
2900 /*
2901 * Send an OPTIONS request to the server, requiring SSL or TLS
2902 * encryption on the link...
2903 */
2904
2905 http->field_authorization = NULL; /* Don't free the auth string */
2906
2907 httpClearFields(http);
2908 httpSetField(http, HTTP_FIELD_CONNECTION, "upgrade");
2909 httpSetField(http, HTTP_FIELD_UPGRADE, "TLS/1.0, SSL/2.0, SSL/3.0");
2910
2911 if ((ret = httpOptions(http, "*")) == 0)
2912 {
2913 /*
2914 * Wait for the secure connection...
2915 */
2916
2917 while (httpUpdate(http) == HTTP_CONTINUE);
2918 }
2919
2920 httpFlush(http);
2921
2922 /*
2923 * Restore the HTTP request data...
2924 */
2925
2926 memcpy(http->fields, myhttp.fields, sizeof(http->fields));
2927 http->data_encoding = myhttp.data_encoding;
2928 http->data_remaining = myhttp.data_remaining;
2929 http->_data_remaining = myhttp._data_remaining;
2930 http->expect = myhttp.expect;
2931 http->field_authorization = myhttp.field_authorization;
2932 http->digest_tries = myhttp.digest_tries;
2933
2934 /*
2935 * See if we actually went secure...
2936 */
2937
2938 if (!http->tls)
2939 {
2940 /*
2941 * Server does not support HTTP upgrade...
2942 */
2943
2944 DEBUG_puts("Server does not support HTTP upgrade!");
2945
2946 # ifdef WIN32
2947 closesocket(http->fd);
2948 # else
2949 close(http->fd);
2950 # endif
2951
2952 http->fd = -1;
2953
2954 return (-1);
2955 }
2956 else
2957 return (ret);
2958 }
2959 #endif /* HAVE_SSL */
2960
2961
2962 /*
2963 * 'http_wait()' - Wait for data available on a connection.
2964 */
2965
2966 static int /* O - 1 if data is available, 0 otherwise */
2967 http_wait(http_t *http, /* I - Connection to server */
2968 int msec, /* I - Milliseconds to wait */
2969 int usessl) /* I - Use SSL context? */
2970 {
2971 #ifdef HAVE_POLL
2972 struct pollfd pfd; /* Polled file descriptor */
2973 #else
2974 fd_set input_set; /* select() input set */
2975 struct timeval timeout; /* Timeout */
2976 #endif /* HAVE_POLL */
2977 int nfds; /* Result from select()/poll() */
2978
2979
2980 DEBUG_printf(("http_wait(http=%p, msec=%d)\n", http, msec));
2981
2982 if (http->fd < 0)
2983 return (0);
2984
2985 /*
2986 * Check the SSL/TLS buffers for data first...
2987 */
2988
2989 #ifdef HAVE_SSL
2990 if (http->tls && usessl)
2991 {
2992 # ifdef HAVE_LIBSSL
2993 if (SSL_pending((SSL *)(http->tls)))
2994 return (1);
2995 # elif defined(HAVE_GNUTLS)
2996 if (gnutls_record_check_pending(((http_tls_t *)(http->tls))->session))
2997 return (1);
2998 # elif defined(HAVE_CDSASSL)
2999 size_t bytes; /* Bytes that are available */
3000
3001 if (!SSLGetBufferedReadSize(((http_tls_t *)http->tls)->session, &bytes) && bytes > 0)
3002 return (1);
3003 # endif /* HAVE_LIBSSL */
3004 }
3005 #endif /* HAVE_SSL */
3006
3007 /*
3008 * Then try doing a select() or poll() to poll the socket...
3009 */
3010
3011 #ifdef HAVE_POLL
3012 pfd.fd = http->fd;
3013 pfd.events = POLLIN;
3014
3015 while ((nfds = poll(&pfd, 1, msec)) < 0 && errno == EINTR);
3016
3017 #else
3018 do
3019 {
3020 FD_ZERO(&input_set);
3021 FD_SET(http->fd, &input_set);
3022
3023 DEBUG_printf(("http_wait: msec=%d, http->fd=%d\n", msec, http->fd));
3024
3025 if (msec >= 0)
3026 {
3027 timeout.tv_sec = msec / 1000;
3028 timeout.tv_usec = (msec % 1000) * 1000;
3029
3030 nfds = select(http->fd + 1, &input_set, NULL, NULL, &timeout);
3031 }
3032 else
3033 nfds = select(http->fd + 1, &input_set, NULL, NULL, NULL);
3034
3035 DEBUG_printf(("http_wait: select() returned %d...\n", nfds));
3036 }
3037 # ifdef WIN32
3038 while (nfds < 0 && WSAGetLastError() == WSAEINTR);
3039 # else
3040 while (nfds < 0 && errno == EINTR);
3041 # endif /* WIN32 */
3042 #endif /* HAVE_POLL */
3043
3044 DEBUG_printf(("http_wait: returning with nfds=%d...\n", nfds));
3045
3046 return (nfds > 0);
3047 }
3048
3049
3050 /*
3051 * 'http_write()' - Write a buffer to a HTTP connection.
3052 */
3053
3054 static int /* O - Number of bytes written */
3055 http_write(http_t *http, /* I - Connection to server */
3056 const char *buffer, /* I - Buffer for data */
3057 int length) /* I - Number of bytes to write */
3058 {
3059 int tbytes, /* Total bytes sent */
3060 bytes; /* Bytes sent */
3061
3062
3063 tbytes = 0;
3064
3065 while (length > 0)
3066 {
3067 #ifdef HAVE_SSL
3068 if (http->tls)
3069 bytes = http_write_ssl(http, buffer, length);
3070 else
3071 #endif /* HAVE_SSL */
3072 bytes = send(http->fd, buffer, length, 0);
3073
3074 if (bytes < 0)
3075 {
3076 #ifdef WIN32
3077 if (WSAGetLastError() != http->error)
3078 {
3079 http->error = WSAGetLastError();
3080 continue;
3081 }
3082 #else
3083 if (errno == EINTR)
3084 continue;
3085 else if (errno != http->error && errno != ECONNRESET)
3086 {
3087 http->error = errno;
3088 continue;
3089 }
3090 #endif /* WIN32 */
3091
3092 DEBUG_puts("http_write: error writing data...\n");
3093
3094 return (-1);
3095 }
3096
3097 buffer += bytes;
3098 tbytes += bytes;
3099 length -= bytes;
3100 }
3101
3102 #ifdef DEBUG
3103 {
3104 int i, j, ch;
3105 printf("http_write: wrote %d bytes: \n", tbytes);
3106 for (i = 0, buffer -= tbytes; i < tbytes; i += 16)
3107 {
3108 printf(" ");
3109
3110 for (j = 0; j < 16 && (i + j) < tbytes; j ++)
3111 printf(" %02X", buffer[i + j] & 255);
3112
3113 while (j < 16)
3114 {
3115 printf(" ");
3116 j ++;
3117 }
3118
3119 printf(" ");
3120 for (j = 0; j < 16 && (i + j) < tbytes; j ++)
3121 {
3122 ch = buffer[i + j] & 255;
3123
3124 if (ch < ' ' || ch == 127)
3125 ch = '.';
3126
3127 putchar(ch);
3128 }
3129 putchar('\n');
3130 }
3131 }
3132 #endif /* DEBUG */
3133
3134 return (tbytes);
3135 }
3136
3137
3138 /*
3139 * 'http_write_chunk()' - Write a chunked buffer.
3140 */
3141
3142 static int /* O - Number bytes written */
3143 http_write_chunk(http_t *http, /* I - Connection to server */
3144 const char *buffer, /* I - Buffer to write */
3145 int length) /* I - Length of buffer */
3146 {
3147 char header[255]; /* Chunk header */
3148 int bytes; /* Bytes written */
3149
3150 DEBUG_printf(("http_write_chunk(http=%p, buffer=%p, length=%d)\n",
3151 http, buffer, length));
3152
3153 /*
3154 * Write the chunk header, data, and trailer.
3155 */
3156
3157 sprintf(header, "%x\r\n", length);
3158 if (http_write(http, header, (int)strlen(header)) < 0)
3159 {
3160 DEBUG_puts(" http_write of length failed!");
3161 return (-1);
3162 }
3163
3164 if ((bytes = http_write(http, buffer, length)) < 0)
3165 {
3166 DEBUG_puts(" http_write of buffer failed!");
3167 return (-1);
3168 }
3169
3170 if (http_write(http, "\r\n", 2) < 0)
3171 {
3172 DEBUG_puts(" http_write of CR LF failed!");
3173 return (-1);
3174 }
3175
3176 return (bytes);
3177 }
3178
3179
3180 #ifdef HAVE_SSL
3181 /*
3182 * 'http_write_ssl()' - Write to a SSL/TLS connection.
3183 */
3184
3185 static int /* O - Bytes written */
3186 http_write_ssl(http_t *http, /* I - Connection to server */
3187 const char *buf, /* I - Buffer holding data */
3188 int len) /* I - Length of buffer */
3189 {
3190 # if defined(HAVE_LIBSSL)
3191 return (SSL_write((SSL *)(http->tls), buf, len));
3192
3193 # elif defined(HAVE_GNUTLS)
3194 return (gnutls_record_send(((http_tls_t *)(http->tls))->session, buf, len));
3195 # elif defined(HAVE_CDSASSL)
3196 int result; /* Return value */
3197 OSStatus error; /* Error info */
3198 size_t processed; /* Number of bytes processed */
3199
3200
3201 error = SSLWrite(((http_tls_t *)http->tls)->session, buf, len, &processed);
3202
3203 switch (error)
3204 {
3205 case 0 :
3206 result = (int)processed;
3207 break;
3208 case errSSLClosedGraceful :
3209 result = 0;
3210 break;
3211 case errSSLWouldBlock :
3212 if (processed)
3213 result = (int)processed;
3214 else
3215 {
3216 result = -1;
3217 errno = EINTR;
3218 }
3219 break;
3220 default :
3221 errno = EPIPE;
3222 result = -1;
3223 break;
3224 }
3225
3226 return (result);
3227 # endif /* HAVE_LIBSSL */
3228 }
3229 #endif /* HAVE_SSL */
3230
3231
3232 /*
3233 * End of "$Id: http.c 6724 2007-07-25 20:39:33Z mike $".
3234 */