2 * "$Id: http.c 5753 2006-07-18 19:53:24Z mike $"
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.
543 * @since CUPS 1.1.19@
546 const char * /* O - Cookie data or NULL */
547 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
549 return (http
? http
->cookie
: NULL
);
554 * 'httpGetFd()' - Get the file descriptor associated with a connection.
559 int /* O - File descriptor or -1 if none */
560 httpGetFd(http_t
*http
) /* I - HTTP connection */
562 return (http
? http
->fd
: -1);
567 * 'httpGetField()' - Get a field value from a request/response.
570 const char * /* O - Field value */
571 httpGetField(http_t
*http
, /* I - HTTP connection */
572 http_field_t field
) /* I - Field to get */
574 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
577 return (http
->fields
[field
]);
582 * 'httpGetLength()' - Get the amount of data remaining from the
583 * content-length or transfer-encoding fields.
585 * This function is deprecated and will not return lengths larger than
586 * 2^31 - 1; use httpGetLength2() instead.
591 int /* O - Content length */
592 httpGetLength(http_t
*http
) /* I - HTTP connection */
595 * Get the read content length and return the 32-bit value.
600 httpGetLength2(http
);
602 return (http
->_data_remaining
);
610 * 'httpGetLength2()' - Get the amount of data remaining from the
611 * content-length or transfer-encoding fields.
613 * This function returns the complete content length, even for
614 * content larger than 2^31 - 1.
619 off_t
/* O - Content length */
620 httpGetLength2(http_t
*http
) /* I - HTTP connection */
622 DEBUG_printf(("httpGetLength2(http=%p), state=%d\n", http
, http
->state
));
627 if (!strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
629 DEBUG_puts("httpGetLength2: chunked request!");
631 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
632 http
->data_remaining
= 0;
636 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
639 * The following is a hack for HTTP servers that don't send a
640 * content-length or transfer-encoding field...
642 * If there is no content-length then the connection must close
643 * after the transfer is complete...
646 if (http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] == '\0')
647 http
->data_remaining
= 2147483647;
649 http
->data_remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
652 DEBUG_printf(("httpGetLength2: content_length=" CUPS_LLFMT
"\n",
653 CUPS_LLCAST http
->data_remaining
));
656 if (http
->data_remaining
<= INT_MAX
)
657 http
->_data_remaining
= (int)http
->data_remaining
;
659 http
->_data_remaining
= INT_MAX
;
661 return (http
->data_remaining
);
666 * 'httpGetStatus()' - Get the status of the last HTTP request.
671 http_status_t
/* O - HTTP status */
672 httpGetStatus(http_t
*http
) /* I - HTTP connection */
674 return (http
? http
->status
: HTTP_ERROR
);
679 * 'httpGetSubField()' - Get a sub-field value.
684 char * /* O - Value or NULL */
685 httpGetSubField(http_t
*http
, /* I - HTTP connection */
686 http_field_t field
, /* I - Field index */
687 const char *name
, /* I - Name of sub-field */
688 char *value
) /* O - Value string */
690 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
695 * 'httpGetSubField2()' - Get a sub-field value.
700 char * /* O - Value or NULL */
701 httpGetSubField2(http_t
*http
, /* I - HTTP connection */
702 http_field_t field
, /* I - Field index */
703 const char *name
, /* I - Name of sub-field */
704 char *value
, /* O - Value string */
705 int valuelen
) /* I - Size of value buffer */
707 const char *fptr
; /* Pointer into field */
708 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
709 *ptr
, /* Pointer into string buffer */
710 *end
; /* End of value buffer */
712 DEBUG_printf(("httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, valuelen=%d)\n",
713 http
, field
, name
, value
, valuelen
));
715 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
716 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
719 end
= value
+ valuelen
- 1;
721 for (fptr
= http
->fields
[field
]; *fptr
;)
724 * Skip leading whitespace...
727 while (isspace(*fptr
& 255))
737 * Get the sub-field name...
741 *fptr
&& *fptr
!= '=' && !isspace(*fptr
& 255) &&
742 ptr
< (temp
+ sizeof(temp
) - 1);
747 DEBUG_printf(("httpGetSubField: name=\"%s\"\n", temp
));
750 * Skip trailing chars up to the '='...
753 while (isspace(*fptr
& 255))
763 * Skip = and leading whitespace...
768 while (isspace(*fptr
& 255))
774 * Read quoted string...
777 for (ptr
= value
, fptr
++;
778 *fptr
&& *fptr
!= '\"' && ptr
< end
;
783 while (*fptr
&& *fptr
!= '\"')
792 * Read unquoted string...
796 *fptr
&& !isspace(*fptr
& 255) && *fptr
!= ',' && ptr
< end
;
801 while (*fptr
&& !isspace(*fptr
& 255) && *fptr
!= ',')
805 DEBUG_printf(("httpGetSubField: value=\"%s\"\n", value
));
808 * See if this is the one...
811 if (!strcmp(name
, temp
))
822 * 'httpGets()' - Get a line of text from a HTTP connection.
825 char * /* O - Line or NULL */
826 httpGets(char *line
, /* I - Line to read into */
827 int length
, /* I - Max length of buffer */
828 http_t
*http
) /* I - HTTP connection */
830 char *lineptr
, /* Pointer into line */
831 *lineend
, /* End of line */
832 *bufptr
, /* Pointer into input buffer */
833 *bufend
; /* Pointer to end of buffer */
834 int bytes
, /* Number of bytes read */
835 eol
; /* End-of-line? */
838 DEBUG_printf(("httpGets(line=%p, length=%d, http=%p)\n", line
, length
, http
));
840 if (http
== NULL
|| line
== NULL
)
844 * Read a line from the buffer...
848 lineend
= line
+ length
- 1;
851 while (lineptr
< lineend
)
854 * Pre-load the buffer as needed...
863 while (http
->used
== 0)
866 * No newline; see if there is more data to be read...
869 if (!http
->blocking
&& !http_wait(http
, 10000))
871 DEBUG_puts("httpGets: Timed out!");
872 http
->error
= ETIMEDOUT
;
878 bytes
= http_read_ssl(http
, http
->buffer
+ http
->used
,
879 HTTP_MAX_BUFFER
- http
->used
);
881 #endif /* HAVE_SSL */
882 bytes
= recv(http
->fd
, http
->buffer
+ http
->used
,
883 HTTP_MAX_BUFFER
- http
->used
, 0);
885 DEBUG_printf(("httpGets: read %d bytes...\n", bytes
));
890 * Nope, can't get a line this time...
894 if (WSAGetLastError() != http
->error
)
896 http
->error
= WSAGetLastError();
900 DEBUG_printf(("httpGets: recv() error %d!\n", WSAGetLastError()));
902 DEBUG_printf(("httpGets: recv() error %d!\n", errno
));
906 else if (errno
!= http
->error
)
923 * Yup, update the amount used...
930 * Now copy as much of the current line as possible...
933 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
934 lineptr
< lineend
&& bufptr
< bufend
;)
942 else if (*bufptr
== 0x0d)
945 *lineptr
++ = *bufptr
++;
948 http
->used
-= bufptr
- http
->buffer
;
950 memmove(http
->buffer
, bufptr
, http
->used
);
958 http
->activity
= time(NULL
);
962 DEBUG_printf(("httpGets: Returning \"%s\"\n", line
));
968 DEBUG_puts("httpGets: No new line available!");
975 * 'httpHead()' - Send a HEAD request to the server.
978 int /* O - Status of call (0 = success) */
979 httpHead(http_t
*http
, /* I - HTTP connection */
980 const char *uri
) /* I - URI for head */
982 return (http_send(http
, HTTP_HEAD
, uri
));
987 * 'httpInitialize()' - Initialize the HTTP interface library and set the
988 * default HTTP proxy (if any).
996 struct timeval curtime
; /* Current time in microseconds */
998 int i
; /* Looping var */
999 unsigned char data
[1024]; /* Seed data */
1000 #endif /* HAVE_LIBSSL */
1003 WSADATA winsockdata
; /* WinSock data */
1004 static int initialized
= 0; /* Has WinSock been initialized? */
1008 WSAStartup(MAKEWORD(1,1), &winsockdata
);
1009 #elif !defined(SO_NOSIGPIPE)
1011 * Ignore SIGPIPE signals...
1015 sigset(SIGPIPE
, SIG_IGN
);
1016 # elif defined(HAVE_SIGACTION)
1017 struct sigaction action
; /* POSIX sigaction data */
1020 memset(&action
, 0, sizeof(action
));
1021 action
.sa_handler
= SIG_IGN
;
1022 sigaction(SIGPIPE
, &action
, NULL
);
1024 signal(SIGPIPE
, SIG_IGN
);
1025 # endif /* !SO_NOSIGPIPE */
1029 gnutls_global_init();
1030 #endif /* HAVE_GNUTLS */
1033 SSL_load_error_strings();
1037 * Using the current time is a dubious random seed, but on some systems
1038 * it is the best we can do (on others, this seed isn't even used...)
1043 gettimeofday(&curtime
, NULL
);
1044 srand(curtime
.tv_sec
+ curtime
.tv_usec
);
1047 for (i
= 0; i
< sizeof(data
); i
++)
1048 data
[i
] = rand(); /* Yes, this is a poor source of random data... */
1050 RAND_seed(&data
, sizeof(data
));
1051 #endif /* HAVE_LIBSSL */
1056 * 'httpOptions()' - Send an OPTIONS request to the server.
1059 int /* O - Status of call (0 = success) */
1060 httpOptions(http_t
*http
, /* I - HTTP connection */
1061 const char *uri
) /* I - URI for options */
1063 return (http_send(http
, HTTP_OPTIONS
, uri
));
1068 * 'httpPost()' - Send a POST request to the server.
1071 int /* O - Status of call (0 = success) */
1072 httpPost(http_t
*http
, /* I - HTTP connection */
1073 const char *uri
) /* I - URI for post */
1075 return (http_send(http
, HTTP_POST
, uri
));
1080 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1085 int /* O - Number of bytes written */
1086 httpPrintf(http_t
*http
, /* I - HTTP connection */
1087 const char *format
, /* I - printf-style format string */
1088 ...) /* I - Additional args as needed */
1090 int bytes
; /* Number of bytes to write */
1091 char buf
[16384]; /* Buffer for formatted string */
1092 va_list ap
; /* Variable argument pointer */
1095 DEBUG_printf(("httpPrintf(http=%p, format=\"%s\", ...)\n", http
, format
));
1097 va_start(ap
, format
);
1098 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1101 DEBUG_printf(("httpPrintf: %s", buf
));
1105 DEBUG_puts(" flushing existing data...");
1107 if (httpFlushWrite(http
) < 0)
1111 return (http_write(http
, buf
, bytes
));
1116 * 'httpPut()' - Send a PUT request to the server.
1119 int /* O - Status of call (0 = success) */
1120 httpPut(http_t
*http
, /* I - HTTP connection */
1121 const char *uri
) /* I - URI to put */
1123 return (http_send(http
, HTTP_PUT
, uri
));
1128 * 'httpRead()' - Read data from a HTTP connection.
1130 * This function is deprecated. Use the httpRead2() function which can
1131 * read more than 2GB of data.
1136 int /* O - Number of bytes read */
1137 httpRead(http_t
*http
, /* I - HTTP connection */
1138 char *buffer
, /* I - Buffer for data */
1139 int length
) /* I - Maximum number of bytes */
1141 return ((int)httpRead2(http
, buffer
, length
));
1146 * 'httpRead2()' - Read data from a HTTP connection.
1151 ssize_t
/* O - Number of bytes read */
1152 httpRead2(http_t
*http
, /* I - HTTP connection */
1153 char *buffer
, /* I - Buffer for data */
1154 size_t length
) /* I - Maximum number of bytes */
1156 ssize_t bytes
; /* Bytes read */
1157 char len
[32]; /* Length string */
1160 DEBUG_printf(("httpRead(http=%p, buffer=%p, length=%d)\n",
1161 http
, buffer
, length
));
1163 if (http
== NULL
|| buffer
== NULL
)
1166 http
->activity
= time(NULL
);
1171 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1172 http
->data_remaining
<= 0)
1174 DEBUG_puts("httpRead2: Getting chunk length...");
1176 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1178 DEBUG_puts("httpRead2: Could not get length!");
1182 http
->data_remaining
= strtoll(len
, NULL
, 16);
1183 if (http
->data_remaining
< 0)
1185 DEBUG_puts("httpRead2: Negative chunk length!");
1190 DEBUG_printf(("httpRead2: data_remaining=" CUPS_LLFMT
"\n",
1191 CUPS_LLCAST http
->data_remaining
));
1193 if (http
->data_remaining
<= 0)
1196 * A zero-length chunk ends a transfer; unless we are reading POST
1200 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1201 httpGets(len
, sizeof(len
), http
);
1203 if (http
->state
== HTTP_POST_RECV
)
1206 http
->state
= HTTP_WAITING
;
1209 * Prevent future reads for this request...
1212 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1216 else if (length
> http
->data_remaining
)
1217 length
= http
->data_remaining
;
1219 if (http
->used
== 0 && length
<= 256)
1222 * Buffer small reads for better performance...
1225 if (!http
->blocking
&& !httpWait(http
, 10000))
1228 if (http
->data_remaining
> sizeof(http
->buffer
))
1229 bytes
= sizeof(http
->buffer
);
1231 bytes
= http
->data_remaining
;
1235 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1237 #endif /* HAVE_SSL */
1239 DEBUG_printf(("httpRead2: reading %d bytes from socket into buffer...\n",
1242 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1244 DEBUG_printf(("httpRead2: read %d bytes from socket into buffer...\n",
1253 http
->error
= WSAGetLastError();
1258 http
->error
= errno
;
1265 http
->error
= EPIPE
;
1272 if (length
> http
->used
)
1273 length
= http
->used
;
1277 DEBUG_printf(("httpRead2: grabbing %d bytes from input buffer...\n", bytes
));
1279 memcpy(buffer
, http
->buffer
, length
);
1280 http
->used
-= length
;
1283 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
1288 if (!http
->blocking
&& !httpWait(http
, 10000))
1291 bytes
= http_read_ssl(http
, buffer
, length
);
1293 #endif /* HAVE_SSL */
1296 if (!http
->blocking
&& !httpWait(http
, 10000))
1299 DEBUG_printf(("httpRead2: reading %d bytes from socket...\n", length
));
1301 while ((bytes
= recv(http
->fd
, buffer
, length
, 0)) < 0)
1305 DEBUG_printf(("httpRead2: read %d bytes from socket...\n", bytes
));
1310 http
->data_remaining
-= bytes
;
1312 if (http
->data_remaining
<= INT_MAX
)
1313 http
->_data_remaining
= (int)http
->data_remaining
;
1315 http
->_data_remaining
= INT_MAX
;
1320 http
->error
= WSAGetLastError();
1325 http
->error
= errno
;
1330 http
->error
= EPIPE
;
1334 if (http
->data_remaining
== 0)
1336 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1337 httpGets(len
, sizeof(len
), http
);
1339 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
1341 if (http
->state
== HTTP_POST_RECV
)
1344 http
->state
= HTTP_WAITING
;
1351 printf("httpRead2: Read %d bytes:\n", bytes
);
1352 for (i
= 0; i
< bytes
; i
+= 16)
1356 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1357 printf(" %02X", buffer
[i
+ j
] & 255);
1366 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1368 ch
= buffer
[i
+ j
] & 255;
1370 if (ch
< ' ' || ch
>= 127)
1384 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
1386 * '_httpReadCDSA()' - Read function for CDSA decryption code.
1389 OSStatus
/* O - -1 on error, 0 on success */
1391 SSLConnectionRef connection
, /* I - SSL/TLS connection */
1392 void *data
, /* I - Data buffer */
1393 size_t *dataLength
) /* IO - Number of bytes */
1395 OSStatus result
; /* Return value */
1396 ssize_t bytes
; /* Number of bytes read */
1397 cdsa_conn_ref_t u
; /* Connection reference union */
1400 u
.connection
= connection
;
1403 bytes
= recv(u
.sock
, data
, *dataLength
, 0);
1404 while (bytes
== -1 && errno
== EINTR
);
1406 if (bytes
== *dataLength
)
1410 *dataLength
= bytes
;
1411 result
= errSSLWouldBlock
;
1418 result
= errSSLClosedGraceful
;
1419 else if (errno
== EAGAIN
)
1420 result
= errSSLWouldBlock
;
1422 result
= errSSLClosedAbort
;
1427 #endif /* HAVE_SSL && HAVE_CDSASSL */
1431 * 'httpReconnect()' - Reconnect to a HTTP server.
1434 int /* O - 0 on success, non-zero on failure */
1435 httpReconnect(http_t
*http
) /* I - HTTP connection */
1437 http_addrlist_t
*addr
; /* Connected address */
1440 DEBUG_printf(("httpReconnect(http=%p)\n", http
));
1447 http_shutdown_ssl(http
);
1448 #endif /* HAVE_SSL */
1451 * Close any previously open socket...
1457 closesocket(http
->fd
);
1466 * Connect to the server...
1469 if ((addr
= httpAddrConnect(http
->addrlist
, &(http
->fd
))) == NULL
)
1472 * Unable to connect...
1476 http
->error
= WSAGetLastError();
1478 http
->error
= errno
;
1480 http
->status
= HTTP_ERROR
;
1485 http
->hostaddr
= &(addr
->addr
);
1487 http
->status
= HTTP_CONTINUE
;
1490 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
1493 * Always do encryption via SSL.
1496 if (http_setup_ssl(http
) != 0)
1499 closesocket(http
->fd
);
1507 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
1508 return (http_upgrade(http
));
1509 #endif /* HAVE_SSL */
1516 * 'httpSetCookie()' - Set the cookie value(s)...
1518 * @since CUPS 1.1.19@
1522 httpSetCookie(http_t
*http
, /* I - Connection */
1523 const char *cookie
) /* I - Cookie string */
1532 http
->cookie
= strdup(cookie
);
1534 http
->cookie
= NULL
;
1539 * 'httpSetExpect()' - Set the Expect: header in a request.
1541 * Currently only HTTP_CONTINUE is supported for the "expect" argument.
1547 httpSetExpect(http_t
*http
, /* I - HTTP connection */
1548 http_status_t expect
) /* I - HTTP status to expect (HTTP_CONTINUE) */
1551 http
->expect
= expect
;
1556 * 'httpSetField()' - Set the value of an HTTP header.
1560 httpSetField(http_t
*http
, /* I - HTTP connection */
1561 http_field_t field
, /* I - Field index */
1562 const char *value
) /* I - Value */
1565 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
1566 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
1570 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
1575 * 'httpSetLength()' - Set the content-length and content-encoding.
1581 httpSetLength(http_t
*http
, /* I - HTTP connection */
1582 size_t length
) /* I - Length (0 for chunked) */
1589 strcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked");
1590 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
1594 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
1595 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
1596 CUPS_LLFMT
, CUPS_LLCAST length
);
1602 * 'httpTrace()' - Send an TRACE request to the server.
1605 int /* O - Status of call (0 = success) */
1606 httpTrace(http_t
*http
, /* I - HTTP connection */
1607 const char *uri
) /* I - URI for trace */
1609 return (http_send(http
, HTTP_TRACE
, uri
));
1614 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1617 http_status_t
/* O - HTTP status */
1618 httpUpdate(http_t
*http
) /* I - HTTP connection */
1620 char line
[32768], /* Line from connection... */
1621 *value
; /* Pointer to value on line */
1622 http_field_t field
; /* Field index */
1623 int major
, minor
, /* HTTP version numbers */
1624 status
; /* Request status */
1627 DEBUG_printf(("httpUpdate(http=%p), state=%d\n", http
, http
->state
));
1630 * Flush pending data, if any...
1635 DEBUG_puts(" flushing buffer...");
1637 if (httpFlushWrite(http
) < 0)
1638 return (HTTP_ERROR
);
1642 * If we haven't issued any commands, then there is nothing to "update"...
1645 if (http
->state
== HTTP_WAITING
)
1646 return (HTTP_CONTINUE
);
1649 * Grab all of the lines we can from the connection...
1652 while (httpGets(line
, sizeof(line
), http
) != NULL
)
1654 DEBUG_printf(("httpUpdate: Got \"%s\"\n", line
));
1656 if (line
[0] == '\0')
1659 * Blank line means the start of the data section (if any). Return
1660 * the result code, too...
1662 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
1663 * Instead, we just return HTTP_CONTINUE to the caller and keep on
1667 if (http
->status
== HTTP_CONTINUE
)
1668 return (http
->status
);
1670 if (http
->status
< HTTP_BAD_REQUEST
)
1671 http
->digest_tries
= 0;
1674 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
1676 if (http_setup_ssl(http
) != 0)
1679 closesocket(http
->fd
);
1684 return (HTTP_ERROR
);
1687 return (HTTP_CONTINUE
);
1689 #endif /* HAVE_SSL */
1691 httpGetLength2(http
);
1693 switch (http
->state
)
1697 case HTTP_POST_RECV
:
1700 case HTTP_POST_SEND
:
1705 http
->state
= HTTP_WAITING
;
1709 return (http
->status
);
1711 else if (strncmp(line
, "HTTP/", 5) == 0)
1714 * Got the beginning of a response...
1717 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &status
) != 3)
1718 return (HTTP_ERROR
);
1720 http
->version
= (http_version_t
)(major
* 100 + minor
);
1721 http
->status
= (http_status_t
)status
;
1723 else if ((value
= strchr(line
, ':')) != NULL
)
1730 while (isspace(*value
& 255))
1734 * Be tolerants of servers that send unknown attribute fields...
1737 if (!strcasecmp(line
, "expect"))
1740 * "Expect: 100-continue" or similar...
1743 http
->expect
= (http_status_t
)atoi(value
);
1745 else if (!strcasecmp(line
, "cookie"))
1748 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
1751 httpSetCookie(http
, value
);
1753 else if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
1755 DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line
));
1759 httpSetField(http
, field
, value
);
1763 http
->status
= HTTP_ERROR
;
1764 return (HTTP_ERROR
);
1769 * See if there was an error...
1772 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
1773 return (http
->status
);
1777 DEBUG_printf(("httpUpdate: socket error %d - %s\n", http
->error
,
1778 strerror(http
->error
)));
1779 http
->status
= HTTP_ERROR
;
1780 return (HTTP_ERROR
);
1784 * If we haven't already returned, then there is nothing new...
1787 return (HTTP_CONTINUE
);
1792 * 'httpWait()' - Wait for data available on a connection.
1794 * @since CUPS 1.1.19@
1797 int /* O - 1 if data is available, 0 otherwise */
1798 httpWait(http_t
*http
, /* I - HTTP connection */
1799 int msec
) /* I - Milliseconds to wait */
1802 * First see if there is data in the buffer...
1812 * Flush pending data, if any...
1817 if (httpFlushWrite(http
) < 0)
1822 * If not, check the SSL/TLS buffers and do a select() on the connection...
1825 return (http_wait(http
, msec
));
1830 * 'httpWrite()' - Write data to a HTTP connection.
1832 * This function is deprecated. Use the httpWrite2() function which can
1833 * write more than 2GB of data.
1838 int /* O - Number of bytes written */
1839 httpWrite(http_t
*http
, /* I - HTTP connection */
1840 const char *buffer
, /* I - Buffer for data */
1841 int length
) /* I - Number of bytes to write */
1843 return ((int)httpWrite2(http
, buffer
, length
));
1848 * 'httpWrite2()' - Write data to a HTTP connection.
1853 ssize_t
/* O - Number of bytes written */
1854 httpWrite2(http_t
*http
, /* I - HTTP connection */
1855 const char *buffer
, /* I - Buffer for data */
1856 size_t length
) /* I - Number of bytes to write */
1858 ssize_t bytes
; /* Bytes written */
1861 DEBUG_printf(("httpWrite(http=%p, buffer=%p, length=%d)\n", http
,
1865 * Range check input...
1868 if (http
== NULL
|| buffer
== NULL
)
1872 * Mark activity on the connection...
1875 http
->activity
= time(NULL
);
1878 * Buffer small writes for better performance...
1883 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
1885 DEBUG_printf((" flushing buffer (wused=%d, length=%d)\n",
1886 http
->wused
, length
));
1888 httpFlushWrite(http
);
1891 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
))
1894 * Write to buffer...
1897 DEBUG_printf((" copying %d bytes to wbuffer...\n", length
));
1899 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
1900 http
->wused
+= length
;
1906 * Otherwise write the data directly...
1909 DEBUG_printf((" writing %d bytes to socket...\n", length
));
1911 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1912 bytes
= http_write_chunk(http
, buffer
, length
);
1914 bytes
= http_write(http
, buffer
, length
);
1916 DEBUG_printf((" wrote %d bytes...\n", bytes
));
1919 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1920 http
->data_remaining
-= bytes
;
1926 * Handle end-of-request processing...
1929 if ((http
->data_encoding
== HTTP_ENCODE_CHUNKED
&& length
== 0) ||
1930 (http
->data_encoding
== HTTP_ENCODE_LENGTH
&& http
->data_remaining
== 0))
1933 * Finished with the transfer; unless we are sending POST or PUT
1937 DEBUG_puts("httpWrite: changing states...");
1940 httpFlushWrite(http
);
1942 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1945 * Send a 0-length chunk at the end of the request...
1948 http_write(http
, "0\r\n\r\n", 5);
1951 * Reset the data state...
1954 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1955 http
->data_remaining
= 0;
1958 if (http
->state
== HTTP_POST_RECV
)
1960 else if (http
->state
== HTTP_PUT_RECV
)
1961 http
->state
= HTTP_STATUS
;
1963 http
->state
= HTTP_WAITING
;
1970 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
1972 * '_httpWriteCDSA()' - Write function for CDSA encryption code.
1975 OSStatus
/* O - -1 on error, 0 on success */
1977 SSLConnectionRef connection
, /* I - SSL/TLS connection */
1978 const void *data
, /* I - Data buffer */
1979 size_t *dataLength
) /* IO - Number of bytes */
1981 OSStatus result
; /* Return value */
1982 ssize_t bytes
; /* Number of bytes read */
1983 cdsa_conn_ref_t u
; /* Connection reference union */
1986 u
.connection
= connection
;
1989 bytes
= write(u
.sock
, data
, *dataLength
);
1990 while (bytes
== -1 && errno
== EINTR
);
1992 if (bytes
== *dataLength
)
1994 else if (bytes
>= 0)
1996 *dataLength
= bytes
;
1997 result
= errSSLWouldBlock
;
2003 if (errno
== EAGAIN
)
2004 result
= errSSLWouldBlock
;
2006 result
= errSSLClosedAbort
;
2011 #endif /* HAVE_SSL && HAVE_CDSASSL */
2015 * 'http_field()' - Return the field index for a field name.
2018 static http_field_t
/* O - Field index */
2019 http_field(const char *name
) /* I - String name */
2021 int i
; /* Looping var */
2024 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2025 if (strcasecmp(name
, http_fields
[i
]) == 0)
2026 return ((http_field_t
)i
);
2028 return (HTTP_FIELD_UNKNOWN
);
2034 * 'http_read_ssl()' - Read from a SSL/TLS connection.
2037 static int /* O - Bytes read */
2038 http_read_ssl(http_t
*http
, /* I - HTTP connection */
2039 char *buf
, /* I - Buffer to store data */
2040 int len
) /* I - Length of buffer */
2042 # if defined(HAVE_LIBSSL)
2043 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
2045 # elif defined(HAVE_GNUTLS)
2046 return (gnutls_record_recv(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
2048 # elif defined(HAVE_CDSASSL)
2049 int result
; /* Return value */
2050 OSStatus error
; /* Error info */
2051 size_t processed
; /* Number of bytes processed */
2054 error
= SSLRead(((http_tls_t
*)http
->tls
)->session
, buf
, len
, &processed
);
2059 result
= (int)processed
;
2061 case errSSLClosedGraceful
:
2064 case errSSLWouldBlock
:
2066 result
= (int)processed
;
2080 # endif /* HAVE_LIBSSL */
2082 #endif /* HAVE_SSL */
2086 * 'http_send()' - Send a request with all fields and the trailing blank line.
2089 static int /* O - 0 on success, non-zero on error */
2090 http_send(http_t
*http
, /* I - HTTP connection */
2091 http_state_t request
, /* I - Request code */
2092 const char *uri
) /* I - URI */
2094 int i
; /* Looping var */
2095 char *ptr
, /* Pointer in buffer */
2096 buf
[1024]; /* Encoded URI buffer */
2097 static const char * const codes
[] =
2098 { /* Request code strings */
2113 static const char hex
[] = "0123456789ABCDEF";
2117 DEBUG_printf(("http_send(http=%p, request=HTTP_%s, uri=\"%s\")\n",
2118 http
, codes
[request
], uri
));
2120 if (http
== NULL
|| uri
== NULL
)
2124 * Set the User-Agent field if it isn't already...
2127 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
2128 httpSetField(http
, HTTP_FIELD_USER_AGENT
, CUPS_MINIMAL
);
2131 * Encode the URI as needed...
2134 for (ptr
= buf
; *uri
!= '\0' && ptr
< (buf
+ sizeof(buf
) - 1); uri
++)
2135 if (*uri
<= ' ' || *uri
>= 127)
2137 if (ptr
< (buf
+ sizeof(buf
) - 1))
2139 if (ptr
< (buf
+ sizeof(buf
) - 1))
2140 *ptr
++ = hex
[(*uri
>> 4) & 15];
2141 if (ptr
< (buf
+ sizeof(buf
) - 1))
2142 *ptr
++ = hex
[*uri
& 15];
2150 * See if we had an error the last time around; if so, reconnect...
2153 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
2154 if (httpReconnect(http
))
2158 * Send the request header...
2161 http
->state
= request
;
2162 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
2165 http
->status
= HTTP_CONTINUE
;
2168 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
2170 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
2171 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
2173 #endif /* HAVE_SSL */
2175 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
2177 http
->status
= HTTP_ERROR
;
2181 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2182 if (http
->fields
[i
][0] != '\0')
2184 DEBUG_printf(("%s: %s\n", http_fields
[i
], http
->fields
[i
]));
2186 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], http
->fields
[i
]) < 1)
2188 http
->status
= HTTP_ERROR
;
2194 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
2196 http
->status
= HTTP_ERROR
;
2200 if (http
->expect
== HTTP_CONTINUE
&&
2201 (http
->state
== HTTP_POST_RECV
|| http
->state
== HTTP_PUT_RECV
))
2202 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
2204 http
->status
= HTTP_ERROR
;
2208 if (httpPrintf(http
, "\r\n") < 1)
2210 http
->status
= HTTP_ERROR
;
2214 httpGetLength2(http
);
2215 httpClearFields(http
);
2223 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
2226 static int /* O - Status of connection */
2227 http_setup_ssl(http_t
*http
) /* I - HTTP connection */
2230 SSL_CTX
*context
; /* Context for encryption */
2231 SSL
*conn
; /* Connection for encryption */
2232 # elif defined(HAVE_GNUTLS)
2233 http_tls_t
*conn
; /* TLS session object */
2234 gnutls_certificate_client_credentials
*credentials
;
2235 /* TLS credentials */
2236 # elif defined(HAVE_CDSASSL)
2237 OSStatus error
; /* Error code */
2238 http_tls_t
*conn
; /* CDSA connection information */
2239 cdsa_conn_ref_t u
; /* Connection reference union */
2240 # endif /* HAVE_LIBSSL */
2243 DEBUG_printf(("http_setup_ssl(http=%p)\n", http
));
2246 context
= SSL_CTX_new(SSLv23_client_method());
2248 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
2250 conn
= SSL_new(context
);
2252 SSL_set_fd(conn
, http
->fd
);
2253 if (SSL_connect(conn
) != 1)
2256 unsigned long error
; /* Error code */
2258 while ((error
= ERR_get_error()) != 0)
2259 printf("http_setup_ssl: %s\n", ERR_error_string(error
, NULL
));
2262 SSL_CTX_free(context
);
2266 http
->error
= WSAGetLastError();
2268 http
->error
= errno
;
2270 http
->status
= HTTP_ERROR
;
2272 return (HTTP_ERROR
);
2275 # elif defined(HAVE_GNUTLS)
2276 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
2278 http
->error
= errno
;
2279 http
->status
= HTTP_ERROR
;
2284 credentials
= (gnutls_certificate_client_credentials
*)
2285 malloc(sizeof(gnutls_certificate_client_credentials
));
2286 if (credentials
== NULL
)
2290 http
->error
= errno
;
2291 http
->status
= HTTP_ERROR
;
2296 gnutls_certificate_allocate_credentials(credentials
);
2298 gnutls_init(&(conn
->session
), GNUTLS_CLIENT
);
2299 gnutls_set_default_priority(conn
->session
);
2300 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
2301 gnutls_transport_set_ptr(conn
->session
,
2302 (gnutls_transport_ptr
)((long)http
->fd
));
2304 if ((gnutls_handshake(conn
->session
)) != GNUTLS_E_SUCCESS
)
2306 http
->error
= errno
;
2307 http
->status
= HTTP_ERROR
;
2312 conn
->credentials
= credentials
;
2314 # elif defined(HAVE_CDSASSL)
2315 conn
= (http_tls_t
*)calloc(1, sizeof(http_tls_t
));
2320 if ((error
= SSLNewContext(false, &conn
->session
)))
2322 http
->error
= error
;
2323 http
->status
= HTTP_ERROR
;
2330 * Use a union to resolve warnings about int/pointer size mismatches...
2333 u
.connection
= NULL
;
2335 error
= SSLSetConnection(conn
->session
, u
.connection
);
2338 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
2341 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
2344 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
2347 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
2351 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
2357 http
->error
= error
;
2358 http
->status
= HTTP_ERROR
;
2360 SSLDisposeContext(conn
->session
);
2366 # endif /* HAVE_CDSASSL */
2371 #endif /* HAVE_SSL */
2376 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
2380 http_shutdown_ssl(http_t
*http
) /* I - HTTP connection */
2383 SSL_CTX
*context
; /* Context for encryption */
2384 SSL
*conn
; /* Connection for encryption */
2387 conn
= (SSL
*)(http
->tls
);
2388 context
= SSL_get_SSL_CTX(conn
);
2391 SSL_CTX_free(context
);
2394 # elif defined(HAVE_GNUTLS)
2395 http_tls_t
*conn
; /* Encryption session */
2396 gnutls_certificate_client_credentials
*credentials
;
2397 /* TLS credentials */
2400 conn
= (http_tls_t
*)(http
->tls
);
2401 credentials
= (gnutls_certificate_client_credentials
*)(conn
->credentials
);
2403 gnutls_bye(conn
->session
, GNUTLS_SHUT_RDWR
);
2404 gnutls_deinit(conn
->session
);
2405 gnutls_certificate_free_credentials(*credentials
);
2409 # elif defined(HAVE_CDSASSL)
2410 http_tls_t
*conn
; /* CDSA connection information */
2413 conn
= (http_tls_t
*)(http
->tls
);
2415 while (SSLClose(conn
->session
) == errSSLWouldBlock
)
2418 SSLDisposeContext(conn
->session
);
2420 if (conn
->certsArray
)
2421 CFRelease(conn
->certsArray
);
2424 # endif /* HAVE_LIBSSL */
2428 #endif /* HAVE_SSL */
2433 * 'http_upgrade()' - Force upgrade to TLS encryption.
2436 static int /* O - Status of connection */
2437 http_upgrade(http_t
*http
) /* I - HTTP connection */
2439 int ret
; /* Return value */
2440 http_t myhttp
; /* Local copy of HTTP data */
2443 DEBUG_printf(("http_upgrade(%p)\n", http
));
2446 * Copy the HTTP data to a local variable so we can do the OPTIONS
2447 * request without interfering with the existing request data...
2450 memcpy(&myhttp
, http
, sizeof(myhttp
));
2453 * Send an OPTIONS request to the server, requiring SSL or TLS
2454 * encryption on the link...
2457 httpClearFields(&myhttp
);
2458 httpSetField(&myhttp
, HTTP_FIELD_CONNECTION
, "upgrade");
2459 httpSetField(&myhttp
, HTTP_FIELD_UPGRADE
, "TLS/1.0, SSL/2.0, SSL/3.0");
2461 if ((ret
= httpOptions(&myhttp
, "*")) == 0)
2464 * Wait for the secure connection...
2467 while (httpUpdate(&myhttp
) == HTTP_CONTINUE
);
2473 * Copy the HTTP data back over, if any...
2476 http
->fd
= myhttp
.fd
;
2477 http
->error
= myhttp
.error
;
2478 http
->activity
= myhttp
.activity
;
2479 http
->status
= myhttp
.status
;
2480 http
->version
= myhttp
.version
;
2481 http
->keep_alive
= myhttp
.keep_alive
;
2482 http
->used
= myhttp
.used
;
2485 memcpy(http
->buffer
, myhttp
.buffer
, http
->used
);
2487 http
->auth_type
= myhttp
.auth_type
;
2488 http
->nonce_count
= myhttp
.nonce_count
;
2490 memcpy(http
->nonce
, myhttp
.nonce
, sizeof(http
->nonce
));
2492 http
->tls
= myhttp
.tls
;
2493 http
->encryption
= myhttp
.encryption
;
2496 * See if we actually went secure...
2502 * Server does not support HTTP upgrade...
2505 DEBUG_puts("Server does not support HTTP upgrade!");
2508 closesocket(http
->fd
);
2520 #endif /* HAVE_SSL */
2524 * 'http_wait()' - Wait for data available on a connection.
2527 static int /* O - 1 if data is available, 0 otherwise */
2528 http_wait(http_t
*http
, /* I - HTTP connection */
2529 int msec
) /* I - Milliseconds to wait */
2532 struct rlimit limit
; /* Runtime limit */
2533 int set_size
; /* Size of select set */
2535 struct timeval timeout
; /* Timeout */
2536 int nfds
; /* Result from select() */
2539 DEBUG_printf(("http_wait(http=%p, msec=%d)\n", http
, msec
));
2545 * Check the SSL/TLS buffers for data first...
2552 if (SSL_pending((SSL
*)(http
->tls
)))
2554 # elif defined(HAVE_GNUTLS)
2555 if (gnutls_record_check_pending(((http_tls_t
*)(http
->tls
))->session
))
2557 # elif defined(HAVE_CDSASSL)
2558 size_t bytes
; /* Bytes that are available */
2560 if (!SSLGetBufferedReadSize(((http_tls_t
*)http
->tls
)->session
, &bytes
) && bytes
> 0)
2562 # endif /* HAVE_LIBSSL */
2564 #endif /* HAVE_SSL */
2567 * Then try doing a select() to poll the socket...
2570 if (!http
->input_set
)
2574 * Windows has a fixed-size select() structure, different (surprise,
2575 * surprise!) from all UNIX implementations. Just allocate this
2576 * fixed structure...
2579 http
->input_set
= calloc(1, sizeof(fd_set
));
2582 * Allocate the select() input set based upon the max number of file
2583 * descriptors available for this process...
2586 getrlimit(RLIMIT_NOFILE
, &limit
);
2588 set_size
= (limit
.rlim_cur
+ 31) / 8 + 4;
2589 if (set_size
< sizeof(fd_set
))
2590 set_size
= sizeof(fd_set
);
2592 http
->input_set
= calloc(1, set_size
);
2595 if (!http
->input_set
)
2601 FD_SET(http
->fd
, http
->input_set
);
2603 DEBUG_printf(("http_wait: msec=%d, http->fd=%d\n", msec
, http
->fd
));
2607 timeout
.tv_sec
= msec
/ 1000;
2608 timeout
.tv_usec
= (msec
% 1000) * 1000;
2610 nfds
= select(http
->fd
+ 1, http
->input_set
, NULL
, NULL
, &timeout
);
2613 nfds
= select(http
->fd
+ 1, http
->input_set
, NULL
, NULL
, NULL
);
2615 DEBUG_printf(("http_wait: select() returned %d...\n", nfds
));
2618 while (nfds
< 0 && WSAGetLastError() == WSAEINTR
);
2620 while (nfds
< 0 && errno
== EINTR
);
2623 FD_CLR(http
->fd
, http
->input_set
);
2625 DEBUG_printf(("http_wait: returning with nfds=%d...\n", nfds
));
2632 * 'http_write()' - Write a buffer to a HTTP connection.
2635 static int /* O - Number of bytes written */
2636 http_write(http_t
*http
, /* I - HTTP connection */
2637 const char *buffer
, /* I - Buffer for data */
2638 int length
) /* I - Number of bytes to write */
2640 int tbytes
, /* Total bytes sent */
2641 bytes
; /* Bytes sent */
2650 bytes
= http_write_ssl(http
, buffer
, length
);
2652 #endif /* HAVE_SSL */
2653 bytes
= send(http
->fd
, buffer
, length
, 0);
2658 if (WSAGetLastError() != http
->error
)
2660 http
->error
= WSAGetLastError();
2666 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
2668 http
->error
= errno
;
2673 DEBUG_puts("http_write: error writing data...\n");
2686 printf("http_write: wrote %d bytes: \n", tbytes
);
2687 for (i
= 0, buffer
-= tbytes
; i
< tbytes
; i
+= 16)
2691 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
2692 printf(" %02X", buffer
[i
+ j
] & 255);
2701 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
2703 ch
= buffer
[i
+ j
] & 255;
2705 if (ch
< ' ' || ch
== 127)
2720 * 'http_write_chunk()' - Write a chunked buffer.
2723 static int /* O - Number bytes written */
2724 http_write_chunk(http_t
*http
, /* I - HTTP connection */
2725 const char *buffer
, /* I - Buffer to write */
2726 int length
) /* I - Length of buffer */
2728 char header
[255]; /* Chunk header */
2729 int bytes
; /* Bytes written */
2731 DEBUG_printf(("http_write_chunk(http=%p, buffer=%p, length=%d)\n",
2732 http
, buffer
, length
));
2735 * Write the chunk header, data, and trailer.
2738 sprintf(header
, "%x\r\n", length
);
2739 if (http_write(http
, header
, strlen(header
)) < 0)
2741 DEBUG_puts(" http_write of length failed!");
2745 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
2747 DEBUG_puts(" http_write of buffer failed!");
2751 if (http_write(http
, "\r\n", 2) < 0)
2753 DEBUG_puts(" http_write of CR LF failed!");
2763 * 'http_write_ssl()' - Write to a SSL/TLS connection.
2766 static int /* O - Bytes written */
2767 http_write_ssl(http_t
*http
, /* I - HTTP connection */
2768 const char *buf
, /* I - Buffer holding data */
2769 int len
) /* I - Length of buffer */
2771 # if defined(HAVE_LIBSSL)
2772 return (SSL_write((SSL
*)(http
->tls
), buf
, len
));
2774 # elif defined(HAVE_GNUTLS)
2775 return (gnutls_record_send(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
2776 # elif defined(HAVE_CDSASSL)
2777 int result
; /* Return value */
2778 OSStatus error
; /* Error info */
2779 size_t processed
; /* Number of bytes processed */
2782 error
= SSLWrite(((http_tls_t
*)http
->tls
)->session
, buf
, len
, &processed
);
2787 result
= (int)processed
;
2789 case errSSLClosedGraceful
:
2792 case errSSLWouldBlock
:
2794 result
= (int)processed
;
2808 # endif /* HAVE_LIBSSL */
2810 #endif /* HAVE_SSL */
2814 * End of "$Id: http.c 5753 2006-07-18 19:53:24Z mike $".