2 * "$Id: http.c 148 2006-04-25 16:54:17Z njacobs $"
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 * httpGetDateTime() - Get a time value from a formatted date/time string.
56 * httpUpdate() - Update the current HTTP state for incoming data.
57 * httpDecode64() - Base64-decode a string.
58 * httpDecode64_2() - Base64-decode a string.
59 * httpEncode64() - Base64-encode a string.
60 * httpEncode64_2() - Base64-encode a string.
61 * httpGetLength() - Get the amount of data remaining from the
62 * content-length or transfer-encoding fields.
63 * http_field() - Return the field index for a field name.
64 * http_send() - Send a request with all fields and the trailing
66 * http_wait() - Wait for data available on a connection.
67 * http_upgrade() - Force upgrade to TLS encryption.
68 * http_setup_ssl() - Set up SSL/TLS on a connection.
69 * http_shutdown_ssl() - Shut down SSL/TLS on a connection.
70 * http_read_ssl() - Read from a SSL/TLS connection.
71 * http_write_ssl() - Write to a SSL/TLS connection.
72 * CDSAReadFunc() - Read function for CDSA decryption code.
73 * CDSAWriteFunc() - Write function for CDSA encryption code.
76 #pragma ident "%Z%%M% %I% %E% SMI"
79 * Include necessary headers...
82 #include "http-private.h"
97 # include <sys/time.h>
98 # include <sys/resource.h>
103 * Some operating systems have done away with the Fxxxx constants for
104 * the fcntl() call; this works around that "feature"...
108 # define FNONBLK O_NONBLOCK
109 #endif /* !FNONBLK */
116 static http_field_t
http_field(const char *name
);
117 static int http_send(http_t
*http
, http_state_t request
,
119 static int http_wait(http_t
*http
, int msec
);
121 static int http_upgrade(http_t
*http
);
122 static int http_setup_ssl(http_t
*http
);
123 static void http_shutdown_ssl(http_t
*http
);
124 static int http_read_ssl(http_t
*http
, char *buf
, int len
);
125 static int http_write_ssl(http_t
*http
, const char *buf
, int len
);
127 static OSStatus
CDSAReadFunc(SSLConnectionRef connection
, void *data
, size_t *dataLength
);
128 static OSStatus
CDSAWriteFunc(SSLConnectionRef connection
, const void *data
, size_t *dataLength
);
129 # endif /* HAVE_CDSASSL */
130 #endif /* HAVE_SSL */
137 static const char * const http_fields
[] =
154 "If-Unmodified-since",
167 static const char * const days
[7] =
177 static const char * const months
[12] =
194 httpDumpData(FILE *fp
, const char *tag
, const char *buffer
, int bytes
)
198 fprintf(fp
, "%s %d(0x%x) bytes...\n", tag
, bytes
, bytes
);
199 for (i
= 0; i
< bytes
; i
+= 16) {
200 fprintf(fp
, "%s ", (tag
? tag
: ""));
202 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
203 fprintf(fp
, " %02X", buffer
[i
+ j
] & 255);
211 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++) {
212 ch
= buffer
[i
+ j
] & 255;
213 if (ch
< ' ' || ch
== 127)
223 * 'httpInitialize()' - Initialize the HTTP interface library and set the
224 * default HTTP proxy (if any).
232 struct timeval curtime
; /* Current time in microseconds */
234 int i
; /* Looping var */
235 unsigned char data
[1024]; /* Seed data */
236 #endif /* HAVE_LIBSSL */
239 WSADATA winsockdata
; /* WinSock data */
240 static int initialized
= 0; /* Has WinSock been initialized? */
244 WSAStartup(MAKEWORD(1,1), &winsockdata
);
245 #elif defined(HAVE_SIGSET)
246 sigset(SIGPIPE
, SIG_IGN
);
247 #elif defined(HAVE_SIGACTION)
248 struct sigaction action
; /* POSIX sigaction data */
252 * Ignore SIGPIPE signals...
255 memset(&action
, 0, sizeof(action
));
256 action
.sa_handler
= SIG_IGN
;
257 sigaction(SIGPIPE
, &action
, NULL
);
259 signal(SIGPIPE
, SIG_IGN
);
263 gnutls_global_init();
264 #endif /* HAVE_GNUTLS */
267 SSL_load_error_strings();
271 * Using the current time is a dubious random seed, but on some systems
272 * it is the best we can do (on others, this seed isn't even used...)
277 gettimeofday(&curtime
, NULL
);
278 srand(curtime
.tv_sec
+ curtime
.tv_usec
);
281 for (i
= 0; i
< sizeof(data
); i
++)
282 data
[i
] = rand(); /* Yes, this is a poor source of random data... */
284 RAND_seed(&data
, sizeof(data
));
285 #endif /* HAVE_LIBSSL */
290 * 'httpCheck()' - Check to see if there is a pending response from the server.
293 int /* O - 0 = no data, 1 = data available */
294 httpCheck(http_t
*http
) /* I - HTTP connection */
296 return (httpWait(http
, 0));
301 * 'httpClearCookie()' - Clear the cookie value(s).
305 httpClearCookie(http_t
*http
) /* I - Connection */
319 * 'httpClose()' - Close an HTTP connection...
323 httpClose(http_t
*http
) /* I - Connection to close */
325 DEBUG_printf(("httpClose(http=%p)\n", http
));
331 free(http
->input_set
);
338 http_shutdown_ssl(http
);
339 #endif /* HAVE_SSL */
342 closesocket(http
->fd
);
352 * 'httpConnect()' - Connect to a HTTP server.
355 http_t
* /* O - New HTTP connection */
356 httpConnect(const char *host
, /* I - Host to connect to */
357 int port
) /* I - Port number */
359 http_encryption_t encrypt
; /* Type of encryption to use */
363 * Set the default encryption status...
367 encrypt
= HTTP_ENCRYPT_ALWAYS
;
369 encrypt
= HTTP_ENCRYPT_IF_REQUESTED
;
371 return (httpConnectEncrypt(host
, port
, encrypt
));
376 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
379 http_t
* /* O - New HTTP connection */
380 httpConnectEncrypt(const char *host
, /* I - Host to connect to */
381 int port
, /* I - Port number */
382 http_encryption_t encrypt
)
383 /* I - Type of encryption to use */
385 int i
; /* Looping var */
386 http_t
*http
; /* New HTTP connection */
387 struct hostent
*hostaddr
; /* Host address data */
390 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encrypt=%d)\n",
391 host
? host
: "(null)", port
, encrypt
));
402 if ((hostaddr
= httpGetHostByName(host
)) == NULL
)
405 * This hack to make users that don't have a localhost entry in
406 * their hosts file or DNS happy...
409 if (strcasecmp(host
, "localhost") != 0)
411 else if ((hostaddr
= httpGetHostByName("127.0.0.1")) == NULL
)
416 * Verify that it is an IPv4, IPv6, or domain address...
419 if ((hostaddr
->h_addrtype
!= AF_INET
|| hostaddr
->h_length
!= 4)
421 && (hostaddr
->h_addrtype
!= AF_INET6
|| hostaddr
->h_length
!= 16)
422 #endif /* AF_INET6 */
424 && (hostaddr
->h_addrtype
!= AF_LOCAL
)
425 #endif /* AF_LOCAL */
430 * Allocate memory for the structure...
433 http
= calloc(sizeof(http_t
), 1);
437 http
->version
= HTTP_1_1
;
439 http
->activity
= time(NULL
);
443 * Set the encryption status...
446 if (port
== 443) /* Always use encryption for https */
447 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
449 http
->encryption
= encrypt
;
452 * Loop through the addresses we have until one of them connects...
455 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
457 for (i
= 0; hostaddr
->h_addr_list
[i
]; i
++)
460 * Load the address...
463 httpAddrLoad(hostaddr
, port
, i
, &(http
->hostaddr
));
466 * Connect to the remote system...
469 if (!httpReconnect(http
))
474 * Could not connect to any known address - bail out!
483 * 'httpEncryption()' - Set the required encryption on the link.
486 int /* O - -1 on error, 0 on success */
487 httpEncryption(http_t
*http
, /* I - HTTP data */
488 http_encryption_t e
) /* I - New encryption preference */
490 DEBUG_printf(("httpEncryption(http=%p, e=%d)\n", http
, e
));
496 http
->encryption
= e
;
498 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
499 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
500 return (httpReconnect(http
));
501 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
502 return (http_upgrade(http
));
506 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
510 #endif /* HAVE_SSL */
515 * 'httpReconnect()' - Reconnect to a HTTP server...
518 int /* O - 0 on success, non-zero on failure */
519 httpReconnect(http_t
*http
) /* I - HTTP data */
521 int val
; /* Socket option value */
522 int status
; /* Connect status */
525 DEBUG_printf(("httpReconnect(http=%p)\n", http
));
532 http_shutdown_ssl(http
);
533 #endif /* HAVE_SSL */
536 * Close any previously open socket...
541 closesocket(http
->fd
);
547 * Create the socket and set options to allow reuse.
550 if ((http
->fd
= socket(http
->hostaddr
.addr
.sa_family
, SOCK_STREAM
, 0)) < 0)
553 http
->error
= WSAGetLastError();
557 http
->status
= HTTP_ERROR
;
562 fcntl(http
->fd
, F_SETFD
, FD_CLOEXEC
); /* Close this socket when starting *
563 * other processes... */
564 #endif /* FD_CLOEXEC */
567 setsockopt(http
->fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *)&val
, sizeof(val
));
571 setsockopt(http
->fd
, SOL_SOCKET
, SO_REUSEPORT
, &val
, sizeof(val
));
572 #endif /* SO_REUSEPORT */
575 * Using TCP_NODELAY improves responsiveness, especially on systems
576 * with a slow loopback interface... Since we write large buffers
577 * when sending print files and requests, there shouldn't be any
578 * performance penalty for this...
583 setsockopt(http
->fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&val
, sizeof(val
));
585 setsockopt(http
->fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
589 * Connect to the server...
593 if (http
->hostaddr
.addr
.sa_family
== AF_INET6
)
594 status
= connect(http
->fd
, (struct sockaddr
*)&(http
->hostaddr
),
595 sizeof(http
->hostaddr
.ipv6
));
597 #endif /* AF_INET6 */
599 if (http
->hostaddr
.addr
.sa_family
== AF_LOCAL
)
600 status
= connect(http
->fd
, (struct sockaddr
*)&(http
->hostaddr
),
601 SUN_LEN(&(http
->hostaddr
.un
)));
603 #endif /* AF_LOCAL */
604 status
= connect(http
->fd
, (struct sockaddr
*)&(http
->hostaddr
),
605 sizeof(http
->hostaddr
.ipv4
));
610 http
->error
= WSAGetLastError();
614 http
->status
= HTTP_ERROR
;
617 closesocket(http
->fd
);
628 http
->status
= HTTP_CONTINUE
;
631 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
634 * Always do encryption via SSL.
637 if (http_setup_ssl(http
) != 0)
640 closesocket(http
->fd
);
648 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
649 return (http_upgrade(http
));
650 #endif /* HAVE_SSL */
657 * 'httpGetSubField()' - Get a sub-field value.
660 char * /* O - Value or NULL */
661 httpGetSubField(http_t
*http
, /* I - HTTP data */
662 http_field_t field
, /* I - Field index */
663 const char *name
, /* I - Name of sub-field */
664 char *value
) /* O - Value string */
666 const char *fptr
; /* Pointer into field */
667 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
668 *ptr
; /* Pointer into string buffer */
671 DEBUG_printf(("httpGetSubField(http=%p, field=%d, name=\"%s\", value=%p)\n",
672 http
, field
, name
, value
));
675 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
676 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
677 name
== NULL
|| value
== NULL
)
680 for (fptr
= http
->fields
[field
]; *fptr
;)
683 * Skip leading whitespace...
686 while (isspace(*fptr
& 255))
696 * Get the sub-field name...
700 *fptr
&& *fptr
!= '=' && !isspace(*fptr
& 255) && ptr
< (temp
+ sizeof(temp
) - 1);
705 DEBUG_printf(("httpGetSubField: name=\"%s\"\n", temp
));
708 * Skip trailing chars up to the '='...
711 while (isspace(*fptr
& 255))
721 * Skip = and leading whitespace...
726 while (isspace(*fptr
& 255))
732 * Read quoted string...
735 for (ptr
= value
, fptr
++;
736 *fptr
&& *fptr
!= '\"' && ptr
< (value
+ HTTP_MAX_VALUE
- 1);
741 while (*fptr
&& *fptr
!= '\"')
750 * Read unquoted string...
754 *fptr
&& !isspace(*fptr
& 255) && *fptr
!= ',' && ptr
< (value
+ HTTP_MAX_VALUE
- 1);
759 while (*fptr
&& !isspace(*fptr
& 255) && *fptr
!= ',')
763 DEBUG_printf(("httpGetSubField: value=\"%s\"\n", value
));
766 * See if this is the one...
769 if (strcmp(name
, temp
) == 0)
780 * 'httpSetField()' - Set the value of an HTTP header.
784 httpSetField(http_t
*http
, /* I - HTTP data */
785 http_field_t field
, /* I - Field index */
786 const char *value
) /* I - Value */
789 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
790 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
794 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
799 * 'httpDelete()' - Send a DELETE request to the server.
802 int /* O - Status of call (0 = success) */
803 httpDelete(http_t
*http
, /* I - HTTP data */
804 const char *uri
) /* I - URI to delete */
806 return (http_send(http
, HTTP_DELETE
, uri
));
811 * 'httpGet()' - Send a GET request to the server.
814 int /* O - Status of call (0 = success) */
815 httpGet(http_t
*http
, /* I - HTTP data */
816 const char *uri
) /* I - URI to get */
818 return (http_send(http
, HTTP_GET
, uri
));
823 * 'httpHead()' - Send a HEAD request to the server.
826 int /* O - Status of call (0 = success) */
827 httpHead(http_t
*http
, /* I - HTTP data */
828 const char *uri
) /* I - URI for head */
830 return (http_send(http
, HTTP_HEAD
, uri
));
835 * 'httpOptions()' - Send an OPTIONS request to the server.
838 int /* O - Status of call (0 = success) */
839 httpOptions(http_t
*http
, /* I - HTTP data */
840 const char *uri
) /* I - URI for options */
842 return (http_send(http
, HTTP_OPTIONS
, uri
));
847 * 'httpPost()' - Send a POST request to the server.
850 int /* O - Status of call (0 = success) */
851 httpPost(http_t
*http
, /* I - HTTP data */
852 const char *uri
) /* I - URI for post */
856 return (http_send(http
, HTTP_POST
, uri
));
861 * 'httpPut()' - Send a PUT request to the server.
864 int /* O - Status of call (0 = success) */
865 httpPut(http_t
*http
, /* I - HTTP data */
866 const char *uri
) /* I - URI to put */
870 return (http_send(http
, HTTP_PUT
, uri
));
875 * 'httpTrace()' - Send an TRACE request to the server.
878 int /* O - Status of call (0 = success) */
879 httpTrace(http_t
*http
, /* I - HTTP data */
880 const char *uri
) /* I - URI for trace */
882 return (http_send(http
, HTTP_TRACE
, uri
));
887 * 'httpFlush()' - Flush data from a HTTP connection.
891 httpFlush(http_t
*http
) /* I - HTTP data */
893 char buffer
[8192]; /* Junk buffer */
896 DEBUG_printf(("httpFlush(http=%p), state=%d\n", http
, http
->state
));
898 while (httpRead(http
, buffer
, sizeof(buffer
)) > 0);
903 * 'httpRead()' - Read data from a HTTP connection.
906 int /* O - Number of bytes read */
907 httpRead(http_t
*http
, /* I - HTTP data */
908 char *buffer
, /* I - Buffer for data */
909 int length
) /* I - Maximum number of bytes */
911 int bytes
; /* Bytes read */
912 char len
[32]; /* Length string */
915 DEBUG_printf(("httpRead(http=%p, buffer=%p, length=%d)\n",
916 http
, buffer
, length
));
918 if (http
== NULL
|| buffer
== NULL
)
921 http
->activity
= time(NULL
);
926 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
927 http
->data_remaining
<= 0)
929 DEBUG_puts("httpRead: Getting chunk length...");
931 if (httpGets(len
, sizeof(len
), http
) == NULL
)
933 DEBUG_puts("httpRead: Could not get length!");
937 http
->data_remaining
= strtol(len
, NULL
, 16);
938 if (http
->data_remaining
< 0)
940 DEBUG_puts("httpRead: Negative chunk length!");
945 DEBUG_printf(("httpRead: data_remaining=%d\n", http
->data_remaining
));
947 if (http
->data_remaining
<= 0)
950 * A zero-length chunk ends a transfer; unless we are reading POST
954 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
955 httpGets(len
, sizeof(len
), http
);
957 if (http
->state
== HTTP_POST_RECV
)
960 http
->state
= HTTP_WAITING
;
963 * Prevent future reads for this request...
966 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
970 else if (length
> http
->data_remaining
)
971 length
= http
->data_remaining
;
973 if (http
->used
== 0 && length
<= 256)
976 * Buffer small reads for better performance...
979 if (!http
->blocking
&& !httpWait(http
, 1000))
982 if (http
->data_remaining
> sizeof(http
->buffer
))
983 bytes
= sizeof(http
->buffer
);
985 bytes
= http
->data_remaining
;
989 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
991 #endif /* HAVE_SSL */
993 DEBUG_printf(("httpRead: reading %d bytes from socket into buffer...\n",
996 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
998 DEBUG_printf(("httpRead: read %d bytes from socket into buffer...\n",
1001 httpDumpData(stdout
, "httpRead:", http
->buffer
, bytes
);
1010 http
->error
= WSAGetLastError();
1015 http
->error
= errno
;
1022 http
->error
= EPIPE
;
1029 if (length
> http
->used
)
1030 length
= http
->used
;
1034 DEBUG_printf(("httpRead: grabbing %d bytes from input buffer...\n", bytes
));
1036 memcpy(buffer
, http
->buffer
, length
);
1037 http
->used
-= length
;
1040 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
1045 if (!http
->blocking
&& !httpWait(http
, 1000))
1048 bytes
= http_read_ssl(http
, buffer
, length
);
1050 #endif /* HAVE_SSL */
1053 if (!http
->blocking
&& !httpWait(http
, 1000))
1056 DEBUG_printf(("httpRead: reading %d bytes from socket...\n", length
));
1058 while ((bytes
= recv(http
->fd
, buffer
, length
, 0)) < 0)
1061 DEBUG_printf(("httpRead: read %d bytes from socket...\n", bytes
));
1064 httpDumpData(stdout
, "httpRead:", buffer
, bytes
);
1068 http
->data_remaining
-= bytes
;
1072 http
->error
= WSAGetLastError();
1077 http
->error
= errno
;
1082 http
->error
= EPIPE
;
1086 if (http
->data_remaining
== 0)
1088 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1089 httpGets(len
, sizeof(len
), http
);
1091 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
1093 if (http
->state
== HTTP_POST_RECV
)
1096 http
->state
= HTTP_WAITING
;
1105 * 'httpSetCookie()' - Set the cookie value(s)...
1109 httpSetCookie(http_t
*http
, /* I - Connection */
1110 const char *cookie
) /* I - Cookie string */
1119 http
->cookie
= strdup(cookie
);
1121 http
->cookie
= NULL
;
1126 * 'httpWait()' - Wait for data available on a connection.
1129 int /* O - 1 if data is available, 0 otherwise */
1130 httpWait(http_t
*http
, /* I - HTTP data */
1131 int msec
) /* I - Milliseconds to wait */
1134 * First see if there is data in the buffer...
1144 * If not, check the SSL/TLS buffers and do a select() on the connection...
1147 return (http_wait(http
, msec
));
1152 * 'httpWrite()' - Write data to a HTTP connection.
1155 int /* O - Number of bytes written */
1156 httpWrite(http_t
*http
, /* I - HTTP data */
1157 const char *buffer
, /* I - Buffer for data */
1158 int length
) /* I - Number of bytes to write */
1160 int tbytes
, /* Total bytes sent */
1161 bytes
; /* Bytes sent */
1164 if (http
== NULL
|| buffer
== NULL
)
1167 http
->activity
= time(NULL
);
1169 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1171 if (httpPrintf(http
, "%x\r\n", length
) < 0)
1177 * A zero-length chunk ends a transfer; unless we are sending POST
1178 * or PUT data, go idle...
1181 DEBUG_printf(("httpWrite: changing states from %d", http
->state
));
1183 if (http
->state
== HTTP_POST_RECV
)
1185 else if (http
->state
== HTTP_PUT_RECV
)
1186 http
->state
= HTTP_STATUS
;
1188 http
->state
= HTTP_WAITING
;
1189 DEBUG_printf((" to %d\n", http
->state
));
1191 if (httpPrintf(http
, "\r\n") < 0)
1204 bytes
= http_write_ssl(http
, buffer
, length
);
1206 #endif /* HAVE_SSL */
1207 bytes
= send(http
->fd
, buffer
, length
, 0);
1211 httpDumpData(stdout
, "httpWrite:", buffer
, bytes
);
1218 if (WSAGetLastError() != http
->error
)
1220 http
->error
= WSAGetLastError();
1226 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
1228 http
->error
= errno
;
1233 DEBUG_puts("httpWrite: error writing data...\n");
1241 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1242 http
->data_remaining
-= bytes
;
1245 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1246 if (httpPrintf(http
, "\r\n") < 0)
1249 if (http
->data_remaining
== 0 && http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1252 * Finished with the transfer; unless we are sending POST or PUT
1256 DEBUG_printf(("httpWrite: changing states from %d", http
->state
));
1258 if (http
->state
== HTTP_POST_RECV
)
1260 else if (http
->state
== HTTP_PUT_RECV
)
1261 http
->state
= HTTP_STATUS
;
1263 http
->state
= HTTP_WAITING
;
1265 DEBUG_printf((" to %d\n", http
->state
));
1273 * 'httpGets()' - Get a line of text from a HTTP connection.
1276 char * /* O - Line or NULL */
1277 httpGets(char *line
, /* I - Line to read into */
1278 int length
, /* I - Max length of buffer */
1279 http_t
*http
) /* I - HTTP data */
1281 char *lineptr
, /* Pointer into line */
1282 *bufptr
, /* Pointer into input buffer */
1283 *bufend
; /* Pointer to end of buffer */
1284 int bytes
; /* Number of bytes read */
1287 DEBUG_printf(("httpGets(line=%p, length=%d, http=%p)\n", line
, length
, http
));
1289 if (http
== NULL
|| line
== NULL
)
1293 * Pre-scan the buffer and see if there is a newline in there...
1304 bufptr
= http
->buffer
;
1305 bufend
= http
->buffer
+ http
->used
;
1307 while (bufptr
< bufend
)
1308 if (*bufptr
== 0x0a)
1313 if (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
)
1316 * No newline; see if there is more data to be read...
1319 if (!http
->blocking
&& !http_wait(http
, 1000))
1324 bytes
= http_read_ssl(http
, bufend
, HTTP_MAX_BUFFER
- http
->used
);
1326 #endif /* HAVE_SSL */
1327 bytes
= recv(http
->fd
, bufend
, HTTP_MAX_BUFFER
- http
->used
, 0);
1329 DEBUG_printf(("httpGets: read %d bytes...\n", bytes
));
1331 httpDumpData(stdout
, "httpGets:", bufend
, bytes
);
1337 * Nope, can't get a line this time...
1341 if (WSAGetLastError() != http
->error
)
1343 http
->error
= WSAGetLastError();
1347 DEBUG_printf(("httpGets: recv() error %d!\n", WSAGetLastError()));
1349 DEBUG_printf(("httpGets: recv() error %d!\n", errno
));
1353 else if (errno
!= http
->error
)
1355 http
->error
= errno
;
1362 else if (bytes
== 0)
1364 http
->error
= EPIPE
;
1370 * Yup, update the amount used and the end pointer...
1373 http
->used
+= bytes
;
1378 while (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
);
1380 http
->activity
= time(NULL
);
1383 * Read a line from the buffer...
1387 bufptr
= http
->buffer
;
1391 while (bufptr
< bufend
&& bytes
< length
)
1395 if (*bufptr
== 0x0a)
1400 else if (*bufptr
== 0x0d)
1403 *lineptr
++ = *bufptr
++;
1410 http
->used
-= bytes
;
1412 memmove(http
->buffer
, bufptr
, http
->used
);
1414 DEBUG_printf(("httpGets: Returning \"%s\"\n", line
));
1418 DEBUG_puts("httpGets: No new line available!");
1425 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1428 int /* O - Number of bytes written */
1429 httpPrintf(http_t
*http
, /* I - HTTP data */
1430 const char *format
, /* I - printf-style format string */
1431 ...) /* I - Additional args as needed */
1433 int bytes
, /* Number of bytes to write */
1434 nbytes
, /* Number of bytes written */
1435 tbytes
; /* Number of bytes all together */
1436 char buf
[HTTP_MAX_BUFFER
], /* Buffer for formatted string */
1437 *bufptr
; /* Pointer into buffer */
1438 va_list ap
; /* Variable argument pointer */
1441 DEBUG_printf(("httpPrintf: httpPrintf(http=%p, format=\"%s\", ...)\n", http
, format
));
1443 va_start(ap
, format
);
1444 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1447 DEBUG_printf(("httpPrintf: %s", buf
));
1449 for (tbytes
= 0, bufptr
= buf
; tbytes
< bytes
; tbytes
+= nbytes
, bufptr
+= nbytes
)
1453 nbytes
= http_write_ssl(http
, bufptr
, bytes
- tbytes
);
1455 #endif /* HAVE_SSL */
1456 nbytes
= send(http
->fd
, bufptr
, bytes
- tbytes
, 0);
1460 httpDumpData(stdout
, "httpPrintf:", bufptr
, nbytes
);
1468 if (WSAGetLastError() != http
->error
)
1470 http
->error
= WSAGetLastError();
1476 else if (errno
!= http
->error
)
1478 http
->error
= errno
;
1492 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
1495 const char * /* O - Date/time string */
1496 httpGetDateString(time_t t
) /* I - UNIX time */
1499 static char datetime
[256];
1503 snprintf(datetime
, sizeof(datetime
), "%s, %02d %s %d %02d:%02d:%02d GMT",
1504 days
[tdate
->tm_wday
], tdate
->tm_mday
, months
[tdate
->tm_mon
],
1505 tdate
->tm_year
+ 1900, tdate
->tm_hour
, tdate
->tm_min
, tdate
->tm_sec
);
1512 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
1515 time_t /* O - UNIX time */
1516 httpGetDateTime(const char *s
) /* I - Date/time string */
1518 int i
; /* Looping var */
1519 struct tm tdate
; /* Time/date structure */
1520 char mon
[16]; /* Abbreviated month name */
1521 int day
, year
; /* Day of month and year */
1522 int hour
, min
, sec
; /* Time */
1525 if (sscanf(s
, "%*s%d%15s%d%d:%d:%d", &day
, mon
, &year
, &hour
, &min
, &sec
) < 6)
1528 for (i
= 0; i
< 12; i
++)
1529 if (strcasecmp(mon
, months
[i
]) == 0)
1536 tdate
.tm_mday
= day
;
1537 tdate
.tm_year
= year
- 1900;
1538 tdate
.tm_hour
= hour
;
1543 return (mktime(&tdate
));
1548 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1551 http_status_t
/* O - HTTP status */
1552 httpUpdate(http_t
*http
) /* I - HTTP data */
1554 char line
[1024], /* Line from connection... */
1555 *value
; /* Pointer to value on line */
1556 http_field_t field
; /* Field index */
1557 int major
, minor
, /* HTTP version numbers */
1558 status
; /* Request status */
1561 DEBUG_printf(("httpUpdate(http=%p), state=%d\n", http
, http
->state
));
1564 * If we haven't issued any commands, then there is nothing to "update"...
1567 if (http
->state
== HTTP_WAITING
)
1568 return (HTTP_CONTINUE
);
1571 * Grab all of the lines we can from the connection...
1575 while (httpGets(line
, sizeof(line
), http
) != NULL
)
1577 DEBUG_printf(("httpUpdate: Got \"%s\"\n", line
));
1579 if (line
[0] == '\0')
1582 * Blank line means the start of the data section (if any). Return
1583 * the result code, too...
1585 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
1586 * Instead, we just return HTTP_CONTINUE to the caller and keep on
1590 if (http
->status
== HTTP_CONTINUE
)
1591 return (http
->status
);
1593 if (http
->status
< HTTP_BAD_REQUEST
)
1594 http
->digest_tries
= 0;
1597 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
1599 if (http_setup_ssl(http
) != 0)
1602 closesocket(http
->fd
);
1607 return (HTTP_ERROR
);
1610 return (HTTP_CONTINUE
);
1612 #endif /* HAVE_SSL */
1614 httpGetLength(http
);
1616 switch (http
->state
)
1620 case HTTP_POST_RECV
:
1623 case HTTP_POST_SEND
:
1627 http
->state
= HTTP_WAITING
;
1631 return (http
->status
);
1633 else if (strncmp(line
, "HTTP/", 5) == 0)
1636 * Got the beginning of a response...
1639 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &status
) != 3)
1640 return (HTTP_ERROR
);
1642 http
->version
= (http_version_t
)(major
* 100 + minor
);
1643 http
->status
= (http_status_t
)status
;
1645 else if ((value
= strchr(line
, ':')) != NULL
)
1652 while (isspace(*value
& 255))
1656 * Be tolerants of servers that send unknown attribute fields...
1659 if (!strcasecmp(line
, "expect"))
1662 * "Expect: 100-continue" or similar...
1665 http
->expect
= (http_status_t
)atoi(value
);
1667 else if (!strcasecmp(line
, "cookie"))
1670 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
1673 httpSetCookie(http
, value
);
1675 else if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
1677 DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line
));
1681 httpSetField(http
, field
, value
);
1685 http
->status
= HTTP_ERROR
;
1686 return (HTTP_ERROR
);
1691 * See if there was an error...
1694 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
1695 return (http
->status
);
1699 DEBUG_printf(("httpUpdate: socket error %d - %s\n", http
->error
,
1700 strerror(http
->error
)));
1701 http
->status
= HTTP_ERROR
;
1702 return (HTTP_ERROR
);
1706 * If we haven't already returned, then there is nothing new...
1709 return (HTTP_CONTINUE
);
1714 * 'httpDecode64()' - Base64-decode a string.
1717 char * /* O - Decoded string */
1718 httpDecode64(char *out
, /* I - String to write to */
1719 const char *in
) /* I - String to read from */
1721 int outlen
; /* Output buffer length */
1725 * Use the old maximum buffer size for binary compatibility...
1730 return (httpDecode64_2(out
, &outlen
, in
));
1735 * 'httpDecode64_2()' - Base64-decode a string.
1738 char * /* O - Decoded string */
1739 httpDecode64_2(char *out
, /* I - String to write to */
1740 int *outlen
, /* IO - Size of output string */
1741 const char *in
) /* I - String to read from */
1743 int pos
, /* Bit position */
1744 base64
; /* Value of this character */
1745 char *outptr
, /* Output pointer */
1746 *outend
; /* End of output buffer */
1750 * Range check input...
1753 if (!out
|| !outlen
|| *outlen
< 1 || !in
|| !*in
)
1757 * Convert from base-64 to bytes...
1760 for (outptr
= out
, outend
= out
+ *outlen
- 1, pos
= 0; *in
!= '\0'; in
++)
1763 * Decode this character into a number from 0 to 63...
1766 if (*in
>= 'A' && *in
<= 'Z')
1768 else if (*in
>= 'a' && *in
<= 'z')
1769 base64
= *in
- 'a' + 26;
1770 else if (*in
>= '0' && *in
<= '9')
1771 base64
= *in
- '0' + 52;
1772 else if (*in
== '+')
1774 else if (*in
== '/')
1776 else if (*in
== '=')
1782 * Store the result in the appropriate chars...
1788 if (outptr
< outend
)
1789 *outptr
= base64
<< 2;
1793 if (outptr
< outend
)
1794 *outptr
++ |= (base64
>> 4) & 3;
1795 if (outptr
< outend
)
1796 *outptr
= (base64
<< 4) & 255;
1800 if (outptr
< outend
)
1801 *outptr
++ |= (base64
>> 2) & 15;
1802 if (outptr
< outend
)
1803 *outptr
= (base64
<< 6) & 255;
1807 if (outptr
< outend
)
1808 *outptr
++ |= base64
;
1817 * Return the decoded string and size...
1820 *outlen
= (int)(outptr
- out
);
1827 * 'httpEncode64()' - Base64-encode a string.
1830 char * /* O - Encoded string */
1831 httpEncode64(char *out
, /* I - String to write to */
1832 const char *in
) /* I - String to read from */
1834 return (httpEncode64_2(out
, 512, in
, strlen(in
)));
1839 * 'httpEncode64_2()' - Base64-encode a string.
1842 char * /* O - Encoded string */
1843 httpEncode64_2(char *out
, /* I - String to write to */
1844 int outlen
, /* I - Size of output string */
1845 const char *in
, /* I - String to read from */
1846 int inlen
) /* I - Size of input string */
1848 char *outptr
, /* Output pointer */
1849 *outend
; /* End of output buffer */
1850 static const char base64
[] = /* Base64 characters... */
1852 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1853 "abcdefghijklmnopqrstuvwxyz"
1860 * Range check input...
1863 if (!out
|| outlen
< 1 || !in
|| inlen
< 1)
1867 * Convert bytes to base-64...
1870 for (outptr
= out
, outend
= out
+ outlen
- 1; inlen
> 0; in
++, inlen
--)
1873 * Encode the up to 3 characters as 4 Base64 numbers...
1876 if (outptr
< outend
)
1877 *outptr
++ = base64
[(in
[0] & 255) >> 2];
1878 if (outptr
< outend
)
1879 *outptr
++ = base64
[(((in
[0] & 255) << 4) | ((in
[1] & 255) >> 4)) & 63];
1885 if (outptr
< outend
)
1887 if (outptr
< outend
)
1892 if (outptr
< outend
)
1893 *outptr
++ = base64
[(((in
[0] & 255) << 2) | ((in
[1] & 255) >> 6)) & 63];
1899 if (outptr
< outend
)
1904 if (outptr
< outend
)
1905 *outptr
++ = base64
[in
[0] & 63];
1911 * Return the encoded string...
1919 * 'httpGetLength()' - Get the amount of data remaining from the
1920 * content-length or transfer-encoding fields.
1923 int /* O - Content length */
1924 httpGetLength(http_t
*http
) /* I - HTTP data */
1926 DEBUG_printf(("httpGetLength(http=%p), state=%d\n", http
, http
->state
));
1928 if (strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked") == 0)
1930 DEBUG_puts("httpGetLength: chunked request!");
1932 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
1933 http
->data_remaining
= 0;
1937 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1940 * The following is a hack for HTTP servers that don't send a
1941 * content-length or transfer-encoding field...
1943 * If there is no content-length then the connection must close
1944 * after the transfer is complete...
1947 if (http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] == '\0')
1948 http
->data_remaining
= 2147483647;
1950 http
->data_remaining
= atoi(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
]);
1952 DEBUG_printf(("httpGetLength: content_length=%d\n", http
->data_remaining
));
1955 return (http
->data_remaining
);
1960 * 'http_field()' - Return the field index for a field name.
1963 static http_field_t
/* O - Field index */
1964 http_field(const char *name
) /* I - String name */
1966 int i
; /* Looping var */
1969 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
1970 if (strcasecmp(name
, http_fields
[i
]) == 0)
1971 return ((http_field_t
)i
);
1973 return (HTTP_FIELD_UNKNOWN
);
1978 * 'http_send()' - Send a request with all fields and the trailing blank line.
1981 static int /* O - 0 on success, non-zero on error */
1982 http_send(http_t
*http
, /* I - HTTP data */
1983 http_state_t request
, /* I - Request code */
1984 const char *uri
) /* I - URI */
1986 int i
; /* Looping var */
1987 char *ptr
, /* Pointer in buffer */
1988 buf
[1024]; /* Encoded URI buffer */
1989 static const char * const codes
[] =
1990 { /* Request code strings */
2005 static const char hex
[] = "0123456789ABCDEF";
2009 DEBUG_printf(("http_send(http=%p, request=HTTP_%s, uri=\"%s\")\n",
2010 http
, codes
[request
], uri
));
2012 if (http
== NULL
|| uri
== NULL
)
2016 * Encode the URI as needed...
2019 for (ptr
= buf
; *uri
!= '\0' && ptr
< (buf
+ sizeof(buf
) - 1); uri
++)
2020 if (*uri
<= ' ' || *uri
>= 127)
2022 if (ptr
< (buf
+ sizeof(buf
) - 1))
2024 if (ptr
< (buf
+ sizeof(buf
) - 1))
2025 *ptr
++ = hex
[(*uri
>> 4) & 15];
2026 if (ptr
< (buf
+ sizeof(buf
) - 1))
2027 *ptr
++ = hex
[*uri
& 15];
2035 * See if we had an error the last time around; if so, reconnect...
2038 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
2039 httpReconnect(http
);
2042 * Send the request header...
2045 http
->state
= request
;
2046 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
2049 http
->status
= HTTP_CONTINUE
;
2052 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
2054 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
2055 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
2057 #endif /* HAVE_SSL */
2059 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
2061 http
->status
= HTTP_ERROR
;
2065 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2066 if (http
->fields
[i
][0] != '\0')
2068 DEBUG_printf(("%s: %s\n", http_fields
[i
], http
->fields
[i
]));
2070 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], http
->fields
[i
]) < 1)
2072 http
->status
= HTTP_ERROR
;
2077 if (httpPrintf(http
, "\r\n") < 1)
2079 http
->status
= HTTP_ERROR
;
2083 httpClearFields(http
);
2090 * 'http_wait()' - Wait for data available on a connection.
2093 static int /* O - 1 if data is available, 0 otherwise */
2094 http_wait(http_t
*http
, /* I - HTTP data */
2095 int msec
) /* I - Milliseconds to wait */
2098 struct rlimit limit
; /* Runtime limit */
2100 struct timeval timeout
; /* Timeout */
2101 int nfds
; /* Result from select() */
2102 int set_size
; /* Size of select set */
2105 DEBUG_printf(("http_wait(http=%p, msec=%d)\n", http
, msec
));
2108 * Check the SSL/TLS buffers for data first...
2115 if (SSL_pending((SSL
*)(http
->tls
)))
2117 # elif defined(HAVE_GNUTLS)
2118 if (gnutls_record_check_pending(((http_tls_t
*)(http
->tls
))->session
))
2120 # elif defined(HAVE_CDSASSL)
2121 size_t bytes
; /* Bytes that are available */
2123 if (!SSLGetBufferedReadSize((SSLContextRef
)http
->tls
, &bytes
) && bytes
> 0)
2125 # endif /* HAVE_LIBSSL */
2127 #endif /* HAVE_SSL */
2130 * Then try doing a select() to poll the socket...
2133 if (!http
->input_set
)
2137 * Windows has a fixed-size select() structure, different (surprise,
2138 * surprise!) from all UNIX implementations. Just allocate this
2139 * fixed structure...
2142 http
->input_set
= calloc(1, sizeof(fd_set
));
2145 * Allocate the select() input set based upon the max number of file
2146 * descriptors available for this process...
2149 getrlimit(RLIMIT_NOFILE
, &limit
);
2151 set_size
= (limit
.rlim_cur
+ 31) / 8 + 4;
2152 if (set_size
< sizeof(fd_set
))
2153 set_size
= sizeof(fd_set
);
2155 http
->input_set
= calloc(1, set_size
);
2158 if (!http
->input_set
)
2164 FD_SET(http
->fd
, http
->input_set
);
2168 timeout
.tv_sec
= msec
/ 1000;
2169 timeout
.tv_usec
= (msec
% 1000) * 1000;
2171 nfds
= select(http
->fd
+ 1, http
->input_set
, NULL
, NULL
, &timeout
);
2174 nfds
= select(http
->fd
+ 1, http
->input_set
, NULL
, NULL
, NULL
);
2177 while (nfds
< 0 && WSAGetLastError() == WSAEINTR
);
2179 while (nfds
< 0 && errno
== EINTR
);
2182 FD_CLR(http
->fd
, http
->input_set
);
2190 * 'http_upgrade()' - Force upgrade to TLS encryption.
2193 static int /* O - Status of connection */
2194 http_upgrade(http_t
*http
) /* I - HTTP data */
2196 int ret
; /* Return value */
2197 http_t myhttp
; /* Local copy of HTTP data */
2200 DEBUG_printf(("http_upgrade(%p)\n", http
));
2203 * Copy the HTTP data to a local variable so we can do the OPTIONS
2204 * request without interfering with the existing request data...
2207 memcpy(&myhttp
, http
, sizeof(myhttp
));
2210 * Send an OPTIONS request to the server, requiring SSL or TLS
2211 * encryption on the link...
2214 httpClearFields(&myhttp
);
2215 httpSetField(&myhttp
, HTTP_FIELD_CONNECTION
, "upgrade");
2216 httpSetField(&myhttp
, HTTP_FIELD_UPGRADE
, "TLS/1.0, SSL/2.0, SSL/3.0");
2218 if ((ret
= httpOptions(&myhttp
, "*")) == 0)
2221 * Wait for the secure connection...
2224 while (httpUpdate(&myhttp
) == HTTP_CONTINUE
);
2230 * Copy the HTTP data back over, if any...
2233 http
->fd
= myhttp
.fd
;
2234 http
->error
= myhttp
.error
;
2235 http
->activity
= myhttp
.activity
;
2236 http
->status
= myhttp
.status
;
2237 http
->version
= myhttp
.version
;
2238 http
->keep_alive
= myhttp
.keep_alive
;
2239 http
->used
= myhttp
.used
;
2242 memcpy(http
->buffer
, myhttp
.buffer
, http
->used
);
2244 http
->auth_type
= myhttp
.auth_type
;
2245 http
->nonce_count
= myhttp
.nonce_count
;
2247 memcpy(http
->nonce
, myhttp
.nonce
, sizeof(http
->nonce
));
2249 http
->tls
= myhttp
.tls
;
2250 http
->encryption
= myhttp
.encryption
;
2253 * See if we actually went secure...
2259 * Server does not support HTTP upgrade...
2262 DEBUG_puts("Server does not support HTTP upgrade!");
2265 closesocket(http
->fd
);
2280 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
2283 static int /* O - Status of connection */
2284 http_setup_ssl(http_t
*http
) /* I - HTTP data */
2287 SSL_CTX
*context
; /* Context for encryption */
2288 SSL
*conn
; /* Connection for encryption */
2289 # elif defined(HAVE_GNUTLS)
2290 http_tls_t
*conn
; /* TLS session object */
2291 gnutls_certificate_client_credentials
*credentials
;
2292 /* TLS credentials */
2293 # elif defined(HAVE_CDSASSL)
2294 SSLContextRef conn
; /* Context for encryption */
2295 OSStatus error
; /* Error info */
2296 # endif /* HAVE_LIBSSL */
2299 DEBUG_printf(("http_setup_ssl(http=%p)\n", http
));
2302 context
= SSL_CTX_new(SSLv23_client_method());
2304 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
2306 conn
= SSL_new(context
);
2308 SSL_set_fd(conn
, http
->fd
);
2309 if (SSL_connect(conn
) != 1)
2312 unsigned long error
; /* Error code */
2314 while ((error
= ERR_get_error()) != 0)
2315 printf("http_setup_ssl: %s\n", ERR_error_string(error
, NULL
));
2318 SSL_CTX_free(context
);
2322 http
->error
= WSAGetLastError();
2324 http
->error
= errno
;
2326 http
->status
= HTTP_ERROR
;
2328 return (HTTP_ERROR
);
2331 # elif defined(HAVE_GNUTLS)
2332 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
2336 http
->error
= errno
;
2337 http
->status
= HTTP_ERROR
;
2342 credentials
= (gnutls_certificate_client_credentials
*)
2343 malloc(sizeof(gnutls_certificate_client_credentials
));
2344 if (credentials
== NULL
)
2348 http
->error
= errno
;
2349 http
->status
= HTTP_ERROR
;
2354 gnutls_certificate_allocate_credentials(credentials
);
2356 gnutls_init(&(conn
->session
), GNUTLS_CLIENT
);
2357 gnutls_set_default_priority(conn
->session
);
2358 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
2359 gnutls_transport_set_ptr(conn
->session
, http
->fd
);
2361 if ((gnutls_handshake(conn
->session
)) != GNUTLS_E_SUCCESS
)
2363 http
->error
= errno
;
2364 http
->status
= HTTP_ERROR
;
2369 conn
->credentials
= credentials
;
2371 # elif defined(HAVE_CDSASSL)
2372 error
= SSLNewContext(false, &conn
);
2375 error
= SSLSetIOFuncs(conn
, CDSAReadFunc
, CDSAWriteFunc
);
2378 error
= SSLSetConnection(conn
, (SSLConnectionRef
)http
->fd
);
2381 error
= SSLSetAllowsExpiredCerts(conn
, true);
2384 error
= SSLSetAllowsAnyRoot(conn
, true);
2387 error
= SSLHandshake(conn
);
2391 http
->error
= error
;
2392 http
->status
= HTTP_ERROR
;
2394 SSLDisposeContext(conn
);
2400 # endif /* HAVE_CDSASSL */
2408 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
2412 http_shutdown_ssl(http_t
*http
) /* I - HTTP data */
2415 SSL_CTX
*context
; /* Context for encryption */
2416 SSL
*conn
; /* Connection for encryption */
2419 conn
= (SSL
*)(http
->tls
);
2420 context
= SSL_get_SSL_CTX(conn
);
2423 SSL_CTX_free(context
);
2426 # elif defined(HAVE_GNUTLS)
2427 http_tls_t
*conn
; /* Encryption session */
2428 gnutls_certificate_client_credentials
*credentials
;
2429 /* TLS credentials */
2432 conn
= (http_tls_t
*)(http
->tls
);
2433 credentials
= (gnutls_certificate_client_credentials
*)(conn
->credentials
);
2435 gnutls_bye(conn
->session
, GNUTLS_SHUT_RDWR
);
2436 gnutls_deinit(conn
->session
);
2437 gnutls_certificate_free_credentials(*credentials
);
2441 # elif defined(HAVE_CDSASSL)
2442 SSLClose((SSLContextRef
)http
->tls
);
2443 SSLDisposeContext((SSLContextRef
)http
->tls
);
2444 # endif /* HAVE_LIBSSL */
2451 * 'http_read_ssl()' - Read from a SSL/TLS connection.
2454 static int /* O - Bytes read */
2455 http_read_ssl(http_t
*http
, /* I - HTTP data */
2456 char *buf
, /* I - Buffer to store data */
2457 int len
) /* I - Length of buffer */
2459 # if defined(HAVE_LIBSSL)
2460 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
2462 # elif defined(HAVE_GNUTLS)
2463 return (gnutls_record_recv(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
2465 # elif defined(HAVE_CDSASSL)
2466 OSStatus error
; /* Error info */
2467 size_t processed
; /* Number of bytes processed */
2470 error
= SSLRead((SSLContextRef
)http
->tls
, buf
, len
, &processed
);
2476 http
->error
= error
;
2480 # endif /* HAVE_LIBSSL */
2485 * 'http_write_ssl()' - Write to a SSL/TLS connection.
2488 static int /* O - Bytes written */
2489 http_write_ssl(http_t
*http
, /* I - HTTP data */
2490 const char *buf
, /* I - Buffer holding data */
2491 int len
) /* I - Length of buffer */
2493 # if defined(HAVE_LIBSSL)
2494 return (SSL_write((SSL
*)(http
->tls
), buf
, len
));
2496 # elif defined(HAVE_GNUTLS)
2497 return (gnutls_record_send(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
2498 # elif defined(HAVE_CDSASSL)
2499 OSStatus error
; /* Error info */
2500 size_t processed
; /* Number of bytes processed */
2503 error
= SSLWrite((SSLContextRef
)http
->tls
, buf
, len
, &processed
);
2509 http
->error
= error
;
2512 # endif /* HAVE_LIBSSL */
2516 # if defined(HAVE_CDSASSL)
2518 * 'CDSAReadFunc()' - Read function for CDSA decryption code.
2521 static OSStatus
/* O - -1 on error, 0 on success */
2522 CDSAReadFunc(SSLConnectionRef connection
, /* I - SSL/TLS connection */
2523 void *data
, /* I - Data buffer */
2524 size_t *dataLength
) /* IO - Number of bytes */
2526 ssize_t bytes
; /* Number of bytes read */
2529 httpDumpData(stdout
, "CDSAReadFunc:", data
, *dataLength
);
2531 bytes
= recv((int)connection
, data
, *dataLength
, 0);
2534 *dataLength
= bytes
;
2543 * 'CDSAWriteFunc()' - Write function for CDSA encryption code.
2546 static OSStatus
/* O - -1 on error, 0 on success */
2547 CDSAWriteFunc(SSLConnectionRef connection
, /* I - SSL/TLS connection */
2548 const void *data
, /* I - Data buffer */
2549 size_t *dataLength
) /* IO - Number of bytes */
2554 bytes
= write((int)connection
, data
, *dataLength
);
2557 *dataLength
= bytes
;
2563 # endif /* HAVE_CDSASSL */
2564 #endif /* HAVE_SSL */
2568 * End of "$Id: http.c 148 2006-04-25 16:54:17Z njacobs $"