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