2 * "$Id: http.c 5961 2006-09-16 19:08:36Z 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 if (http
->hostname
[0] == '/')
226 httpSetField(http
, HTTP_FIELD_HOST
, "localhost");
228 httpSetField(http
, HTTP_FIELD_HOST
, http
->hostname
);
230 http
->expect
= (http_status_t
)0;
236 * 'httpClose()' - Close an HTTP connection...
240 httpClose(http_t
*http
) /* I - HTTP connection */
242 DEBUG_printf(("httpClose(http=%p)\n", http
));
247 httpAddrFreeList(http
->addrlist
);
250 free(http
->input_set
);
257 http_shutdown_ssl(http
);
258 #endif /* HAVE_SSL */
261 closesocket(http
->fd
);
271 * 'httpConnect()' - Connect to a HTTP server.
274 http_t
* /* O - New HTTP connection */
275 httpConnect(const char *host
, /* I - Host to connect to */
276 int port
) /* I - Port number */
278 http_encryption_t encryption
; /* Type of encryption to use */
282 * Set the default encryption status...
286 encryption
= HTTP_ENCRYPT_ALWAYS
;
288 encryption
= HTTP_ENCRYPT_IF_REQUESTED
;
290 return (httpConnectEncrypt(host
, port
, encryption
));
295 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
298 http_t
* /* O - New HTTP connection */
300 const char *host
, /* I - Host to connect to */
301 int port
, /* I - Port number */
302 http_encryption_t encryption
) /* I - Type of encryption to use */
304 http_t
*http
; /* New HTTP connection */
305 http_addrlist_t
*addrlist
; /* Host address data */
306 char service
[255]; /* Service name */
309 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)\n",
310 host
? host
: "(null)", port
, encryption
));
321 sprintf(service
, "%d", port
);
323 if ((addrlist
= httpAddrGetList(host
, AF_UNSPEC
, service
)) == NULL
)
327 * Allocate memory for the structure...
330 http
= calloc(sizeof(http_t
), 1);
334 http
->version
= HTTP_1_1
;
336 http
->activity
= time(NULL
);
340 * Set the encryption status...
343 if (port
== 443) /* Always use encryption for https */
344 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
346 http
->encryption
= encryption
;
349 * Loop through the addresses we have until one of them connects...
352 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
355 * Connect to the remote system...
358 http
->addrlist
= addrlist
;
360 if (!httpReconnect(http
))
364 * Could not connect to any known address - bail out!
367 httpAddrFreeList(addrlist
);
376 * 'httpDelete()' - Send a DELETE request to the server.
379 int /* O - Status of call (0 = success) */
380 httpDelete(http_t
*http
, /* I - HTTP connection */
381 const char *uri
) /* I - URI to delete */
383 return (http_send(http
, HTTP_DELETE
, uri
));
388 * 'httpEncryption()' - Set the required encryption on the link.
391 int /* O - -1 on error, 0 on success */
392 httpEncryption(http_t
*http
, /* I - HTTP connection */
393 http_encryption_t e
) /* I - New encryption preference */
395 DEBUG_printf(("httpEncryption(http=%p, e=%d)\n", http
, e
));
401 http
->encryption
= e
;
403 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
404 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
405 return (httpReconnect(http
));
406 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
407 return (http_upgrade(http
));
411 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
415 #endif /* HAVE_SSL */
420 * 'httpError()' - Get the last error on a connection.
423 int /* O - Error code (errno) value */
424 httpError(http_t
*http
) /* I - HTTP connection */
427 return (http
->error
);
434 * 'httpFlush()' - Flush data from a HTTP connection.
438 httpFlush(http_t
*http
) /* I - HTTP connection */
440 char buffer
[8192]; /* Junk buffer */
441 int blocking
; /* To block or not to block */
444 DEBUG_printf(("httpFlush(http=%p), state=%d\n", http
, http
->state
));
447 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
450 blocking
= http
->blocking
;
454 * Read any data we can...
457 while (httpRead2(http
, buffer
, sizeof(buffer
)) > 0);
460 * Restore blocking and reset the connection if we didn't get all of
461 * the remaining data...
464 http
->blocking
= blocking
;
466 if (http
->state
!= HTTP_WAITING
&& http
->fd
>= 0)
469 * Didn't get the data back, so close the current connection.
472 http
->state
= HTTP_WAITING
;
476 http_shutdown_ssl(http
);
477 #endif /* HAVE_SSL */
480 closesocket(http
->fd
);
491 * 'httpFlushWrite()' - Flush data in write buffer.
496 int /* O - Bytes written or -1 on error */
497 httpFlushWrite(http_t
*http
) /* I - HTTP connection */
499 int bytes
; /* Bytes written */
502 DEBUG_printf(("httpFlushWrite(http=%p)\n", http
));
504 if (!http
|| !http
->wused
)
507 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
508 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
510 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
519 * 'httpGet()' - Send a GET request to the server.
522 int /* O - Status of call (0 = success) */
523 httpGet(http_t
*http
, /* I - HTTP connection */
524 const char *uri
) /* I - URI to get */
526 return (http_send(http
, HTTP_GET
, uri
));
531 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
536 int /* O - 1 if blocking, 0 if non-blocking */
537 httpGetBlocking(http_t
*http
) /* I - HTTP connection */
539 return (http
? http
->blocking
: 0);
544 * 'httpGetCookie()' - Get any cookie data from the response.
546 * @since CUPS 1.1.19@
549 const char * /* O - Cookie data or NULL */
550 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
552 return (http
? http
->cookie
: NULL
);
557 * 'httpGetFd()' - Get the file descriptor associated with a connection.
562 int /* O - File descriptor or -1 if none */
563 httpGetFd(http_t
*http
) /* I - HTTP connection */
565 return (http
? http
->fd
: -1);
570 * 'httpGetField()' - Get a field value from a request/response.
573 const char * /* O - Field value */
574 httpGetField(http_t
*http
, /* I - HTTP connection */
575 http_field_t field
) /* I - Field to get */
577 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
580 return (http
->fields
[field
]);
585 * 'httpGetLength()' - Get the amount of data remaining from the
586 * content-length or transfer-encoding fields.
588 * This function is deprecated and will not return lengths larger than
589 * 2^31 - 1; use httpGetLength2() instead.
594 int /* O - Content length */
595 httpGetLength(http_t
*http
) /* I - HTTP connection */
598 * Get the read content length and return the 32-bit value.
603 httpGetLength2(http
);
605 return (http
->_data_remaining
);
613 * 'httpGetLength2()' - Get the amount of data remaining from the
614 * content-length or transfer-encoding fields.
616 * This function returns the complete content length, even for
617 * content larger than 2^31 - 1.
622 off_t
/* O - Content length */
623 httpGetLength2(http_t
*http
) /* I - HTTP connection */
625 DEBUG_printf(("httpGetLength2(http=%p), state=%d\n", http
, http
->state
));
630 if (!strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
632 DEBUG_puts("httpGetLength2: chunked request!");
634 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
635 http
->data_remaining
= 0;
639 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
642 * The following is a hack for HTTP servers that don't send a
643 * content-length or transfer-encoding field...
645 * If there is no content-length then the connection must close
646 * after the transfer is complete...
649 if (http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] == '\0')
650 http
->data_remaining
= 2147483647;
652 http
->data_remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
655 DEBUG_printf(("httpGetLength2: content_length=" CUPS_LLFMT
"\n",
656 CUPS_LLCAST http
->data_remaining
));
659 if (http
->data_remaining
<= INT_MAX
)
660 http
->_data_remaining
= (int)http
->data_remaining
;
662 http
->_data_remaining
= INT_MAX
;
664 return (http
->data_remaining
);
669 * 'httpGetStatus()' - Get the status of the last HTTP request.
674 http_status_t
/* O - HTTP status */
675 httpGetStatus(http_t
*http
) /* I - HTTP connection */
677 return (http
? http
->status
: HTTP_ERROR
);
682 * 'httpGetSubField()' - Get a sub-field value.
687 char * /* O - Value or NULL */
688 httpGetSubField(http_t
*http
, /* I - HTTP connection */
689 http_field_t field
, /* I - Field index */
690 const char *name
, /* I - Name of sub-field */
691 char *value
) /* O - Value string */
693 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
698 * 'httpGetSubField2()' - Get a sub-field value.
703 char * /* O - Value or NULL */
704 httpGetSubField2(http_t
*http
, /* I - HTTP connection */
705 http_field_t field
, /* I - Field index */
706 const char *name
, /* I - Name of sub-field */
707 char *value
, /* O - Value string */
708 int valuelen
) /* I - Size of value buffer */
710 const char *fptr
; /* Pointer into field */
711 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
712 *ptr
, /* Pointer into string buffer */
713 *end
; /* End of value buffer */
715 DEBUG_printf(("httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, valuelen=%d)\n",
716 http
, field
, name
, value
, valuelen
));
718 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
719 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
722 end
= value
+ valuelen
- 1;
724 for (fptr
= http
->fields
[field
]; *fptr
;)
727 * Skip leading whitespace...
730 while (isspace(*fptr
& 255))
740 * Get the sub-field name...
744 *fptr
&& *fptr
!= '=' && !isspace(*fptr
& 255) &&
745 ptr
< (temp
+ sizeof(temp
) - 1);
750 DEBUG_printf(("httpGetSubField: name=\"%s\"\n", temp
));
753 * Skip trailing chars up to the '='...
756 while (isspace(*fptr
& 255))
766 * Skip = and leading whitespace...
771 while (isspace(*fptr
& 255))
777 * Read quoted string...
780 for (ptr
= value
, fptr
++;
781 *fptr
&& *fptr
!= '\"' && ptr
< end
;
786 while (*fptr
&& *fptr
!= '\"')
795 * Read unquoted string...
799 *fptr
&& !isspace(*fptr
& 255) && *fptr
!= ',' && ptr
< end
;
804 while (*fptr
&& !isspace(*fptr
& 255) && *fptr
!= ',')
808 DEBUG_printf(("httpGetSubField: value=\"%s\"\n", value
));
811 * See if this is the one...
814 if (!strcmp(name
, temp
))
825 * 'httpGets()' - Get a line of text from a HTTP connection.
828 char * /* O - Line or NULL */
829 httpGets(char *line
, /* I - Line to read into */
830 int length
, /* I - Max length of buffer */
831 http_t
*http
) /* I - HTTP connection */
833 char *lineptr
, /* Pointer into line */
834 *lineend
, /* End of line */
835 *bufptr
, /* Pointer into input buffer */
836 *bufend
; /* Pointer to end of buffer */
837 int bytes
, /* Number of bytes read */
838 eol
; /* End-of-line? */
841 DEBUG_printf(("httpGets(line=%p, length=%d, http=%p)\n", line
, length
, http
));
843 if (http
== NULL
|| line
== NULL
)
847 * Read a line from the buffer...
851 lineend
= line
+ length
- 1;
854 while (lineptr
< lineend
)
857 * Pre-load the buffer as needed...
866 while (http
->used
== 0)
869 * No newline; see if there is more data to be read...
872 if (!http
->blocking
&& !http_wait(http
, 10000))
874 DEBUG_puts("httpGets: Timed out!");
875 http
->error
= ETIMEDOUT
;
881 bytes
= http_read_ssl(http
, http
->buffer
+ http
->used
,
882 HTTP_MAX_BUFFER
- http
->used
);
884 #endif /* HAVE_SSL */
885 bytes
= recv(http
->fd
, http
->buffer
+ http
->used
,
886 HTTP_MAX_BUFFER
- http
->used
, 0);
888 DEBUG_printf(("httpGets: read %d bytes...\n", bytes
));
893 * Nope, can't get a line this time...
897 if (WSAGetLastError() != http
->error
)
899 http
->error
= WSAGetLastError();
903 DEBUG_printf(("httpGets: recv() error %d!\n", WSAGetLastError()));
905 DEBUG_printf(("httpGets: recv() error %d!\n", errno
));
909 else if (errno
!= http
->error
)
926 * Yup, update the amount used...
933 * Now copy as much of the current line as possible...
936 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
937 lineptr
< lineend
&& bufptr
< bufend
;)
945 else if (*bufptr
== 0x0d)
948 *lineptr
++ = *bufptr
++;
951 http
->used
-= bufptr
- http
->buffer
;
953 memmove(http
->buffer
, bufptr
, http
->used
);
961 http
->activity
= time(NULL
);
965 DEBUG_printf(("httpGets: Returning \"%s\"\n", line
));
971 DEBUG_puts("httpGets: No new line available!");
978 * 'httpHead()' - Send a HEAD request to the server.
981 int /* O - Status of call (0 = success) */
982 httpHead(http_t
*http
, /* I - HTTP connection */
983 const char *uri
) /* I - URI for head */
985 return (http_send(http
, HTTP_HEAD
, uri
));
990 * 'httpInitialize()' - Initialize the HTTP interface library and set the
991 * default HTTP proxy (if any).
999 struct timeval curtime
; /* Current time in microseconds */
1000 # endif /* !WIN32 */
1001 int i
; /* Looping var */
1002 unsigned char data
[1024]; /* Seed data */
1003 #endif /* HAVE_LIBSSL */
1006 WSADATA winsockdata
; /* WinSock data */
1007 static int initialized
= 0; /* Has WinSock been initialized? */
1011 WSAStartup(MAKEWORD(1,1), &winsockdata
);
1012 #elif !defined(SO_NOSIGPIPE)
1014 * Ignore SIGPIPE signals...
1018 sigset(SIGPIPE
, SIG_IGN
);
1019 # elif defined(HAVE_SIGACTION)
1020 struct sigaction action
; /* POSIX sigaction data */
1023 memset(&action
, 0, sizeof(action
));
1024 action
.sa_handler
= SIG_IGN
;
1025 sigaction(SIGPIPE
, &action
, NULL
);
1027 signal(SIGPIPE
, SIG_IGN
);
1028 # endif /* !SO_NOSIGPIPE */
1032 gnutls_global_init();
1033 #endif /* HAVE_GNUTLS */
1036 SSL_load_error_strings();
1040 * Using the current time is a dubious random seed, but on some systems
1041 * it is the best we can do (on others, this seed isn't even used...)
1046 gettimeofday(&curtime
, NULL
);
1047 srand(curtime
.tv_sec
+ curtime
.tv_usec
);
1050 for (i
= 0; i
< sizeof(data
); i
++)
1051 data
[i
] = rand(); /* Yes, this is a poor source of random data... */
1053 RAND_seed(&data
, sizeof(data
));
1054 #endif /* HAVE_LIBSSL */
1059 * 'httpOptions()' - Send an OPTIONS request to the server.
1062 int /* O - Status of call (0 = success) */
1063 httpOptions(http_t
*http
, /* I - HTTP connection */
1064 const char *uri
) /* I - URI for options */
1066 return (http_send(http
, HTTP_OPTIONS
, uri
));
1071 * 'httpPost()' - Send a POST request to the server.
1074 int /* O - Status of call (0 = success) */
1075 httpPost(http_t
*http
, /* I - HTTP connection */
1076 const char *uri
) /* I - URI for post */
1078 return (http_send(http
, HTTP_POST
, uri
));
1083 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1088 int /* O - Number of bytes written */
1089 httpPrintf(http_t
*http
, /* I - HTTP connection */
1090 const char *format
, /* I - printf-style format string */
1091 ...) /* I - Additional args as needed */
1093 int bytes
; /* Number of bytes to write */
1094 char buf
[16384]; /* Buffer for formatted string */
1095 va_list ap
; /* Variable argument pointer */
1098 DEBUG_printf(("httpPrintf(http=%p, format=\"%s\", ...)\n", http
, format
));
1100 va_start(ap
, format
);
1101 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1104 DEBUG_printf(("httpPrintf: %s", buf
));
1106 if (http
->data_encoding
== HTTP_ENCODE_FIELDS
)
1107 return (httpWrite2(http
, buf
, bytes
));
1112 DEBUG_puts(" flushing existing data...");
1114 if (httpFlushWrite(http
) < 0)
1118 return (http_write(http
, buf
, bytes
));
1124 * 'httpPut()' - Send a PUT request to the server.
1127 int /* O - Status of call (0 = success) */
1128 httpPut(http_t
*http
, /* I - HTTP connection */
1129 const char *uri
) /* I - URI to put */
1131 return (http_send(http
, HTTP_PUT
, uri
));
1136 * 'httpRead()' - Read data from a HTTP connection.
1138 * This function is deprecated. Use the httpRead2() function which can
1139 * read more than 2GB of data.
1144 int /* O - Number of bytes read */
1145 httpRead(http_t
*http
, /* I - HTTP connection */
1146 char *buffer
, /* I - Buffer for data */
1147 int length
) /* I - Maximum number of bytes */
1149 return ((int)httpRead2(http
, buffer
, length
));
1154 * 'httpRead2()' - Read data from a HTTP connection.
1159 ssize_t
/* O - Number of bytes read */
1160 httpRead2(http_t
*http
, /* I - HTTP connection */
1161 char *buffer
, /* I - Buffer for data */
1162 size_t length
) /* I - Maximum number of bytes */
1164 ssize_t bytes
; /* Bytes read */
1165 char len
[32]; /* Length string */
1168 DEBUG_printf(("httpRead(http=%p, buffer=%p, length=%d)\n",
1169 http
, buffer
, length
));
1171 if (http
== NULL
|| buffer
== NULL
)
1174 http
->activity
= time(NULL
);
1179 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1180 http
->data_remaining
<= 0)
1182 DEBUG_puts("httpRead2: Getting chunk length...");
1184 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1186 DEBUG_puts("httpRead2: Could not get length!");
1190 http
->data_remaining
= strtoll(len
, NULL
, 16);
1191 if (http
->data_remaining
< 0)
1193 DEBUG_puts("httpRead2: Negative chunk length!");
1198 DEBUG_printf(("httpRead2: data_remaining=" CUPS_LLFMT
"\n",
1199 CUPS_LLCAST http
->data_remaining
));
1201 if (http
->data_remaining
<= 0)
1204 * A zero-length chunk ends a transfer; unless we are reading POST
1208 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1209 httpGets(len
, sizeof(len
), http
);
1211 if (http
->state
== HTTP_POST_RECV
)
1214 http
->state
= HTTP_WAITING
;
1217 * Prevent future reads for this request...
1220 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1224 else if (length
> http
->data_remaining
)
1225 length
= http
->data_remaining
;
1227 if (http
->used
== 0 && length
<= 256)
1230 * Buffer small reads for better performance...
1233 if (!http
->blocking
&& !httpWait(http
, 10000))
1236 if (http
->data_remaining
> sizeof(http
->buffer
))
1237 bytes
= sizeof(http
->buffer
);
1239 bytes
= http
->data_remaining
;
1243 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1245 #endif /* HAVE_SSL */
1247 DEBUG_printf(("httpRead2: reading %d bytes from socket into buffer...\n",
1250 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1252 DEBUG_printf(("httpRead2: read %d bytes from socket into buffer...\n",
1261 http
->error
= WSAGetLastError();
1266 http
->error
= errno
;
1273 http
->error
= EPIPE
;
1280 if (length
> http
->used
)
1281 length
= http
->used
;
1285 DEBUG_printf(("httpRead2: grabbing %d bytes from input buffer...\n", bytes
));
1287 memcpy(buffer
, http
->buffer
, length
);
1288 http
->used
-= length
;
1291 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
1296 if (!http
->blocking
&& !httpWait(http
, 10000))
1299 bytes
= http_read_ssl(http
, buffer
, length
);
1301 #endif /* HAVE_SSL */
1304 if (!http
->blocking
&& !httpWait(http
, 10000))
1307 DEBUG_printf(("httpRead2: reading %d bytes from socket...\n", length
));
1309 while ((bytes
= recv(http
->fd
, buffer
, length
, 0)) < 0)
1313 DEBUG_printf(("httpRead2: read %d bytes from socket...\n", bytes
));
1318 http
->data_remaining
-= bytes
;
1320 if (http
->data_remaining
<= INT_MAX
)
1321 http
->_data_remaining
= (int)http
->data_remaining
;
1323 http
->_data_remaining
= INT_MAX
;
1328 http
->error
= WSAGetLastError();
1333 http
->error
= errno
;
1338 http
->error
= EPIPE
;
1342 if (http
->data_remaining
== 0)
1344 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1345 httpGets(len
, sizeof(len
), http
);
1347 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
1349 if (http
->state
== HTTP_POST_RECV
)
1352 http
->state
= HTTP_WAITING
;
1359 printf("httpRead2: Read %d bytes:\n", bytes
);
1360 for (i
= 0; i
< bytes
; i
+= 16)
1364 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1365 printf(" %02X", buffer
[i
+ j
] & 255);
1374 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1376 ch
= buffer
[i
+ j
] & 255;
1378 if (ch
< ' ' || ch
>= 127)
1392 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
1394 * '_httpReadCDSA()' - Read function for CDSA decryption code.
1397 OSStatus
/* O - -1 on error, 0 on success */
1399 SSLConnectionRef connection
, /* I - SSL/TLS connection */
1400 void *data
, /* I - Data buffer */
1401 size_t *dataLength
) /* IO - Number of bytes */
1403 OSStatus result
; /* Return value */
1404 ssize_t bytes
; /* Number of bytes read */
1405 cdsa_conn_ref_t u
; /* Connection reference union */
1408 u
.connection
= connection
;
1411 bytes
= recv(u
.sock
, data
, *dataLength
, 0);
1412 while (bytes
== -1 && errno
== EINTR
);
1414 if (bytes
== *dataLength
)
1418 *dataLength
= bytes
;
1419 result
= errSSLWouldBlock
;
1426 result
= errSSLClosedGraceful
;
1427 else if (errno
== EAGAIN
)
1428 result
= errSSLWouldBlock
;
1430 result
= errSSLClosedAbort
;
1435 #endif /* HAVE_SSL && HAVE_CDSASSL */
1439 * 'httpReconnect()' - Reconnect to a HTTP server.
1442 int /* O - 0 on success, non-zero on failure */
1443 httpReconnect(http_t
*http
) /* I - HTTP connection */
1445 http_addrlist_t
*addr
; /* Connected address */
1448 DEBUG_printf(("httpReconnect(http=%p)\n", http
));
1455 http_shutdown_ssl(http
);
1456 #endif /* HAVE_SSL */
1459 * Close any previously open socket...
1465 closesocket(http
->fd
);
1474 * Connect to the server...
1477 if ((addr
= httpAddrConnect(http
->addrlist
, &(http
->fd
))) == NULL
)
1480 * Unable to connect...
1484 http
->error
= WSAGetLastError();
1486 http
->error
= errno
;
1488 http
->status
= HTTP_ERROR
;
1493 http
->hostaddr
= &(addr
->addr
);
1495 http
->status
= HTTP_CONTINUE
;
1498 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
1501 * Always do encryption via SSL.
1504 if (http_setup_ssl(http
) != 0)
1507 closesocket(http
->fd
);
1515 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
1516 return (http_upgrade(http
));
1517 #endif /* HAVE_SSL */
1524 * 'httpSetCookie()' - Set the cookie value(s)...
1526 * @since CUPS 1.1.19@
1530 httpSetCookie(http_t
*http
, /* I - Connection */
1531 const char *cookie
) /* I - Cookie string */
1540 http
->cookie
= strdup(cookie
);
1542 http
->cookie
= NULL
;
1547 * 'httpSetExpect()' - Set the Expect: header in a request.
1549 * Currently only HTTP_CONTINUE is supported for the "expect" argument.
1555 httpSetExpect(http_t
*http
, /* I - HTTP connection */
1556 http_status_t expect
) /* I - HTTP status to expect (HTTP_CONTINUE) */
1559 http
->expect
= expect
;
1564 * 'httpSetField()' - Set the value of an HTTP header.
1568 httpSetField(http_t
*http
, /* I - HTTP connection */
1569 http_field_t field
, /* I - Field index */
1570 const char *value
) /* I - Value */
1573 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
1574 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
1578 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
1583 * 'httpSetLength()' - Set the content-length and content-encoding.
1589 httpSetLength(http_t
*http
, /* I - HTTP connection */
1590 size_t length
) /* I - Length (0 for chunked) */
1597 strcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked");
1598 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
1602 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
1603 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
1604 CUPS_LLFMT
, CUPS_LLCAST length
);
1610 * 'httpTrace()' - Send an TRACE request to the server.
1613 int /* O - Status of call (0 = success) */
1614 httpTrace(http_t
*http
, /* I - HTTP connection */
1615 const char *uri
) /* I - URI for trace */
1617 return (http_send(http
, HTTP_TRACE
, uri
));
1622 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1625 http_status_t
/* O - HTTP status */
1626 httpUpdate(http_t
*http
) /* I - HTTP connection */
1628 char line
[32768], /* Line from connection... */
1629 *value
; /* Pointer to value on line */
1630 http_field_t field
; /* Field index */
1631 int major
, minor
, /* HTTP version numbers */
1632 status
; /* Request status */
1635 DEBUG_printf(("httpUpdate(http=%p), state=%d\n", http
, http
->state
));
1638 * Flush pending data, if any...
1643 DEBUG_puts(" flushing buffer...");
1645 if (httpFlushWrite(http
) < 0)
1646 return (HTTP_ERROR
);
1650 * If we haven't issued any commands, then there is nothing to "update"...
1653 if (http
->state
== HTTP_WAITING
)
1654 return (HTTP_CONTINUE
);
1657 * Grab all of the lines we can from the connection...
1660 while (httpGets(line
, sizeof(line
), http
) != NULL
)
1662 DEBUG_printf(("httpUpdate: Got \"%s\"\n", line
));
1664 if (line
[0] == '\0')
1667 * Blank line means the start of the data section (if any). Return
1668 * the result code, too...
1670 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
1671 * Instead, we just return HTTP_CONTINUE to the caller and keep on
1675 if (http
->status
== HTTP_CONTINUE
)
1676 return (http
->status
);
1678 if (http
->status
< HTTP_BAD_REQUEST
)
1679 http
->digest_tries
= 0;
1682 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
1684 if (http_setup_ssl(http
) != 0)
1687 closesocket(http
->fd
);
1692 return (HTTP_ERROR
);
1695 return (HTTP_CONTINUE
);
1697 #endif /* HAVE_SSL */
1699 httpGetLength2(http
);
1701 switch (http
->state
)
1705 case HTTP_POST_RECV
:
1708 case HTTP_POST_SEND
:
1713 http
->state
= HTTP_WAITING
;
1717 return (http
->status
);
1719 else if (strncmp(line
, "HTTP/", 5) == 0)
1722 * Got the beginning of a response...
1725 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &status
) != 3)
1726 return (HTTP_ERROR
);
1728 http
->version
= (http_version_t
)(major
* 100 + minor
);
1729 http
->status
= (http_status_t
)status
;
1731 else if ((value
= strchr(line
, ':')) != NULL
)
1738 while (isspace(*value
& 255))
1742 * Be tolerants of servers that send unknown attribute fields...
1745 if (!strcasecmp(line
, "expect"))
1748 * "Expect: 100-continue" or similar...
1751 http
->expect
= (http_status_t
)atoi(value
);
1753 else if (!strcasecmp(line
, "cookie"))
1756 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
1759 httpSetCookie(http
, value
);
1761 else if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
1763 DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line
));
1767 httpSetField(http
, field
, value
);
1771 http
->status
= HTTP_ERROR
;
1772 return (HTTP_ERROR
);
1777 * See if there was an error...
1780 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
1781 return (http
->status
);
1785 DEBUG_printf(("httpUpdate: socket error %d - %s\n", http
->error
,
1786 strerror(http
->error
)));
1787 http
->status
= HTTP_ERROR
;
1788 return (HTTP_ERROR
);
1792 * If we haven't already returned, then there is nothing new...
1795 return (HTTP_CONTINUE
);
1800 * 'httpWait()' - Wait for data available on a connection.
1802 * @since CUPS 1.1.19@
1805 int /* O - 1 if data is available, 0 otherwise */
1806 httpWait(http_t
*http
, /* I - HTTP connection */
1807 int msec
) /* I - Milliseconds to wait */
1810 * First see if there is data in the buffer...
1820 * Flush pending data, if any...
1825 if (httpFlushWrite(http
) < 0)
1830 * If not, check the SSL/TLS buffers and do a select() on the connection...
1833 return (http_wait(http
, msec
));
1838 * 'httpWrite()' - Write data to a HTTP connection.
1840 * This function is deprecated. Use the httpWrite2() function which can
1841 * write more than 2GB of data.
1846 int /* O - Number of bytes written */
1847 httpWrite(http_t
*http
, /* I - HTTP connection */
1848 const char *buffer
, /* I - Buffer for data */
1849 int length
) /* I - Number of bytes to write */
1851 return ((int)httpWrite2(http
, buffer
, length
));
1856 * 'httpWrite2()' - Write data to a HTTP connection.
1861 ssize_t
/* O - Number of bytes written */
1862 httpWrite2(http_t
*http
, /* I - HTTP connection */
1863 const char *buffer
, /* I - Buffer for data */
1864 size_t length
) /* I - Number of bytes to write */
1866 ssize_t bytes
; /* Bytes written */
1869 DEBUG_printf(("httpWrite(http=%p, buffer=%p, length=%d)\n", http
,
1873 * Range check input...
1876 if (http
== NULL
|| buffer
== NULL
)
1880 * Mark activity on the connection...
1883 http
->activity
= time(NULL
);
1886 * Buffer small writes for better performance...
1891 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
1893 DEBUG_printf((" flushing buffer (wused=%d, length=%d)\n",
1894 http
->wused
, length
));
1896 httpFlushWrite(http
);
1899 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
))
1902 * Write to buffer...
1905 DEBUG_printf((" copying %d bytes to wbuffer...\n", length
));
1907 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
1908 http
->wused
+= length
;
1914 * Otherwise write the data directly...
1917 DEBUG_printf((" writing %d bytes to socket...\n", length
));
1919 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1920 bytes
= http_write_chunk(http
, buffer
, length
);
1922 bytes
= http_write(http
, buffer
, length
);
1924 DEBUG_printf((" wrote %d bytes...\n", bytes
));
1927 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1928 http
->data_remaining
-= bytes
;
1934 * Handle end-of-request processing...
1937 if ((http
->data_encoding
== HTTP_ENCODE_CHUNKED
&& length
== 0) ||
1938 (http
->data_encoding
== HTTP_ENCODE_LENGTH
&& http
->data_remaining
== 0))
1941 * Finished with the transfer; unless we are sending POST or PUT
1945 DEBUG_puts("httpWrite: changing states...");
1948 httpFlushWrite(http
);
1950 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1953 * Send a 0-length chunk at the end of the request...
1956 http_write(http
, "0\r\n\r\n", 5);
1959 * Reset the data state...
1962 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1963 http
->data_remaining
= 0;
1966 if (http
->state
== HTTP_POST_RECV
)
1968 else if (http
->state
== HTTP_PUT_RECV
)
1969 http
->state
= HTTP_STATUS
;
1971 http
->state
= HTTP_WAITING
;
1978 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
1980 * '_httpWriteCDSA()' - Write function for CDSA encryption code.
1983 OSStatus
/* O - -1 on error, 0 on success */
1985 SSLConnectionRef connection
, /* I - SSL/TLS connection */
1986 const void *data
, /* I - Data buffer */
1987 size_t *dataLength
) /* IO - Number of bytes */
1989 OSStatus result
; /* Return value */
1990 ssize_t bytes
; /* Number of bytes read */
1991 cdsa_conn_ref_t u
; /* Connection reference union */
1994 u
.connection
= connection
;
1997 bytes
= write(u
.sock
, data
, *dataLength
);
1998 while (bytes
== -1 && errno
== EINTR
);
2000 if (bytes
== *dataLength
)
2002 else if (bytes
>= 0)
2004 *dataLength
= bytes
;
2005 result
= errSSLWouldBlock
;
2011 if (errno
== EAGAIN
)
2012 result
= errSSLWouldBlock
;
2014 result
= errSSLClosedAbort
;
2019 #endif /* HAVE_SSL && HAVE_CDSASSL */
2023 * 'http_field()' - Return the field index for a field name.
2026 static http_field_t
/* O - Field index */
2027 http_field(const char *name
) /* I - String name */
2029 int i
; /* Looping var */
2032 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2033 if (strcasecmp(name
, http_fields
[i
]) == 0)
2034 return ((http_field_t
)i
);
2036 return (HTTP_FIELD_UNKNOWN
);
2042 * 'http_read_ssl()' - Read from a SSL/TLS connection.
2045 static int /* O - Bytes read */
2046 http_read_ssl(http_t
*http
, /* I - HTTP connection */
2047 char *buf
, /* I - Buffer to store data */
2048 int len
) /* I - Length of buffer */
2050 # if defined(HAVE_LIBSSL)
2051 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
2053 # elif defined(HAVE_GNUTLS)
2054 return (gnutls_record_recv(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
2056 # elif defined(HAVE_CDSASSL)
2057 int result
; /* Return value */
2058 OSStatus error
; /* Error info */
2059 size_t processed
; /* Number of bytes processed */
2062 error
= SSLRead(((http_tls_t
*)http
->tls
)->session
, buf
, len
, &processed
);
2067 result
= (int)processed
;
2069 case errSSLClosedGraceful
:
2072 case errSSLWouldBlock
:
2074 result
= (int)processed
;
2088 # endif /* HAVE_LIBSSL */
2090 #endif /* HAVE_SSL */
2094 * 'http_send()' - Send a request with all fields and the trailing blank line.
2097 static int /* O - 0 on success, non-zero on error */
2098 http_send(http_t
*http
, /* I - HTTP connection */
2099 http_state_t request
, /* I - Request code */
2100 const char *uri
) /* I - URI */
2102 int i
; /* Looping var */
2103 char *ptr
, /* Pointer in buffer */
2104 buf
[1024]; /* Encoded URI buffer */
2105 static const char * const codes
[] =
2106 { /* Request code strings */
2121 static const char hex
[] = "0123456789ABCDEF";
2125 DEBUG_printf(("http_send(http=%p, request=HTTP_%s, uri=\"%s\")\n",
2126 http
, codes
[request
], uri
));
2128 if (http
== NULL
|| uri
== NULL
)
2132 * Set the User-Agent field if it isn't already...
2135 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
2136 httpSetField(http
, HTTP_FIELD_USER_AGENT
, CUPS_MINIMAL
);
2139 * Encode the URI as needed...
2142 for (ptr
= buf
; *uri
!= '\0' && ptr
< (buf
+ sizeof(buf
) - 1); uri
++)
2143 if (*uri
<= ' ' || *uri
>= 127)
2145 if (ptr
< (buf
+ sizeof(buf
) - 1))
2147 if (ptr
< (buf
+ sizeof(buf
) - 1))
2148 *ptr
++ = hex
[(*uri
>> 4) & 15];
2149 if (ptr
< (buf
+ sizeof(buf
) - 1))
2150 *ptr
++ = hex
[*uri
& 15];
2158 * See if we had an error the last time around; if so, reconnect...
2161 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
2162 if (httpReconnect(http
))
2166 * Flush any written data that is pending...
2170 httpFlushWrite(http
);
2173 * Send the request header...
2176 http
->state
= request
;
2177 http
->data_encoding
= HTTP_ENCODE_FIELDS
;
2179 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
2182 http
->status
= HTTP_CONTINUE
;
2185 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
2187 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
2188 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
2190 #endif /* HAVE_SSL */
2192 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
2194 http
->status
= HTTP_ERROR
;
2198 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2199 if (http
->fields
[i
][0] != '\0')
2201 DEBUG_printf(("%s: %s\n", http_fields
[i
], http
->fields
[i
]));
2203 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], http
->fields
[i
]) < 1)
2205 http
->status
= HTTP_ERROR
;
2211 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
2213 http
->status
= HTTP_ERROR
;
2217 if (http
->expect
== HTTP_CONTINUE
&&
2218 (http
->state
== HTTP_POST_RECV
|| http
->state
== HTTP_PUT_RECV
))
2219 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
2221 http
->status
= HTTP_ERROR
;
2225 if (httpPrintf(http
, "\r\n") < 1)
2227 http
->status
= HTTP_ERROR
;
2231 httpFlushWrite(http
);
2232 httpGetLength2(http
);
2233 httpClearFields(http
);
2241 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
2244 static int /* O - Status of connection */
2245 http_setup_ssl(http_t
*http
) /* I - HTTP connection */
2248 SSL_CTX
*context
; /* Context for encryption */
2249 SSL
*conn
; /* Connection for encryption */
2250 # elif defined(HAVE_GNUTLS)
2251 http_tls_t
*conn
; /* TLS session object */
2252 gnutls_certificate_client_credentials
*credentials
;
2253 /* TLS credentials */
2254 # elif defined(HAVE_CDSASSL)
2255 OSStatus error
; /* Error code */
2256 http_tls_t
*conn
; /* CDSA connection information */
2257 cdsa_conn_ref_t u
; /* Connection reference union */
2258 # endif /* HAVE_LIBSSL */
2261 DEBUG_printf(("http_setup_ssl(http=%p)\n", http
));
2264 context
= SSL_CTX_new(SSLv23_client_method());
2266 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
2268 conn
= SSL_new(context
);
2270 SSL_set_fd(conn
, http
->fd
);
2271 if (SSL_connect(conn
) != 1)
2274 unsigned long error
; /* Error code */
2276 while ((error
= ERR_get_error()) != 0)
2277 printf("http_setup_ssl: %s\n", ERR_error_string(error
, NULL
));
2280 SSL_CTX_free(context
);
2284 http
->error
= WSAGetLastError();
2286 http
->error
= errno
;
2288 http
->status
= HTTP_ERROR
;
2290 return (HTTP_ERROR
);
2293 # elif defined(HAVE_GNUTLS)
2294 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
2296 http
->error
= errno
;
2297 http
->status
= HTTP_ERROR
;
2302 credentials
= (gnutls_certificate_client_credentials
*)
2303 malloc(sizeof(gnutls_certificate_client_credentials
));
2304 if (credentials
== NULL
)
2308 http
->error
= errno
;
2309 http
->status
= HTTP_ERROR
;
2314 gnutls_certificate_allocate_credentials(credentials
);
2316 gnutls_init(&(conn
->session
), GNUTLS_CLIENT
);
2317 gnutls_set_default_priority(conn
->session
);
2318 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
2319 gnutls_transport_set_ptr(conn
->session
,
2320 (gnutls_transport_ptr
)((long)http
->fd
));
2322 if ((gnutls_handshake(conn
->session
)) != GNUTLS_E_SUCCESS
)
2324 http
->error
= errno
;
2325 http
->status
= HTTP_ERROR
;
2330 conn
->credentials
= credentials
;
2332 # elif defined(HAVE_CDSASSL)
2333 conn
= (http_tls_t
*)calloc(1, sizeof(http_tls_t
));
2338 if ((error
= SSLNewContext(false, &conn
->session
)))
2340 http
->error
= error
;
2341 http
->status
= HTTP_ERROR
;
2348 * Use a union to resolve warnings about int/pointer size mismatches...
2351 u
.connection
= NULL
;
2353 error
= SSLSetConnection(conn
->session
, u
.connection
);
2356 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
2359 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
2362 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
2365 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
2369 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
2375 http
->error
= error
;
2376 http
->status
= HTTP_ERROR
;
2378 SSLDisposeContext(conn
->session
);
2384 # endif /* HAVE_CDSASSL */
2389 #endif /* HAVE_SSL */
2394 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
2398 http_shutdown_ssl(http_t
*http
) /* I - HTTP connection */
2401 SSL_CTX
*context
; /* Context for encryption */
2402 SSL
*conn
; /* Connection for encryption */
2405 conn
= (SSL
*)(http
->tls
);
2406 context
= SSL_get_SSL_CTX(conn
);
2409 SSL_CTX_free(context
);
2412 # elif defined(HAVE_GNUTLS)
2413 http_tls_t
*conn
; /* Encryption session */
2414 gnutls_certificate_client_credentials
*credentials
;
2415 /* TLS credentials */
2418 conn
= (http_tls_t
*)(http
->tls
);
2419 credentials
= (gnutls_certificate_client_credentials
*)(conn
->credentials
);
2421 gnutls_bye(conn
->session
, GNUTLS_SHUT_RDWR
);
2422 gnutls_deinit(conn
->session
);
2423 gnutls_certificate_free_credentials(*credentials
);
2427 # elif defined(HAVE_CDSASSL)
2428 http_tls_t
*conn
; /* CDSA connection information */
2431 conn
= (http_tls_t
*)(http
->tls
);
2433 while (SSLClose(conn
->session
) == errSSLWouldBlock
)
2436 SSLDisposeContext(conn
->session
);
2438 if (conn
->certsArray
)
2439 CFRelease(conn
->certsArray
);
2442 # endif /* HAVE_LIBSSL */
2446 #endif /* HAVE_SSL */
2451 * 'http_upgrade()' - Force upgrade to TLS encryption.
2454 static int /* O - Status of connection */
2455 http_upgrade(http_t
*http
) /* I - HTTP connection */
2457 int ret
; /* Return value */
2458 http_t myhttp
; /* Local copy of HTTP data */
2461 DEBUG_printf(("http_upgrade(%p)\n", http
));
2464 * Copy the HTTP data to a local variable so we can do the OPTIONS
2465 * request without interfering with the existing request data...
2468 memcpy(&myhttp
, http
, sizeof(myhttp
));
2471 * Send an OPTIONS request to the server, requiring SSL or TLS
2472 * encryption on the link...
2475 httpClearFields(&myhttp
);
2476 httpSetField(&myhttp
, HTTP_FIELD_CONNECTION
, "upgrade");
2477 httpSetField(&myhttp
, HTTP_FIELD_UPGRADE
, "TLS/1.0, SSL/2.0, SSL/3.0");
2479 if ((ret
= httpOptions(&myhttp
, "*")) == 0)
2482 * Wait for the secure connection...
2485 while (httpUpdate(&myhttp
) == HTTP_CONTINUE
);
2491 * Copy the HTTP data back over, if any...
2494 http
->fd
= myhttp
.fd
;
2495 http
->error
= myhttp
.error
;
2496 http
->activity
= myhttp
.activity
;
2497 http
->status
= myhttp
.status
;
2498 http
->version
= myhttp
.version
;
2499 http
->keep_alive
= myhttp
.keep_alive
;
2500 http
->used
= myhttp
.used
;
2503 memcpy(http
->buffer
, myhttp
.buffer
, http
->used
);
2505 http
->auth_type
= myhttp
.auth_type
;
2506 http
->nonce_count
= myhttp
.nonce_count
;
2508 memcpy(http
->nonce
, myhttp
.nonce
, sizeof(http
->nonce
));
2510 http
->tls
= myhttp
.tls
;
2511 http
->encryption
= myhttp
.encryption
;
2514 * See if we actually went secure...
2520 * Server does not support HTTP upgrade...
2523 DEBUG_puts("Server does not support HTTP upgrade!");
2526 closesocket(http
->fd
);
2538 #endif /* HAVE_SSL */
2542 * 'http_wait()' - Wait for data available on a connection.
2545 static int /* O - 1 if data is available, 0 otherwise */
2546 http_wait(http_t
*http
, /* I - HTTP connection */
2547 int msec
) /* I - Milliseconds to wait */
2550 struct rlimit limit
; /* Runtime limit */
2551 int set_size
; /* Size of select set */
2553 struct timeval timeout
; /* Timeout */
2554 int nfds
; /* Result from select() */
2557 DEBUG_printf(("http_wait(http=%p, msec=%d)\n", http
, msec
));
2563 * Check the SSL/TLS buffers for data first...
2570 if (SSL_pending((SSL
*)(http
->tls
)))
2572 # elif defined(HAVE_GNUTLS)
2573 if (gnutls_record_check_pending(((http_tls_t
*)(http
->tls
))->session
))
2575 # elif defined(HAVE_CDSASSL)
2576 size_t bytes
; /* Bytes that are available */
2578 if (!SSLGetBufferedReadSize(((http_tls_t
*)http
->tls
)->session
, &bytes
) && bytes
> 0)
2580 # endif /* HAVE_LIBSSL */
2582 #endif /* HAVE_SSL */
2585 * Then try doing a select() to poll the socket...
2588 if (!http
->input_set
)
2592 * Windows has a fixed-size select() structure, different (surprise,
2593 * surprise!) from all UNIX implementations. Just allocate this
2594 * fixed structure...
2597 http
->input_set
= calloc(1, sizeof(fd_set
));
2600 * Allocate the select() input set based upon the max number of file
2601 * descriptors available for this process...
2604 getrlimit(RLIMIT_NOFILE
, &limit
);
2606 set_size
= (limit
.rlim_cur
+ 31) / 8 + 4;
2607 if (set_size
< sizeof(fd_set
))
2608 set_size
= sizeof(fd_set
);
2610 http
->input_set
= calloc(1, set_size
);
2613 if (!http
->input_set
)
2619 FD_SET(http
->fd
, http
->input_set
);
2621 DEBUG_printf(("http_wait: msec=%d, http->fd=%d\n", msec
, http
->fd
));
2625 timeout
.tv_sec
= msec
/ 1000;
2626 timeout
.tv_usec
= (msec
% 1000) * 1000;
2628 nfds
= select(http
->fd
+ 1, http
->input_set
, NULL
, NULL
, &timeout
);
2631 nfds
= select(http
->fd
+ 1, http
->input_set
, NULL
, NULL
, NULL
);
2633 DEBUG_printf(("http_wait: select() returned %d...\n", nfds
));
2636 while (nfds
< 0 && WSAGetLastError() == WSAEINTR
);
2638 while (nfds
< 0 && errno
== EINTR
);
2641 FD_CLR(http
->fd
, http
->input_set
);
2643 DEBUG_printf(("http_wait: returning with nfds=%d...\n", nfds
));
2650 * 'http_write()' - Write a buffer to a HTTP connection.
2653 static int /* O - Number of bytes written */
2654 http_write(http_t
*http
, /* I - HTTP connection */
2655 const char *buffer
, /* I - Buffer for data */
2656 int length
) /* I - Number of bytes to write */
2658 int tbytes
, /* Total bytes sent */
2659 bytes
; /* Bytes sent */
2668 bytes
= http_write_ssl(http
, buffer
, length
);
2670 #endif /* HAVE_SSL */
2671 bytes
= send(http
->fd
, buffer
, length
, 0);
2676 if (WSAGetLastError() != http
->error
)
2678 http
->error
= WSAGetLastError();
2684 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
2686 http
->error
= errno
;
2691 DEBUG_puts("http_write: error writing data...\n");
2704 printf("http_write: wrote %d bytes: \n", tbytes
);
2705 for (i
= 0, buffer
-= tbytes
; i
< tbytes
; i
+= 16)
2709 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
2710 printf(" %02X", buffer
[i
+ j
] & 255);
2719 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
2721 ch
= buffer
[i
+ j
] & 255;
2723 if (ch
< ' ' || ch
== 127)
2738 * 'http_write_chunk()' - Write a chunked buffer.
2741 static int /* O - Number bytes written */
2742 http_write_chunk(http_t
*http
, /* I - HTTP connection */
2743 const char *buffer
, /* I - Buffer to write */
2744 int length
) /* I - Length of buffer */
2746 char header
[255]; /* Chunk header */
2747 int bytes
; /* Bytes written */
2749 DEBUG_printf(("http_write_chunk(http=%p, buffer=%p, length=%d)\n",
2750 http
, buffer
, length
));
2753 * Write the chunk header, data, and trailer.
2756 sprintf(header
, "%x\r\n", length
);
2757 if (http_write(http
, header
, strlen(header
)) < 0)
2759 DEBUG_puts(" http_write of length failed!");
2763 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
2765 DEBUG_puts(" http_write of buffer failed!");
2769 if (http_write(http
, "\r\n", 2) < 0)
2771 DEBUG_puts(" http_write of CR LF failed!");
2781 * 'http_write_ssl()' - Write to a SSL/TLS connection.
2784 static int /* O - Bytes written */
2785 http_write_ssl(http_t
*http
, /* I - HTTP connection */
2786 const char *buf
, /* I - Buffer holding data */
2787 int len
) /* I - Length of buffer */
2789 # if defined(HAVE_LIBSSL)
2790 return (SSL_write((SSL
*)(http
->tls
), buf
, len
));
2792 # elif defined(HAVE_GNUTLS)
2793 return (gnutls_record_send(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
2794 # elif defined(HAVE_CDSASSL)
2795 int result
; /* Return value */
2796 OSStatus error
; /* Error info */
2797 size_t processed
; /* Number of bytes processed */
2800 error
= SSLWrite(((http_tls_t
*)http
->tls
)->session
, buf
, len
, &processed
);
2805 result
= (int)processed
;
2807 case errSSLClosedGraceful
:
2810 case errSSLWouldBlock
:
2812 result
= (int)processed
;
2826 # endif /* HAVE_LIBSSL */
2828 #endif /* HAVE_SSL */
2832 * End of "$Id: http.c 5961 2006-09-16 19:08:36Z mike $".