2 * "$Id: http.c,v 1.141 2004/08/18 15:34:02 mike Exp $"
4 * HTTP routines for the Common UNIX Printing System (CUPS).
6 * Copyright 1997-2004 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-3142 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.
77 * Include necessary headers...
80 #include "http-private.h"
95 # include <sys/time.h>
96 # include <sys/resource.h>
101 * Some operating systems have done away with the Fxxxx constants for
102 * the fcntl() call; this works around that "feature"...
106 # define FNONBLK O_NONBLOCK
107 #endif /* !FNONBLK */
114 static http_field_t
http_field(const char *name
);
115 static int http_send(http_t
*http
, http_state_t request
,
117 static int http_wait(http_t
*http
, int msec
);
119 static int http_upgrade(http_t
*http
);
120 static int http_setup_ssl(http_t
*http
);
121 static void http_shutdown_ssl(http_t
*http
);
122 static int http_read_ssl(http_t
*http
, char *buf
, int len
);
123 static int http_write_ssl(http_t
*http
, const char *buf
, int len
);
125 static OSStatus
CDSAReadFunc(SSLConnectionRef connection
, void *data
, size_t *dataLength
);
126 static OSStatus
CDSAWriteFunc(SSLConnectionRef connection
, const void *data
, size_t *dataLength
);
127 # endif /* HAVE_CDSASSL */
128 #endif /* HAVE_SSL */
135 static const char * const http_fields
[] =
152 "If-Unmodified-since",
165 static const char * const days
[7] =
175 static const char * const months
[12] =
193 * 'httpInitialize()' - Initialize the HTTP interface library and set the
194 * default HTTP proxy (if any).
202 struct timeval curtime
; /* Current time in microseconds */
204 int i
; /* Looping var */
205 unsigned char data
[1024]; /* Seed data */
206 #endif /* HAVE_LIBSSL */
209 WSADATA winsockdata
; /* WinSock data */
210 static int initialized
= 0; /* Has WinSock been initialized? */
214 WSAStartup(MAKEWORD(1,1), &winsockdata
);
215 #elif defined(HAVE_SIGSET)
216 sigset(SIGPIPE
, SIG_IGN
);
217 #elif defined(HAVE_SIGACTION)
218 struct sigaction action
; /* POSIX sigaction data */
222 * Ignore SIGPIPE signals...
225 memset(&action
, 0, sizeof(action
));
226 action
.sa_handler
= SIG_IGN
;
227 sigaction(SIGPIPE
, &action
, NULL
);
229 signal(SIGPIPE
, SIG_IGN
);
233 gnutls_global_init();
234 #endif /* HAVE_GNUTLS */
237 SSL_load_error_strings();
241 * Using the current time is a dubious random seed, but on some systems
242 * it is the best we can do (on others, this seed isn't even used...)
247 gettimeofday(&curtime
, NULL
);
248 srand(curtime
.tv_sec
+ curtime
.tv_usec
);
251 for (i
= 0; i
< sizeof(data
); i
++)
252 data
[i
] = rand(); /* Yes, this is a poor source of random data... */
254 RAND_seed(&data
, sizeof(data
));
255 #endif /* HAVE_LIBSSL */
260 * 'httpCheck()' - Check to see if there is a pending response from the server.
263 int /* O - 0 = no data, 1 = data available */
264 httpCheck(http_t
*http
) /* I - HTTP connection */
266 return (httpWait(http
, 0));
271 * 'httpClearCookie()' - Clear the cookie value(s).
275 httpClearCookie(http_t
*http
) /* I - Connection */
289 * 'httpClose()' - Close an HTTP connection...
293 httpClose(http_t
*http
) /* I - Connection to close */
295 DEBUG_printf(("httpClose(http=%p)\n", http
));
301 free(http
->input_set
);
308 http_shutdown_ssl(http
);
309 #endif /* HAVE_SSL */
312 closesocket(http
->fd
);
322 * 'httpConnect()' - Connect to a HTTP server.
325 http_t
* /* O - New HTTP connection */
326 httpConnect(const char *host
, /* I - Host to connect to */
327 int port
) /* I - Port number */
329 http_encryption_t encrypt
;/* Type of encryption to use */
333 * Set the default encryption status...
337 encrypt
= HTTP_ENCRYPT_ALWAYS
;
339 encrypt
= HTTP_ENCRYPT_IF_REQUESTED
;
341 return (httpConnectEncrypt(host
, port
, encrypt
));
346 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
349 http_t
* /* O - New HTTP connection */
350 httpConnectEncrypt(const char *host
, /* I - Host to connect to */
351 int port
, /* I - Port number */
352 http_encryption_t encrypt
)
353 /* I - Type of encryption to use */
355 int i
; /* Looping var */
356 http_t
*http
; /* New HTTP connection */
357 struct hostent
*hostaddr
; /* Host address data */
360 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encrypt=%d)\n",
361 host
? host
: "(null)", port
, encrypt
));
372 if ((hostaddr
= httpGetHostByName(host
)) == NULL
)
375 * This hack to make users that don't have a localhost entry in
376 * their hosts file or DNS happy...
379 if (strcasecmp(host
, "localhost") != 0)
381 else if ((hostaddr
= httpGetHostByName("127.0.0.1")) == NULL
)
386 * Verify that it is an IPv4 address (IPv6 support will come in CUPS 1.2...)
389 if (hostaddr
->h_addrtype
!= AF_INET
|| hostaddr
->h_length
!= 4)
393 * Allocate memory for the structure...
396 http
= calloc(sizeof(http_t
), 1);
400 http
->version
= HTTP_1_1
;
402 http
->activity
= time(NULL
);
406 * Copy the hostname and port and then "reconnect"...
409 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
410 http
->hostaddr
.sin_family
= hostaddr
->h_addrtype
;
412 http
->hostaddr
.sin_port
= htons((u_short
)port
);
414 http
->hostaddr
.sin_port
= htons(port
);
418 * Set the encryption status...
421 if (port
== 443) /* Always use encryption for https */
422 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
424 http
->encryption
= encrypt
;
427 * Loop through the addresses we have until one of them connects...
430 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
432 for (i
= 0; hostaddr
->h_addr_list
[i
]; i
++)
435 * Load the address...
438 memcpy((char *)&(http
->hostaddr
.sin_addr
), hostaddr
->h_addr_list
[i
],
442 * Connect to the remote system...
445 if (!httpReconnect(http
))
450 * Could not connect to any known address - bail out!
459 * 'httpEncryption()' - Set the required encryption on the link.
462 int /* O - -1 on error, 0 on success */
463 httpEncryption(http_t
*http
, /* I - HTTP data */
464 http_encryption_t e
) /* I - New encryption preference */
466 DEBUG_printf(("httpEncryption(http=%p, e=%d)\n", http
, e
));
472 http
->encryption
= e
;
474 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
475 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
476 return (httpReconnect(http
));
477 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
478 return (http_upgrade(http
));
482 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
486 #endif /* HAVE_SSL */
491 * 'httpReconnect()' - Reconnect to a HTTP server...
494 int /* O - 0 on success, non-zero on failure */
495 httpReconnect(http_t
*http
) /* I - HTTP data */
497 int val
; /* Socket option value */
500 DEBUG_printf(("httpReconnect(http=%p)\n", http
));
507 http_shutdown_ssl(http
);
508 #endif /* HAVE_SSL */
511 * Close any previously open socket...
516 closesocket(http
->fd
);
522 * Create the socket and set options to allow reuse.
525 if ((http
->fd
= socket(AF_INET
, SOCK_STREAM
, 0)) < 0)
528 http
->error
= WSAGetLastError();
532 http
->status
= HTTP_ERROR
;
537 fcntl(http
->fd
, F_SETFD
, FD_CLOEXEC
); /* Close this socket when starting *
538 * other processes... */
539 #endif /* FD_CLOEXEC */
542 setsockopt(http
->fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *)&val
, sizeof(val
));
546 setsockopt(http
->fd
, SOL_SOCKET
, SO_REUSEPORT
, &val
, sizeof(val
));
547 #endif /* SO_REUSEPORT */
550 * Using TCP_NODELAY improves responsiveness, especially on systems
551 * with a slow loopback interface... Since we write large buffers
552 * when sending print files and requests, there shouldn't be any
553 * performance penalty for this...
558 setsockopt(http
->fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&val
, sizeof(val
));
560 setsockopt(http
->fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
564 * Connect to the server...
567 if (connect(http
->fd
, (struct sockaddr
*)&(http
->hostaddr
),
568 sizeof(http
->hostaddr
)) < 0)
571 http
->error
= WSAGetLastError();
575 http
->status
= HTTP_ERROR
;
578 closesocket(http
->fd
);
589 http
->status
= HTTP_CONTINUE
;
592 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
595 * Always do encryption via SSL.
598 if (http_setup_ssl(http
) != 0)
601 closesocket(http
->fd
);
609 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
610 return (http_upgrade(http
));
611 #endif /* HAVE_SSL */
618 * 'httpGetSubField()' - Get a sub-field value.
621 char * /* O - Value or NULL */
622 httpGetSubField(http_t
*http
, /* I - HTTP data */
623 http_field_t field
, /* I - Field index */
624 const char *name
, /* I - Name of sub-field */
625 char *value
) /* O - Value string */
627 const char *fptr
; /* Pointer into field */
628 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
629 *ptr
; /* Pointer into string buffer */
632 DEBUG_printf(("httpGetSubField(http=%p, field=%d, name=\"%s\", value=%p)\n",
633 http
, field
, name
, value
));
636 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
637 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
638 name
== NULL
|| value
== NULL
)
641 for (fptr
= http
->fields
[field
]; *fptr
;)
644 * Skip leading whitespace...
647 while (isspace(*fptr
& 255))
657 * Get the sub-field name...
661 *fptr
&& *fptr
!= '=' && !isspace(*fptr
& 255) && ptr
< (temp
+ sizeof(temp
) - 1);
666 DEBUG_printf(("httpGetSubField: name=\"%s\"\n", temp
));
669 * Skip trailing chars up to the '='...
672 while (isspace(*fptr
& 255))
682 * Skip = and leading whitespace...
687 while (isspace(*fptr
& 255))
693 * Read quoted string...
696 for (ptr
= value
, fptr
++;
697 *fptr
&& *fptr
!= '\"' && ptr
< (value
+ HTTP_MAX_VALUE
- 1);
702 while (*fptr
&& *fptr
!= '\"')
711 * Read unquoted string...
715 *fptr
&& !isspace(*fptr
& 255) && *fptr
!= ',' && ptr
< (value
+ HTTP_MAX_VALUE
- 1);
720 while (*fptr
&& !isspace(*fptr
& 255) && *fptr
!= ',')
724 DEBUG_printf(("httpGetSubField: value=\"%s\"\n", value
));
727 * See if this is the one...
730 if (strcmp(name
, temp
) == 0)
741 * 'httpSetField()' - Set the value of an HTTP header.
745 httpSetField(http_t
*http
, /* I - HTTP data */
746 http_field_t field
, /* I - Field index */
747 const char *value
) /* I - Value */
750 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
751 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
755 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
760 * 'httpDelete()' - Send a DELETE request to the server.
763 int /* O - Status of call (0 = success) */
764 httpDelete(http_t
*http
, /* I - HTTP data */
765 const char *uri
) /* I - URI to delete */
767 return (http_send(http
, HTTP_DELETE
, uri
));
772 * 'httpGet()' - Send a GET request to the server.
775 int /* O - Status of call (0 = success) */
776 httpGet(http_t
*http
, /* I - HTTP data */
777 const char *uri
) /* I - URI to get */
779 return (http_send(http
, HTTP_GET
, uri
));
784 * 'httpHead()' - Send a HEAD request to the server.
787 int /* O - Status of call (0 = success) */
788 httpHead(http_t
*http
, /* I - HTTP data */
789 const char *uri
) /* I - URI for head */
791 return (http_send(http
, HTTP_HEAD
, uri
));
796 * 'httpOptions()' - Send an OPTIONS request to the server.
799 int /* O - Status of call (0 = success) */
800 httpOptions(http_t
*http
, /* I - HTTP data */
801 const char *uri
) /* I - URI for options */
803 return (http_send(http
, HTTP_OPTIONS
, uri
));
808 * 'httpPost()' - Send a POST request to the server.
811 int /* O - Status of call (0 = success) */
812 httpPost(http_t
*http
, /* I - HTTP data */
813 const char *uri
) /* I - URI for post */
817 return (http_send(http
, HTTP_POST
, uri
));
822 * 'httpPut()' - Send a PUT request to the server.
825 int /* O - Status of call (0 = success) */
826 httpPut(http_t
*http
, /* I - HTTP data */
827 const char *uri
) /* I - URI to put */
831 return (http_send(http
, HTTP_PUT
, uri
));
836 * 'httpTrace()' - Send an TRACE request to the server.
839 int /* O - Status of call (0 = success) */
840 httpTrace(http_t
*http
, /* I - HTTP data */
841 const char *uri
) /* I - URI for trace */
843 return (http_send(http
, HTTP_TRACE
, uri
));
848 * 'httpFlush()' - Flush data from a HTTP connection.
852 httpFlush(http_t
*http
) /* I - HTTP data */
854 char buffer
[8192]; /* Junk buffer */
857 DEBUG_printf(("httpFlush(http=%p), state=%d\n", http
, http
->state
));
859 while (httpRead(http
, buffer
, sizeof(buffer
)) > 0);
864 * 'httpRead()' - Read data from a HTTP connection.
867 int /* O - Number of bytes read */
868 httpRead(http_t
*http
, /* I - HTTP data */
869 char *buffer
, /* I - Buffer for data */
870 int length
) /* I - Maximum number of bytes */
872 int bytes
; /* Bytes read */
873 char len
[32]; /* Length string */
876 DEBUG_printf(("httpRead(http=%p, buffer=%p, length=%d)\n",
877 http
, buffer
, length
));
879 if (http
== NULL
|| buffer
== NULL
)
882 http
->activity
= time(NULL
);
887 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
888 http
->data_remaining
<= 0)
890 DEBUG_puts("httpRead: Getting chunk length...");
892 if (httpGets(len
, sizeof(len
), http
) == NULL
)
894 DEBUG_puts("httpRead: Could not get length!");
898 http
->data_remaining
= strtol(len
, NULL
, 16);
899 if (http
->data_remaining
< 0)
901 DEBUG_puts("httpRead: Negative chunk length!");
906 DEBUG_printf(("httpRead: data_remaining=%d\n", http
->data_remaining
));
908 if (http
->data_remaining
<= 0)
911 * A zero-length chunk ends a transfer; unless we are reading POST
915 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
916 httpGets(len
, sizeof(len
), http
);
918 if (http
->state
== HTTP_POST_RECV
)
921 http
->state
= HTTP_WAITING
;
924 * Prevent future reads for this request...
927 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
931 else if (length
> http
->data_remaining
)
932 length
= http
->data_remaining
;
934 if (http
->used
== 0 && length
<= 256)
937 * Buffer small reads for better performance...
940 if (!http
->blocking
&& !httpWait(http
, 1000))
943 if (http
->data_remaining
> sizeof(http
->buffer
))
944 bytes
= sizeof(http
->buffer
);
946 bytes
= http
->data_remaining
;
950 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
952 #endif /* HAVE_SSL */
954 DEBUG_printf(("httpRead: reading %d bytes from socket into buffer...\n",
957 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
959 DEBUG_printf(("httpRead: read %d bytes from socket into buffer...\n",
968 http
->error
= WSAGetLastError();
987 if (length
> http
->used
)
992 DEBUG_printf(("httpRead: grabbing %d bytes from input buffer...\n", bytes
));
994 memcpy(buffer
, http
->buffer
, length
);
995 http
->used
-= length
;
998 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
1003 if (!http
->blocking
&& !httpWait(http
, 1000))
1006 bytes
= http_read_ssl(http
, buffer
, length
);
1008 #endif /* HAVE_SSL */
1011 if (!http
->blocking
&& !httpWait(http
, 1000))
1014 DEBUG_printf(("httpRead: reading %d bytes from socket...\n", length
));
1015 bytes
= recv(http
->fd
, buffer
, length
, 0);
1016 DEBUG_printf(("httpRead: read %d bytes from socket...\n", bytes
));
1020 http
->data_remaining
-= bytes
;
1024 http
->error
= WSAGetLastError();
1029 http
->error
= errno
;
1034 http
->error
= EPIPE
;
1038 if (http
->data_remaining
== 0)
1040 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1041 httpGets(len
, sizeof(len
), http
);
1043 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
1045 if (http
->state
== HTTP_POST_RECV
)
1048 http
->state
= HTTP_WAITING
;
1055 printf("httpRead: Read %d bytes:\n", bytes
);
1056 for (i
= 0; i
< bytes
; i
+= 16)
1060 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1061 printf(" %02X", buffer
[i
+ j
] & 255);
1070 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1072 ch
= buffer
[i
+ j
] & 255;
1074 if (ch
< ' ' || ch
== 127)
1089 * 'httpSetCookie()' - Set the cookie value(s)...
1093 httpSetCookie(http_t
*http
, /* I - Connection */
1094 const char *cookie
) /* I - Cookie string */
1103 http
->cookie
= strdup(cookie
);
1105 http
->cookie
= NULL
;
1110 * 'httpWait()' - Wait for data available on a connection.
1113 int /* O - 1 if data is available, 0 otherwise */
1114 httpWait(http_t
*http
, /* I - HTTP data */
1115 int msec
) /* I - Milliseconds to wait */
1118 * First see if there is data in the buffer...
1128 * If not, check the SSL/TLS buffers and do a select() on the connection...
1131 return (http_wait(http
, msec
));
1136 * 'httpWrite()' - Write data to a HTTP connection.
1139 int /* O - Number of bytes written */
1140 httpWrite(http_t
*http
, /* I - HTTP data */
1141 const char *buffer
, /* I - Buffer for data */
1142 int length
) /* I - Number of bytes to write */
1144 int tbytes
, /* Total bytes sent */
1145 bytes
; /* Bytes sent */
1148 if (http
== NULL
|| buffer
== NULL
)
1151 http
->activity
= time(NULL
);
1153 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1155 if (httpPrintf(http
, "%x\r\n", length
) < 0)
1161 * A zero-length chunk ends a transfer; unless we are sending POST
1162 * or PUT data, go idle...
1165 DEBUG_puts("httpWrite: changing states...");
1167 if (http
->state
== HTTP_POST_RECV
)
1169 else if (http
->state
== HTTP_PUT_RECV
)
1170 http
->state
= HTTP_STATUS
;
1172 http
->state
= HTTP_WAITING
;
1174 if (httpPrintf(http
, "\r\n") < 0)
1187 bytes
= http_write_ssl(http
, buffer
, length
);
1189 #endif /* HAVE_SSL */
1190 bytes
= send(http
->fd
, buffer
, length
, 0);
1195 if (WSAGetLastError() != http
->error
)
1197 http
->error
= WSAGetLastError();
1203 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
1205 http
->error
= errno
;
1210 DEBUG_puts("httpWrite: error writing data...\n");
1218 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1219 http
->data_remaining
-= bytes
;
1222 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1223 if (httpPrintf(http
, "\r\n") < 0)
1226 if (http
->data_remaining
== 0 && http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1229 * Finished with the transfer; unless we are sending POST or PUT
1233 DEBUG_puts("httpWrite: changing states...");
1235 if (http
->state
== HTTP_POST_RECV
)
1237 else if (http
->state
== HTTP_PUT_RECV
)
1238 http
->state
= HTTP_STATUS
;
1240 http
->state
= HTTP_WAITING
;
1246 printf("httpWrite: wrote %d bytes: \n", tbytes
);
1247 for (i
= 0, buffer
-= tbytes
; i
< tbytes
; i
+= 16)
1251 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
1252 printf(" %02X", buffer
[i
+ j
] & 255);
1261 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
1263 ch
= buffer
[i
+ j
] & 255;
1265 if (ch
< ' ' || ch
== 127)
1279 * 'httpGets()' - Get a line of text from a HTTP connection.
1282 char * /* O - Line or NULL */
1283 httpGets(char *line
, /* I - Line to read into */
1284 int length
, /* I - Max length of buffer */
1285 http_t
*http
) /* I - HTTP data */
1287 char *lineptr
, /* Pointer into line */
1288 *bufptr
, /* Pointer into input buffer */
1289 *bufend
; /* Pointer to end of buffer */
1290 int bytes
; /* Number of bytes read */
1293 DEBUG_printf(("httpGets(line=%p, length=%d, http=%p)\n", line
, length
, http
));
1295 if (http
== NULL
|| line
== NULL
)
1299 * Pre-scan the buffer and see if there is a newline in there...
1310 bufptr
= http
->buffer
;
1311 bufend
= http
->buffer
+ http
->used
;
1313 while (bufptr
< bufend
)
1314 if (*bufptr
== 0x0a)
1319 if (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
)
1322 * No newline; see if there is more data to be read...
1325 if (!http
->blocking
&& !http_wait(http
, 1000))
1330 bytes
= http_read_ssl(http
, bufend
, HTTP_MAX_BUFFER
- http
->used
);
1332 #endif /* HAVE_SSL */
1333 bytes
= recv(http
->fd
, bufend
, HTTP_MAX_BUFFER
- http
->used
, 0);
1335 DEBUG_printf(("httpGets: read %d bytes...\n", bytes
));
1340 * Nope, can't get a line this time...
1344 if (WSAGetLastError() != http
->error
)
1346 http
->error
= WSAGetLastError();
1350 DEBUG_printf(("httpGets: recv() error %d!\n", WSAGetLastError()));
1352 DEBUG_printf(("httpGets: recv() error %d!\n", errno
));
1356 else if (errno
!= http
->error
)
1358 http
->error
= errno
;
1365 else if (bytes
== 0)
1367 http
->error
= EPIPE
;
1373 * Yup, update the amount used and the end pointer...
1376 http
->used
+= bytes
;
1381 while (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
);
1383 http
->activity
= time(NULL
);
1386 * Read a line from the buffer...
1390 bufptr
= http
->buffer
;
1394 while (bufptr
< bufend
&& bytes
< length
)
1398 if (*bufptr
== 0x0a)
1403 else if (*bufptr
== 0x0d)
1406 *lineptr
++ = *bufptr
++;
1413 http
->used
-= bytes
;
1415 memmove(http
->buffer
, bufptr
, http
->used
);
1417 DEBUG_printf(("httpGets: Returning \"%s\"\n", line
));
1421 DEBUG_puts("httpGets: No new line available!");
1428 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1431 int /* O - Number of bytes written */
1432 httpPrintf(http_t
*http
, /* I - HTTP data */
1433 const char *format
, /* I - printf-style format string */
1434 ...) /* I - Additional args as needed */
1436 int bytes
, /* Number of bytes to write */
1437 nbytes
, /* Number of bytes written */
1438 tbytes
; /* Number of bytes all together */
1439 char buf
[HTTP_MAX_BUFFER
], /* Buffer for formatted string */
1440 *bufptr
; /* Pointer into buffer */
1441 va_list ap
; /* Variable argument pointer */
1444 DEBUG_printf(("httpPrintf(http=%p, format=\"%s\", ...)\n", http
, format
));
1446 va_start(ap
, format
);
1447 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1450 DEBUG_printf(("httpPrintf: %s", buf
));
1452 for (tbytes
= 0, bufptr
= buf
; tbytes
< bytes
; tbytes
+= nbytes
, bufptr
+= nbytes
)
1456 nbytes
= http_write_ssl(http
, bufptr
, bytes
- tbytes
);
1458 #endif /* HAVE_SSL */
1459 nbytes
= send(http
->fd
, bufptr
, bytes
- tbytes
, 0);
1466 if (WSAGetLastError() != http
->error
)
1468 http
->error
= WSAGetLastError();
1474 else if (errno
!= http
->error
)
1476 http
->error
= errno
;
1490 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
1493 const char * /* O - Date/time string */
1494 httpGetDateString(time_t t
) /* I - UNIX time */
1497 static char datetime
[256];
1501 snprintf(datetime
, sizeof(datetime
), "%s, %02d %s %d %02d:%02d:%02d GMT",
1502 days
[tdate
->tm_wday
], tdate
->tm_mday
, months
[tdate
->tm_mon
],
1503 tdate
->tm_year
+ 1900, tdate
->tm_hour
, tdate
->tm_min
, tdate
->tm_sec
);
1510 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
1513 time_t /* O - UNIX time */
1514 httpGetDateTime(const char *s
) /* I - Date/time string */
1516 int i
; /* Looping var */
1517 struct tm tdate
; /* Time/date structure */
1518 char mon
[16]; /* Abbreviated month name */
1519 int day
, year
; /* Day of month and year */
1520 int hour
, min
, sec
; /* Time */
1523 if (sscanf(s
, "%*s%d%15s%d%d:%d:%d", &day
, mon
, &year
, &hour
, &min
, &sec
) < 6)
1526 for (i
= 0; i
< 12; i
++)
1527 if (strcasecmp(mon
, months
[i
]) == 0)
1534 tdate
.tm_mday
= day
;
1535 tdate
.tm_year
= year
- 1900;
1536 tdate
.tm_hour
= hour
;
1541 return (mktime(&tdate
));
1546 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1549 http_status_t
/* O - HTTP status */
1550 httpUpdate(http_t
*http
) /* I - HTTP data */
1552 char line
[1024], /* Line from connection... */
1553 *value
; /* Pointer to value on line */
1554 http_field_t field
; /* Field index */
1555 int major
, minor
, /* HTTP version numbers */
1556 status
; /* Request status */
1559 DEBUG_printf(("httpUpdate(http=%p), state=%d\n", http
, http
->state
));
1562 * If we haven't issued any commands, then there is nothing to "update"...
1565 if (http
->state
== HTTP_WAITING
)
1566 return (HTTP_CONTINUE
);
1569 * Grab all of the lines we can from the connection...
1572 while (httpGets(line
, sizeof(line
), http
) != NULL
)
1574 DEBUG_printf(("httpUpdate: Got \"%s\"\n", line
));
1576 if (line
[0] == '\0')
1579 * Blank line means the start of the data section (if any). Return
1580 * the result code, too...
1582 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
1583 * Instead, we just return HTTP_CONTINUE to the caller and keep on
1587 if (http
->status
== HTTP_CONTINUE
)
1588 return (http
->status
);
1590 if (http
->status
< HTTP_BAD_REQUEST
)
1591 http
->digest_tries
= 0;
1594 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
1596 if (http_setup_ssl(http
) != 0)
1599 closesocket(http
->fd
);
1604 return (HTTP_ERROR
);
1607 return (HTTP_CONTINUE
);
1609 #endif /* HAVE_SSL */
1611 httpGetLength(http
);
1613 switch (http
->state
)
1617 case HTTP_POST_RECV
:
1620 case HTTP_POST_SEND
:
1624 http
->state
= HTTP_WAITING
;
1628 return (http
->status
);
1630 else if (strncmp(line
, "HTTP/", 5) == 0)
1633 * Got the beginning of a response...
1636 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &status
) != 3)
1637 return (HTTP_ERROR
);
1639 http
->version
= (http_version_t
)(major
* 100 + minor
);
1640 http
->status
= (http_status_t
)status
;
1642 else if ((value
= strchr(line
, ':')) != NULL
)
1649 while (isspace(*value
& 255))
1653 * Be tolerants of servers that send unknown attribute fields...
1656 if (!strcasecmp(line
, "expect"))
1659 * "Expect: 100-continue" or similar...
1662 http
->expect
= (http_status_t
)atoi(value
);
1664 else if (!strcasecmp(line
, "cookie"))
1667 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
1670 httpSetCookie(http
, value
);
1672 else if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
1674 DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line
));
1678 httpSetField(http
, field
, value
);
1682 http
->status
= HTTP_ERROR
;
1683 return (HTTP_ERROR
);
1688 * See if there was an error...
1691 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
1692 return (http
->status
);
1696 DEBUG_printf(("httpUpdate: socket error %d - %s\n", http
->error
,
1697 strerror(http
->error
)));
1698 http
->status
= HTTP_ERROR
;
1699 return (HTTP_ERROR
);
1703 * If we haven't already returned, then there is nothing new...
1706 return (HTTP_CONTINUE
);
1711 * 'httpDecode64()' - Base64-decode a string.
1714 char * /* O - Decoded string */
1715 httpDecode64(char *out
, /* I - String to write to */
1716 const char *in
) /* I - String to read from */
1718 int outlen
; /* Output buffer length */
1722 * Use the old maximum buffer size for binary compatibility...
1727 return (httpDecode64_2(out
, &outlen
, in
));
1732 * 'httpDecode64_2()' - Base64-decode a string.
1735 char * /* O - Decoded string */
1736 httpDecode64_2(char *out
, /* I - String to write to */
1737 int *outlen
, /* IO - Size of output string */
1738 const char *in
) /* I - String to read from */
1740 int pos
, /* Bit position */
1741 base64
; /* Value of this character */
1742 char *outptr
, /* Output pointer */
1743 *outend
; /* End of output buffer */
1747 * Range check input...
1750 if (!out
|| !outlen
|| *outlen
< 1 || !in
|| !*in
)
1754 * Convert from base-64 to bytes...
1757 for (outptr
= out
, outend
= out
+ *outlen
- 1, pos
= 0; *in
!= '\0'; in
++)
1760 * Decode this character into a number from 0 to 63...
1763 if (*in
>= 'A' && *in
<= 'Z')
1765 else if (*in
>= 'a' && *in
<= 'z')
1766 base64
= *in
- 'a' + 26;
1767 else if (*in
>= '0' && *in
<= '9')
1768 base64
= *in
- '0' + 52;
1769 else if (*in
== '+')
1771 else if (*in
== '/')
1773 else if (*in
== '=')
1779 * Store the result in the appropriate chars...
1785 if (outptr
< outend
)
1786 *outptr
= base64
<< 2;
1790 if (outptr
< outend
)
1791 *outptr
++ |= (base64
>> 4) & 3;
1792 if (outptr
< outend
)
1793 *outptr
= (base64
<< 4) & 255;
1797 if (outptr
< outend
)
1798 *outptr
++ |= (base64
>> 2) & 15;
1799 if (outptr
< outend
)
1800 *outptr
= (base64
<< 6) & 255;
1804 if (outptr
< outend
)
1805 *outptr
++ |= base64
;
1814 * Return the decoded string and size...
1817 *outlen
= (int)(outptr
- out
);
1824 * 'httpEncode64()' - Base64-encode a string.
1827 char * /* O - Encoded string */
1828 httpEncode64(char *out
, /* I - String to write to */
1829 const char *in
) /* I - String to read from */
1831 return (httpEncode64_2(out
, 512, in
, strlen(in
)));
1836 * 'httpEncode64_2()' - Base64-encode a string.
1839 char * /* O - Encoded string */
1840 httpEncode64_2(char *out
, /* I - String to write to */
1841 int outlen
, /* I - Size of output string */
1842 const char *in
, /* I - String to read from */
1843 int inlen
) /* I - Size of input string */
1845 char *outptr
, /* Output pointer */
1846 *outend
; /* End of output buffer */
1847 static const char base64
[] = /* Base64 characters... */
1849 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1850 "abcdefghijklmnopqrstuvwxyz"
1857 * Range check input...
1860 if (!out
|| outlen
< 1 || !in
|| inlen
< 1)
1864 * Convert bytes to base-64...
1867 for (outptr
= out
, outend
= out
+ outlen
- 1; inlen
> 0; in
++, inlen
--)
1870 * Encode the up to 3 characters as 4 Base64 numbers...
1873 if (outptr
< outend
)
1874 *outptr
++ = base64
[in
[0] >> 2];
1875 if (outptr
< outend
)
1876 *outptr
++ = base64
[((in
[0] << 4) | (in
[1] >> 4)) & 63];
1882 if (outptr
< outend
)
1884 if (outptr
< outend
)
1889 if (outptr
< outend
)
1890 *outptr
++ = base64
[((in
[0] << 2) | (in
[1] >> 6)) & 63];
1896 if (outptr
< outend
)
1901 if (outptr
< outend
)
1902 *outptr
++ = base64
[in
[0] & 63];
1908 * Return the encoded string...
1916 * 'httpGetLength()' - Get the amount of data remaining from the
1917 * content-length or transfer-encoding fields.
1920 int /* O - Content length */
1921 httpGetLength(http_t
*http
) /* I - HTTP data */
1923 DEBUG_printf(("httpGetLength(http=%p), state=%d\n", http
, http
->state
));
1925 if (strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked") == 0)
1927 DEBUG_puts("httpGetLength: chunked request!");
1929 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
1930 http
->data_remaining
= 0;
1934 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1937 * The following is a hack for HTTP servers that don't send a
1938 * content-length or transfer-encoding field...
1940 * If there is no content-length then the connection must close
1941 * after the transfer is complete...
1944 if (http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] == '\0')
1945 http
->data_remaining
= 2147483647;
1947 http
->data_remaining
= atoi(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
]);
1949 DEBUG_printf(("httpGetLength: content_length=%d\n", http
->data_remaining
));
1952 return (http
->data_remaining
);
1957 * 'http_field()' - Return the field index for a field name.
1960 static http_field_t
/* O - Field index */
1961 http_field(const char *name
) /* I - String name */
1963 int i
; /* Looping var */
1966 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
1967 if (strcasecmp(name
, http_fields
[i
]) == 0)
1968 return ((http_field_t
)i
);
1970 return (HTTP_FIELD_UNKNOWN
);
1975 * 'http_send()' - Send a request with all fields and the trailing blank line.
1978 static int /* O - 0 on success, non-zero on error */
1979 http_send(http_t
*http
, /* I - HTTP data */
1980 http_state_t request
, /* I - Request code */
1981 const char *uri
) /* I - URI */
1983 int i
; /* Looping var */
1984 char *ptr
, /* Pointer in buffer */
1985 buf
[1024]; /* Encoded URI buffer */
1986 static const char * const codes
[] =
1987 { /* Request code strings */
2002 static const char hex
[] = "0123456789ABCDEF";
2006 DEBUG_printf(("http_send(http=%p, request=HTTP_%s, uri=\"%s\")\n",
2007 http
, codes
[request
], uri
));
2009 if (http
== NULL
|| uri
== NULL
)
2013 * Encode the URI as needed...
2016 for (ptr
= buf
; *uri
!= '\0' && ptr
< (buf
+ sizeof(buf
) - 1); uri
++)
2017 if (*uri
<= ' ' || *uri
>= 127)
2019 if (ptr
< (buf
+ sizeof(buf
) - 1))
2021 if (ptr
< (buf
+ sizeof(buf
) - 1))
2022 *ptr
++ = hex
[(*uri
>> 4) & 15];
2023 if (ptr
< (buf
+ sizeof(buf
) - 1))
2024 *ptr
++ = hex
[*uri
& 15];
2032 * See if we had an error the last time around; if so, reconnect...
2035 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
2036 httpReconnect(http
);
2039 * Send the request header...
2042 http
->state
= request
;
2043 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
2046 http
->status
= HTTP_CONTINUE
;
2049 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
2051 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
2052 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
2054 #endif /* HAVE_SSL */
2056 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
2058 http
->status
= HTTP_ERROR
;
2062 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2063 if (http
->fields
[i
][0] != '\0')
2065 DEBUG_printf(("%s: %s\n", http_fields
[i
], http
->fields
[i
]));
2067 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], http
->fields
[i
]) < 1)
2069 http
->status
= HTTP_ERROR
;
2074 if (httpPrintf(http
, "\r\n") < 1)
2076 http
->status
= HTTP_ERROR
;
2080 httpClearFields(http
);
2087 * 'http_wait()' - Wait for data available on a connection.
2090 static int /* O - 1 if data is available, 0 otherwise */
2091 http_wait(http_t
*http
, /* I - HTTP data */
2092 int msec
) /* I - Milliseconds to wait */
2095 struct rlimit limit
; /* Runtime limit */
2097 struct timeval timeout
; /* Timeout */
2098 int nfds
; /* Result from select() */
2099 int set_size
; /* Size of select set */
2102 DEBUG_printf(("http_wait(http=%p, msec=%d)\n", http
, msec
));
2105 * Check the SSL/TLS buffers for data first...
2112 if (SSL_pending((SSL
*)(http
->tls
)))
2114 # elif defined(HAVE_GNUTLS)
2115 if (gnutls_record_check_pending(((http_tls_t
*)(http
->tls
))->session
))
2117 # elif defined(HAVE_CDSASSL)
2118 size_t bytes
; /* Bytes that are available */
2120 if (!SSLGetBufferedReadSize((SSLContextRef
)http
->tls
, &bytes
) && bytes
> 0)
2122 # endif /* HAVE_LIBSSL */
2124 #endif /* HAVE_SSL */
2127 * Then try doing a select() to poll the socket...
2130 if (!http
->input_set
)
2134 * Windows has a fixed-size select() structure, different (surprise,
2135 * surprise!) from all UNIX implementations. Just allocate this
2136 * fixed structure...
2139 http
->input_set
= calloc(1, sizeof(fd_set
));
2142 * Allocate the select() input set based upon the max number of file
2143 * descriptors available for this process...
2146 getrlimit(RLIMIT_NOFILE
, &limit
);
2148 set_size
= (limit
.rlim_cur
+ 31) / 8 + 4;
2149 if (set_size
< sizeof(fd_set
))
2150 set_size
= sizeof(fd_set
);
2152 http
->input_set
= calloc(1, set_size
);
2155 if (!http
->input_set
)
2159 FD_SET(http
->fd
, http
->input_set
);
2163 timeout
.tv_sec
= msec
/ 1000;
2164 timeout
.tv_usec
= (msec
% 1000) * 1000;
2166 nfds
= select(http
->fd
+ 1, http
->input_set
, NULL
, NULL
, &timeout
);
2169 nfds
= select(http
->fd
+ 1, http
->input_set
, NULL
, NULL
, NULL
);
2171 FD_CLR(http
->fd
, http
->input_set
);
2179 * 'http_upgrade()' - Force upgrade to TLS encryption.
2182 static int /* O - Status of connection */
2183 http_upgrade(http_t
*http
) /* I - HTTP data */
2185 int ret
; /* Return value */
2186 http_t myhttp
; /* Local copy of HTTP data */
2189 DEBUG_printf(("http_upgrade(%p)\n", http
));
2192 * Copy the HTTP data to a local variable so we can do the OPTIONS
2193 * request without interfering with the existing request data...
2196 memcpy(&myhttp
, http
, sizeof(myhttp
));
2199 * Send an OPTIONS request to the server, requiring SSL or TLS
2200 * encryption on the link...
2203 httpClearFields(&myhttp
);
2204 httpSetField(&myhttp
, HTTP_FIELD_CONNECTION
, "upgrade");
2205 httpSetField(&myhttp
, HTTP_FIELD_UPGRADE
, "TLS/1.0, SSL/2.0, SSL/3.0");
2207 if ((ret
= httpOptions(&myhttp
, "*")) == 0)
2210 * Wait for the secure connection...
2213 while (httpUpdate(&myhttp
) == HTTP_CONTINUE
);
2219 * Copy the HTTP data back over, if any...
2222 http
->fd
= myhttp
.fd
;
2223 http
->error
= myhttp
.error
;
2224 http
->activity
= myhttp
.activity
;
2225 http
->status
= myhttp
.status
;
2226 http
->version
= myhttp
.version
;
2227 http
->keep_alive
= myhttp
.keep_alive
;
2228 http
->used
= myhttp
.used
;
2231 memcpy(http
->buffer
, myhttp
.buffer
, http
->used
);
2233 http
->auth_type
= myhttp
.auth_type
;
2234 http
->nonce_count
= myhttp
.nonce_count
;
2236 memcpy(http
->nonce
, myhttp
.nonce
, sizeof(http
->nonce
));
2238 http
->tls
= myhttp
.tls
;
2239 http
->encryption
= myhttp
.encryption
;
2242 * See if we actually went secure...
2248 * Server does not support HTTP upgrade...
2251 DEBUG_puts("Server does not support HTTP upgrade!");
2254 closesocket(http
->fd
);
2269 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
2272 static int /* O - Status of connection */
2273 http_setup_ssl(http_t
*http
) /* I - HTTP data */
2276 SSL_CTX
*context
; /* Context for encryption */
2277 SSL
*conn
; /* Connection for encryption */
2278 # elif defined(HAVE_GNUTLS)
2279 http_tls_t
*conn
; /* TLS session object */
2280 gnutls_certificate_client_credentials
*credentials
;
2281 /* TLS credentials */
2282 # elif defined(HAVE_CDSASSL)
2283 SSLContextRef conn
; /* Context for encryption */
2284 OSStatus error
; /* Error info */
2285 # endif /* HAVE_LIBSSL */
2288 DEBUG_printf(("http_setup_ssl(http=%p)\n", http
));
2291 context
= SSL_CTX_new(SSLv23_client_method());
2292 conn
= SSL_new(context
);
2294 SSL_set_fd(conn
, http
->fd
);
2295 if (SSL_connect(conn
) != 1)
2298 unsigned long error
; /* Error code */
2300 while ((error
= ERR_get_error()) != 0)
2301 printf("http_setup_ssl: %s\n", ERR_error_string(error
, NULL
));
2304 SSL_CTX_free(context
);
2308 http
->error
= WSAGetLastError();
2310 http
->error
= errno
;
2312 http
->status
= HTTP_ERROR
;
2314 return (HTTP_ERROR
);
2317 # elif defined(HAVE_GNUTLS)
2318 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
2322 http
->error
= errno
;
2323 http
->status
= HTTP_ERROR
;
2328 credentials
= (gnutls_certificate_client_credentials
*)
2329 malloc(sizeof(gnutls_certificate_client_credentials
));
2330 if (credentials
== NULL
)
2334 http
->error
= errno
;
2335 http
->status
= HTTP_ERROR
;
2340 gnutls_certificate_allocate_credentials(credentials
);
2342 gnutls_init(&(conn
->session
), GNUTLS_CLIENT
);
2343 gnutls_set_default_priority(conn
->session
);
2344 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
2345 gnutls_transport_set_ptr(conn
->session
, http
->fd
);
2347 if ((gnutls_handshake(conn
->session
)) != GNUTLS_E_SUCCESS
)
2349 http
->error
= errno
;
2350 http
->status
= HTTP_ERROR
;
2355 conn
->credentials
= credentials
;
2357 # elif defined(HAVE_CDSASSL)
2358 error
= SSLNewContext(false, &conn
);
2361 error
= SSLSetIOFuncs(conn
, CDSAReadFunc
, CDSAWriteFunc
);
2364 error
= SSLSetConnection(conn
, (SSLConnectionRef
)http
->fd
);
2367 error
= SSLSetAllowsExpiredCerts(conn
, true);
2370 error
= SSLSetAllowsAnyRoot(conn
, true);
2373 error
= SSLHandshake(conn
);
2377 http
->error
= error
;
2378 http
->status
= HTTP_ERROR
;
2380 SSLDisposeContext(conn
);
2386 # endif /* HAVE_CDSASSL */
2394 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
2398 http_shutdown_ssl(http_t
*http
) /* I - HTTP data */
2401 SSL_CTX
*context
; /* Context for encryption */
2402 SSL
*conn
; /* Connection for encryption */
2405 conn
= (SSL
*)(http
->tls
);
2406 context
= SSL_get_SSL_CTX(conn
);
2409 SSL_CTX_free(context
);
2412 # elif defined(HAVE_GNUTLS)
2413 http_tls_t
*conn
; /* Encryption session */
2414 gnutls_certificate_client_credentials
*credentials
;
2415 /* TLS credentials */
2418 conn
= (http_tls_t
*)(http
->tls
);
2419 credentials
= (gnutls_certificate_client_credentials
*)(conn
->credentials
);
2421 gnutls_bye(conn
->session
, GNUTLS_SHUT_RDWR
);
2422 gnutls_deinit(conn
->session
);
2423 gnutls_certificate_free_credentials(*credentials
);
2427 # elif defined(HAVE_CDSASSL)
2428 SSLClose((SSLContextRef
)http
->tls
);
2429 SSLDisposeContext((SSLContextRef
)http
->tls
);
2430 # endif /* HAVE_LIBSSL */
2437 * 'http_read_ssl()' - Read from a SSL/TLS connection.
2440 static int /* O - Bytes read */
2441 http_read_ssl(http_t
*http
, /* I - HTTP data */
2442 char *buf
, /* I - Buffer to store data */
2443 int len
) /* I - Length of buffer */
2445 # if defined(HAVE_LIBSSL)
2446 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
2448 # elif defined(HAVE_GNUTLS)
2449 return (gnutls_record_recv(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
2451 # elif defined(HAVE_CDSASSL)
2452 OSStatus error
; /* Error info */
2453 size_t processed
; /* Number of bytes processed */
2456 error
= SSLRead((SSLContextRef
)http
->tls
, buf
, len
, &processed
);
2462 http
->error
= error
;
2466 # endif /* HAVE_LIBSSL */
2471 * 'http_write_ssl()' - Write to a SSL/TLS connection.
2474 static int /* O - Bytes written */
2475 http_write_ssl(http_t
*http
, /* I - HTTP data */
2476 const char *buf
, /* I - Buffer holding data */
2477 int len
) /* I - Length of buffer */
2479 # if defined(HAVE_LIBSSL)
2480 return (SSL_write((SSL
*)(http
->tls
), buf
, len
));
2482 # elif defined(HAVE_GNUTLS)
2483 return (gnutls_record_send(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
2484 # elif defined(HAVE_CDSASSL)
2485 OSStatus error
; /* Error info */
2486 size_t processed
; /* Number of bytes processed */
2489 error
= SSLWrite((SSLContextRef
)http
->tls
, buf
, len
, &processed
);
2495 http
->error
= error
;
2498 # endif /* HAVE_LIBSSL */
2502 # if defined(HAVE_CDSASSL)
2504 * 'CDSAReadFunc()' - Read function for CDSA decryption code.
2507 static OSStatus
/* O - -1 on error, 0 on success */
2508 CDSAReadFunc(SSLConnectionRef connection
, /* I - SSL/TLS connection */
2509 void *data
, /* I - Data buffer */
2510 size_t *dataLength
) /* IO - Number of bytes */
2512 ssize_t bytes
; /* Number of bytes read */
2515 bytes
= recv((int)connection
, data
, *dataLength
, 0);
2518 *dataLength
= bytes
;
2527 * 'CDSAWriteFunc()' - Write function for CDSA encryption code.
2530 static OSStatus
/* O - -1 on error, 0 on success */
2531 CDSAWriteFunc(SSLConnectionRef connection
, /* I - SSL/TLS connection */
2532 const void *data
, /* I - Data buffer */
2533 size_t *dataLength
) /* IO - Number of bytes */
2538 bytes
= write((int)connection
, data
, *dataLength
);
2541 *dataLength
= bytes
;
2547 # endif /* HAVE_CDSASSL */
2548 #endif /* HAVE_SSL */
2552 * End of "$Id: http.c,v 1.141 2004/08/18 15:34:02 mike Exp $".