4 * HTTP routines for the Common UNIX Printing System (CUPS).
6 * Copyright 1997-2006 by Easy Software Products, all rights reserved.
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
15 * Attn: CUPS Licensing Information
16 * Easy Software Products
17 * 44141 Airport View Drive, Suite 204
18 * Hollywood, Maryland 20636 USA
20 * Voice: (301) 373-9600
21 * EMail: cups-info@cups.org
22 * WWW: http://www.cups.org
24 * This file is subject to the Apple OS-Developed Software exception.
28 * httpBlocking() - Set blocking/non-blocking behavior on a connection.
29 * httpCheck() - Check to see if there is a pending response from
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
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
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.
88 * Include necessary headers...
91 #include "http-private.h"
99 # include <sys/time.h>
100 # include <sys/resource.h>
105 * Some operating systems have done away with the Fxxxx constants for
106 * the fcntl() call; this works around that "feature"...
110 # define FNONBLK O_NONBLOCK
111 #endif /* !FNONBLK */
118 static http_field_t
http_field(const char *name
);
119 static int http_send(http_t
*http
, http_state_t request
,
121 static int http_wait(http_t
*http
, int msec
);
122 static int http_write(http_t
*http
, const char *buffer
,
124 static int http_write_chunk(http_t
*http
, const char *buffer
,
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 */
139 static const char * const http_fields
[] =
156 "If-Unmodified-since",
172 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
176 httpBlocking(http_t
*http
, /* I - HTTP connection */
177 int b
) /* I - 1 = blocking, 0 = non-blocking */
185 * 'httpCheck()' - Check to see if there is a pending response from the server.
188 int /* O - 0 = no data, 1 = data available */
189 httpCheck(http_t
*http
) /* I - HTTP connection */
191 return (httpWait(http
, 0));
196 * 'httpClearCookie()' - Clear the cookie value(s).
198 * @since CUPS 1.1.19@
202 httpClearCookie(http_t
*http
) /* I - HTTP connection */
216 * 'httpClearFields()' - Clear HTTP request fields.
220 httpClearFields(http_t
*http
) /* I - HTTP connection */
224 memset(http
->fields
, 0, sizeof(http
->fields
));
225 httpSetField(http
, HTTP_FIELD_HOST
, http
->hostname
);
227 http
->expect
= (http_status_t
)0;
233 * 'httpClose()' - Close an HTTP connection...
237 httpClose(http_t
*http
) /* I - HTTP connection */
239 DEBUG_printf(("httpClose(http=%p)\n", http
));
244 httpAddrFreeList(http
->addrlist
);
247 free(http
->input_set
);
254 http_shutdown_ssl(http
);
255 #endif /* HAVE_SSL */
258 closesocket(http
->fd
);
268 * 'httpConnect()' - Connect to a HTTP server.
271 http_t
* /* O - New HTTP connection */
272 httpConnect(const char *host
, /* I - Host to connect to */
273 int port
) /* I - Port number */
275 http_encryption_t encryption
; /* Type of encryption to use */
279 * Set the default encryption status...
283 encryption
= HTTP_ENCRYPT_ALWAYS
;
285 encryption
= HTTP_ENCRYPT_IF_REQUESTED
;
287 return (httpConnectEncrypt(host
, port
, encryption
));
292 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
295 http_t
* /* O - New HTTP connection */
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 */
301 http_t
*http
; /* New HTTP connection */
302 http_addrlist_t
*addrlist
; /* Host address data */
303 char service
[255]; /* Service name */
306 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)\n",
307 host
? host
: "(null)", port
, encryption
));
318 sprintf(service
, "%d", port
);
320 if ((addrlist
= httpAddrGetList(host
, AF_UNSPEC
, service
)) == NULL
)
324 * Allocate memory for the structure...
327 http
= calloc(sizeof(http_t
), 1);
331 http
->version
= HTTP_1_1
;
333 http
->activity
= time(NULL
);
337 * Set the encryption status...
340 if (port
== 443) /* Always use encryption for https */
341 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
343 http
->encryption
= encryption
;
346 * Loop through the addresses we have until one of them connects...
349 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
352 * Connect to the remote system...
355 http
->addrlist
= addrlist
;
357 if (!httpReconnect(http
))
361 * Could not connect to any known address - bail out!
364 httpAddrFreeList(addrlist
);
373 * 'httpDelete()' - Send a DELETE request to the server.
376 int /* O - Status of call (0 = success) */
377 httpDelete(http_t
*http
, /* I - HTTP connection */
378 const char *uri
) /* I - URI to delete */
380 return (http_send(http
, HTTP_DELETE
, uri
));
385 * 'httpEncryption()' - Set the required encryption on the link.
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 */
392 DEBUG_printf(("httpEncryption(http=%p, e=%d)\n", http
, e
));
398 http
->encryption
= e
;
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
));
408 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
412 #endif /* HAVE_SSL */
417 * 'httpError()' - Get the last error on a connection.
420 int /* O - Error code (errno) value */
421 httpError(http_t
*http
) /* I - HTTP connection */
424 return (http
->error
);
431 * 'httpFlush()' - Flush data from a HTTP connection.
435 httpFlush(http_t
*http
) /* I - HTTP connection */
437 char buffer
[8192]; /* Junk buffer */
438 int blocking
; /* To block or not to block */
441 DEBUG_printf(("httpFlush(http=%p), state=%d\n", http
, http
->state
));
444 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
447 blocking
= http
->blocking
;
451 * Read any data we can...
454 while (httpRead2(http
, buffer
, sizeof(buffer
)) > 0);
457 * Restore blocking and reset the connection if we didn't get all of
458 * the remaining data...
461 http
->blocking
= blocking
;
463 if (http
->state
!= HTTP_WAITING
&& http
->fd
>= 0)
466 * Didn't get the data back, so close the current connection.
469 http
->state
= HTTP_WAITING
;
473 http_shutdown_ssl(http
);
474 #endif /* HAVE_SSL */
477 closesocket(http
->fd
);
488 * 'httpFlushWrite()' - Flush data in write buffer.
493 int /* O - Bytes written or -1 on error */
494 httpFlushWrite(http_t
*http
) /* I - HTTP connection */
496 int bytes
; /* Bytes written */
499 DEBUG_printf(("httpFlushWrite(http=%p)\n", http
));
501 if (!http
|| !http
->wused
)
504 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
505 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
507 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
516 * 'httpGet()' - Send a GET request to the server.
519 int /* O - Status of call (0 = success) */
520 httpGet(http_t
*http
, /* I - HTTP connection */
521 const char *uri
) /* I - URI to get */
523 return (http_send(http
, HTTP_GET
, uri
));
528 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
533 int /* O - 1 if blocking, 0 if non-blocking */
534 httpGetBlocking(http_t
*http
) /* I - HTTP connection */
536 return (http
? http
->blocking
: 0);
541 * 'httpGetCookie()' - Get any cookie data from the response.
544 const char * /* O - Cookie data or NULL */
545 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
547 return (http
? http
->cookie
: NULL
);
552 * 'httpGetFd()' - Get the file descriptor associated with a connection.
557 int /* O - File descriptor or -1 if none */
558 httpGetFd(http_t
*http
) /* I - HTTP connection */
560 return (http
? http
->fd
: -1);
565 * 'httpGetField()' - Get a field value from a request/response.
568 const char * /* O - Field value */
569 httpGetField(http_t
*http
, /* I - HTTP connection */
570 http_field_t field
) /* I - Field to get */
572 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
575 return (http
->fields
[field
]);
580 * 'httpGetLength()' - Get the amount of data remaining from the
581 * content-length or transfer-encoding fields.
583 * This function is deprecated and will not return lengths larger than
584 * 2^31 - 1; use httpGetLength2() instead.
589 int /* O - Content length */
590 httpGetLength(http_t
*http
) /* I - HTTP connection */
593 * Get the read content length and return the 32-bit value.
598 httpGetLength2(http
);
600 return (http
->_data_remaining
);
608 * 'httpGetLength2()' - Get the amount of data remaining from the
609 * content-length or transfer-encoding fields.
611 * This function returns the complete content length, even for
612 * content larger than 2^31 - 1.
617 off_t
/* O - Content length */
618 httpGetLength2(http_t
*http
) /* I - HTTP connection */
620 DEBUG_printf(("httpGetLength2(http=%p), state=%d\n", http
, http
->state
));
625 if (!strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
627 DEBUG_puts("httpGetLength2: chunked request!");
629 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
630 http
->data_remaining
= 0;
634 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
637 * The following is a hack for HTTP servers that don't send a
638 * content-length or transfer-encoding field...
640 * If there is no content-length then the connection must close
641 * after the transfer is complete...
644 if (http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] == '\0')
645 http
->data_remaining
= 2147483647;
647 http
->data_remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
650 DEBUG_printf(("httpGetLength2: content_length=" CUPS_LLFMT
"\n",
651 CUPS_LLCAST http
->data_remaining
));
654 if (http
->data_remaining
<= INT_MAX
)
655 http
->_data_remaining
= (int)http
->data_remaining
;
657 http
->_data_remaining
= INT_MAX
;
659 return (http
->data_remaining
);
664 * 'httpGetStatus()' - Get the status of the last HTTP request.
669 http_status_t
/* O - HTTP status */
670 httpGetStatus(http_t
*http
) /* I - HTTP connection */
672 return (http
? http
->status
: HTTP_ERROR
);
677 * 'httpGetSubField()' - Get a sub-field value.
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 */
688 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
693 * 'httpGetSubField2()' - Get a sub-field value.
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 */
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 */
710 DEBUG_printf(("httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, valuelen=%d)\n",
711 http
, field
, name
, value
, valuelen
));
713 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
714 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
717 end
= value
+ valuelen
- 1;
719 for (fptr
= http
->fields
[field
]; *fptr
;)
722 * Skip leading whitespace...
725 while (isspace(*fptr
& 255))
735 * Get the sub-field name...
739 *fptr
&& *fptr
!= '=' && !isspace(*fptr
& 255) &&
740 ptr
< (temp
+ sizeof(temp
) - 1);
745 DEBUG_printf(("httpGetSubField: name=\"%s\"\n", temp
));
748 * Skip trailing chars up to the '='...
751 while (isspace(*fptr
& 255))
761 * Skip = and leading whitespace...
766 while (isspace(*fptr
& 255))
772 * Read quoted string...
775 for (ptr
= value
, fptr
++;
776 *fptr
&& *fptr
!= '\"' && ptr
< end
;
781 while (*fptr
&& *fptr
!= '\"')
790 * Read unquoted string...
794 *fptr
&& !isspace(*fptr
& 255) && *fptr
!= ',' && ptr
< end
;
799 while (*fptr
&& !isspace(*fptr
& 255) && *fptr
!= ',')
803 DEBUG_printf(("httpGetSubField: value=\"%s\"\n", value
));
806 * See if this is the one...
809 if (!strcmp(name
, temp
))
820 * 'httpGets()' - Get a line of text from a HTTP connection.
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 */
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? */
836 DEBUG_printf(("httpGets(line=%p, length=%d, http=%p)\n", line
, length
, http
));
838 if (http
== NULL
|| line
== NULL
)
842 * Read a line from the buffer...
846 lineend
= line
+ length
- 1;
849 while (lineptr
< lineend
)
852 * Pre-load the buffer as needed...
861 while (http
->used
== 0)
864 * No newline; see if there is more data to be read...
867 if (!http
->blocking
&& !http_wait(http
, 1000))
872 bytes
= http_read_ssl(http
, http
->buffer
+ http
->used
,
873 HTTP_MAX_BUFFER
- http
->used
);
875 #endif /* HAVE_SSL */
876 bytes
= recv(http
->fd
, http
->buffer
+ http
->used
,
877 HTTP_MAX_BUFFER
- http
->used
, 0);
879 DEBUG_printf(("httpGets: read %d bytes...\n", bytes
));
884 * Nope, can't get a line this time...
888 if (WSAGetLastError() != http
->error
)
890 http
->error
= WSAGetLastError();
894 DEBUG_printf(("httpGets: recv() error %d!\n", WSAGetLastError()));
896 DEBUG_printf(("httpGets: recv() error %d!\n", errno
));
900 else if (errno
!= http
->error
)
917 * Yup, update the amount used...
924 * Now copy as much of the current line as possible...
927 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
928 lineptr
< lineend
&& bufptr
< bufend
;)
936 else if (*bufptr
== 0x0d)
939 *lineptr
++ = *bufptr
++;
942 http
->used
-= bufptr
- http
->buffer
;
944 memmove(http
->buffer
, bufptr
, http
->used
);
952 http
->activity
= time(NULL
);
956 DEBUG_printf(("httpGets: Returning \"%s\"\n", line
));
962 DEBUG_puts("httpGets: No new line available!");
969 * 'httpHead()' - Send a HEAD request to the server.
972 int /* O - Status of call (0 = success) */
973 httpHead(http_t
*http
, /* I - HTTP connection */
974 const char *uri
) /* I - URI for head */
976 return (http_send(http
, HTTP_HEAD
, uri
));
981 * 'httpInitialize()' - Initialize the HTTP interface library and set the
982 * default HTTP proxy (if any).
990 struct timeval curtime
; /* Current time in microseconds */
992 int i
; /* Looping var */
993 unsigned char data
[1024]; /* Seed data */
994 #endif /* HAVE_LIBSSL */
997 WSADATA winsockdata
; /* WinSock data */
998 static int initialized
= 0; /* Has WinSock been initialized? */
1002 WSAStartup(MAKEWORD(1,1), &winsockdata
);
1003 #elif !defined(SO_NOSIGPIPE)
1005 * Ignore SIGPIPE signals...
1009 sigset(SIGPIPE
, SIG_IGN
);
1010 # elif defined(HAVE_SIGACTION)
1011 struct sigaction action
; /* POSIX sigaction data */
1014 memset(&action
, 0, sizeof(action
));
1015 action
.sa_handler
= SIG_IGN
;
1016 sigaction(SIGPIPE
, &action
, NULL
);
1018 signal(SIGPIPE
, SIG_IGN
);
1019 # endif /* !SO_NOSIGPIPE */
1023 gnutls_global_init();
1024 #endif /* HAVE_GNUTLS */
1027 SSL_load_error_strings();
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...)
1037 gettimeofday(&curtime
, NULL
);
1038 srand(curtime
.tv_sec
+ curtime
.tv_usec
);
1041 for (i
= 0; i
< sizeof(data
); i
++)
1042 data
[i
] = rand(); /* Yes, this is a poor source of random data... */
1044 RAND_seed(&data
, sizeof(data
));
1045 #endif /* HAVE_LIBSSL */
1050 * 'httpOptions()' - Send an OPTIONS request to the server.
1053 int /* O - Status of call (0 = success) */
1054 httpOptions(http_t
*http
, /* I - HTTP connection */
1055 const char *uri
) /* I - URI for options */
1057 return (http_send(http
, HTTP_OPTIONS
, uri
));
1062 * 'httpPost()' - Send a POST request to the server.
1065 int /* O - Status of call (0 = success) */
1066 httpPost(http_t
*http
, /* I - HTTP connection */
1067 const char *uri
) /* I - URI for post */
1069 return (http_send(http
, HTTP_POST
, uri
));
1074 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
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 */
1084 int bytes
; /* Number of bytes to write */
1085 char buf
[16384]; /* Buffer for formatted string */
1086 va_list ap
; /* Variable argument pointer */
1089 DEBUG_printf(("httpPrintf(http=%p, format=\"%s\", ...)\n", http
, format
));
1091 va_start(ap
, format
);
1092 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1095 DEBUG_printf(("httpPrintf: %s", buf
));
1099 DEBUG_puts(" flushing existing data...");
1101 if (httpFlushWrite(http
) < 0)
1105 return (http_write(http
, buf
, bytes
));
1110 * 'httpPut()' - Send a PUT request to the server.
1113 int /* O - Status of call (0 = success) */
1114 httpPut(http_t
*http
, /* I - HTTP connection */
1115 const char *uri
) /* I - URI to put */
1117 return (http_send(http
, HTTP_PUT
, uri
));
1122 * 'httpRead()' - Read data from a HTTP connection.
1124 * This function is deprecated. Use the httpRead2() function which can
1125 * read more than 2GB of data.
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 */
1135 return ((int)httpRead2(http
, buffer
, length
));
1140 * 'httpRead2()' - Read data from a HTTP connection.
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 */
1150 ssize_t bytes
; /* Bytes read */
1151 char len
[32]; /* Length string */
1154 DEBUG_printf(("httpRead(http=%p, buffer=%p, length=%d)\n",
1155 http
, buffer
, length
));
1157 if (http
== NULL
|| buffer
== NULL
)
1160 http
->activity
= time(NULL
);
1165 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1166 http
->data_remaining
<= 0)
1168 DEBUG_puts("httpRead2: Getting chunk length...");
1170 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1172 DEBUG_puts("httpRead2: Could not get length!");
1176 http
->data_remaining
= strtoll(len
, NULL
, 16);
1177 if (http
->data_remaining
< 0)
1179 DEBUG_puts("httpRead2: Negative chunk length!");
1184 DEBUG_printf(("httpRead2: data_remaining=" CUPS_LLFMT
"\n",
1185 CUPS_LLCAST http
->data_remaining
));
1187 if (http
->data_remaining
<= 0)
1190 * A zero-length chunk ends a transfer; unless we are reading POST
1194 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1195 httpGets(len
, sizeof(len
), http
);
1197 if (http
->state
== HTTP_POST_RECV
)
1200 http
->state
= HTTP_WAITING
;
1203 * Prevent future reads for this request...
1206 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1210 else if (length
> http
->data_remaining
)
1211 length
= http
->data_remaining
;
1213 if (http
->used
== 0 && length
<= 256)
1216 * Buffer small reads for better performance...
1219 if (!http
->blocking
&& !httpWait(http
, 1000))
1222 if (http
->data_remaining
> sizeof(http
->buffer
))
1223 bytes
= sizeof(http
->buffer
);
1225 bytes
= http
->data_remaining
;
1229 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1231 #endif /* HAVE_SSL */
1233 DEBUG_printf(("httpRead2: reading %d bytes from socket into buffer...\n",
1236 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1238 DEBUG_printf(("httpRead2: read %d bytes from socket into buffer...\n",
1247 http
->error
= WSAGetLastError();
1252 http
->error
= errno
;
1259 http
->error
= EPIPE
;
1266 if (length
> http
->used
)
1267 length
= http
->used
;
1271 DEBUG_printf(("httpRead2: grabbing %d bytes from input buffer...\n", bytes
));
1273 memcpy(buffer
, http
->buffer
, length
);
1274 http
->used
-= length
;
1277 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
1282 if (!http
->blocking
&& !httpWait(http
, 1000))
1285 bytes
= http_read_ssl(http
, buffer
, length
);
1287 #endif /* HAVE_SSL */
1290 if (!http
->blocking
&& !httpWait(http
, 1000))
1293 DEBUG_printf(("httpRead2: reading %d bytes from socket...\n", length
));
1295 while ((bytes
= recv(http
->fd
, buffer
, length
, 0)) < 0)
1299 DEBUG_printf(("httpRead2: read %d bytes from socket...\n", bytes
));
1304 http
->data_remaining
-= bytes
;
1306 if (http
->data_remaining
<= INT_MAX
)
1307 http
->_data_remaining
= (int)http
->data_remaining
;
1309 http
->_data_remaining
= INT_MAX
;
1314 http
->error
= WSAGetLastError();
1319 http
->error
= errno
;
1324 http
->error
= EPIPE
;
1328 if (http
->data_remaining
== 0)
1330 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1331 httpGets(len
, sizeof(len
), http
);
1333 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
1335 if (http
->state
== HTTP_POST_RECV
)
1338 http
->state
= HTTP_WAITING
;
1345 printf("httpRead2: Read %d bytes:\n", bytes
);
1346 for (i
= 0; i
< bytes
; i
+= 16)
1350 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1351 printf(" %02X", buffer
[i
+ j
] & 255);
1360 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1362 ch
= buffer
[i
+ j
] & 255;
1364 if (ch
< ' ' || ch
>= 127)
1378 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
1380 * '_httpReadCDSA()' - Read function for CDSA decryption code.
1383 OSStatus
/* O - -1 on error, 0 on success */
1385 SSLConnectionRef connection
, /* I - SSL/TLS connection */
1386 void *data
, /* I - Data buffer */
1387 size_t *dataLength
) /* IO - Number of bytes */
1389 OSStatus result
; /* Return value */
1390 ssize_t bytes
; /* Number of bytes read */
1395 bytes
= recv((int)connection
, data
, *dataLength
, 0);
1399 result
= (bytes
== *dataLength
);
1400 *dataLength
= bytes
;
1406 return (errSSLClosedAbort
);
1408 if (errno
== EAGAIN
)
1409 return (errSSLWouldBlock
);
1412 return (errSSLClosedAbort
);
1415 return (errSSLInternal
);
1418 #endif /* HAVE_SSL && HAVE_CDSASSL */
1422 * 'httpReconnect()' - Reconnect to a HTTP server.
1425 int /* O - 0 on success, non-zero on failure */
1426 httpReconnect(http_t
*http
) /* I - HTTP connection */
1428 http_addrlist_t
*addr
; /* Connected address */
1431 DEBUG_printf(("httpReconnect(http=%p)\n", http
));
1438 http_shutdown_ssl(http
);
1439 #endif /* HAVE_SSL */
1442 * Close any previously open socket...
1448 closesocket(http
->fd
);
1457 * Connect to the server...
1460 if ((addr
= httpAddrConnect(http
->addrlist
, &(http
->fd
))) == NULL
)
1463 * Unable to connect...
1467 http
->error
= WSAGetLastError();
1469 http
->error
= errno
;
1471 http
->status
= HTTP_ERROR
;
1476 http
->hostaddr
= &(addr
->addr
);
1478 http
->status
= HTTP_CONTINUE
;
1481 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
1484 * Always do encryption via SSL.
1487 if (http_setup_ssl(http
) != 0)
1490 closesocket(http
->fd
);
1498 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
1499 return (http_upgrade(http
));
1500 #endif /* HAVE_SSL */
1507 * 'httpSetCookie()' - Set the cookie value(s)...
1509 * @since CUPS 1.1.19@
1513 httpSetCookie(http_t
*http
, /* I - Connection */
1514 const char *cookie
) /* I - Cookie string */
1523 http
->cookie
= strdup(cookie
);
1525 http
->cookie
= NULL
;
1530 * 'httpSetExpect()' - Set the Expect: header in a request.
1532 * Currently only HTTP_CONTINUE is supported for the "expect" argument.
1538 httpSetExpect(http_t
*http
, /* I - HTTP connection */
1539 http_status_t expect
) /* I - HTTP status to expect (HTTP_CONTINUE) */
1542 http
->expect
= expect
;
1547 * 'httpSetField()' - Set the value of an HTTP header.
1551 httpSetField(http_t
*http
, /* I - HTTP connection */
1552 http_field_t field
, /* I - Field index */
1553 const char *value
) /* I - Value */
1556 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
1557 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
1561 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
1566 * 'httpSetLength()' - Set the content-length and content-encoding.
1572 httpSetLength(http_t
*http
, /* I - HTTP connection */
1573 size_t length
) /* I - Length (0 for chunked) */
1580 strcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked");
1581 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
1585 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
1586 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
1587 CUPS_LLFMT
, CUPS_LLCAST length
);
1593 * 'httpTrace()' - Send an TRACE request to the server.
1596 int /* O - Status of call (0 = success) */
1597 httpTrace(http_t
*http
, /* I - HTTP connection */
1598 const char *uri
) /* I - URI for trace */
1600 return (http_send(http
, HTTP_TRACE
, uri
));
1605 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1608 http_status_t
/* O - HTTP status */
1609 httpUpdate(http_t
*http
) /* I - HTTP connection */
1611 char line
[32768], /* Line from connection... */
1612 *value
; /* Pointer to value on line */
1613 http_field_t field
; /* Field index */
1614 int major
, minor
, /* HTTP version numbers */
1615 status
; /* Request status */
1618 DEBUG_printf(("httpUpdate(http=%p), state=%d\n", http
, http
->state
));
1621 * Flush pending data, if any...
1626 DEBUG_puts(" flushing buffer...");
1628 if (httpFlushWrite(http
) < 0)
1629 return (HTTP_ERROR
);
1633 * If we haven't issued any commands, then there is nothing to "update"...
1636 if (http
->state
== HTTP_WAITING
)
1637 return (HTTP_CONTINUE
);
1640 * Grab all of the lines we can from the connection...
1643 while (httpGets(line
, sizeof(line
), http
) != NULL
)
1645 DEBUG_printf(("httpUpdate: Got \"%s\"\n", line
));
1647 if (line
[0] == '\0')
1650 * Blank line means the start of the data section (if any). Return
1651 * the result code, too...
1653 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
1654 * Instead, we just return HTTP_CONTINUE to the caller and keep on
1658 if (http
->status
== HTTP_CONTINUE
)
1659 return (http
->status
);
1661 if (http
->status
< HTTP_BAD_REQUEST
)
1662 http
->digest_tries
= 0;
1665 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
1667 if (http_setup_ssl(http
) != 0)
1670 closesocket(http
->fd
);
1675 return (HTTP_ERROR
);
1678 return (HTTP_CONTINUE
);
1680 #endif /* HAVE_SSL */
1682 httpGetLength2(http
);
1684 switch (http
->state
)
1688 case HTTP_POST_RECV
:
1691 case HTTP_POST_SEND
:
1695 http
->state
= HTTP_WAITING
;
1699 return (http
->status
);
1701 else if (strncmp(line
, "HTTP/", 5) == 0)
1704 * Got the beginning of a response...
1707 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &status
) != 3)
1708 return (HTTP_ERROR
);
1710 http
->version
= (http_version_t
)(major
* 100 + minor
);
1711 http
->status
= (http_status_t
)status
;
1713 else if ((value
= strchr(line
, ':')) != NULL
)
1720 while (isspace(*value
& 255))
1724 * Be tolerants of servers that send unknown attribute fields...
1727 if (!strcasecmp(line
, "expect"))
1730 * "Expect: 100-continue" or similar...
1733 http
->expect
= (http_status_t
)atoi(value
);
1735 else if (!strcasecmp(line
, "cookie"))
1738 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
1741 httpSetCookie(http
, value
);
1743 else if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
1745 DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line
));
1749 httpSetField(http
, field
, value
);
1753 http
->status
= HTTP_ERROR
;
1754 return (HTTP_ERROR
);
1759 * See if there was an error...
1762 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
1763 return (http
->status
);
1767 DEBUG_printf(("httpUpdate: socket error %d - %s\n", http
->error
,
1768 strerror(http
->error
)));
1769 http
->status
= HTTP_ERROR
;
1770 return (HTTP_ERROR
);
1774 * If we haven't already returned, then there is nothing new...
1777 return (HTTP_CONTINUE
);
1782 * 'httpWait()' - Wait for data available on a connection.
1784 * @since CUPS 1.1.19@
1787 int /* O - 1 if data is available, 0 otherwise */
1788 httpWait(http_t
*http
, /* I - HTTP connection */
1789 int msec
) /* I - Milliseconds to wait */
1792 * First see if there is data in the buffer...
1802 * If not, check the SSL/TLS buffers and do a select() on the connection...
1805 return (http_wait(http
, msec
));
1810 * 'httpWrite()' - Write data to a HTTP connection.
1812 * This function is deprecated. Use the httpWrite2() function which can
1813 * write more than 2GB of data.
1818 int /* O - Number of bytes written */
1819 httpWrite(http_t
*http
, /* I - HTTP connection */
1820 const char *buffer
, /* I - Buffer for data */
1821 int length
) /* I - Number of bytes to write */
1823 return ((int)httpWrite2(http
, buffer
, length
));
1828 * 'httpWrite2()' - Write data to a HTTP connection.
1833 ssize_t
/* O - Number of bytes written */
1834 httpWrite2(http_t
*http
, /* I - HTTP connection */
1835 const char *buffer
, /* I - Buffer for data */
1836 size_t length
) /* I - Number of bytes to write */
1838 ssize_t bytes
; /* Bytes written */
1841 DEBUG_printf(("httpWrite(http=%p, buffer=%p, length=%d)\n", http
,
1845 * Range check input...
1848 if (http
== NULL
|| buffer
== NULL
)
1852 * Mark activity on the connection...
1855 http
->activity
= time(NULL
);
1858 * Buffer small writes for better performance...
1863 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
1865 DEBUG_printf((" flushing buffer (wused=%d, length=%d)\n",
1866 http
->wused
, length
));
1868 httpFlushWrite(http
);
1871 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
))
1874 * Write to buffer...
1877 DEBUG_printf((" copying %d bytes to wbuffer...\n", length
));
1879 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
1880 http
->wused
+= length
;
1886 * Otherwise write the data directly...
1889 DEBUG_printf((" writing %d bytes to socket...\n", length
));
1891 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1892 bytes
= http_write_chunk(http
, buffer
, length
);
1894 bytes
= http_write(http
, buffer
, length
);
1896 DEBUG_printf((" wrote %d bytes...\n", bytes
));
1899 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1900 http
->data_remaining
-= bytes
;
1906 * Handle end-of-request processing...
1909 if ((http
->data_encoding
== HTTP_ENCODE_CHUNKED
&& length
== 0) ||
1910 (http
->data_encoding
== HTTP_ENCODE_LENGTH
&& http
->data_remaining
== 0))
1913 * Finished with the transfer; unless we are sending POST or PUT
1917 DEBUG_puts("httpWrite: changing states...");
1920 httpFlushWrite(http
);
1922 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1925 * Send a 0-length chunk at the end of the request...
1928 http_write(http
, "0\r\n\r\n", 5);
1931 * Reset the data state...
1934 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1935 http
->data_remaining
= 0;
1938 if (http
->state
== HTTP_POST_RECV
)
1940 else if (http
->state
== HTTP_PUT_RECV
)
1941 http
->state
= HTTP_STATUS
;
1943 http
->state
= HTTP_WAITING
;
1950 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
1952 * '_httpWriteCDSA()' - Write function for CDSA encryption code.
1955 OSStatus
/* O - -1 on error, 0 on success */
1957 SSLConnectionRef connection
, /* I - SSL/TLS connection */
1958 const void *data
, /* I - Data buffer */
1959 size_t *dataLength
) /* IO - Number of bytes */
1961 OSStatus result
; /* Return value */
1962 ssize_t bytes
; /* Number of bytes read */
1967 bytes
= write((int)connection
, data
, *dataLength
);
1971 result
= (bytes
== *dataLength
) ? 0 : errSSLWouldBlock
;
1972 *dataLength
= bytes
;
1977 if (errno
== EAGAIN
)
1978 return (errSSLWouldBlock
);
1981 return (errSSLClosedAbort
);
1984 return (errSSLInternal
);
1987 #endif /* HAVE_SSL && HAVE_CDSASSL */
1991 * 'http_field()' - Return the field index for a field name.
1994 static http_field_t
/* O - Field index */
1995 http_field(const char *name
) /* I - String name */
1997 int i
; /* Looping var */
2000 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2001 if (strcasecmp(name
, http_fields
[i
]) == 0)
2002 return ((http_field_t
)i
);
2004 return (HTTP_FIELD_UNKNOWN
);
2010 * 'http_read_ssl()' - Read from a SSL/TLS connection.
2013 static int /* O - Bytes read */
2014 http_read_ssl(http_t
*http
, /* I - HTTP connection */
2015 char *buf
, /* I - Buffer to store data */
2016 int len
) /* I - Length of buffer */
2018 # if defined(HAVE_LIBSSL)
2019 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
2021 # elif defined(HAVE_GNUTLS)
2022 return (gnutls_record_recv(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
2024 # elif defined(HAVE_CDSASSL)
2025 int result
; /* Return value */
2026 OSStatus error
; /* Error info */
2027 size_t processed
; /* Number of bytes processed */
2030 error
= SSLRead((SSLContextRef
)http
->tls
, buf
, len
, &processed
);
2035 result
= (int)processed
;
2037 case errSSLClosedGraceful
:
2040 case errSSLWouldBlock
:
2051 # endif /* HAVE_LIBSSL */
2053 #endif /* HAVE_SSL */
2057 * 'http_send()' - Send a request with all fields and the trailing blank line.
2060 static int /* O - 0 on success, non-zero on error */
2061 http_send(http_t
*http
, /* I - HTTP connection */
2062 http_state_t request
, /* I - Request code */
2063 const char *uri
) /* I - URI */
2065 int i
; /* Looping var */
2066 char *ptr
, /* Pointer in buffer */
2067 buf
[1024]; /* Encoded URI buffer */
2068 static const char * const codes
[] =
2069 { /* Request code strings */
2084 static const char hex
[] = "0123456789ABCDEF";
2088 DEBUG_printf(("http_send(http=%p, request=HTTP_%s, uri=\"%s\")\n",
2089 http
, codes
[request
], uri
));
2091 if (http
== NULL
|| uri
== NULL
)
2095 * Set the User-Agent field if it isn't already...
2098 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
2099 httpSetField(http
, HTTP_FIELD_USER_AGENT
, CUPS_MINIMAL
);
2102 * Encode the URI as needed...
2105 for (ptr
= buf
; *uri
!= '\0' && ptr
< (buf
+ sizeof(buf
) - 1); uri
++)
2106 if (*uri
<= ' ' || *uri
>= 127)
2108 if (ptr
< (buf
+ sizeof(buf
) - 1))
2110 if (ptr
< (buf
+ sizeof(buf
) - 1))
2111 *ptr
++ = hex
[(*uri
>> 4) & 15];
2112 if (ptr
< (buf
+ sizeof(buf
) - 1))
2113 *ptr
++ = hex
[*uri
& 15];
2121 * See if we had an error the last time around; if so, reconnect...
2124 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
2125 if (httpReconnect(http
))
2129 * Send the request header...
2132 http
->state
= request
;
2133 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
2136 http
->status
= HTTP_CONTINUE
;
2139 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
2141 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
2142 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
2144 #endif /* HAVE_SSL */
2146 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
2148 http
->status
= HTTP_ERROR
;
2152 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2153 if (http
->fields
[i
][0] != '\0')
2155 DEBUG_printf(("%s: %s\n", http_fields
[i
], http
->fields
[i
]));
2157 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], http
->fields
[i
]) < 1)
2159 http
->status
= HTTP_ERROR
;
2165 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
2167 http
->status
= HTTP_ERROR
;
2171 if (http
->expect
== HTTP_CONTINUE
&&
2172 (http
->state
== HTTP_POST_RECV
|| http
->state
== HTTP_PUT_RECV
))
2173 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
2175 http
->status
= HTTP_ERROR
;
2179 if (httpPrintf(http
, "\r\n") < 1)
2181 http
->status
= HTTP_ERROR
;
2185 httpGetLength2(http
);
2186 httpClearFields(http
);
2194 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
2197 static int /* O - Status of connection */
2198 http_setup_ssl(http_t
*http
) /* I - HTTP connection */
2201 SSL_CTX
*context
; /* Context for encryption */
2202 SSL
*conn
; /* Connection for encryption */
2203 # elif defined(HAVE_GNUTLS)
2204 http_tls_t
*conn
; /* TLS session object */
2205 gnutls_certificate_client_credentials
*credentials
;
2206 /* TLS credentials */
2207 # elif defined(HAVE_CDSASSL)
2208 SSLContextRef conn
; /* Context for encryption */
2209 OSStatus error
; /* Error info */
2210 # endif /* HAVE_LIBSSL */
2213 DEBUG_printf(("http_setup_ssl(http=%p)\n", http
));
2216 context
= SSL_CTX_new(SSLv23_client_method());
2218 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
2220 conn
= SSL_new(context
);
2222 SSL_set_fd(conn
, http
->fd
);
2223 if (SSL_connect(conn
) != 1)
2226 unsigned long error
; /* Error code */
2228 while ((error
= ERR_get_error()) != 0)
2229 printf("http_setup_ssl: %s\n", ERR_error_string(error
, NULL
));
2232 SSL_CTX_free(context
);
2236 http
->error
= WSAGetLastError();
2238 http
->error
= errno
;
2240 http
->status
= HTTP_ERROR
;
2242 return (HTTP_ERROR
);
2245 # elif defined(HAVE_GNUTLS)
2246 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
2250 http
->error
= errno
;
2251 http
->status
= HTTP_ERROR
;
2256 credentials
= (gnutls_certificate_client_credentials
*)
2257 malloc(sizeof(gnutls_certificate_client_credentials
));
2258 if (credentials
== NULL
)
2262 http
->error
= errno
;
2263 http
->status
= HTTP_ERROR
;
2268 gnutls_certificate_allocate_credentials(credentials
);
2270 gnutls_init(&(conn
->session
), GNUTLS_CLIENT
);
2271 gnutls_set_default_priority(conn
->session
);
2272 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
2273 gnutls_transport_set_ptr(conn
->session
, http
->fd
);
2275 if ((gnutls_handshake(conn
->session
)) != GNUTLS_E_SUCCESS
)
2277 http
->error
= errno
;
2278 http
->status
= HTTP_ERROR
;
2283 conn
->credentials
= credentials
;
2285 # elif defined(HAVE_CDSASSL)
2286 error
= SSLNewContext(false, &conn
);
2289 error
= SSLSetIOFuncs(conn
, _httpReadCDSA
, _httpWriteCDSA
);
2292 error
= SSLSetConnection(conn
, (SSLConnectionRef
)http
->fd
);
2295 error
= SSLSetAllowsExpiredCerts(conn
, true);
2298 error
= SSLSetAllowsAnyRoot(conn
, true);
2301 error
= SSLHandshake(conn
);
2305 http
->error
= error
;
2306 http
->status
= HTTP_ERROR
;
2308 SSLDisposeContext(conn
);
2314 # endif /* HAVE_CDSASSL */
2319 #endif /* HAVE_SSL */
2324 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
2328 http_shutdown_ssl(http_t
*http
) /* I - HTTP connection */
2331 SSL_CTX
*context
; /* Context for encryption */
2332 SSL
*conn
; /* Connection for encryption */
2335 conn
= (SSL
*)(http
->tls
);
2336 context
= SSL_get_SSL_CTX(conn
);
2339 SSL_CTX_free(context
);
2342 # elif defined(HAVE_GNUTLS)
2343 http_tls_t
*conn
; /* Encryption session */
2344 gnutls_certificate_client_credentials
*credentials
;
2345 /* TLS credentials */
2348 conn
= (http_tls_t
*)(http
->tls
);
2349 credentials
= (gnutls_certificate_client_credentials
*)(conn
->credentials
);
2351 gnutls_bye(conn
->session
, GNUTLS_SHUT_RDWR
);
2352 gnutls_deinit(conn
->session
);
2353 gnutls_certificate_free_credentials(*credentials
);
2357 # elif defined(HAVE_CDSASSL)
2358 SSLClose((SSLContextRef
)http
->tls
);
2359 SSLDisposeContext((SSLContextRef
)http
->tls
);
2360 # endif /* HAVE_LIBSSL */
2364 #endif /* HAVE_SSL */
2369 * 'http_upgrade()' - Force upgrade to TLS encryption.
2372 static int /* O - Status of connection */
2373 http_upgrade(http_t
*http
) /* I - HTTP connection */
2375 int ret
; /* Return value */
2376 http_t myhttp
; /* Local copy of HTTP data */
2379 DEBUG_printf(("http_upgrade(%p)\n", http
));
2382 * Copy the HTTP data to a local variable so we can do the OPTIONS
2383 * request without interfering with the existing request data...
2386 memcpy(&myhttp
, http
, sizeof(myhttp
));
2389 * Send an OPTIONS request to the server, requiring SSL or TLS
2390 * encryption on the link...
2393 httpClearFields(&myhttp
);
2394 httpSetField(&myhttp
, HTTP_FIELD_CONNECTION
, "upgrade");
2395 httpSetField(&myhttp
, HTTP_FIELD_UPGRADE
, "TLS/1.0, SSL/2.0, SSL/3.0");
2397 if ((ret
= httpOptions(&myhttp
, "*")) == 0)
2400 * Wait for the secure connection...
2403 while (httpUpdate(&myhttp
) == HTTP_CONTINUE
);
2409 * Copy the HTTP data back over, if any...
2412 http
->fd
= myhttp
.fd
;
2413 http
->error
= myhttp
.error
;
2414 http
->activity
= myhttp
.activity
;
2415 http
->status
= myhttp
.status
;
2416 http
->version
= myhttp
.version
;
2417 http
->keep_alive
= myhttp
.keep_alive
;
2418 http
->used
= myhttp
.used
;
2421 memcpy(http
->buffer
, myhttp
.buffer
, http
->used
);
2423 http
->auth_type
= myhttp
.auth_type
;
2424 http
->nonce_count
= myhttp
.nonce_count
;
2426 memcpy(http
->nonce
, myhttp
.nonce
, sizeof(http
->nonce
));
2428 http
->tls
= myhttp
.tls
;
2429 http
->encryption
= myhttp
.encryption
;
2432 * See if we actually went secure...
2438 * Server does not support HTTP upgrade...
2441 DEBUG_puts("Server does not support HTTP upgrade!");
2444 closesocket(http
->fd
);
2456 #endif /* HAVE_SSL */
2460 * 'http_wait()' - Wait for data available on a connection.
2463 static int /* O - 1 if data is available, 0 otherwise */
2464 http_wait(http_t
*http
, /* I - HTTP connection */
2465 int msec
) /* I - Milliseconds to wait */
2468 struct rlimit limit
; /* Runtime limit */
2469 int set_size
; /* Size of select set */
2471 struct timeval timeout
; /* Timeout */
2472 int nfds
; /* Result from select() */
2475 DEBUG_printf(("http_wait(http=%p, msec=%d)\n", http
, msec
));
2481 * Check the SSL/TLS buffers for data first...
2488 if (SSL_pending((SSL
*)(http
->tls
)))
2490 # elif defined(HAVE_GNUTLS)
2491 if (gnutls_record_check_pending(((http_tls_t
*)(http
->tls
))->session
))
2493 # elif defined(HAVE_CDSASSL)
2494 size_t bytes
; /* Bytes that are available */
2496 if (!SSLGetBufferedReadSize((SSLContextRef
)http
->tls
, &bytes
) && bytes
> 0)
2498 # endif /* HAVE_LIBSSL */
2500 #endif /* HAVE_SSL */
2503 * Then try doing a select() to poll the socket...
2506 if (!http
->input_set
)
2510 * Windows has a fixed-size select() structure, different (surprise,
2511 * surprise!) from all UNIX implementations. Just allocate this
2512 * fixed structure...
2515 http
->input_set
= calloc(1, sizeof(fd_set
));
2518 * Allocate the select() input set based upon the max number of file
2519 * descriptors available for this process...
2522 getrlimit(RLIMIT_NOFILE
, &limit
);
2524 set_size
= (limit
.rlim_cur
+ 31) / 8 + 4;
2525 if (set_size
< sizeof(fd_set
))
2526 set_size
= sizeof(fd_set
);
2528 http
->input_set
= calloc(1, set_size
);
2531 if (!http
->input_set
)
2537 FD_SET(http
->fd
, http
->input_set
);
2541 timeout
.tv_sec
= msec
/ 1000;
2542 timeout
.tv_usec
= (msec
% 1000) * 1000;
2544 nfds
= select(http
->fd
+ 1, http
->input_set
, NULL
, NULL
, &timeout
);
2547 nfds
= select(http
->fd
+ 1, http
->input_set
, NULL
, NULL
, NULL
);
2550 while (nfds
< 0 && WSAGetLastError() == WSAEINTR
);
2552 while (nfds
< 0 && errno
== EINTR
);
2555 FD_CLR(http
->fd
, http
->input_set
);
2562 * 'http_write()' - Write a buffer to a HTTP connection.
2565 static int /* O - Number of bytes written */
2566 http_write(http_t
*http
, /* I - HTTP connection */
2567 const char *buffer
, /* I - Buffer for data */
2568 int length
) /* I - Number of bytes to write */
2570 int tbytes
, /* Total bytes sent */
2571 bytes
; /* Bytes sent */
2580 bytes
= http_write_ssl(http
, buffer
, length
);
2582 #endif /* HAVE_SSL */
2583 bytes
= send(http
->fd
, buffer
, length
, 0);
2588 if (WSAGetLastError() != http
->error
)
2590 http
->error
= WSAGetLastError();
2596 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
2598 http
->error
= errno
;
2603 DEBUG_puts("http_write: error writing data...\n");
2616 printf("http_write: wrote %d bytes: \n", tbytes
);
2617 for (i
= 0, buffer
-= tbytes
; i
< tbytes
; i
+= 16)
2621 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
2622 printf(" %02X", buffer
[i
+ j
] & 255);
2631 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
2633 ch
= buffer
[i
+ j
] & 255;
2635 if (ch
< ' ' || ch
== 127)
2650 * 'http_write_chunk()' - Write a chunked buffer.
2653 static int /* O - Number bytes written */
2654 http_write_chunk(http_t
*http
, /* I - HTTP connection */
2655 const char *buffer
, /* I - Buffer to write */
2656 int length
) /* I - Length of buffer */
2658 char header
[255]; /* Chunk header */
2659 int bytes
; /* Bytes written */
2661 DEBUG_printf(("http_write_chunk(http=%p, buffer=%p, length=%d)\n",
2662 http
, buffer
, length
));
2665 * Write the chunk header, data, and trailer.
2668 sprintf(header
, "%x\r\n", length
);
2669 if (http_write(http
, header
, strlen(header
)) < 0)
2671 DEBUG_puts(" http_write of length failed!");
2675 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
2677 DEBUG_puts(" http_write of buffer failed!");
2681 if (http_write(http
, "\r\n", 2) < 0)
2683 DEBUG_puts(" http_write of CR LF failed!");
2693 * 'http_write_ssl()' - Write to a SSL/TLS connection.
2696 static int /* O - Bytes written */
2697 http_write_ssl(http_t
*http
, /* I - HTTP connection */
2698 const char *buf
, /* I - Buffer holding data */
2699 int len
) /* I - Length of buffer */
2701 # if defined(HAVE_LIBSSL)
2702 return (SSL_write((SSL
*)(http
->tls
), buf
, len
));
2704 # elif defined(HAVE_GNUTLS)
2705 return (gnutls_record_send(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
2706 # elif defined(HAVE_CDSASSL)
2707 int result
; /* Return value */
2708 OSStatus error
; /* Error info */
2709 size_t processed
; /* Number of bytes processed */
2712 error
= SSLWrite((SSLContextRef
)http
->tls
, buf
, len
, &processed
);
2717 result
= (int)processed
;
2719 case errSSLClosedGraceful
:
2722 case errSSLWouldBlock
:
2733 # endif /* HAVE_LIBSSL */
2735 #endif /* HAVE_SSL */