2 * "$Id: http.c 5282 2006-03-13 12:10:33Z 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
, 1000))
874 bytes
= http_read_ssl(http
, http
->buffer
+ http
->used
,
875 HTTP_MAX_BUFFER
- http
->used
);
877 #endif /* HAVE_SSL */
878 bytes
= recv(http
->fd
, http
->buffer
+ http
->used
,
879 HTTP_MAX_BUFFER
- http
->used
, 0);
881 DEBUG_printf(("httpGets: read %d bytes...\n", bytes
));
886 * Nope, can't get a line this time...
890 if (WSAGetLastError() != http
->error
)
892 http
->error
= WSAGetLastError();
896 DEBUG_printf(("httpGets: recv() error %d!\n", WSAGetLastError()));
898 DEBUG_printf(("httpGets: recv() error %d!\n", errno
));
902 else if (errno
!= http
->error
)
919 * Yup, update the amount used...
926 * Now copy as much of the current line as possible...
929 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
930 lineptr
< lineend
&& bufptr
< bufend
;)
938 else if (*bufptr
== 0x0d)
941 *lineptr
++ = *bufptr
++;
944 http
->used
-= bufptr
- http
->buffer
;
946 memmove(http
->buffer
, bufptr
, http
->used
);
954 http
->activity
= time(NULL
);
958 DEBUG_printf(("httpGets: Returning \"%s\"\n", line
));
964 DEBUG_puts("httpGets: No new line available!");
971 * 'httpHead()' - Send a HEAD request to the server.
974 int /* O - Status of call (0 = success) */
975 httpHead(http_t
*http
, /* I - HTTP connection */
976 const char *uri
) /* I - URI for head */
978 return (http_send(http
, HTTP_HEAD
, uri
));
983 * 'httpInitialize()' - Initialize the HTTP interface library and set the
984 * default HTTP proxy (if any).
992 struct timeval curtime
; /* Current time in microseconds */
994 int i
; /* Looping var */
995 unsigned char data
[1024]; /* Seed data */
996 #endif /* HAVE_LIBSSL */
999 WSADATA winsockdata
; /* WinSock data */
1000 static int initialized
= 0; /* Has WinSock been initialized? */
1004 WSAStartup(MAKEWORD(1,1), &winsockdata
);
1005 #elif !defined(SO_NOSIGPIPE)
1007 * Ignore SIGPIPE signals...
1011 sigset(SIGPIPE
, SIG_IGN
);
1012 # elif defined(HAVE_SIGACTION)
1013 struct sigaction action
; /* POSIX sigaction data */
1016 memset(&action
, 0, sizeof(action
));
1017 action
.sa_handler
= SIG_IGN
;
1018 sigaction(SIGPIPE
, &action
, NULL
);
1020 signal(SIGPIPE
, SIG_IGN
);
1021 # endif /* !SO_NOSIGPIPE */
1025 gnutls_global_init();
1026 #endif /* HAVE_GNUTLS */
1029 SSL_load_error_strings();
1033 * Using the current time is a dubious random seed, but on some systems
1034 * it is the best we can do (on others, this seed isn't even used...)
1039 gettimeofday(&curtime
, NULL
);
1040 srand(curtime
.tv_sec
+ curtime
.tv_usec
);
1043 for (i
= 0; i
< sizeof(data
); i
++)
1044 data
[i
] = rand(); /* Yes, this is a poor source of random data... */
1046 RAND_seed(&data
, sizeof(data
));
1047 #endif /* HAVE_LIBSSL */
1052 * 'httpOptions()' - Send an OPTIONS request to the server.
1055 int /* O - Status of call (0 = success) */
1056 httpOptions(http_t
*http
, /* I - HTTP connection */
1057 const char *uri
) /* I - URI for options */
1059 return (http_send(http
, HTTP_OPTIONS
, uri
));
1064 * 'httpPost()' - Send a POST request to the server.
1067 int /* O - Status of call (0 = success) */
1068 httpPost(http_t
*http
, /* I - HTTP connection */
1069 const char *uri
) /* I - URI for post */
1071 return (http_send(http
, HTTP_POST
, uri
));
1076 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1081 int /* O - Number of bytes written */
1082 httpPrintf(http_t
*http
, /* I - HTTP connection */
1083 const char *format
, /* I - printf-style format string */
1084 ...) /* I - Additional args as needed */
1086 int bytes
; /* Number of bytes to write */
1087 char buf
[16384]; /* Buffer for formatted string */
1088 va_list ap
; /* Variable argument pointer */
1091 DEBUG_printf(("httpPrintf(http=%p, format=\"%s\", ...)\n", http
, format
));
1093 va_start(ap
, format
);
1094 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1097 DEBUG_printf(("httpPrintf: %s", buf
));
1101 DEBUG_puts(" flushing existing data...");
1103 if (httpFlushWrite(http
) < 0)
1107 return (http_write(http
, buf
, bytes
));
1112 * 'httpPut()' - Send a PUT request to the server.
1115 int /* O - Status of call (0 = success) */
1116 httpPut(http_t
*http
, /* I - HTTP connection */
1117 const char *uri
) /* I - URI to put */
1119 return (http_send(http
, HTTP_PUT
, uri
));
1124 * 'httpRead()' - Read data from a HTTP connection.
1126 * This function is deprecated. Use the httpRead2() function which can
1127 * read more than 2GB of data.
1132 int /* O - Number of bytes read */
1133 httpRead(http_t
*http
, /* I - HTTP connection */
1134 char *buffer
, /* I - Buffer for data */
1135 int length
) /* I - Maximum number of bytes */
1137 return ((int)httpRead2(http
, buffer
, length
));
1142 * 'httpRead2()' - Read data from a HTTP connection.
1147 ssize_t
/* O - Number of bytes read */
1148 httpRead2(http_t
*http
, /* I - HTTP connection */
1149 char *buffer
, /* I - Buffer for data */
1150 size_t length
) /* I - Maximum number of bytes */
1152 ssize_t bytes
; /* Bytes read */
1153 char len
[32]; /* Length string */
1156 DEBUG_printf(("httpRead(http=%p, buffer=%p, length=%d)\n",
1157 http
, buffer
, length
));
1159 if (http
== NULL
|| buffer
== NULL
)
1162 http
->activity
= time(NULL
);
1167 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1168 http
->data_remaining
<= 0)
1170 DEBUG_puts("httpRead2: Getting chunk length...");
1172 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1174 DEBUG_puts("httpRead2: Could not get length!");
1178 http
->data_remaining
= strtoll(len
, NULL
, 16);
1179 if (http
->data_remaining
< 0)
1181 DEBUG_puts("httpRead2: Negative chunk length!");
1186 DEBUG_printf(("httpRead2: data_remaining=" CUPS_LLFMT
"\n",
1187 CUPS_LLCAST http
->data_remaining
));
1189 if (http
->data_remaining
<= 0)
1192 * A zero-length chunk ends a transfer; unless we are reading POST
1196 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1197 httpGets(len
, sizeof(len
), http
);
1199 if (http
->state
== HTTP_POST_RECV
)
1202 http
->state
= HTTP_WAITING
;
1205 * Prevent future reads for this request...
1208 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1212 else if (length
> http
->data_remaining
)
1213 length
= http
->data_remaining
;
1215 if (http
->used
== 0 && length
<= 256)
1218 * Buffer small reads for better performance...
1221 if (!http
->blocking
&& !httpWait(http
, 1000))
1224 if (http
->data_remaining
> sizeof(http
->buffer
))
1225 bytes
= sizeof(http
->buffer
);
1227 bytes
= http
->data_remaining
;
1231 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1233 #endif /* HAVE_SSL */
1235 DEBUG_printf(("httpRead2: reading %d bytes from socket into buffer...\n",
1238 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1240 DEBUG_printf(("httpRead2: read %d bytes from socket into buffer...\n",
1249 http
->error
= WSAGetLastError();
1254 http
->error
= errno
;
1261 http
->error
= EPIPE
;
1268 if (length
> http
->used
)
1269 length
= http
->used
;
1273 DEBUG_printf(("httpRead2: grabbing %d bytes from input buffer...\n", bytes
));
1275 memcpy(buffer
, http
->buffer
, length
);
1276 http
->used
-= length
;
1279 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
1284 if (!http
->blocking
&& !httpWait(http
, 1000))
1287 bytes
= http_read_ssl(http
, buffer
, length
);
1289 #endif /* HAVE_SSL */
1292 if (!http
->blocking
&& !httpWait(http
, 1000))
1295 DEBUG_printf(("httpRead2: reading %d bytes from socket...\n", length
));
1297 while ((bytes
= recv(http
->fd
, buffer
, length
, 0)) < 0)
1301 DEBUG_printf(("httpRead2: read %d bytes from socket...\n", bytes
));
1306 http
->data_remaining
-= bytes
;
1308 if (http
->data_remaining
<= INT_MAX
)
1309 http
->_data_remaining
= (int)http
->data_remaining
;
1311 http
->_data_remaining
= INT_MAX
;
1316 http
->error
= WSAGetLastError();
1321 http
->error
= errno
;
1326 http
->error
= EPIPE
;
1330 if (http
->data_remaining
== 0)
1332 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1333 httpGets(len
, sizeof(len
), http
);
1335 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
1337 if (http
->state
== HTTP_POST_RECV
)
1340 http
->state
= HTTP_WAITING
;
1347 printf("httpRead2: Read %d bytes:\n", bytes
);
1348 for (i
= 0; i
< bytes
; i
+= 16)
1352 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1353 printf(" %02X", buffer
[i
+ j
] & 255);
1362 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1364 ch
= buffer
[i
+ j
] & 255;
1366 if (ch
< ' ' || ch
>= 127)
1380 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
1382 * '_httpReadCDSA()' - Read function for CDSA decryption code.
1385 OSStatus
/* O - -1 on error, 0 on success */
1387 SSLConnectionRef connection
, /* I - SSL/TLS connection */
1388 void *data
, /* I - Data buffer */
1389 size_t *dataLength
) /* IO - Number of bytes */
1391 OSStatus result
; /* Return value */
1392 ssize_t bytes
; /* Number of bytes read */
1395 bytes
= recv((int)connection
, data
, *dataLength
, 0);
1396 while (bytes
== -1 && errno
== EINTR
);
1398 if (bytes
== *dataLength
)
1402 *dataLength
= bytes
;
1403 result
= errSSLWouldBlock
;
1410 result
= errSSLClosedAbort
;
1411 else if (errno
== EAGAIN
)
1412 result
= errSSLWouldBlock
;
1413 else if (errno
== EPIPE
)
1414 result
= errSSLClosedAbort
;
1416 result
= errSSLInternal
;
1421 #endif /* HAVE_SSL && HAVE_CDSASSL */
1425 * 'httpReconnect()' - Reconnect to a HTTP server.
1428 int /* O - 0 on success, non-zero on failure */
1429 httpReconnect(http_t
*http
) /* I - HTTP connection */
1431 http_addrlist_t
*addr
; /* Connected address */
1434 DEBUG_printf(("httpReconnect(http=%p)\n", http
));
1441 http_shutdown_ssl(http
);
1442 #endif /* HAVE_SSL */
1445 * Close any previously open socket...
1451 closesocket(http
->fd
);
1460 * Connect to the server...
1463 if ((addr
= httpAddrConnect(http
->addrlist
, &(http
->fd
))) == NULL
)
1466 * Unable to connect...
1470 http
->error
= WSAGetLastError();
1472 http
->error
= errno
;
1474 http
->status
= HTTP_ERROR
;
1479 http
->hostaddr
= &(addr
->addr
);
1481 http
->status
= HTTP_CONTINUE
;
1484 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
1487 * Always do encryption via SSL.
1490 if (http_setup_ssl(http
) != 0)
1493 closesocket(http
->fd
);
1501 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
1502 return (http_upgrade(http
));
1503 #endif /* HAVE_SSL */
1510 * 'httpSetCookie()' - Set the cookie value(s)...
1512 * @since CUPS 1.1.19@
1516 httpSetCookie(http_t
*http
, /* I - Connection */
1517 const char *cookie
) /* I - Cookie string */
1526 http
->cookie
= strdup(cookie
);
1528 http
->cookie
= NULL
;
1533 * 'httpSetExpect()' - Set the Expect: header in a request.
1535 * Currently only HTTP_CONTINUE is supported for the "expect" argument.
1541 httpSetExpect(http_t
*http
, /* I - HTTP connection */
1542 http_status_t expect
) /* I - HTTP status to expect (HTTP_CONTINUE) */
1545 http
->expect
= expect
;
1550 * 'httpSetField()' - Set the value of an HTTP header.
1554 httpSetField(http_t
*http
, /* I - HTTP connection */
1555 http_field_t field
, /* I - Field index */
1556 const char *value
) /* I - Value */
1559 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
1560 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
1564 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
1569 * 'httpSetLength()' - Set the content-length and content-encoding.
1575 httpSetLength(http_t
*http
, /* I - HTTP connection */
1576 size_t length
) /* I - Length (0 for chunked) */
1583 strcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked");
1584 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
1588 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
1589 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
1590 CUPS_LLFMT
, CUPS_LLCAST length
);
1596 * 'httpTrace()' - Send an TRACE request to the server.
1599 int /* O - Status of call (0 = success) */
1600 httpTrace(http_t
*http
, /* I - HTTP connection */
1601 const char *uri
) /* I - URI for trace */
1603 return (http_send(http
, HTTP_TRACE
, uri
));
1608 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1611 http_status_t
/* O - HTTP status */
1612 httpUpdate(http_t
*http
) /* I - HTTP connection */
1614 char line
[32768], /* Line from connection... */
1615 *value
; /* Pointer to value on line */
1616 http_field_t field
; /* Field index */
1617 int major
, minor
, /* HTTP version numbers */
1618 status
; /* Request status */
1621 DEBUG_printf(("httpUpdate(http=%p), state=%d\n", http
, http
->state
));
1624 * Flush pending data, if any...
1629 DEBUG_puts(" flushing buffer...");
1631 if (httpFlushWrite(http
) < 0)
1632 return (HTTP_ERROR
);
1636 * If we haven't issued any commands, then there is nothing to "update"...
1639 if (http
->state
== HTTP_WAITING
)
1640 return (HTTP_CONTINUE
);
1643 * Grab all of the lines we can from the connection...
1646 while (httpGets(line
, sizeof(line
), http
) != NULL
)
1648 DEBUG_printf(("httpUpdate: Got \"%s\"\n", line
));
1650 if (line
[0] == '\0')
1653 * Blank line means the start of the data section (if any). Return
1654 * the result code, too...
1656 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
1657 * Instead, we just return HTTP_CONTINUE to the caller and keep on
1661 if (http
->status
== HTTP_CONTINUE
)
1662 return (http
->status
);
1664 if (http
->status
< HTTP_BAD_REQUEST
)
1665 http
->digest_tries
= 0;
1668 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
1670 if (http_setup_ssl(http
) != 0)
1673 closesocket(http
->fd
);
1678 return (HTTP_ERROR
);
1681 return (HTTP_CONTINUE
);
1683 #endif /* HAVE_SSL */
1685 httpGetLength2(http
);
1687 switch (http
->state
)
1691 case HTTP_POST_RECV
:
1694 case HTTP_POST_SEND
:
1699 http
->state
= HTTP_WAITING
;
1703 return (http
->status
);
1705 else if (strncmp(line
, "HTTP/", 5) == 0)
1708 * Got the beginning of a response...
1711 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &status
) != 3)
1712 return (HTTP_ERROR
);
1714 http
->version
= (http_version_t
)(major
* 100 + minor
);
1715 http
->status
= (http_status_t
)status
;
1717 else if ((value
= strchr(line
, ':')) != NULL
)
1724 while (isspace(*value
& 255))
1728 * Be tolerants of servers that send unknown attribute fields...
1731 if (!strcasecmp(line
, "expect"))
1734 * "Expect: 100-continue" or similar...
1737 http
->expect
= (http_status_t
)atoi(value
);
1739 else if (!strcasecmp(line
, "cookie"))
1742 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
1745 httpSetCookie(http
, value
);
1747 else if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
1749 DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line
));
1753 httpSetField(http
, field
, value
);
1757 http
->status
= HTTP_ERROR
;
1758 return (HTTP_ERROR
);
1763 * See if there was an error...
1766 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
1767 return (http
->status
);
1771 DEBUG_printf(("httpUpdate: socket error %d - %s\n", http
->error
,
1772 strerror(http
->error
)));
1773 http
->status
= HTTP_ERROR
;
1774 return (HTTP_ERROR
);
1778 * If we haven't already returned, then there is nothing new...
1781 return (HTTP_CONTINUE
);
1786 * 'httpWait()' - Wait for data available on a connection.
1788 * @since CUPS 1.1.19@
1791 int /* O - 1 if data is available, 0 otherwise */
1792 httpWait(http_t
*http
, /* I - HTTP connection */
1793 int msec
) /* I - Milliseconds to wait */
1796 * First see if there is data in the buffer...
1806 * If not, check the SSL/TLS buffers and do a select() on the connection...
1809 return (http_wait(http
, msec
));
1814 * 'httpWrite()' - Write data to a HTTP connection.
1816 * This function is deprecated. Use the httpWrite2() function which can
1817 * write more than 2GB of data.
1822 int /* O - Number of bytes written */
1823 httpWrite(http_t
*http
, /* I - HTTP connection */
1824 const char *buffer
, /* I - Buffer for data */
1825 int length
) /* I - Number of bytes to write */
1827 return ((int)httpWrite2(http
, buffer
, length
));
1832 * 'httpWrite2()' - Write data to a HTTP connection.
1837 ssize_t
/* O - Number of bytes written */
1838 httpWrite2(http_t
*http
, /* I - HTTP connection */
1839 const char *buffer
, /* I - Buffer for data */
1840 size_t length
) /* I - Number of bytes to write */
1842 ssize_t bytes
; /* Bytes written */
1845 DEBUG_printf(("httpWrite(http=%p, buffer=%p, length=%d)\n", http
,
1849 * Range check input...
1852 if (http
== NULL
|| buffer
== NULL
)
1856 * Mark activity on the connection...
1859 http
->activity
= time(NULL
);
1862 * Buffer small writes for better performance...
1867 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
1869 DEBUG_printf((" flushing buffer (wused=%d, length=%d)\n",
1870 http
->wused
, length
));
1872 httpFlushWrite(http
);
1875 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
))
1878 * Write to buffer...
1881 DEBUG_printf((" copying %d bytes to wbuffer...\n", length
));
1883 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
1884 http
->wused
+= length
;
1890 * Otherwise write the data directly...
1893 DEBUG_printf((" writing %d bytes to socket...\n", length
));
1895 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1896 bytes
= http_write_chunk(http
, buffer
, length
);
1898 bytes
= http_write(http
, buffer
, length
);
1900 DEBUG_printf((" wrote %d bytes...\n", bytes
));
1903 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1904 http
->data_remaining
-= bytes
;
1910 * Handle end-of-request processing...
1913 if ((http
->data_encoding
== HTTP_ENCODE_CHUNKED
&& length
== 0) ||
1914 (http
->data_encoding
== HTTP_ENCODE_LENGTH
&& http
->data_remaining
== 0))
1917 * Finished with the transfer; unless we are sending POST or PUT
1921 DEBUG_puts("httpWrite: changing states...");
1924 httpFlushWrite(http
);
1926 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1929 * Send a 0-length chunk at the end of the request...
1932 http_write(http
, "0\r\n\r\n", 5);
1935 * Reset the data state...
1938 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1939 http
->data_remaining
= 0;
1942 if (http
->state
== HTTP_POST_RECV
)
1944 else if (http
->state
== HTTP_PUT_RECV
)
1945 http
->state
= HTTP_STATUS
;
1947 http
->state
= HTTP_WAITING
;
1954 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
1956 * '_httpWriteCDSA()' - Write function for CDSA encryption code.
1959 OSStatus
/* O - -1 on error, 0 on success */
1961 SSLConnectionRef connection
, /* I - SSL/TLS connection */
1962 const void *data
, /* I - Data buffer */
1963 size_t *dataLength
) /* IO - Number of bytes */
1965 OSStatus result
; /* Return value */
1966 ssize_t bytes
; /* Number of bytes read */
1969 bytes
= write((int)connection
, data
, *dataLength
);
1970 while (bytes
== -1 && errno
== EINTR
);
1972 if (bytes
== *dataLength
)
1974 else if (bytes
>= 0)
1976 *dataLength
= bytes
;
1977 result
= errSSLWouldBlock
;
1983 if (errno
== EAGAIN
)
1984 result
= errSSLWouldBlock
;
1985 else if (errno
== EPIPE
)
1986 result
= errSSLClosedAbort
;
1988 result
= errSSLInternal
;
1993 #endif /* HAVE_SSL && HAVE_CDSASSL */
1997 * 'http_field()' - Return the field index for a field name.
2000 static http_field_t
/* O - Field index */
2001 http_field(const char *name
) /* I - String name */
2003 int i
; /* Looping var */
2006 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2007 if (strcasecmp(name
, http_fields
[i
]) == 0)
2008 return ((http_field_t
)i
);
2010 return (HTTP_FIELD_UNKNOWN
);
2016 * 'http_read_ssl()' - Read from a SSL/TLS connection.
2019 static int /* O - Bytes read */
2020 http_read_ssl(http_t
*http
, /* I - HTTP connection */
2021 char *buf
, /* I - Buffer to store data */
2022 int len
) /* I - Length of buffer */
2024 # if defined(HAVE_LIBSSL)
2025 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
2027 # elif defined(HAVE_GNUTLS)
2028 return (gnutls_record_recv(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
2030 # elif defined(HAVE_CDSASSL)
2031 int result
; /* Return value */
2032 OSStatus error
; /* Error info */
2033 size_t processed
; /* Number of bytes processed */
2036 error
= SSLRead((SSLContextRef
)http
->tls
, buf
, len
, &processed
);
2041 result
= (int)processed
;
2043 case errSSLClosedGraceful
:
2046 case errSSLWouldBlock
:
2048 result
= (int)processed
;
2062 # endif /* HAVE_LIBSSL */
2064 #endif /* HAVE_SSL */
2068 * 'http_send()' - Send a request with all fields and the trailing blank line.
2071 static int /* O - 0 on success, non-zero on error */
2072 http_send(http_t
*http
, /* I - HTTP connection */
2073 http_state_t request
, /* I - Request code */
2074 const char *uri
) /* I - URI */
2076 int i
; /* Looping var */
2077 char *ptr
, /* Pointer in buffer */
2078 buf
[1024]; /* Encoded URI buffer */
2079 static const char * const codes
[] =
2080 { /* Request code strings */
2095 static const char hex
[] = "0123456789ABCDEF";
2099 DEBUG_printf(("http_send(http=%p, request=HTTP_%s, uri=\"%s\")\n",
2100 http
, codes
[request
], uri
));
2102 if (http
== NULL
|| uri
== NULL
)
2106 * Set the User-Agent field if it isn't already...
2109 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
2110 httpSetField(http
, HTTP_FIELD_USER_AGENT
, CUPS_MINIMAL
);
2113 * Encode the URI as needed...
2116 for (ptr
= buf
; *uri
!= '\0' && ptr
< (buf
+ sizeof(buf
) - 1); uri
++)
2117 if (*uri
<= ' ' || *uri
>= 127)
2119 if (ptr
< (buf
+ sizeof(buf
) - 1))
2121 if (ptr
< (buf
+ sizeof(buf
) - 1))
2122 *ptr
++ = hex
[(*uri
>> 4) & 15];
2123 if (ptr
< (buf
+ sizeof(buf
) - 1))
2124 *ptr
++ = hex
[*uri
& 15];
2132 * See if we had an error the last time around; if so, reconnect...
2135 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
2136 if (httpReconnect(http
))
2140 * Send the request header...
2143 http
->state
= request
;
2144 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
2147 http
->status
= HTTP_CONTINUE
;
2150 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
2152 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
2153 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
2155 #endif /* HAVE_SSL */
2157 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
2159 http
->status
= HTTP_ERROR
;
2163 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2164 if (http
->fields
[i
][0] != '\0')
2166 DEBUG_printf(("%s: %s\n", http_fields
[i
], http
->fields
[i
]));
2168 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], http
->fields
[i
]) < 1)
2170 http
->status
= HTTP_ERROR
;
2176 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
2178 http
->status
= HTTP_ERROR
;
2182 if (http
->expect
== HTTP_CONTINUE
&&
2183 (http
->state
== HTTP_POST_RECV
|| http
->state
== HTTP_PUT_RECV
))
2184 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
2186 http
->status
= HTTP_ERROR
;
2190 if (httpPrintf(http
, "\r\n") < 1)
2192 http
->status
= HTTP_ERROR
;
2196 httpGetLength2(http
);
2197 httpClearFields(http
);
2205 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
2208 static int /* O - Status of connection */
2209 http_setup_ssl(http_t
*http
) /* I - HTTP connection */
2212 SSL_CTX
*context
; /* Context for encryption */
2213 SSL
*conn
; /* Connection for encryption */
2214 # elif defined(HAVE_GNUTLS)
2215 http_tls_t
*conn
; /* TLS session object */
2216 gnutls_certificate_client_credentials
*credentials
;
2217 /* TLS credentials */
2218 # elif defined(HAVE_CDSASSL)
2219 SSLContextRef conn
; /* Context for encryption */
2220 OSStatus error
; /* Error info */
2221 # endif /* HAVE_LIBSSL */
2224 DEBUG_printf(("http_setup_ssl(http=%p)\n", http
));
2227 context
= SSL_CTX_new(SSLv23_client_method());
2229 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
2231 conn
= SSL_new(context
);
2233 SSL_set_fd(conn
, http
->fd
);
2234 if (SSL_connect(conn
) != 1)
2237 unsigned long error
; /* Error code */
2239 while ((error
= ERR_get_error()) != 0)
2240 printf("http_setup_ssl: %s\n", ERR_error_string(error
, NULL
));
2243 SSL_CTX_free(context
);
2247 http
->error
= WSAGetLastError();
2249 http
->error
= errno
;
2251 http
->status
= HTTP_ERROR
;
2253 return (HTTP_ERROR
);
2256 # elif defined(HAVE_GNUTLS)
2257 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
2261 http
->error
= errno
;
2262 http
->status
= HTTP_ERROR
;
2267 credentials
= (gnutls_certificate_client_credentials
*)
2268 malloc(sizeof(gnutls_certificate_client_credentials
));
2269 if (credentials
== NULL
)
2273 http
->error
= errno
;
2274 http
->status
= HTTP_ERROR
;
2279 gnutls_certificate_allocate_credentials(credentials
);
2281 gnutls_init(&(conn
->session
), GNUTLS_CLIENT
);
2282 gnutls_set_default_priority(conn
->session
);
2283 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
2284 gnutls_transport_set_ptr(conn
->session
,
2285 (gnutls_transport_ptr
)((long)http
->fd
));
2287 if ((gnutls_handshake(conn
->session
)) != GNUTLS_E_SUCCESS
)
2289 http
->error
= errno
;
2290 http
->status
= HTTP_ERROR
;
2295 conn
->credentials
= credentials
;
2297 # elif defined(HAVE_CDSASSL)
2298 error
= SSLNewContext(false, &conn
);
2301 error
= SSLSetIOFuncs(conn
, _httpReadCDSA
, _httpWriteCDSA
);
2304 error
= SSLSetConnection(conn
, (SSLConnectionRef
)http
->fd
);
2307 error
= SSLSetAllowsExpiredCerts(conn
, true);
2310 error
= SSLSetAllowsAnyRoot(conn
, true);
2314 while ((error
= SSLHandshake(conn
)) == errSSLWouldBlock
)
2320 http
->error
= error
;
2321 http
->status
= HTTP_ERROR
;
2323 SSLDisposeContext(conn
);
2329 # endif /* HAVE_CDSASSL */
2334 #endif /* HAVE_SSL */
2339 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
2343 http_shutdown_ssl(http_t
*http
) /* I - HTTP connection */
2346 SSL_CTX
*context
; /* Context for encryption */
2347 SSL
*conn
; /* Connection for encryption */
2350 conn
= (SSL
*)(http
->tls
);
2351 context
= SSL_get_SSL_CTX(conn
);
2354 SSL_CTX_free(context
);
2357 # elif defined(HAVE_GNUTLS)
2358 http_tls_t
*conn
; /* Encryption session */
2359 gnutls_certificate_client_credentials
*credentials
;
2360 /* TLS credentials */
2363 conn
= (http_tls_t
*)(http
->tls
);
2364 credentials
= (gnutls_certificate_client_credentials
*)(conn
->credentials
);
2366 gnutls_bye(conn
->session
, GNUTLS_SHUT_RDWR
);
2367 gnutls_deinit(conn
->session
);
2368 gnutls_certificate_free_credentials(*credentials
);
2372 # elif defined(HAVE_CDSASSL)
2373 while (SSLClose((SSLContextRef
)http
->tls
) == errSSLWouldBlock
)
2376 SSLDisposeContext((SSLContextRef
)http
->tls
);
2377 # endif /* HAVE_LIBSSL */
2381 #endif /* HAVE_SSL */
2386 * 'http_upgrade()' - Force upgrade to TLS encryption.
2389 static int /* O - Status of connection */
2390 http_upgrade(http_t
*http
) /* I - HTTP connection */
2392 int ret
; /* Return value */
2393 http_t myhttp
; /* Local copy of HTTP data */
2396 DEBUG_printf(("http_upgrade(%p)\n", http
));
2399 * Copy the HTTP data to a local variable so we can do the OPTIONS
2400 * request without interfering with the existing request data...
2403 memcpy(&myhttp
, http
, sizeof(myhttp
));
2406 * Send an OPTIONS request to the server, requiring SSL or TLS
2407 * encryption on the link...
2410 httpClearFields(&myhttp
);
2411 httpSetField(&myhttp
, HTTP_FIELD_CONNECTION
, "upgrade");
2412 httpSetField(&myhttp
, HTTP_FIELD_UPGRADE
, "TLS/1.0, SSL/2.0, SSL/3.0");
2414 if ((ret
= httpOptions(&myhttp
, "*")) == 0)
2417 * Wait for the secure connection...
2420 while (httpUpdate(&myhttp
) == HTTP_CONTINUE
);
2426 * Copy the HTTP data back over, if any...
2429 http
->fd
= myhttp
.fd
;
2430 http
->error
= myhttp
.error
;
2431 http
->activity
= myhttp
.activity
;
2432 http
->status
= myhttp
.status
;
2433 http
->version
= myhttp
.version
;
2434 http
->keep_alive
= myhttp
.keep_alive
;
2435 http
->used
= myhttp
.used
;
2438 memcpy(http
->buffer
, myhttp
.buffer
, http
->used
);
2440 http
->auth_type
= myhttp
.auth_type
;
2441 http
->nonce_count
= myhttp
.nonce_count
;
2443 memcpy(http
->nonce
, myhttp
.nonce
, sizeof(http
->nonce
));
2445 http
->tls
= myhttp
.tls
;
2446 http
->encryption
= myhttp
.encryption
;
2449 * See if we actually went secure...
2455 * Server does not support HTTP upgrade...
2458 DEBUG_puts("Server does not support HTTP upgrade!");
2461 closesocket(http
->fd
);
2473 #endif /* HAVE_SSL */
2477 * 'http_wait()' - Wait for data available on a connection.
2480 static int /* O - 1 if data is available, 0 otherwise */
2481 http_wait(http_t
*http
, /* I - HTTP connection */
2482 int msec
) /* I - Milliseconds to wait */
2485 struct rlimit limit
; /* Runtime limit */
2486 int set_size
; /* Size of select set */
2488 struct timeval timeout
; /* Timeout */
2489 int nfds
; /* Result from select() */
2492 DEBUG_printf(("http_wait(http=%p, msec=%d)\n", http
, msec
));
2498 * Check the SSL/TLS buffers for data first...
2505 if (SSL_pending((SSL
*)(http
->tls
)))
2507 # elif defined(HAVE_GNUTLS)
2508 if (gnutls_record_check_pending(((http_tls_t
*)(http
->tls
))->session
))
2510 # elif defined(HAVE_CDSASSL)
2511 size_t bytes
; /* Bytes that are available */
2513 if (!SSLGetBufferedReadSize((SSLContextRef
)http
->tls
, &bytes
) && bytes
> 0)
2515 # endif /* HAVE_LIBSSL */
2517 #endif /* HAVE_SSL */
2520 * Then try doing a select() to poll the socket...
2523 if (!http
->input_set
)
2527 * Windows has a fixed-size select() structure, different (surprise,
2528 * surprise!) from all UNIX implementations. Just allocate this
2529 * fixed structure...
2532 http
->input_set
= calloc(1, sizeof(fd_set
));
2535 * Allocate the select() input set based upon the max number of file
2536 * descriptors available for this process...
2539 getrlimit(RLIMIT_NOFILE
, &limit
);
2541 set_size
= (limit
.rlim_cur
+ 31) / 8 + 4;
2542 if (set_size
< sizeof(fd_set
))
2543 set_size
= sizeof(fd_set
);
2545 http
->input_set
= calloc(1, set_size
);
2548 if (!http
->input_set
)
2554 FD_SET(http
->fd
, http
->input_set
);
2558 timeout
.tv_sec
= msec
/ 1000;
2559 timeout
.tv_usec
= (msec
% 1000) * 1000;
2561 nfds
= select(http
->fd
+ 1, http
->input_set
, NULL
, NULL
, &timeout
);
2564 nfds
= select(http
->fd
+ 1, http
->input_set
, NULL
, NULL
, NULL
);
2567 while (nfds
< 0 && WSAGetLastError() == WSAEINTR
);
2569 while (nfds
< 0 && errno
== EINTR
);
2572 FD_CLR(http
->fd
, http
->input_set
);
2579 * 'http_write()' - Write a buffer to a HTTP connection.
2582 static int /* O - Number of bytes written */
2583 http_write(http_t
*http
, /* I - HTTP connection */
2584 const char *buffer
, /* I - Buffer for data */
2585 int length
) /* I - Number of bytes to write */
2587 int tbytes
, /* Total bytes sent */
2588 bytes
; /* Bytes sent */
2597 bytes
= http_write_ssl(http
, buffer
, length
);
2599 #endif /* HAVE_SSL */
2600 bytes
= send(http
->fd
, buffer
, length
, 0);
2605 if (WSAGetLastError() != http
->error
)
2607 http
->error
= WSAGetLastError();
2613 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
2615 http
->error
= errno
;
2620 DEBUG_puts("http_write: error writing data...\n");
2633 printf("http_write: wrote %d bytes: \n", tbytes
);
2634 for (i
= 0, buffer
-= tbytes
; i
< tbytes
; i
+= 16)
2638 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
2639 printf(" %02X", buffer
[i
+ j
] & 255);
2648 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
2650 ch
= buffer
[i
+ j
] & 255;
2652 if (ch
< ' ' || ch
== 127)
2667 * 'http_write_chunk()' - Write a chunked buffer.
2670 static int /* O - Number bytes written */
2671 http_write_chunk(http_t
*http
, /* I - HTTP connection */
2672 const char *buffer
, /* I - Buffer to write */
2673 int length
) /* I - Length of buffer */
2675 char header
[255]; /* Chunk header */
2676 int bytes
; /* Bytes written */
2678 DEBUG_printf(("http_write_chunk(http=%p, buffer=%p, length=%d)\n",
2679 http
, buffer
, length
));
2682 * Write the chunk header, data, and trailer.
2685 sprintf(header
, "%x\r\n", length
);
2686 if (http_write(http
, header
, strlen(header
)) < 0)
2688 DEBUG_puts(" http_write of length failed!");
2692 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
2694 DEBUG_puts(" http_write of buffer failed!");
2698 if (http_write(http
, "\r\n", 2) < 0)
2700 DEBUG_puts(" http_write of CR LF failed!");
2710 * 'http_write_ssl()' - Write to a SSL/TLS connection.
2713 static int /* O - Bytes written */
2714 http_write_ssl(http_t
*http
, /* I - HTTP connection */
2715 const char *buf
, /* I - Buffer holding data */
2716 int len
) /* I - Length of buffer */
2718 # if defined(HAVE_LIBSSL)
2719 return (SSL_write((SSL
*)(http
->tls
), buf
, len
));
2721 # elif defined(HAVE_GNUTLS)
2722 return (gnutls_record_send(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
2723 # elif defined(HAVE_CDSASSL)
2724 int result
; /* Return value */
2725 OSStatus error
; /* Error info */
2726 size_t processed
; /* Number of bytes processed */
2729 error
= SSLWrite((SSLContextRef
)http
->tls
, buf
, len
, &processed
);
2734 result
= (int)processed
;
2736 case errSSLClosedGraceful
:
2739 case errSSLWouldBlock
:
2741 result
= (int)processed
;
2755 # endif /* HAVE_LIBSSL */
2757 #endif /* HAVE_SSL */
2761 * End of "$Id: http.c 5282 2006-03-13 12:10:33Z mike $".