2 * "$Id: http.c 5138 2006-02-21 10:49:06Z 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 * httpSetField() - Set the value of an HTTP header.
67 * httpSetLength() - Set the content-length and transfer-encoding.
68 * httpTrace() - Send an TRACE request to the server.
69 * httpUpdate() - Update the current HTTP state for incoming data.
70 * httpWait() - Wait for data available on a connection.
71 * httpWrite() - Write data to a HTTP connection.
72 * httpWrite2() - Write data to a HTTP connection.
73 * _httpWriteCDSA() - Write function for CDSA encryption code.
74 * http_field() - Return the field index for a field name.
75 * http_read_ssl() - Read from a SSL/TLS connection.
76 * http_send() - Send a request with all fields and the trailing
78 * http_setup_ssl() - Set up SSL/TLS on a connection.
79 * http_shutdown_ssl() - Shut down SSL/TLS on a connection.
80 * http_upgrade() - Force upgrade to TLS encryption.
81 * http_wait() - Wait for data available on a connection.
82 * http_write() - Write data to a connection.
83 * http_write_ssl() - Write to a SSL/TLS connection.
87 * Include necessary headers...
90 #include "http-private.h"
98 # include <sys/time.h>
99 # include <sys/resource.h>
104 * Some operating systems have done away with the Fxxxx constants for
105 * the fcntl() call; this works around that "feature"...
109 # define FNONBLK O_NONBLOCK
110 #endif /* !FNONBLK */
117 static http_field_t
http_field(const char *name
);
118 static int http_send(http_t
*http
, http_state_t request
,
120 static int http_wait(http_t
*http
, int msec
);
121 static int http_write(http_t
*http
, const char *buffer
,
123 static int http_write_chunk(http_t
*http
, const char *buffer
,
126 static int http_read_ssl(http_t
*http
, char *buf
, int len
);
127 static int http_setup_ssl(http_t
*http
);
128 static void http_shutdown_ssl(http_t
*http
);
129 static int http_upgrade(http_t
*http
);
130 static int http_write_ssl(http_t
*http
, const char *buf
, int len
);
131 #endif /* HAVE_SSL */
138 static const char * const http_fields
[] =
155 "If-Unmodified-since",
171 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
175 httpBlocking(http_t
*http
, /* I - HTTP connection */
176 int b
) /* I - 1 = blocking, 0 = non-blocking */
184 * 'httpCheck()' - Check to see if there is a pending response from the server.
187 int /* O - 0 = no data, 1 = data available */
188 httpCheck(http_t
*http
) /* I - HTTP connection */
190 return (httpWait(http
, 0));
195 * 'httpClearCookie()' - Clear the cookie value(s).
197 * @since CUPS 1.1.19@
201 httpClearCookie(http_t
*http
) /* I - HTTP connection */
215 * 'httpClearFields()' - Clear HTTP request fields.
219 httpClearFields(http_t
*http
) /* I - HTTP connection */
223 memset(http
->fields
, 0, sizeof(http
->fields
));
224 httpSetField(http
, HTTP_FIELD_HOST
, http
->hostname
);
230 * 'httpClose()' - Close an HTTP connection...
234 httpClose(http_t
*http
) /* I - HTTP connection */
236 DEBUG_printf(("httpClose(http=%p)\n", http
));
241 httpAddrFreeList(http
->addrlist
);
244 free(http
->input_set
);
251 http_shutdown_ssl(http
);
252 #endif /* HAVE_SSL */
255 closesocket(http
->fd
);
265 * 'httpConnect()' - Connect to a HTTP server.
268 http_t
* /* O - New HTTP connection */
269 httpConnect(const char *host
, /* I - Host to connect to */
270 int port
) /* I - Port number */
272 http_encryption_t encryption
; /* Type of encryption to use */
276 * Set the default encryption status...
280 encryption
= HTTP_ENCRYPT_ALWAYS
;
282 encryption
= HTTP_ENCRYPT_IF_REQUESTED
;
284 return (httpConnectEncrypt(host
, port
, encryption
));
289 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
292 http_t
* /* O - New HTTP connection */
294 const char *host
, /* I - Host to connect to */
295 int port
, /* I - Port number */
296 http_encryption_t encryption
) /* I - Type of encryption to use */
298 http_t
*http
; /* New HTTP connection */
299 http_addrlist_t
*addrlist
; /* Host address data */
300 char service
[255]; /* Service name */
303 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)\n",
304 host
? host
: "(null)", port
, encryption
));
315 sprintf(service
, "%d", port
);
317 if ((addrlist
= httpAddrGetList(host
, AF_UNSPEC
, service
)) == NULL
)
321 * Allocate memory for the structure...
324 http
= calloc(sizeof(http_t
), 1);
328 http
->version
= HTTP_1_1
;
330 http
->activity
= time(NULL
);
334 * Set the encryption status...
337 if (port
== 443) /* Always use encryption for https */
338 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
340 http
->encryption
= encryption
;
343 * Loop through the addresses we have until one of them connects...
346 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
349 * Connect to the remote system...
352 http
->addrlist
= addrlist
;
354 if (!httpReconnect(http
))
358 * Could not connect to any known address - bail out!
361 httpAddrFreeList(addrlist
);
370 * 'httpDelete()' - Send a DELETE request to the server.
373 int /* O - Status of call (0 = success) */
374 httpDelete(http_t
*http
, /* I - HTTP connection */
375 const char *uri
) /* I - URI to delete */
377 return (http_send(http
, HTTP_DELETE
, uri
));
382 * 'httpEncryption()' - Set the required encryption on the link.
385 int /* O - -1 on error, 0 on success */
386 httpEncryption(http_t
*http
, /* I - HTTP connection */
387 http_encryption_t e
) /* I - New encryption preference */
389 DEBUG_printf(("httpEncryption(http=%p, e=%d)\n", http
, e
));
395 http
->encryption
= e
;
397 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
398 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
399 return (httpReconnect(http
));
400 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
401 return (http_upgrade(http
));
405 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
409 #endif /* HAVE_SSL */
414 * 'httpError()' - Get the last error on a connection.
417 int /* O - Error code (errno) value */
418 httpError(http_t
*http
) /* I - HTTP connection */
421 return (http
->error
);
428 * 'httpFlush()' - Flush data from a HTTP connection.
432 httpFlush(http_t
*http
) /* I - HTTP connection */
434 char buffer
[8192]; /* Junk buffer */
435 int blocking
; /* To block or not to block */
438 DEBUG_printf(("httpFlush(http=%p), state=%d\n", http
, http
->state
));
441 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
444 blocking
= http
->blocking
;
448 * Read any data we can...
451 while (httpRead2(http
, buffer
, sizeof(buffer
)) > 0);
454 * Restore blocking and reset the connection if we didn't get all of
455 * the remaining data...
458 http
->blocking
= blocking
;
460 if (http
->state
!= HTTP_WAITING
&& http
->fd
>= 0)
463 * Didn't get the data back, so close the current connection.
466 http
->state
= HTTP_WAITING
;
470 http_shutdown_ssl(http
);
471 #endif /* HAVE_SSL */
474 closesocket(http
->fd
);
485 * 'httpFlushWrite()' - Flush data in write buffer.
490 int /* O - Bytes written or -1 on error */
491 httpFlushWrite(http_t
*http
) /* I - HTTP connection */
493 int bytes
; /* Bytes written */
496 DEBUG_printf(("httpFlushWrite(http=%p)\n", http
));
498 if (!http
|| !http
->wused
)
501 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
502 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
504 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
513 * 'httpGet()' - Send a GET request to the server.
516 int /* O - Status of call (0 = success) */
517 httpGet(http_t
*http
, /* I - HTTP connection */
518 const char *uri
) /* I - URI to get */
520 return (http_send(http
, HTTP_GET
, uri
));
525 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
530 int /* O - 1 if blocking, 0 if non-blocking */
531 httpGetBlocking(http_t
*http
) /* I - HTTP connection */
533 return (http
? http
->blocking
: 0);
538 * 'httpGetCookie()' - Get any cookie data from the response.
541 const char * /* O - Cookie data or NULL */
542 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
544 return (http
? http
->cookie
: NULL
);
549 * 'httpGetFd()' - Get the file descriptor associated with a connection.
554 int /* O - File descriptor or -1 if none */
555 httpGetFd(http_t
*http
) /* I - HTTP connection */
557 return (http
? http
->fd
: -1);
562 * 'httpGetField()' - Get a field value from a request/response.
565 const char * /* O - Field value */
566 httpGetField(http_t
*http
, /* I - HTTP connection */
567 http_field_t field
) /* I - Field to get */
569 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
572 return (http
->fields
[field
]);
577 * 'httpGetLength()' - Get the amount of data remaining from the
578 * content-length or transfer-encoding fields.
580 * This function is deprecated and will not return lengths larger than
581 * 2^31 - 1; use httpGetLength2() instead.
586 int /* O - Content length */
587 httpGetLength(http_t
*http
) /* I - HTTP connection */
590 * Get the read content length and return the 32-bit value.
595 httpGetLength2(http
);
597 return (http
->_data_remaining
);
605 * 'httpGetLength2()' - Get the amount of data remaining from the
606 * content-length or transfer-encoding fields.
608 * This function returns the complete content length, even for
609 * content larger than 2^31 - 1.
614 off_t
/* O - Content length */
615 httpGetLength2(http_t
*http
) /* I - HTTP connection */
617 DEBUG_printf(("httpGetLength2(http=%p), state=%d\n", http
, http
->state
));
622 if (!strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
624 DEBUG_puts("httpGetLength2: chunked request!");
626 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
627 http
->data_remaining
= 0;
631 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
634 * The following is a hack for HTTP servers that don't send a
635 * content-length or transfer-encoding field...
637 * If there is no content-length then the connection must close
638 * after the transfer is complete...
641 if (http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] == '\0')
642 http
->data_remaining
= 2147483647;
644 http
->data_remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
647 DEBUG_printf(("httpGetLength2: content_length=" CUPS_LLFMT
"\n",
648 CUPS_LLCAST http
->data_remaining
));
651 if (http
->data_remaining
<= INT_MAX
)
652 http
->_data_remaining
= (int)http
->data_remaining
;
654 http
->_data_remaining
= INT_MAX
;
656 return (http
->data_remaining
);
661 * 'httpGetStatus()' - Get the status of the last HTTP request.
666 http_status_t
/* O - HTTP status */
667 httpGetStatus(http_t
*http
) /* I - HTTP connection */
669 return (http
? http
->status
: HTTP_ERROR
);
674 * 'httpGetSubField()' - Get a sub-field value.
679 char * /* O - Value or NULL */
680 httpGetSubField(http_t
*http
, /* I - HTTP connection */
681 http_field_t field
, /* I - Field index */
682 const char *name
, /* I - Name of sub-field */
683 char *value
) /* O - Value string */
685 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
690 * 'httpGetSubField2()' - Get a sub-field value.
695 char * /* O - Value or NULL */
696 httpGetSubField2(http_t
*http
, /* I - HTTP connection */
697 http_field_t field
, /* I - Field index */
698 const char *name
, /* I - Name of sub-field */
699 char *value
, /* O - Value string */
700 int valuelen
) /* I - Size of value buffer */
702 const char *fptr
; /* Pointer into field */
703 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
704 *ptr
, /* Pointer into string buffer */
705 *end
; /* End of value buffer */
707 DEBUG_printf(("httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, valuelen=%d)\n",
708 http
, field
, name
, value
, valuelen
));
710 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
711 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
714 end
= value
+ valuelen
- 1;
716 for (fptr
= http
->fields
[field
]; *fptr
;)
719 * Skip leading whitespace...
722 while (isspace(*fptr
& 255))
732 * Get the sub-field name...
736 *fptr
&& *fptr
!= '=' && !isspace(*fptr
& 255) &&
737 ptr
< (temp
+ sizeof(temp
) - 1);
742 DEBUG_printf(("httpGetSubField: name=\"%s\"\n", temp
));
745 * Skip trailing chars up to the '='...
748 while (isspace(*fptr
& 255))
758 * Skip = and leading whitespace...
763 while (isspace(*fptr
& 255))
769 * Read quoted string...
772 for (ptr
= value
, fptr
++;
773 *fptr
&& *fptr
!= '\"' && ptr
< end
;
778 while (*fptr
&& *fptr
!= '\"')
787 * Read unquoted string...
791 *fptr
&& !isspace(*fptr
& 255) && *fptr
!= ',' && ptr
< end
;
796 while (*fptr
&& !isspace(*fptr
& 255) && *fptr
!= ',')
800 DEBUG_printf(("httpGetSubField: value=\"%s\"\n", value
));
803 * See if this is the one...
806 if (!strcmp(name
, temp
))
817 * 'httpGets()' - Get a line of text from a HTTP connection.
820 char * /* O - Line or NULL */
821 httpGets(char *line
, /* I - Line to read into */
822 int length
, /* I - Max length of buffer */
823 http_t
*http
) /* I - HTTP connection */
825 char *lineptr
, /* Pointer into line */
826 *lineend
, /* End of line */
827 *bufptr
, /* Pointer into input buffer */
828 *bufend
; /* Pointer to end of buffer */
829 int bytes
, /* Number of bytes read */
830 eol
; /* End-of-line? */
833 DEBUG_printf(("httpGets(line=%p, length=%d, http=%p)\n", line
, length
, http
));
835 if (http
== NULL
|| line
== NULL
)
839 * Read a line from the buffer...
843 lineend
= line
+ length
- 1;
846 while (lineptr
< lineend
)
849 * Pre-load the buffer as needed...
858 while (http
->used
== 0)
861 * No newline; see if there is more data to be read...
864 if (!http
->blocking
&& !http_wait(http
, 1000))
869 bytes
= http_read_ssl(http
, http
->buffer
+ http
->used
,
870 HTTP_MAX_BUFFER
- http
->used
);
872 #endif /* HAVE_SSL */
873 bytes
= recv(http
->fd
, http
->buffer
+ http
->used
,
874 HTTP_MAX_BUFFER
- http
->used
, 0);
876 DEBUG_printf(("httpGets: read %d bytes...\n", bytes
));
881 * Nope, can't get a line this time...
885 if (WSAGetLastError() != http
->error
)
887 http
->error
= WSAGetLastError();
891 DEBUG_printf(("httpGets: recv() error %d!\n", WSAGetLastError()));
893 DEBUG_printf(("httpGets: recv() error %d!\n", errno
));
897 else if (errno
!= http
->error
)
914 * Yup, update the amount used...
921 * Now copy as much of the current line as possible...
924 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
925 lineptr
< lineend
&& bufptr
< bufend
;)
933 else if (*bufptr
== 0x0d)
936 *lineptr
++ = *bufptr
++;
939 http
->used
-= bufptr
- http
->buffer
;
941 memmove(http
->buffer
, bufptr
, http
->used
);
949 http
->activity
= time(NULL
);
953 DEBUG_printf(("httpGets: Returning \"%s\"\n", line
));
959 DEBUG_puts("httpGets: No new line available!");
966 * 'httpHead()' - Send a HEAD request to the server.
969 int /* O - Status of call (0 = success) */
970 httpHead(http_t
*http
, /* I - HTTP connection */
971 const char *uri
) /* I - URI for head */
973 return (http_send(http
, HTTP_HEAD
, uri
));
978 * 'httpInitialize()' - Initialize the HTTP interface library and set the
979 * default HTTP proxy (if any).
987 struct timeval curtime
; /* Current time in microseconds */
989 int i
; /* Looping var */
990 unsigned char data
[1024]; /* Seed data */
991 #endif /* HAVE_LIBSSL */
994 WSADATA winsockdata
; /* WinSock data */
995 static int initialized
= 0; /* Has WinSock been initialized? */
999 WSAStartup(MAKEWORD(1,1), &winsockdata
);
1000 #elif !defined(SO_NOSIGPIPE)
1002 * Ignore SIGPIPE signals...
1006 sigset(SIGPIPE
, SIG_IGN
);
1007 # elif defined(HAVE_SIGACTION)
1008 struct sigaction action
; /* POSIX sigaction data */
1011 memset(&action
, 0, sizeof(action
));
1012 action
.sa_handler
= SIG_IGN
;
1013 sigaction(SIGPIPE
, &action
, NULL
);
1015 signal(SIGPIPE
, SIG_IGN
);
1016 # endif /* !SO_NOSIGPIPE */
1020 gnutls_global_init();
1021 #endif /* HAVE_GNUTLS */
1024 SSL_load_error_strings();
1028 * Using the current time is a dubious random seed, but on some systems
1029 * it is the best we can do (on others, this seed isn't even used...)
1034 gettimeofday(&curtime
, NULL
);
1035 srand(curtime
.tv_sec
+ curtime
.tv_usec
);
1038 for (i
= 0; i
< sizeof(data
); i
++)
1039 data
[i
] = rand(); /* Yes, this is a poor source of random data... */
1041 RAND_seed(&data
, sizeof(data
));
1042 #endif /* HAVE_LIBSSL */
1047 * 'httpOptions()' - Send an OPTIONS request to the server.
1050 int /* O - Status of call (0 = success) */
1051 httpOptions(http_t
*http
, /* I - HTTP connection */
1052 const char *uri
) /* I - URI for options */
1054 return (http_send(http
, HTTP_OPTIONS
, uri
));
1059 * 'httpPost()' - Send a POST request to the server.
1062 int /* O - Status of call (0 = success) */
1063 httpPost(http_t
*http
, /* I - HTTP connection */
1064 const char *uri
) /* I - URI for post */
1066 return (http_send(http
, HTTP_POST
, uri
));
1071 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1076 int /* O - Number of bytes written */
1077 httpPrintf(http_t
*http
, /* I - HTTP connection */
1078 const char *format
, /* I - printf-style format string */
1079 ...) /* I - Additional args as needed */
1081 int bytes
; /* Number of bytes to write */
1082 char buf
[16384]; /* Buffer for formatted string */
1083 va_list ap
; /* Variable argument pointer */
1086 DEBUG_printf(("httpPrintf(http=%p, format=\"%s\", ...)\n", http
, format
));
1088 va_start(ap
, format
);
1089 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1092 DEBUG_printf(("httpPrintf: %s", buf
));
1096 DEBUG_puts(" flushing existing data...");
1098 if (httpFlushWrite(http
) < 0)
1102 return (http_write(http
, buf
, bytes
));
1107 * 'httpPut()' - Send a PUT request to the server.
1110 int /* O - Status of call (0 = success) */
1111 httpPut(http_t
*http
, /* I - HTTP connection */
1112 const char *uri
) /* I - URI to put */
1114 return (http_send(http
, HTTP_PUT
, uri
));
1119 * 'httpRead()' - Read data from a HTTP connection.
1121 * This function is deprecated. Use the httpRead2() function which can
1122 * read more than 2GB of data.
1127 int /* O - Number of bytes read */
1128 httpRead(http_t
*http
, /* I - HTTP connection */
1129 char *buffer
, /* I - Buffer for data */
1130 int length
) /* I - Maximum number of bytes */
1132 return ((int)httpRead2(http
, buffer
, length
));
1137 * 'httpRead2()' - Read data from a HTTP connection.
1142 ssize_t
/* O - Number of bytes read */
1143 httpRead2(http_t
*http
, /* I - HTTP connection */
1144 char *buffer
, /* I - Buffer for data */
1145 size_t length
) /* I - Maximum number of bytes */
1147 ssize_t bytes
; /* Bytes read */
1148 char len
[32]; /* Length string */
1151 DEBUG_printf(("httpRead(http=%p, buffer=%p, length=%d)\n",
1152 http
, buffer
, length
));
1154 if (http
== NULL
|| buffer
== NULL
)
1157 http
->activity
= time(NULL
);
1162 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1163 http
->data_remaining
<= 0)
1165 DEBUG_puts("httpRead2: Getting chunk length...");
1167 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1169 DEBUG_puts("httpRead2: Could not get length!");
1173 http
->data_remaining
= strtoll(len
, NULL
, 16);
1174 if (http
->data_remaining
< 0)
1176 DEBUG_puts("httpRead2: Negative chunk length!");
1181 DEBUG_printf(("httpRead2: data_remaining=" CUPS_LLFMT
"\n",
1182 CUPS_LLCAST http
->data_remaining
));
1184 if (http
->data_remaining
<= 0)
1187 * A zero-length chunk ends a transfer; unless we are reading POST
1191 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1192 httpGets(len
, sizeof(len
), http
);
1194 if (http
->state
== HTTP_POST_RECV
)
1197 http
->state
= HTTP_WAITING
;
1200 * Prevent future reads for this request...
1203 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1207 else if (length
> http
->data_remaining
)
1208 length
= http
->data_remaining
;
1210 if (http
->used
== 0 && length
<= 256)
1213 * Buffer small reads for better performance...
1216 if (!http
->blocking
&& !httpWait(http
, 1000))
1219 if (http
->data_remaining
> sizeof(http
->buffer
))
1220 bytes
= sizeof(http
->buffer
);
1222 bytes
= http
->data_remaining
;
1226 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1228 #endif /* HAVE_SSL */
1230 DEBUG_printf(("httpRead2: reading %d bytes from socket into buffer...\n",
1233 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1235 DEBUG_printf(("httpRead2: read %d bytes from socket into buffer...\n",
1244 http
->error
= WSAGetLastError();
1249 http
->error
= errno
;
1256 http
->error
= EPIPE
;
1263 if (length
> http
->used
)
1264 length
= http
->used
;
1268 DEBUG_printf(("httpRead2: grabbing %d bytes from input buffer...\n", bytes
));
1270 memcpy(buffer
, http
->buffer
, length
);
1271 http
->used
-= length
;
1274 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
1279 if (!http
->blocking
&& !httpWait(http
, 1000))
1282 bytes
= http_read_ssl(http
, buffer
, length
);
1284 #endif /* HAVE_SSL */
1287 if (!http
->blocking
&& !httpWait(http
, 1000))
1290 DEBUG_printf(("httpRead2: reading %d bytes from socket...\n", length
));
1292 while ((bytes
= recv(http
->fd
, buffer
, length
, 0)) < 0)
1296 DEBUG_printf(("httpRead2: read %d bytes from socket...\n", bytes
));
1301 http
->data_remaining
-= bytes
;
1303 if (http
->data_remaining
<= INT_MAX
)
1304 http
->_data_remaining
= (int)http
->data_remaining
;
1306 http
->_data_remaining
= INT_MAX
;
1311 http
->error
= WSAGetLastError();
1316 http
->error
= errno
;
1321 http
->error
= EPIPE
;
1325 if (http
->data_remaining
== 0)
1327 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1328 httpGets(len
, sizeof(len
), http
);
1330 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
1332 if (http
->state
== HTTP_POST_RECV
)
1335 http
->state
= HTTP_WAITING
;
1342 printf("httpRead2: Read %d bytes:\n", bytes
);
1343 for (i
= 0; i
< bytes
; i
+= 16)
1347 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1348 printf(" %02X", buffer
[i
+ j
] & 255);
1357 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1359 ch
= buffer
[i
+ j
] & 255;
1361 if (ch
< ' ' || ch
>= 127)
1375 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
1377 * '_httpReadCDSA()' - Read function for CDSA decryption code.
1380 OSStatus
/* O - -1 on error, 0 on success */
1382 SSLConnectionRef connection
, /* I - SSL/TLS connection */
1383 void *data
, /* I - Data buffer */
1384 size_t *dataLength
) /* IO - Number of bytes */
1386 OSStatus result
; /* Return value */
1387 ssize_t bytes
; /* Number of bytes read */
1392 bytes
= recv((int)connection
, data
, *dataLength
, 0);
1396 result
= (bytes
== *dataLength
);
1397 *dataLength
= bytes
;
1403 return (errSSLClosedAbort
);
1405 if (errno
== EAGAIN
)
1406 return (errSSLWouldBlock
);
1409 return (errSSLClosedAbort
);
1412 return (errSSLInternal
);
1415 #endif /* HAVE_SSL && HAVE_CDSASSL */
1419 * 'httpReconnect()' - Reconnect to a HTTP server.
1422 int /* O - 0 on success, non-zero on failure */
1423 httpReconnect(http_t
*http
) /* I - HTTP connection */
1425 http_addrlist_t
*addr
; /* Connected address */
1428 DEBUG_printf(("httpReconnect(http=%p)\n", http
));
1435 http_shutdown_ssl(http
);
1436 #endif /* HAVE_SSL */
1439 * Close any previously open socket...
1445 closesocket(http
->fd
);
1454 * Connect to the server...
1457 if ((addr
= httpAddrConnect(http
->addrlist
, &(http
->fd
))) == NULL
)
1460 * Unable to connect...
1464 http
->error
= WSAGetLastError();
1466 http
->error
= errno
;
1468 http
->status
= HTTP_ERROR
;
1473 http
->hostaddr
= &(addr
->addr
);
1475 http
->status
= HTTP_CONTINUE
;
1478 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
1481 * Always do encryption via SSL.
1484 if (http_setup_ssl(http
) != 0)
1487 closesocket(http
->fd
);
1495 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
1496 return (http_upgrade(http
));
1497 #endif /* HAVE_SSL */
1504 * 'httpSetCookie()' - Set the cookie value(s)...
1506 * @since CUPS 1.1.19@
1510 httpSetCookie(http_t
*http
, /* I - Connection */
1511 const char *cookie
) /* I - Cookie string */
1520 http
->cookie
= strdup(cookie
);
1522 http
->cookie
= NULL
;
1527 * 'httpSetField()' - Set the value of an HTTP header.
1531 httpSetField(http_t
*http
, /* I - HTTP connection */
1532 http_field_t field
, /* I - Field index */
1533 const char *value
) /* I - Value */
1536 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
1537 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
1541 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
1546 * 'httpSetLength()' - Set the content-length and content-encoding.
1552 httpSetLength(http_t
*http
, /* I - HTTP connection */
1553 size_t length
) /* I - Length (0 for chunked) */
1560 strcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked");
1561 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
1565 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
1566 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
1567 CUPS_LLFMT
, CUPS_LLCAST length
);
1573 * 'httpTrace()' - Send an TRACE request to the server.
1576 int /* O - Status of call (0 = success) */
1577 httpTrace(http_t
*http
, /* I - HTTP connection */
1578 const char *uri
) /* I - URI for trace */
1580 return (http_send(http
, HTTP_TRACE
, uri
));
1585 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1588 http_status_t
/* O - HTTP status */
1589 httpUpdate(http_t
*http
) /* I - HTTP connection */
1591 char line
[32768], /* Line from connection... */
1592 *value
; /* Pointer to value on line */
1593 http_field_t field
; /* Field index */
1594 int major
, minor
, /* HTTP version numbers */
1595 status
; /* Request status */
1598 DEBUG_printf(("httpUpdate(http=%p), state=%d\n", http
, http
->state
));
1601 * Flush pending data, if any...
1606 DEBUG_puts(" flushing buffer...");
1608 if (httpFlushWrite(http
) < 0)
1609 return (HTTP_ERROR
);
1613 * If we haven't issued any commands, then there is nothing to "update"...
1616 if (http
->state
== HTTP_WAITING
)
1617 return (HTTP_CONTINUE
);
1620 * Grab all of the lines we can from the connection...
1623 while (httpGets(line
, sizeof(line
), http
) != NULL
)
1625 DEBUG_printf(("httpUpdate: Got \"%s\"\n", line
));
1627 if (line
[0] == '\0')
1630 * Blank line means the start of the data section (if any). Return
1631 * the result code, too...
1633 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
1634 * Instead, we just return HTTP_CONTINUE to the caller and keep on
1638 if (http
->status
== HTTP_CONTINUE
)
1639 return (http
->status
);
1641 if (http
->status
< HTTP_BAD_REQUEST
)
1642 http
->digest_tries
= 0;
1645 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
1647 if (http_setup_ssl(http
) != 0)
1650 closesocket(http
->fd
);
1655 return (HTTP_ERROR
);
1658 return (HTTP_CONTINUE
);
1660 #endif /* HAVE_SSL */
1662 httpGetLength2(http
);
1664 switch (http
->state
)
1668 case HTTP_POST_RECV
:
1671 case HTTP_POST_SEND
:
1675 http
->state
= HTTP_WAITING
;
1679 return (http
->status
);
1681 else if (strncmp(line
, "HTTP/", 5) == 0)
1684 * Got the beginning of a response...
1687 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &status
) != 3)
1688 return (HTTP_ERROR
);
1690 http
->version
= (http_version_t
)(major
* 100 + minor
);
1691 http
->status
= (http_status_t
)status
;
1693 else if ((value
= strchr(line
, ':')) != NULL
)
1700 while (isspace(*value
& 255))
1704 * Be tolerants of servers that send unknown attribute fields...
1707 if (!strcasecmp(line
, "expect"))
1710 * "Expect: 100-continue" or similar...
1713 http
->expect
= (http_status_t
)atoi(value
);
1715 else if (!strcasecmp(line
, "cookie"))
1718 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
1721 httpSetCookie(http
, value
);
1723 else if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
1725 DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line
));
1729 httpSetField(http
, field
, value
);
1733 http
->status
= HTTP_ERROR
;
1734 return (HTTP_ERROR
);
1739 * See if there was an error...
1742 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
1743 return (http
->status
);
1747 DEBUG_printf(("httpUpdate: socket error %d - %s\n", http
->error
,
1748 strerror(http
->error
)));
1749 http
->status
= HTTP_ERROR
;
1750 return (HTTP_ERROR
);
1754 * If we haven't already returned, then there is nothing new...
1757 return (HTTP_CONTINUE
);
1762 * 'httpWait()' - Wait for data available on a connection.
1764 * @since CUPS 1.1.19@
1767 int /* O - 1 if data is available, 0 otherwise */
1768 httpWait(http_t
*http
, /* I - HTTP connection */
1769 int msec
) /* I - Milliseconds to wait */
1772 * First see if there is data in the buffer...
1782 * If not, check the SSL/TLS buffers and do a select() on the connection...
1785 return (http_wait(http
, msec
));
1790 * 'httpWrite()' - Write data to a HTTP connection.
1792 * This function is deprecated. Use the httpWrite2() function which can
1793 * write more than 2GB of data.
1798 int /* O - Number of bytes written */
1799 httpWrite(http_t
*http
, /* I - HTTP connection */
1800 const char *buffer
, /* I - Buffer for data */
1801 int length
) /* I - Number of bytes to write */
1803 return ((int)httpWrite2(http
, buffer
, length
));
1808 * 'httpWrite2()' - Write data to a HTTP connection.
1813 ssize_t
/* O - Number of bytes written */
1814 httpWrite2(http_t
*http
, /* I - HTTP connection */
1815 const char *buffer
, /* I - Buffer for data */
1816 size_t length
) /* I - Number of bytes to write */
1818 ssize_t bytes
; /* Bytes written */
1821 DEBUG_printf(("httpWrite(http=%p, buffer=%p, length=%d)\n", http
,
1825 * Range check input...
1828 if (http
== NULL
|| buffer
== NULL
)
1832 * Mark activity on the connection...
1835 http
->activity
= time(NULL
);
1838 * Buffer small writes for better performance...
1843 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
1845 DEBUG_printf((" flushing buffer (wused=%d, length=%d)\n",
1846 http
->wused
, length
));
1848 httpFlushWrite(http
);
1851 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
))
1854 * Write to buffer...
1857 DEBUG_printf((" copying %d bytes to wbuffer...\n", length
));
1859 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
1860 http
->wused
+= length
;
1866 * Otherwise write the data directly...
1869 DEBUG_printf((" writing %d bytes to socket...\n", length
));
1871 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1872 bytes
= http_write_chunk(http
, buffer
, length
);
1874 bytes
= http_write(http
, buffer
, length
);
1876 DEBUG_printf((" wrote %d bytes...\n", bytes
));
1879 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1880 http
->data_remaining
-= bytes
;
1886 * Handle end-of-request processing...
1889 if ((http
->data_encoding
== HTTP_ENCODE_CHUNKED
&& length
== 0) ||
1890 (http
->data_encoding
== HTTP_ENCODE_LENGTH
&& http
->data_remaining
== 0))
1893 * Finished with the transfer; unless we are sending POST or PUT
1897 DEBUG_puts("httpWrite: changing states...");
1900 httpFlushWrite(http
);
1902 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1905 * Send a 0-length chunk at the end of the request...
1908 http_write(http
, "0\r\n\r\n", 5);
1911 * Reset the data state...
1914 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1915 http
->data_remaining
= 0;
1918 if (http
->state
== HTTP_POST_RECV
)
1920 else if (http
->state
== HTTP_PUT_RECV
)
1921 http
->state
= HTTP_STATUS
;
1923 http
->state
= HTTP_WAITING
;
1930 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
1932 * '_httpWriteCDSA()' - Write function for CDSA encryption code.
1935 OSStatus
/* O - -1 on error, 0 on success */
1937 SSLConnectionRef connection
, /* I - SSL/TLS connection */
1938 const void *data
, /* I - Data buffer */
1939 size_t *dataLength
) /* IO - Number of bytes */
1941 OSStatus result
; /* Return value */
1942 ssize_t bytes
; /* Number of bytes read */
1947 bytes
= write((int)connection
, data
, *dataLength
);
1951 result
= (bytes
== *dataLength
) ? 0 : errSSLWouldBlock
;
1952 *dataLength
= bytes
;
1957 if (errno
== EAGAIN
)
1958 return (errSSLWouldBlock
);
1961 return (errSSLClosedAbort
);
1964 return (errSSLInternal
);
1967 #endif /* HAVE_SSL && HAVE_CDSASSL */
1971 * 'http_field()' - Return the field index for a field name.
1974 static http_field_t
/* O - Field index */
1975 http_field(const char *name
) /* I - String name */
1977 int i
; /* Looping var */
1980 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
1981 if (strcasecmp(name
, http_fields
[i
]) == 0)
1982 return ((http_field_t
)i
);
1984 return (HTTP_FIELD_UNKNOWN
);
1990 * 'http_read_ssl()' - Read from a SSL/TLS connection.
1993 static int /* O - Bytes read */
1994 http_read_ssl(http_t
*http
, /* I - HTTP connection */
1995 char *buf
, /* I - Buffer to store data */
1996 int len
) /* I - Length of buffer */
1998 # if defined(HAVE_LIBSSL)
1999 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
2001 # elif defined(HAVE_GNUTLS)
2002 return (gnutls_record_recv(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
2004 # elif defined(HAVE_CDSASSL)
2005 int result
; /* Return value */
2006 OSStatus error
; /* Error info */
2007 size_t processed
; /* Number of bytes processed */
2010 error
= SSLRead((SSLContextRef
)http
->tls
, buf
, len
, &processed
);
2015 result
= (int)processed
;
2017 case errSSLClosedGraceful
:
2020 case errSSLWouldBlock
:
2031 # endif /* HAVE_LIBSSL */
2033 #endif /* HAVE_SSL */
2037 * 'http_send()' - Send a request with all fields and the trailing blank line.
2040 static int /* O - 0 on success, non-zero on error */
2041 http_send(http_t
*http
, /* I - HTTP connection */
2042 http_state_t request
, /* I - Request code */
2043 const char *uri
) /* I - URI */
2045 int i
; /* Looping var */
2046 char *ptr
, /* Pointer in buffer */
2047 buf
[1024]; /* Encoded URI buffer */
2048 static const char * const codes
[] =
2049 { /* Request code strings */
2064 static const char hex
[] = "0123456789ABCDEF";
2068 DEBUG_printf(("http_send(http=%p, request=HTTP_%s, uri=\"%s\")\n",
2069 http
, codes
[request
], uri
));
2071 if (http
== NULL
|| uri
== NULL
)
2075 * Set the User-Agent field if it isn't already...
2078 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
2079 httpSetField(http
, HTTP_FIELD_USER_AGENT
, CUPS_MINIMAL
);
2082 * Encode the URI as needed...
2085 for (ptr
= buf
; *uri
!= '\0' && ptr
< (buf
+ sizeof(buf
) - 1); uri
++)
2086 if (*uri
<= ' ' || *uri
>= 127)
2088 if (ptr
< (buf
+ sizeof(buf
) - 1))
2090 if (ptr
< (buf
+ sizeof(buf
) - 1))
2091 *ptr
++ = hex
[(*uri
>> 4) & 15];
2092 if (ptr
< (buf
+ sizeof(buf
) - 1))
2093 *ptr
++ = hex
[*uri
& 15];
2101 * See if we had an error the last time around; if so, reconnect...
2104 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
2105 if (httpReconnect(http
))
2109 * Send the request header...
2112 http
->state
= request
;
2113 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
2116 http
->status
= HTTP_CONTINUE
;
2119 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
2121 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
2122 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
2124 #endif /* HAVE_SSL */
2126 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
2128 http
->status
= HTTP_ERROR
;
2132 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2133 if (http
->fields
[i
][0] != '\0')
2135 DEBUG_printf(("%s: %s\n", http_fields
[i
], http
->fields
[i
]));
2137 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], http
->fields
[i
]) < 1)
2139 http
->status
= HTTP_ERROR
;
2145 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
2147 http
->status
= HTTP_ERROR
;
2151 if (httpPrintf(http
, "\r\n") < 1)
2153 http
->status
= HTTP_ERROR
;
2157 httpGetLength2(http
);
2158 httpClearFields(http
);
2166 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
2169 static int /* O - Status of connection */
2170 http_setup_ssl(http_t
*http
) /* I - HTTP connection */
2173 SSL_CTX
*context
; /* Context for encryption */
2174 SSL
*conn
; /* Connection for encryption */
2175 # elif defined(HAVE_GNUTLS)
2176 http_tls_t
*conn
; /* TLS session object */
2177 gnutls_certificate_client_credentials
*credentials
;
2178 /* TLS credentials */
2179 # elif defined(HAVE_CDSASSL)
2180 SSLContextRef conn
; /* Context for encryption */
2181 OSStatus error
; /* Error info */
2182 # endif /* HAVE_LIBSSL */
2185 DEBUG_printf(("http_setup_ssl(http=%p)\n", http
));
2188 context
= SSL_CTX_new(SSLv23_client_method());
2190 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
2192 conn
= SSL_new(context
);
2194 SSL_set_fd(conn
, http
->fd
);
2195 if (SSL_connect(conn
) != 1)
2198 unsigned long error
; /* Error code */
2200 while ((error
= ERR_get_error()) != 0)
2201 printf("http_setup_ssl: %s\n", ERR_error_string(error
, NULL
));
2204 SSL_CTX_free(context
);
2208 http
->error
= WSAGetLastError();
2210 http
->error
= errno
;
2212 http
->status
= HTTP_ERROR
;
2214 return (HTTP_ERROR
);
2217 # elif defined(HAVE_GNUTLS)
2218 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
2222 http
->error
= errno
;
2223 http
->status
= HTTP_ERROR
;
2228 credentials
= (gnutls_certificate_client_credentials
*)
2229 malloc(sizeof(gnutls_certificate_client_credentials
));
2230 if (credentials
== NULL
)
2234 http
->error
= errno
;
2235 http
->status
= HTTP_ERROR
;
2240 gnutls_certificate_allocate_credentials(credentials
);
2242 gnutls_init(&(conn
->session
), GNUTLS_CLIENT
);
2243 gnutls_set_default_priority(conn
->session
);
2244 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
2245 gnutls_transport_set_ptr(conn
->session
, http
->fd
);
2247 if ((gnutls_handshake(conn
->session
)) != GNUTLS_E_SUCCESS
)
2249 http
->error
= errno
;
2250 http
->status
= HTTP_ERROR
;
2255 conn
->credentials
= credentials
;
2257 # elif defined(HAVE_CDSASSL)
2258 error
= SSLNewContext(false, &conn
);
2261 error
= SSLSetIOFuncs(conn
, _httpReadCDSA
, _httpWriteCDSA
);
2264 error
= SSLSetConnection(conn
, (SSLConnectionRef
)http
->fd
);
2267 error
= SSLSetAllowsExpiredCerts(conn
, true);
2270 error
= SSLSetAllowsAnyRoot(conn
, true);
2273 error
= SSLHandshake(conn
);
2277 http
->error
= error
;
2278 http
->status
= HTTP_ERROR
;
2280 SSLDisposeContext(conn
);
2286 # endif /* HAVE_CDSASSL */
2291 #endif /* HAVE_SSL */
2296 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
2300 http_shutdown_ssl(http_t
*http
) /* I - HTTP connection */
2303 SSL_CTX
*context
; /* Context for encryption */
2304 SSL
*conn
; /* Connection for encryption */
2307 conn
= (SSL
*)(http
->tls
);
2308 context
= SSL_get_SSL_CTX(conn
);
2311 SSL_CTX_free(context
);
2314 # elif defined(HAVE_GNUTLS)
2315 http_tls_t
*conn
; /* Encryption session */
2316 gnutls_certificate_client_credentials
*credentials
;
2317 /* TLS credentials */
2320 conn
= (http_tls_t
*)(http
->tls
);
2321 credentials
= (gnutls_certificate_client_credentials
*)(conn
->credentials
);
2323 gnutls_bye(conn
->session
, GNUTLS_SHUT_RDWR
);
2324 gnutls_deinit(conn
->session
);
2325 gnutls_certificate_free_credentials(*credentials
);
2329 # elif defined(HAVE_CDSASSL)
2330 SSLClose((SSLContextRef
)http
->tls
);
2331 SSLDisposeContext((SSLContextRef
)http
->tls
);
2332 # endif /* HAVE_LIBSSL */
2336 #endif /* HAVE_SSL */
2341 * 'http_upgrade()' - Force upgrade to TLS encryption.
2344 static int /* O - Status of connection */
2345 http_upgrade(http_t
*http
) /* I - HTTP connection */
2347 int ret
; /* Return value */
2348 http_t myhttp
; /* Local copy of HTTP data */
2351 DEBUG_printf(("http_upgrade(%p)\n", http
));
2354 * Copy the HTTP data to a local variable so we can do the OPTIONS
2355 * request without interfering with the existing request data...
2358 memcpy(&myhttp
, http
, sizeof(myhttp
));
2361 * Send an OPTIONS request to the server, requiring SSL or TLS
2362 * encryption on the link...
2365 httpClearFields(&myhttp
);
2366 httpSetField(&myhttp
, HTTP_FIELD_CONNECTION
, "upgrade");
2367 httpSetField(&myhttp
, HTTP_FIELD_UPGRADE
, "TLS/1.0, SSL/2.0, SSL/3.0");
2369 if ((ret
= httpOptions(&myhttp
, "*")) == 0)
2372 * Wait for the secure connection...
2375 while (httpUpdate(&myhttp
) == HTTP_CONTINUE
);
2381 * Copy the HTTP data back over, if any...
2384 http
->fd
= myhttp
.fd
;
2385 http
->error
= myhttp
.error
;
2386 http
->activity
= myhttp
.activity
;
2387 http
->status
= myhttp
.status
;
2388 http
->version
= myhttp
.version
;
2389 http
->keep_alive
= myhttp
.keep_alive
;
2390 http
->used
= myhttp
.used
;
2393 memcpy(http
->buffer
, myhttp
.buffer
, http
->used
);
2395 http
->auth_type
= myhttp
.auth_type
;
2396 http
->nonce_count
= myhttp
.nonce_count
;
2398 memcpy(http
->nonce
, myhttp
.nonce
, sizeof(http
->nonce
));
2400 http
->tls
= myhttp
.tls
;
2401 http
->encryption
= myhttp
.encryption
;
2404 * See if we actually went secure...
2410 * Server does not support HTTP upgrade...
2413 DEBUG_puts("Server does not support HTTP upgrade!");
2416 closesocket(http
->fd
);
2428 #endif /* HAVE_SSL */
2432 * 'http_wait()' - Wait for data available on a connection.
2435 static int /* O - 1 if data is available, 0 otherwise */
2436 http_wait(http_t
*http
, /* I - HTTP connection */
2437 int msec
) /* I - Milliseconds to wait */
2440 struct rlimit limit
; /* Runtime limit */
2441 int set_size
; /* Size of select set */
2443 struct timeval timeout
; /* Timeout */
2444 int nfds
; /* Result from select() */
2447 DEBUG_printf(("http_wait(http=%p, msec=%d)\n", http
, msec
));
2453 * Check the SSL/TLS buffers for data first...
2460 if (SSL_pending((SSL
*)(http
->tls
)))
2462 # elif defined(HAVE_GNUTLS)
2463 if (gnutls_record_check_pending(((http_tls_t
*)(http
->tls
))->session
))
2465 # elif defined(HAVE_CDSASSL)
2466 size_t bytes
; /* Bytes that are available */
2468 if (!SSLGetBufferedReadSize((SSLContextRef
)http
->tls
, &bytes
) && bytes
> 0)
2470 # endif /* HAVE_LIBSSL */
2472 #endif /* HAVE_SSL */
2475 * Then try doing a select() to poll the socket...
2478 if (!http
->input_set
)
2482 * Windows has a fixed-size select() structure, different (surprise,
2483 * surprise!) from all UNIX implementations. Just allocate this
2484 * fixed structure...
2487 http
->input_set
= calloc(1, sizeof(fd_set
));
2490 * Allocate the select() input set based upon the max number of file
2491 * descriptors available for this process...
2494 getrlimit(RLIMIT_NOFILE
, &limit
);
2496 set_size
= (limit
.rlim_cur
+ 31) / 8 + 4;
2497 if (set_size
< sizeof(fd_set
))
2498 set_size
= sizeof(fd_set
);
2500 http
->input_set
= calloc(1, set_size
);
2503 if (!http
->input_set
)
2509 FD_SET(http
->fd
, http
->input_set
);
2513 timeout
.tv_sec
= msec
/ 1000;
2514 timeout
.tv_usec
= (msec
% 1000) * 1000;
2516 nfds
= select(http
->fd
+ 1, http
->input_set
, NULL
, NULL
, &timeout
);
2519 nfds
= select(http
->fd
+ 1, http
->input_set
, NULL
, NULL
, NULL
);
2522 while (nfds
< 0 && WSAGetLastError() == WSAEINTR
);
2524 while (nfds
< 0 && errno
== EINTR
);
2527 FD_CLR(http
->fd
, http
->input_set
);
2534 * 'http_write()' - Write a buffer to a HTTP connection.
2537 static int /* O - Number of bytes written */
2538 http_write(http_t
*http
, /* I - HTTP connection */
2539 const char *buffer
, /* I - Buffer for data */
2540 int length
) /* I - Number of bytes to write */
2542 int tbytes
, /* Total bytes sent */
2543 bytes
; /* Bytes sent */
2552 bytes
= http_write_ssl(http
, buffer
, length
);
2554 #endif /* HAVE_SSL */
2555 bytes
= send(http
->fd
, buffer
, length
, 0);
2560 if (WSAGetLastError() != http
->error
)
2562 http
->error
= WSAGetLastError();
2568 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
2570 http
->error
= errno
;
2575 DEBUG_puts("http_write: error writing data...\n");
2588 printf("http_write: wrote %d bytes: \n", tbytes
);
2589 for (i
= 0, buffer
-= tbytes
; i
< tbytes
; i
+= 16)
2593 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
2594 printf(" %02X", buffer
[i
+ j
] & 255);
2603 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
2605 ch
= buffer
[i
+ j
] & 255;
2607 if (ch
< ' ' || ch
== 127)
2622 * 'http_write_chunk()' - Write a chunked buffer.
2625 static int /* O - Number bytes written */
2626 http_write_chunk(http_t
*http
, /* I - HTTP connection */
2627 const char *buffer
, /* I - Buffer to write */
2628 int length
) /* I - Length of buffer */
2630 char header
[255]; /* Chunk header */
2631 int bytes
; /* Bytes written */
2633 DEBUG_printf(("http_write_chunk(http=%p, buffer=%p, length=%d)\n",
2634 http
, buffer
, length
));
2637 * Write the chunk header, data, and trailer.
2640 sprintf(header
, "%x\r\n", length
);
2641 if (http_write(http
, header
, strlen(header
)) < 0)
2643 DEBUG_puts(" http_write of length failed!");
2647 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
2649 DEBUG_puts(" http_write of buffer failed!");
2653 if (http_write(http
, "\r\n", 2) < 0)
2655 DEBUG_puts(" http_write of CR LF failed!");
2665 * 'http_write_ssl()' - Write to a SSL/TLS connection.
2668 static int /* O - Bytes written */
2669 http_write_ssl(http_t
*http
, /* I - HTTP connection */
2670 const char *buf
, /* I - Buffer holding data */
2671 int len
) /* I - Length of buffer */
2673 # if defined(HAVE_LIBSSL)
2674 return (SSL_write((SSL
*)(http
->tls
), buf
, len
));
2676 # elif defined(HAVE_GNUTLS)
2677 return (gnutls_record_send(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
2678 # elif defined(HAVE_CDSASSL)
2679 int result
; /* Return value */
2680 OSStatus error
; /* Error info */
2681 size_t processed
; /* Number of bytes processed */
2684 error
= SSLWrite((SSLContextRef
)http
->tls
, buf
, len
, &processed
);
2689 result
= (int)processed
;
2691 case errSSLClosedGraceful
:
2694 case errSSLWouldBlock
:
2705 # endif /* HAVE_LIBSSL */
2707 #endif /* HAVE_SSL */
2711 * End of "$Id: http.c 5138 2006-02-21 10:49:06Z mike $".