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