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