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