4 * HTTP routines for the Common UNIX Printing System (CUPS).
6 * Copyright 1997-2005 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 * httpInitialize() - Initialize the HTTP interface library and set the
29 * default HTTP proxy (if any).
30 * httpCheck() - Check to see if there is a pending response from
32 * httpClearCookie() - Clear the cookie value(s).
33 * httpClose() - Close an HTTP connection...
34 * httpConnect() - Connect to a HTTP server.
35 * httpConnectEncrypt() - Connect to a HTTP server using encryption.
36 * httpEncryption() - Set the required encryption on the link.
37 * httpReconnect() - Reconnect to a HTTP server...
38 * httpGetSubField() - Get a sub-field value.
39 * httpSetField() - Set the value of an HTTP header.
40 * httpDelete() - Send a DELETE request to the server.
41 * httpGet() - Send a GET request to the server.
42 * httpHead() - Send a HEAD request to the server.
43 * httpOptions() - Send an OPTIONS request to the server.
44 * httpPost() - Send a POST request to the server.
45 * httpPut() - Send a PUT request to the server.
46 * httpTrace() - Send an TRACE request to the server.
47 * httpFlush() - Flush data from a HTTP connection.
48 * httpRead() - Read data from a HTTP connection.
49 * httpSetCookie() - Set the cookie value(s)...
50 * httpWait() - Wait for data available on a connection.
51 * httpWrite() - Write data to a HTTP connection.
52 * httpGets() - Get a line of text from a HTTP connection.
53 * httpPrintf() - Print a formatted string to a HTTP connection.
54 * httpGetDateString() - Get a formatted date/time string from a time value.
55 * httpGetDateString2() - Get a formatted date/time string from a time value.
56 * httpGetDateTime() - Get a time value from a formatted date/time string.
57 * httpUpdate() - Update the current HTTP state for incoming data.
58 * httpDecode64() - Base64-decode a string.
59 * httpDecode64_2() - Base64-decode a string.
60 * httpEncode64() - Base64-encode a string.
61 * httpEncode64_2() - Base64-encode a string.
62 * httpGetLength() - Get the amount of data remaining from the
63 * content-length or transfer-encoding fields.
64 * http_field() - Return the field index for a field name.
65 * http_send() - Send a request with all fields and the trailing
67 * http_wait() - Wait for data available on a connection.
68 * http_upgrade() - Force upgrade to TLS encryption.
69 * http_setup_ssl() - Set up SSL/TLS on a connection.
70 * http_shutdown_ssl() - Shut down SSL/TLS on a connection.
71 * http_read_ssl() - Read from a SSL/TLS connection.
72 * http_write_ssl() - Write to a SSL/TLS connection.
73 * CDSAReadFunc() - Read function for CDSA decryption code.
74 * CDSAWriteFunc() - Write function for CDSA encryption code.
78 * Include necessary headers...
81 #include "http-private.h"
96 # include <sys/time.h>
97 # include <sys/resource.h>
102 * Some operating systems have done away with the Fxxxx constants for
103 * the fcntl() call; this works around that "feature"...
107 # define FNONBLK O_NONBLOCK
108 #endif /* !FNONBLK */
115 static http_field_t
http_field(const char *name
);
116 static int http_send(http_t
*http
, http_state_t request
,
118 static int http_wait(http_t
*http
, int msec
);
120 static int http_upgrade(http_t
*http
);
121 static int http_setup_ssl(http_t
*http
);
122 static void http_shutdown_ssl(http_t
*http
);
123 static int http_read_ssl(http_t
*http
, char *buf
, int len
);
124 static int http_write_ssl(http_t
*http
, const char *buf
, int len
);
126 static OSStatus
CDSAReadFunc(SSLConnectionRef connection
, void *data
, size_t *dataLength
);
127 static OSStatus
CDSAWriteFunc(SSLConnectionRef connection
, const void *data
, size_t *dataLength
);
128 # endif /* HAVE_CDSASSL */
129 #endif /* HAVE_SSL */
136 static const char * const http_fields
[] =
153 "If-Unmodified-since",
166 static const char * const http_days
[7] =
176 static const char * const http_months
[12] =
194 * 'httpInitialize()' - Initialize the HTTP interface library and set the
195 * default HTTP proxy (if any).
203 struct timeval curtime
; /* Current time in microseconds */
205 int i
; /* Looping var */
206 unsigned char data
[1024]; /* Seed data */
207 #endif /* HAVE_LIBSSL */
210 WSADATA winsockdata
; /* WinSock data */
211 static int initialized
= 0; /* Has WinSock been initialized? */
215 WSAStartup(MAKEWORD(1,1), &winsockdata
);
216 #elif defined(HAVE_SIGSET)
217 sigset(SIGPIPE
, SIG_IGN
);
218 #elif defined(HAVE_SIGACTION)
219 struct sigaction action
; /* POSIX sigaction data */
223 * Ignore SIGPIPE signals...
226 memset(&action
, 0, sizeof(action
));
227 action
.sa_handler
= SIG_IGN
;
228 sigaction(SIGPIPE
, &action
, NULL
);
230 signal(SIGPIPE
, SIG_IGN
);
234 gnutls_global_init();
235 #endif /* HAVE_GNUTLS */
238 SSL_load_error_strings();
242 * Using the current time is a dubious random seed, but on some systems
243 * it is the best we can do (on others, this seed isn't even used...)
248 gettimeofday(&curtime
, NULL
);
249 srand(curtime
.tv_sec
+ curtime
.tv_usec
);
252 for (i
= 0; i
< sizeof(data
); i
++)
253 data
[i
] = rand(); /* Yes, this is a poor source of random data... */
255 RAND_seed(&data
, sizeof(data
));
256 #endif /* HAVE_LIBSSL */
261 * 'httpCheck()' - Check to see if there is a pending response from the server.
264 int /* O - 0 = no data, 1 = data available */
265 httpCheck(http_t
*http
) /* I - HTTP connection */
267 return (httpWait(http
, 0));
272 * 'httpClearCookie()' - Clear the cookie value(s).
276 httpClearCookie(http_t
*http
) /* I - Connection */
290 * 'httpClose()' - Close an HTTP connection...
294 httpClose(http_t
*http
) /* I - Connection to close */
296 DEBUG_printf(("httpClose(http=%p)\n", http
));
302 free(http
->input_set
);
309 http_shutdown_ssl(http
);
310 #endif /* HAVE_SSL */
313 closesocket(http
->fd
);
323 * 'httpConnect()' - Connect to a HTTP server.
326 http_t
* /* O - New HTTP connection */
327 httpConnect(const char *host
, /* I - Host to connect to */
328 int port
) /* I - Port number */
330 http_encryption_t encryption
; /* Type of encryption to use */
334 * Set the default encryption status...
338 encryption
= HTTP_ENCRYPT_ALWAYS
;
340 encryption
= HTTP_ENCRYPT_IF_REQUESTED
;
342 return (httpConnectEncrypt(host
, port
, encryption
));
347 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
350 http_t
* /* O - New HTTP connection */
352 const char *host
, /* I - Host to connect to */
353 int port
, /* I - Port number */
354 http_encryption_t encryption
) /* I - Type of encryption to use */
356 int i
; /* Looping var */
357 http_t
*http
; /* New HTTP connection */
358 struct hostent
*hostaddr
; /* Host address data */
361 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encrypt=%d)\n",
362 host
? host
: "(null)", port
, encrypt
));
373 if ((hostaddr
= httpGetHostByName(host
)) == NULL
)
376 * This hack to make users that don't have a localhost entry in
377 * their hosts file or DNS happy...
380 if (strcasecmp(host
, "localhost") != 0)
382 else if ((hostaddr
= httpGetHostByName("127.0.0.1")) == NULL
)
387 * Verify that it is an IPv4, IPv6, or domain address...
390 if ((hostaddr
->h_addrtype
!= AF_INET
|| hostaddr
->h_length
!= 4)
392 && (hostaddr
->h_addrtype
!= AF_INET6
|| hostaddr
->h_length
!= 16)
393 #endif /* AF_INET6 */
395 && (hostaddr
->h_addrtype
!= AF_LOCAL
)
396 #endif /* AF_LOCAL */
401 * Allocate memory for the structure...
404 http
= calloc(sizeof(http_t
), 1);
408 http
->version
= HTTP_1_1
;
410 http
->activity
= time(NULL
);
414 * Set the encryption status...
417 if (port
== 443) /* Always use encryption for https */
418 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
420 http
->encryption
= encryption
;
423 * Loop through the addresses we have until one of them connects...
426 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
428 for (i
= 0; hostaddr
->h_addr_list
[i
]; i
++)
431 * Load the address...
434 httpAddrLoad(hostaddr
, port
, i
, &(http
->hostaddr
));
437 * Connect to the remote system...
440 if (!httpReconnect(http
))
445 * Could not connect to any known address - bail out!
454 * 'httpEncryption()' - Set the required encryption on the link.
457 int /* O - -1 on error, 0 on success */
458 httpEncryption(http_t
*http
, /* I - HTTP data */
459 http_encryption_t e
) /* I - New encryption preference */
461 DEBUG_printf(("httpEncryption(http=%p, e=%d)\n", http
, e
));
467 http
->encryption
= e
;
469 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
470 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
471 return (httpReconnect(http
));
472 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
473 return (http_upgrade(http
));
477 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
481 #endif /* HAVE_SSL */
486 * 'httpReconnect()' - Reconnect to a HTTP server...
489 int /* O - 0 on success, non-zero on failure */
490 httpReconnect(http_t
*http
) /* I - HTTP data */
492 int val
; /* Socket option value */
493 int status
; /* Connect status */
496 DEBUG_printf(("httpReconnect(http=%p)\n", http
));
503 http_shutdown_ssl(http
);
504 #endif /* HAVE_SSL */
507 * Close any previously open socket...
512 closesocket(http
->fd
);
518 * Create the socket and set options to allow reuse.
521 if ((http
->fd
= socket(http
->hostaddr
.addr
.sa_family
, SOCK_STREAM
, 0)) < 0)
524 http
->error
= WSAGetLastError();
528 http
->status
= HTTP_ERROR
;
533 fcntl(http
->fd
, F_SETFD
, FD_CLOEXEC
); /* Close this socket when starting *
534 * other processes... */
535 #endif /* FD_CLOEXEC */
538 setsockopt(http
->fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *)&val
, sizeof(val
));
542 setsockopt(http
->fd
, SOL_SOCKET
, SO_REUSEPORT
, &val
, sizeof(val
));
543 #endif /* SO_REUSEPORT */
546 * Using TCP_NODELAY improves responsiveness, especially on systems
547 * with a slow loopback interface... Since we write large buffers
548 * when sending print files and requests, there shouldn't be any
549 * performance penalty for this...
554 setsockopt(http
->fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&val
, sizeof(val
));
556 setsockopt(http
->fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
560 * Connect to the server...
564 if (http
->hostaddr
.addr
.sa_family
== AF_INET6
)
565 status
= connect(http
->fd
, (struct sockaddr
*)&(http
->hostaddr
),
566 sizeof(http
->hostaddr
.ipv6
));
568 #endif /* AF_INET6 */
570 if (http
->hostaddr
.addr
.sa_family
== AF_LOCAL
)
571 status
= connect(http
->fd
, (struct sockaddr
*)&(http
->hostaddr
),
572 SUN_LEN(&(http
->hostaddr
.un
)));
574 #endif /* AF_LOCAL */
575 status
= connect(http
->fd
, (struct sockaddr
*)&(http
->hostaddr
),
576 sizeof(http
->hostaddr
.ipv4
));
581 http
->error
= WSAGetLastError();
585 http
->status
= HTTP_ERROR
;
588 closesocket(http
->fd
);
599 http
->status
= HTTP_CONTINUE
;
602 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
605 * Always do encryption via SSL.
608 if (http_setup_ssl(http
) != 0)
611 closesocket(http
->fd
);
619 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
620 return (http_upgrade(http
));
621 #endif /* HAVE_SSL */
628 * 'httpGetSubField()' - Get a sub-field value.
631 char * /* O - Value or NULL */
632 httpGetSubField(http_t
*http
, /* I - HTTP data */
633 http_field_t field
, /* I - Field index */
634 const char *name
, /* I - Name of sub-field */
635 char *value
) /* O - Value string */
637 const char *fptr
; /* Pointer into field */
638 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
639 *ptr
; /* Pointer into string buffer */
642 DEBUG_printf(("httpGetSubField(http=%p, field=%d, name=\"%s\", value=%p)\n",
643 http
, field
, name
, value
));
646 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
647 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
648 name
== NULL
|| value
== NULL
)
651 for (fptr
= http
->fields
[field
]; *fptr
;)
654 * Skip leading whitespace...
657 while (isspace(*fptr
& 255))
667 * Get the sub-field name...
671 *fptr
&& *fptr
!= '=' && !isspace(*fptr
& 255) && ptr
< (temp
+ sizeof(temp
) - 1);
676 DEBUG_printf(("httpGetSubField: name=\"%s\"\n", temp
));
679 * Skip trailing chars up to the '='...
682 while (isspace(*fptr
& 255))
692 * Skip = and leading whitespace...
697 while (isspace(*fptr
& 255))
703 * Read quoted string...
706 for (ptr
= value
, fptr
++;
707 *fptr
&& *fptr
!= '\"' && ptr
< (value
+ HTTP_MAX_VALUE
- 1);
712 while (*fptr
&& *fptr
!= '\"')
721 * Read unquoted string...
725 *fptr
&& !isspace(*fptr
& 255) && *fptr
!= ',' && ptr
< (value
+ HTTP_MAX_VALUE
- 1);
730 while (*fptr
&& !isspace(*fptr
& 255) && *fptr
!= ',')
734 DEBUG_printf(("httpGetSubField: value=\"%s\"\n", value
));
737 * See if this is the one...
740 if (strcmp(name
, temp
) == 0)
751 * 'httpSetField()' - Set the value of an HTTP header.
755 httpSetField(http_t
*http
, /* I - HTTP data */
756 http_field_t field
, /* I - Field index */
757 const char *value
) /* I - Value */
760 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
761 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
765 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
770 * 'httpDelete()' - Send a DELETE request to the server.
773 int /* O - Status of call (0 = success) */
774 httpDelete(http_t
*http
, /* I - HTTP data */
775 const char *uri
) /* I - URI to delete */
777 return (http_send(http
, HTTP_DELETE
, uri
));
782 * 'httpGet()' - Send a GET request to the server.
785 int /* O - Status of call (0 = success) */
786 httpGet(http_t
*http
, /* I - HTTP data */
787 const char *uri
) /* I - URI to get */
789 return (http_send(http
, HTTP_GET
, uri
));
794 * 'httpHead()' - Send a HEAD request to the server.
797 int /* O - Status of call (0 = success) */
798 httpHead(http_t
*http
, /* I - HTTP data */
799 const char *uri
) /* I - URI for head */
801 return (http_send(http
, HTTP_HEAD
, uri
));
806 * 'httpOptions()' - Send an OPTIONS request to the server.
809 int /* O - Status of call (0 = success) */
810 httpOptions(http_t
*http
, /* I - HTTP data */
811 const char *uri
) /* I - URI for options */
813 return (http_send(http
, HTTP_OPTIONS
, uri
));
818 * 'httpPost()' - Send a POST request to the server.
821 int /* O - Status of call (0 = success) */
822 httpPost(http_t
*http
, /* I - HTTP data */
823 const char *uri
) /* I - URI for post */
827 return (http_send(http
, HTTP_POST
, uri
));
832 * 'httpPut()' - Send a PUT request to the server.
835 int /* O - Status of call (0 = success) */
836 httpPut(http_t
*http
, /* I - HTTP data */
837 const char *uri
) /* I - URI to put */
841 return (http_send(http
, HTTP_PUT
, uri
));
846 * 'httpTrace()' - Send an TRACE request to the server.
849 int /* O - Status of call (0 = success) */
850 httpTrace(http_t
*http
, /* I - HTTP data */
851 const char *uri
) /* I - URI for trace */
853 return (http_send(http
, HTTP_TRACE
, uri
));
858 * 'httpFlush()' - Flush data from a HTTP connection.
862 httpFlush(http_t
*http
) /* I - HTTP data */
864 char buffer
[8192]; /* Junk buffer */
867 DEBUG_printf(("httpFlush(http=%p), state=%d\n", http
, http
->state
));
869 while (httpRead(http
, buffer
, sizeof(buffer
)) > 0);
874 * 'httpRead()' - Read data from a HTTP connection.
877 int /* O - Number of bytes read */
878 httpRead(http_t
*http
, /* I - HTTP data */
879 char *buffer
, /* I - Buffer for data */
880 int length
) /* I - Maximum number of bytes */
882 int bytes
; /* Bytes read */
883 char len
[32]; /* Length string */
886 DEBUG_printf(("httpRead(http=%p, buffer=%p, length=%d)\n",
887 http
, buffer
, length
));
889 if (http
== NULL
|| buffer
== NULL
)
892 http
->activity
= time(NULL
);
897 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
898 http
->data_remaining
<= 0)
900 DEBUG_puts("httpRead: Getting chunk length...");
902 if (httpGets(len
, sizeof(len
), http
) == NULL
)
904 DEBUG_puts("httpRead: Could not get length!");
908 http
->data_remaining
= strtol(len
, NULL
, 16);
909 if (http
->data_remaining
< 0)
911 DEBUG_puts("httpRead: Negative chunk length!");
916 DEBUG_printf(("httpRead: data_remaining=%d\n", http
->data_remaining
));
918 if (http
->data_remaining
<= 0)
921 * A zero-length chunk ends a transfer; unless we are reading POST
925 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
926 httpGets(len
, sizeof(len
), http
);
928 if (http
->state
== HTTP_POST_RECV
)
931 http
->state
= HTTP_WAITING
;
934 * Prevent future reads for this request...
937 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
941 else if (length
> http
->data_remaining
)
942 length
= http
->data_remaining
;
944 if (http
->used
== 0 && length
<= 256)
947 * Buffer small reads for better performance...
950 if (!http
->blocking
&& !httpWait(http
, 1000))
953 if (http
->data_remaining
> sizeof(http
->buffer
))
954 bytes
= sizeof(http
->buffer
);
956 bytes
= http
->data_remaining
;
960 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
962 #endif /* HAVE_SSL */
964 DEBUG_printf(("httpRead: reading %d bytes from socket into buffer...\n",
967 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
969 DEBUG_printf(("httpRead: read %d bytes from socket into buffer...\n",
978 http
->error
= WSAGetLastError();
997 if (length
> http
->used
)
1002 DEBUG_printf(("httpRead: grabbing %d bytes from input buffer...\n", bytes
));
1004 memcpy(buffer
, http
->buffer
, length
);
1005 http
->used
-= length
;
1008 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
1013 if (!http
->blocking
&& !httpWait(http
, 1000))
1016 bytes
= http_read_ssl(http
, buffer
, length
);
1018 #endif /* HAVE_SSL */
1021 if (!http
->blocking
&& !httpWait(http
, 1000))
1024 DEBUG_printf(("httpRead: reading %d bytes from socket...\n", length
));
1026 while ((bytes
= recv(http
->fd
, buffer
, length
, 0)) < 0)
1030 DEBUG_printf(("httpRead: read %d bytes from socket...\n", bytes
));
1034 http
->data_remaining
-= bytes
;
1038 http
->error
= WSAGetLastError();
1043 http
->error
= errno
;
1048 http
->error
= EPIPE
;
1052 if (http
->data_remaining
== 0)
1054 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1055 httpGets(len
, sizeof(len
), http
);
1057 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
1059 if (http
->state
== HTTP_POST_RECV
)
1062 http
->state
= HTTP_WAITING
;
1069 printf("httpRead: Read %d bytes:\n", bytes
);
1070 for (i
= 0; i
< bytes
; i
+= 16)
1074 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1075 printf(" %02X", buffer
[i
+ j
] & 255);
1084 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1086 ch
= buffer
[i
+ j
] & 255;
1088 if (ch
< ' ' || ch
== 127)
1103 * 'httpSetCookie()' - Set the cookie value(s)...
1107 httpSetCookie(http_t
*http
, /* I - Connection */
1108 const char *cookie
) /* I - Cookie string */
1117 http
->cookie
= strdup(cookie
);
1119 http
->cookie
= NULL
;
1124 * 'httpWait()' - Wait for data available on a connection.
1127 int /* O - 1 if data is available, 0 otherwise */
1128 httpWait(http_t
*http
, /* I - HTTP data */
1129 int msec
) /* I - Milliseconds to wait */
1132 * First see if there is data in the buffer...
1142 * If not, check the SSL/TLS buffers and do a select() on the connection...
1145 return (http_wait(http
, msec
));
1150 * 'httpWrite()' - Write data to a HTTP connection.
1153 int /* O - Number of bytes written */
1154 httpWrite(http_t
*http
, /* I - HTTP data */
1155 const char *buffer
, /* I - Buffer for data */
1156 int length
) /* I - Number of bytes to write */
1158 int tbytes
, /* Total bytes sent */
1159 bytes
; /* Bytes sent */
1162 if (http
== NULL
|| buffer
== NULL
)
1165 http
->activity
= time(NULL
);
1167 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1169 if (httpPrintf(http
, "%x\r\n", length
) < 0)
1175 * A zero-length chunk ends a transfer; unless we are sending POST
1176 * or PUT data, go idle...
1179 DEBUG_puts("httpWrite: changing states...");
1181 if (http
->state
== HTTP_POST_RECV
)
1183 else if (http
->state
== HTTP_PUT_RECV
)
1184 http
->state
= HTTP_STATUS
;
1186 http
->state
= HTTP_WAITING
;
1188 if (httpPrintf(http
, "\r\n") < 0)
1201 bytes
= http_write_ssl(http
, buffer
, length
);
1203 #endif /* HAVE_SSL */
1204 bytes
= send(http
->fd
, buffer
, length
, 0);
1209 if (WSAGetLastError() != http
->error
)
1211 http
->error
= WSAGetLastError();
1217 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
1219 http
->error
= errno
;
1224 DEBUG_puts("httpWrite: error writing data...\n");
1232 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1233 http
->data_remaining
-= bytes
;
1236 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1237 if (httpPrintf(http
, "\r\n") < 0)
1240 if (http
->data_remaining
== 0 && http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1243 * Finished with the transfer; unless we are sending POST or PUT
1247 DEBUG_puts("httpWrite: changing states...");
1249 if (http
->state
== HTTP_POST_RECV
)
1251 else if (http
->state
== HTTP_PUT_RECV
)
1252 http
->state
= HTTP_STATUS
;
1254 http
->state
= HTTP_WAITING
;
1260 printf("httpWrite: wrote %d bytes: \n", tbytes
);
1261 for (i
= 0, buffer
-= tbytes
; i
< tbytes
; i
+= 16)
1265 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
1266 printf(" %02X", buffer
[i
+ j
] & 255);
1275 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
1277 ch
= buffer
[i
+ j
] & 255;
1279 if (ch
< ' ' || ch
== 127)
1293 * 'httpGets()' - Get a line of text from a HTTP connection.
1296 char * /* O - Line or NULL */
1297 httpGets(char *line
, /* I - Line to read into */
1298 int length
, /* I - Max length of buffer */
1299 http_t
*http
) /* I - HTTP data */
1301 char *lineptr
, /* Pointer into line */
1302 *bufptr
, /* Pointer into input buffer */
1303 *bufend
; /* Pointer to end of buffer */
1304 int bytes
; /* Number of bytes read */
1307 DEBUG_printf(("httpGets(line=%p, length=%d, http=%p)\n", line
, length
, http
));
1309 if (http
== NULL
|| line
== NULL
)
1313 * Pre-scan the buffer and see if there is a newline in there...
1324 bufptr
= http
->buffer
;
1325 bufend
= http
->buffer
+ http
->used
;
1327 while (bufptr
< bufend
)
1328 if (*bufptr
== 0x0a)
1333 if (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
)
1336 * No newline; see if there is more data to be read...
1339 if (!http
->blocking
&& !http_wait(http
, 1000))
1344 bytes
= http_read_ssl(http
, bufend
, HTTP_MAX_BUFFER
- http
->used
);
1346 #endif /* HAVE_SSL */
1347 bytes
= recv(http
->fd
, bufend
, HTTP_MAX_BUFFER
- http
->used
, 0);
1349 DEBUG_printf(("httpGets: read %d bytes...\n", bytes
));
1354 * Nope, can't get a line this time...
1358 if (WSAGetLastError() != http
->error
)
1360 http
->error
= WSAGetLastError();
1364 DEBUG_printf(("httpGets: recv() error %d!\n", WSAGetLastError()));
1366 DEBUG_printf(("httpGets: recv() error %d!\n", errno
));
1370 else if (errno
!= http
->error
)
1372 http
->error
= errno
;
1379 else if (bytes
== 0)
1381 http
->error
= EPIPE
;
1387 * Yup, update the amount used and the end pointer...
1390 http
->used
+= bytes
;
1395 while (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
);
1397 http
->activity
= time(NULL
);
1400 * Read a line from the buffer...
1404 bufptr
= http
->buffer
;
1408 while (bufptr
< bufend
&& bytes
< length
)
1412 if (*bufptr
== 0x0a)
1417 else if (*bufptr
== 0x0d)
1420 *lineptr
++ = *bufptr
++;
1427 http
->used
-= bytes
;
1429 memmove(http
->buffer
, bufptr
, http
->used
);
1431 DEBUG_printf(("httpGets: Returning \"%s\"\n", line
));
1435 DEBUG_puts("httpGets: No new line available!");
1442 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1445 int /* O - Number of bytes written */
1446 httpPrintf(http_t
*http
, /* I - HTTP data */
1447 const char *format
, /* I - printf-style format string */
1448 ...) /* I - Additional args as needed */
1450 int bytes
, /* Number of bytes to write */
1451 nbytes
, /* Number of bytes written */
1452 tbytes
; /* Number of bytes all together */
1453 char buf
[HTTP_MAX_BUFFER
], /* Buffer for formatted string */
1454 *bufptr
; /* Pointer into buffer */
1455 va_list ap
; /* Variable argument pointer */
1458 DEBUG_printf(("httpPrintf(http=%p, format=\"%s\", ...)\n", http
, format
));
1460 va_start(ap
, format
);
1461 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1464 DEBUG_printf(("httpPrintf: %s", buf
));
1466 for (tbytes
= 0, bufptr
= buf
; tbytes
< bytes
; tbytes
+= nbytes
, bufptr
+= nbytes
)
1470 nbytes
= http_write_ssl(http
, bufptr
, bytes
- tbytes
);
1472 #endif /* HAVE_SSL */
1473 nbytes
= send(http
->fd
, bufptr
, bytes
- tbytes
, 0);
1480 if (WSAGetLastError() != http
->error
)
1482 http
->error
= WSAGetLastError();
1488 else if (errno
!= http
->error
)
1490 http
->error
= errno
;
1504 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
1506 * This function is not thread-safe and is therefore deprecated.
1509 const char * /* O - Date/time string */
1510 httpGetDateString(time_t t
) /* I - UNIX time */
1512 static char datetime
[256]; /* Date/time string */
1515 return (httpGetDateString2(t
, datetime
, sizeof(datetime
)));
1520 * 'httpGetDateString2()' - Get a formatted date/time string from a time value.
1523 const char * /* O - Date/time string */
1524 httpGetDateString2(time_t t
, /* I - UNIX time */
1525 char *s
, /* I - String buffer */
1526 int slen
) /* I - Size of string buffer */
1528 struct tm
*tdate
; /* UNIX date/time data */
1532 snprintf(s
, slen
, "%s, %02d %s %d %02d:%02d:%02d GMT",
1533 http_days
[tdate
->tm_wday
], tdate
->tm_mday
,
1534 http_months
[tdate
->tm_mon
], tdate
->tm_year
+ 1900,
1535 tdate
->tm_hour
, tdate
->tm_min
, tdate
->tm_sec
);
1542 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
1545 time_t /* O - UNIX time */
1546 httpGetDateTime(const char *s
) /* I - Date/time string */
1548 int i
; /* Looping var */
1549 char mon
[16]; /* Abbreviated month name */
1550 int day
, year
; /* Day of month and year */
1551 int hour
, min
, sec
; /* Time */
1552 int days
; /* Number of days since 1970 */
1553 static const int normal_days
[] = /* Days to a month, normal years */
1554 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
1555 static const int leap_days
[] = /* Days to a month, leap years */
1556 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 };
1559 DEBUG_printf(("httpGetDateTime(s=\"%s\")\n", s
));
1562 * Extract the date and time from the formatted string...
1565 if (sscanf(s
, "%*s%d%15s%d%d:%d:%d", &day
, mon
, &year
, &hour
, &min
, &sec
) < 6)
1568 DEBUG_printf((" day=%d, mon=\"%s\", year=%d, hour=%d, min=%d, sec=%d\n",
1569 day
, mon
, year
, hour
, min
, sec
));
1572 * Convert the month name to a number from 0 to 11.
1575 for (i
= 0; i
< 12; i
++)
1576 if (!strcasecmp(mon
, http_months
[i
]))
1582 DEBUG_printf((" i=%d\n", i
));
1585 * Now convert the date and time to a UNIX time value in seconds since
1586 * 1970. We can't use mktime() since the timezone may not be UTC but
1587 * the date/time string *is* UTC.
1590 if ((year
& 3) == 0 && ((year
% 100) != 0 || (year
% 400) == 0))
1591 days
= leap_days
[i
] + day
- 1;
1593 days
= normal_days
[i
] + day
- 1;
1595 DEBUG_printf((" days=%d\n", days
));
1597 days
+= (year
- 1970) * 365 + /* 365 days per year (normally) */
1598 ((year
- 1) / 4 - 492) - /* + leap days */
1599 ((year
- 1) / 100 - 19) + /* - 100 year days */
1600 ((year
- 1) / 400 - 4); /* + 400 year days */
1602 DEBUG_printf((" days=%d\n", days
));
1604 return (days
* 86400 + hour
* 3600 + min
* 60 + sec
);
1609 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1612 http_status_t
/* O - HTTP status */
1613 httpUpdate(http_t
*http
) /* I - HTTP data */
1615 char line
[1024], /* Line from connection... */
1616 *value
; /* Pointer to value on line */
1617 http_field_t field
; /* Field index */
1618 int major
, minor
, /* HTTP version numbers */
1619 status
; /* Request status */
1622 DEBUG_printf(("httpUpdate(http=%p), state=%d\n", http
, http
->state
));
1625 * If we haven't issued any commands, then there is nothing to "update"...
1628 if (http
->state
== HTTP_WAITING
)
1629 return (HTTP_CONTINUE
);
1632 * Grab all of the lines we can from the connection...
1635 while (httpGets(line
, sizeof(line
), http
) != NULL
)
1637 DEBUG_printf(("httpUpdate: Got \"%s\"\n", line
));
1639 if (line
[0] == '\0')
1642 * Blank line means the start of the data section (if any). Return
1643 * the result code, too...
1645 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
1646 * Instead, we just return HTTP_CONTINUE to the caller and keep on
1650 if (http
->status
== HTTP_CONTINUE
)
1651 return (http
->status
);
1653 if (http
->status
< HTTP_BAD_REQUEST
)
1654 http
->digest_tries
= 0;
1657 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
1659 if (http_setup_ssl(http
) != 0)
1662 closesocket(http
->fd
);
1667 return (HTTP_ERROR
);
1670 return (HTTP_CONTINUE
);
1672 #endif /* HAVE_SSL */
1674 httpGetLength(http
);
1676 switch (http
->state
)
1680 case HTTP_POST_RECV
:
1683 case HTTP_POST_SEND
:
1687 http
->state
= HTTP_WAITING
;
1691 return (http
->status
);
1693 else if (strncmp(line
, "HTTP/", 5) == 0)
1696 * Got the beginning of a response...
1699 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &status
) != 3)
1700 return (HTTP_ERROR
);
1702 http
->version
= (http_version_t
)(major
* 100 + minor
);
1703 http
->status
= (http_status_t
)status
;
1705 else if ((value
= strchr(line
, ':')) != NULL
)
1712 while (isspace(*value
& 255))
1716 * Be tolerants of servers that send unknown attribute fields...
1719 if (!strcasecmp(line
, "expect"))
1722 * "Expect: 100-continue" or similar...
1725 http
->expect
= (http_status_t
)atoi(value
);
1727 else if (!strcasecmp(line
, "cookie"))
1730 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
1733 httpSetCookie(http
, value
);
1735 else if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
1737 DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line
));
1741 httpSetField(http
, field
, value
);
1745 http
->status
= HTTP_ERROR
;
1746 return (HTTP_ERROR
);
1751 * See if there was an error...
1754 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
1755 return (http
->status
);
1759 DEBUG_printf(("httpUpdate: socket error %d - %s\n", http
->error
,
1760 strerror(http
->error
)));
1761 http
->status
= HTTP_ERROR
;
1762 return (HTTP_ERROR
);
1766 * If we haven't already returned, then there is nothing new...
1769 return (HTTP_CONTINUE
);
1774 * 'httpDecode64()' - Base64-decode a string.
1777 char * /* O - Decoded string */
1778 httpDecode64(char *out
, /* I - String to write to */
1779 const char *in
) /* I - String to read from */
1781 int outlen
; /* Output buffer length */
1785 * Use the old maximum buffer size for binary compatibility...
1790 return (httpDecode64_2(out
, &outlen
, in
));
1795 * 'httpDecode64_2()' - Base64-decode a string.
1798 char * /* O - Decoded string */
1799 httpDecode64_2(char *out
, /* I - String to write to */
1800 int *outlen
, /* IO - Size of output string */
1801 const char *in
) /* I - String to read from */
1803 int pos
, /* Bit position */
1804 base64
; /* Value of this character */
1805 char *outptr
, /* Output pointer */
1806 *outend
; /* End of output buffer */
1810 * Range check input...
1813 if (!out
|| !outlen
|| *outlen
< 1 || !in
|| !*in
)
1817 * Convert from base-64 to bytes...
1820 for (outptr
= out
, outend
= out
+ *outlen
- 1, pos
= 0; *in
!= '\0'; in
++)
1823 * Decode this character into a number from 0 to 63...
1826 if (*in
>= 'A' && *in
<= 'Z')
1828 else if (*in
>= 'a' && *in
<= 'z')
1829 base64
= *in
- 'a' + 26;
1830 else if (*in
>= '0' && *in
<= '9')
1831 base64
= *in
- '0' + 52;
1832 else if (*in
== '+')
1834 else if (*in
== '/')
1836 else if (*in
== '=')
1842 * Store the result in the appropriate chars...
1848 if (outptr
< outend
)
1849 *outptr
= base64
<< 2;
1853 if (outptr
< outend
)
1854 *outptr
++ |= (base64
>> 4) & 3;
1855 if (outptr
< outend
)
1856 *outptr
= (base64
<< 4) & 255;
1860 if (outptr
< outend
)
1861 *outptr
++ |= (base64
>> 2) & 15;
1862 if (outptr
< outend
)
1863 *outptr
= (base64
<< 6) & 255;
1867 if (outptr
< outend
)
1868 *outptr
++ |= base64
;
1877 * Return the decoded string and size...
1880 *outlen
= (int)(outptr
- out
);
1887 * 'httpEncode64()' - Base64-encode a string.
1890 char * /* O - Encoded string */
1891 httpEncode64(char *out
, /* I - String to write to */
1892 const char *in
) /* I - String to read from */
1894 return (httpEncode64_2(out
, 512, in
, strlen(in
)));
1899 * 'httpEncode64_2()' - Base64-encode a string.
1902 char * /* O - Encoded string */
1903 httpEncode64_2(char *out
, /* I - String to write to */
1904 int outlen
, /* I - Size of output string */
1905 const char *in
, /* I - String to read from */
1906 int inlen
) /* I - Size of input string */
1908 char *outptr
, /* Output pointer */
1909 *outend
; /* End of output buffer */
1910 static const char base64
[] = /* Base64 characters... */
1912 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1913 "abcdefghijklmnopqrstuvwxyz"
1920 * Range check input...
1923 if (!out
|| outlen
< 1 || !in
|| inlen
< 1)
1927 * Convert bytes to base-64...
1930 for (outptr
= out
, outend
= out
+ outlen
- 1; inlen
> 0; in
++, inlen
--)
1933 * Encode the up to 3 characters as 4 Base64 numbers...
1936 if (outptr
< outend
)
1937 *outptr
++ = base64
[(in
[0] & 255) >> 2];
1938 if (outptr
< outend
)
1939 *outptr
++ = base64
[(((in
[0] & 255) << 4) | ((in
[1] & 255) >> 4)) & 63];
1945 if (outptr
< outend
)
1947 if (outptr
< outend
)
1952 if (outptr
< outend
)
1953 *outptr
++ = base64
[(((in
[0] & 255) << 2) | ((in
[1] & 255) >> 6)) & 63];
1959 if (outptr
< outend
)
1964 if (outptr
< outend
)
1965 *outptr
++ = base64
[in
[0] & 63];
1971 * Return the encoded string...
1979 * 'httpGetLength()' - Get the amount of data remaining from the
1980 * content-length or transfer-encoding fields.
1983 int /* O - Content length */
1984 httpGetLength(http_t
*http
) /* I - HTTP data */
1986 DEBUG_printf(("httpGetLength(http=%p), state=%d\n", http
, http
->state
));
1988 if (strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked") == 0)
1990 DEBUG_puts("httpGetLength: chunked request!");
1992 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
1993 http
->data_remaining
= 0;
1997 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
2000 * The following is a hack for HTTP servers that don't send a
2001 * content-length or transfer-encoding field...
2003 * If there is no content-length then the connection must close
2004 * after the transfer is complete...
2007 if (http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] == '\0')
2008 http
->data_remaining
= 2147483647;
2010 http
->data_remaining
= atoi(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
]);
2012 DEBUG_printf(("httpGetLength: content_length=%d\n", http
->data_remaining
));
2015 return (http
->data_remaining
);
2020 * 'http_field()' - Return the field index for a field name.
2023 static http_field_t
/* O - Field index */
2024 http_field(const char *name
) /* I - String name */
2026 int i
; /* Looping var */
2029 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2030 if (strcasecmp(name
, http_fields
[i
]) == 0)
2031 return ((http_field_t
)i
);
2033 return (HTTP_FIELD_UNKNOWN
);
2038 * 'http_send()' - Send a request with all fields and the trailing blank line.
2041 static int /* O - 0 on success, non-zero on error */
2042 http_send(http_t
*http
, /* I - HTTP data */
2043 http_state_t request
, /* I - Request code */
2044 const char *uri
) /* I - URI */
2046 int i
; /* Looping var */
2047 char *ptr
, /* Pointer in buffer */
2048 buf
[1024]; /* Encoded URI buffer */
2049 static const char * const codes
[] =
2050 { /* Request code strings */
2065 static const char hex
[] = "0123456789ABCDEF";
2069 DEBUG_printf(("http_send(http=%p, request=HTTP_%s, uri=\"%s\")\n",
2070 http
, codes
[request
], uri
));
2072 if (http
== NULL
|| uri
== NULL
)
2076 * Encode the URI as needed...
2079 for (ptr
= buf
; *uri
!= '\0' && ptr
< (buf
+ sizeof(buf
) - 1); uri
++)
2080 if (*uri
<= ' ' || *uri
>= 127)
2082 if (ptr
< (buf
+ sizeof(buf
) - 1))
2084 if (ptr
< (buf
+ sizeof(buf
) - 1))
2085 *ptr
++ = hex
[(*uri
>> 4) & 15];
2086 if (ptr
< (buf
+ sizeof(buf
) - 1))
2087 *ptr
++ = hex
[*uri
& 15];
2095 * See if we had an error the last time around; if so, reconnect...
2098 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
2099 httpReconnect(http
);
2102 * Send the request header...
2105 http
->state
= request
;
2106 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
2109 http
->status
= HTTP_CONTINUE
;
2112 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
2114 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
2115 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
2117 #endif /* HAVE_SSL */
2119 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
2121 http
->status
= HTTP_ERROR
;
2125 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2126 if (http
->fields
[i
][0] != '\0')
2128 DEBUG_printf(("%s: %s\n", http_fields
[i
], http
->fields
[i
]));
2130 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], http
->fields
[i
]) < 1)
2132 http
->status
= HTTP_ERROR
;
2137 if (httpPrintf(http
, "\r\n") < 1)
2139 http
->status
= HTTP_ERROR
;
2143 httpClearFields(http
);
2150 * 'http_wait()' - Wait for data available on a connection.
2153 static int /* O - 1 if data is available, 0 otherwise */
2154 http_wait(http_t
*http
, /* I - HTTP data */
2155 int msec
) /* I - Milliseconds to wait */
2158 struct rlimit limit
; /* Runtime limit */
2160 struct timeval timeout
; /* Timeout */
2161 int nfds
; /* Result from select() */
2162 int set_size
; /* Size of select set */
2165 DEBUG_printf(("http_wait(http=%p, msec=%d)\n", http
, msec
));
2168 * Check the SSL/TLS buffers for data first...
2175 if (SSL_pending((SSL
*)(http
->tls
)))
2177 # elif defined(HAVE_GNUTLS)
2178 if (gnutls_record_check_pending(((http_tls_t
*)(http
->tls
))->session
))
2180 # elif defined(HAVE_CDSASSL)
2181 size_t bytes
; /* Bytes that are available */
2183 if (!SSLGetBufferedReadSize((SSLContextRef
)http
->tls
, &bytes
) && bytes
> 0)
2185 # endif /* HAVE_LIBSSL */
2187 #endif /* HAVE_SSL */
2190 * Then try doing a select() to poll the socket...
2193 if (!http
->input_set
)
2197 * Windows has a fixed-size select() structure, different (surprise,
2198 * surprise!) from all UNIX implementations. Just allocate this
2199 * fixed structure...
2202 http
->input_set
= calloc(1, sizeof(fd_set
));
2205 * Allocate the select() input set based upon the max number of file
2206 * descriptors available for this process...
2209 getrlimit(RLIMIT_NOFILE
, &limit
);
2211 set_size
= (limit
.rlim_cur
+ 31) / 8 + 4;
2212 if (set_size
< sizeof(fd_set
))
2213 set_size
= sizeof(fd_set
);
2215 http
->input_set
= calloc(1, set_size
);
2218 if (!http
->input_set
)
2224 FD_SET(http
->fd
, http
->input_set
);
2228 timeout
.tv_sec
= msec
/ 1000;
2229 timeout
.tv_usec
= (msec
% 1000) * 1000;
2231 nfds
= select(http
->fd
+ 1, http
->input_set
, NULL
, NULL
, &timeout
);
2234 nfds
= select(http
->fd
+ 1, http
->input_set
, NULL
, NULL
, NULL
);
2237 while (nfds
< 0 && WSAGetLastError() == WSAEINTR
);
2239 while (nfds
< 0 && errno
== EINTR
);
2242 FD_CLR(http
->fd
, http
->input_set
);
2250 * 'http_upgrade()' - Force upgrade to TLS encryption.
2253 static int /* O - Status of connection */
2254 http_upgrade(http_t
*http
) /* I - HTTP data */
2256 int ret
; /* Return value */
2257 http_t myhttp
; /* Local copy of HTTP data */
2260 DEBUG_printf(("http_upgrade(%p)\n", http
));
2263 * Copy the HTTP data to a local variable so we can do the OPTIONS
2264 * request without interfering with the existing request data...
2267 memcpy(&myhttp
, http
, sizeof(myhttp
));
2270 * Send an OPTIONS request to the server, requiring SSL or TLS
2271 * encryption on the link...
2274 httpClearFields(&myhttp
);
2275 httpSetField(&myhttp
, HTTP_FIELD_CONNECTION
, "upgrade");
2276 httpSetField(&myhttp
, HTTP_FIELD_UPGRADE
, "TLS/1.0, SSL/2.0, SSL/3.0");
2278 if ((ret
= httpOptions(&myhttp
, "*")) == 0)
2281 * Wait for the secure connection...
2284 while (httpUpdate(&myhttp
) == HTTP_CONTINUE
);
2290 * Copy the HTTP data back over, if any...
2293 http
->fd
= myhttp
.fd
;
2294 http
->error
= myhttp
.error
;
2295 http
->activity
= myhttp
.activity
;
2296 http
->status
= myhttp
.status
;
2297 http
->version
= myhttp
.version
;
2298 http
->keep_alive
= myhttp
.keep_alive
;
2299 http
->used
= myhttp
.used
;
2302 memcpy(http
->buffer
, myhttp
.buffer
, http
->used
);
2304 http
->auth_type
= myhttp
.auth_type
;
2305 http
->nonce_count
= myhttp
.nonce_count
;
2307 memcpy(http
->nonce
, myhttp
.nonce
, sizeof(http
->nonce
));
2309 http
->tls
= myhttp
.tls
;
2310 http
->encryption
= myhttp
.encryption
;
2313 * See if we actually went secure...
2319 * Server does not support HTTP upgrade...
2322 DEBUG_puts("Server does not support HTTP upgrade!");
2325 closesocket(http
->fd
);
2340 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
2343 static int /* O - Status of connection */
2344 http_setup_ssl(http_t
*http
) /* I - HTTP data */
2347 SSL_CTX
*context
; /* Context for encryption */
2348 SSL
*conn
; /* Connection for encryption */
2349 # elif defined(HAVE_GNUTLS)
2350 http_tls_t
*conn
; /* TLS session object */
2351 gnutls_certificate_client_credentials
*credentials
;
2352 /* TLS credentials */
2353 # elif defined(HAVE_CDSASSL)
2354 SSLContextRef conn
; /* Context for encryption */
2355 OSStatus error
; /* Error info */
2356 # endif /* HAVE_LIBSSL */
2359 DEBUG_printf(("http_setup_ssl(http=%p)\n", http
));
2362 context
= SSL_CTX_new(SSLv23_client_method());
2364 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
2366 conn
= SSL_new(context
);
2368 SSL_set_fd(conn
, http
->fd
);
2369 if (SSL_connect(conn
) != 1)
2372 unsigned long error
; /* Error code */
2374 while ((error
= ERR_get_error()) != 0)
2375 printf("http_setup_ssl: %s\n", ERR_error_string(error
, NULL
));
2378 SSL_CTX_free(context
);
2382 http
->error
= WSAGetLastError();
2384 http
->error
= errno
;
2386 http
->status
= HTTP_ERROR
;
2388 return (HTTP_ERROR
);
2391 # elif defined(HAVE_GNUTLS)
2392 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
2396 http
->error
= errno
;
2397 http
->status
= HTTP_ERROR
;
2402 credentials
= (gnutls_certificate_client_credentials
*)
2403 malloc(sizeof(gnutls_certificate_client_credentials
));
2404 if (credentials
== NULL
)
2408 http
->error
= errno
;
2409 http
->status
= HTTP_ERROR
;
2414 gnutls_certificate_allocate_credentials(credentials
);
2416 gnutls_init(&(conn
->session
), GNUTLS_CLIENT
);
2417 gnutls_set_default_priority(conn
->session
);
2418 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
2419 gnutls_transport_set_ptr(conn
->session
, http
->fd
);
2421 if ((gnutls_handshake(conn
->session
)) != GNUTLS_E_SUCCESS
)
2423 http
->error
= errno
;
2424 http
->status
= HTTP_ERROR
;
2429 conn
->credentials
= credentials
;
2431 # elif defined(HAVE_CDSASSL)
2432 error
= SSLNewContext(false, &conn
);
2435 error
= SSLSetIOFuncs(conn
, CDSAReadFunc
, CDSAWriteFunc
);
2438 error
= SSLSetConnection(conn
, (SSLConnectionRef
)http
->fd
);
2441 error
= SSLSetAllowsExpiredCerts(conn
, true);
2444 error
= SSLSetAllowsAnyRoot(conn
, true);
2447 error
= SSLHandshake(conn
);
2451 http
->error
= error
;
2452 http
->status
= HTTP_ERROR
;
2454 SSLDisposeContext(conn
);
2460 # endif /* HAVE_CDSASSL */
2468 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
2472 http_shutdown_ssl(http_t
*http
) /* I - HTTP data */
2475 SSL_CTX
*context
; /* Context for encryption */
2476 SSL
*conn
; /* Connection for encryption */
2479 conn
= (SSL
*)(http
->tls
);
2480 context
= SSL_get_SSL_CTX(conn
);
2483 SSL_CTX_free(context
);
2486 # elif defined(HAVE_GNUTLS)
2487 http_tls_t
*conn
; /* Encryption session */
2488 gnutls_certificate_client_credentials
*credentials
;
2489 /* TLS credentials */
2492 conn
= (http_tls_t
*)(http
->tls
);
2493 credentials
= (gnutls_certificate_client_credentials
*)(conn
->credentials
);
2495 gnutls_bye(conn
->session
, GNUTLS_SHUT_RDWR
);
2496 gnutls_deinit(conn
->session
);
2497 gnutls_certificate_free_credentials(*credentials
);
2501 # elif defined(HAVE_CDSASSL)
2502 SSLClose((SSLContextRef
)http
->tls
);
2503 SSLDisposeContext((SSLContextRef
)http
->tls
);
2504 # endif /* HAVE_LIBSSL */
2511 * 'http_read_ssl()' - Read from a SSL/TLS connection.
2514 static int /* O - Bytes read */
2515 http_read_ssl(http_t
*http
, /* I - HTTP data */
2516 char *buf
, /* I - Buffer to store data */
2517 int len
) /* I - Length of buffer */
2519 # if defined(HAVE_LIBSSL)
2520 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
2522 # elif defined(HAVE_GNUTLS)
2523 return (gnutls_record_recv(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
2525 # elif defined(HAVE_CDSASSL)
2526 OSStatus error
; /* Error info */
2527 size_t processed
; /* Number of bytes processed */
2530 error
= SSLRead((SSLContextRef
)http
->tls
, buf
, len
, &processed
);
2536 http
->error
= error
;
2540 # endif /* HAVE_LIBSSL */
2545 * 'http_write_ssl()' - Write to a SSL/TLS connection.
2548 static int /* O - Bytes written */
2549 http_write_ssl(http_t
*http
, /* I - HTTP data */
2550 const char *buf
, /* I - Buffer holding data */
2551 int len
) /* I - Length of buffer */
2553 # if defined(HAVE_LIBSSL)
2554 return (SSL_write((SSL
*)(http
->tls
), buf
, len
));
2556 # elif defined(HAVE_GNUTLS)
2557 return (gnutls_record_send(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
2558 # elif defined(HAVE_CDSASSL)
2559 OSStatus error
; /* Error info */
2560 size_t processed
; /* Number of bytes processed */
2563 error
= SSLWrite((SSLContextRef
)http
->tls
, buf
, len
, &processed
);
2569 http
->error
= error
;
2572 # endif /* HAVE_LIBSSL */
2576 # if defined(HAVE_CDSASSL)
2578 * 'CDSAReadFunc()' - Read function for CDSA decryption code.
2581 static OSStatus
/* O - -1 on error, 0 on success */
2582 CDSAReadFunc(SSLConnectionRef connection
, /* I - SSL/TLS connection */
2583 void *data
, /* I - Data buffer */
2584 size_t *dataLength
) /* IO - Number of bytes */
2586 ssize_t bytes
; /* Number of bytes read */
2589 bytes
= recv((int)connection
, data
, *dataLength
, 0);
2592 *dataLength
= bytes
;
2601 * 'CDSAWriteFunc()' - Write function for CDSA encryption code.
2604 static OSStatus
/* O - -1 on error, 0 on success */
2605 CDSAWriteFunc(SSLConnectionRef connection
, /* I - SSL/TLS connection */
2606 const void *data
, /* I - Data buffer */
2607 size_t *dataLength
) /* IO - Number of bytes */
2612 bytes
= write((int)connection
, data
, *dataLength
);
2615 *dataLength
= bytes
;
2621 # endif /* HAVE_CDSASSL */
2622 #endif /* HAVE_SSL */