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