2 * "$Id: http.c,v 1.112 2003/02/11 16:23:53 mike Exp $"
4 * HTTP routines for the Common UNIX Printing System (CUPS).
6 * Copyright 1997-2003 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-3111 USA
20 * Voice: (301) 373-9603
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 * httpClose() - Close an HTTP connection...
33 * httpConnect() - Connect to a HTTP server.
34 * httpConnectEncrypt() - Connect to a HTTP server using encryption.
35 * httpEncryption() - Set the required encryption on the link.
36 * httpReconnect() - Reconnect to a HTTP server...
37 * httpGetSubField() - Get a sub-field value.
38 * httpSetField() - Set the value of an HTTP header.
39 * httpDelete() - Send a DELETE request to the server.
40 * httpGet() - Send a GET request to the server.
41 * httpHead() - Send a HEAD request to the server.
42 * httpOptions() - Send an OPTIONS request to the server.
43 * httpPost() - Send a POST request to the server.
44 * httpPut() - Send a PUT request to the server.
45 * httpTrace() - Send an TRACE request to the server.
46 * httpFlush() - Flush data from a HTTP connection.
47 * httpRead() - Read data from a HTTP connection.
48 * httpWait() - Wait for data available on a connection.
49 * httpWrite() - Write data to a HTTP connection.
50 * httpGets() - Get a line of text from a HTTP connection.
51 * httpPrintf() - Print a formatted string to a HTTP connection.
52 * httpGetDateString() - Get a formatted date/time string from a time value.
53 * httpGetDateTime() - Get a time value from a formatted date/time string.
54 * httpUpdate() - Update the current HTTP state for incoming data.
55 * httpDecode64() - Base64-decode a string.
56 * httpEncode64() - Base64-encode a string.
57 * httpGetLength() - Get the amount of data remaining from the
58 * content-length or transfer-encoding fields.
59 * http_field() - Return the field index for a field name.
60 * http_send() - Send a request with all fields and the trailing
62 * http_upgrade() - Force upgrade to TLS encryption.
63 * http_setup_ssl() - Set up SSL/TLS on a connection.
64 * http_shutdown_ssl() - Shut down SSL/TLS on a connection.
65 * http_read_ssl() - Read from a SSL/TLS connection.
66 * http_write_ssl() - Write to a SSL/TLS connection.
67 * CDSAReadFunc() - Read function for CDSA decryption code.
68 * CDSAWriteFunc() - Write function for CDSA encryption code.
72 * Include necessary headers...
82 #include <sys/resource.h>
85 #include "http-private.h"
95 * Some operating systems have done away with the Fxxxx constants for
96 * the fcntl() call; this works around that "feature"...
100 # define FNONBLK O_NONBLOCK
101 #endif /* !FNONBLK */
108 static http_field_t
http_field(const char *name
);
109 static int http_send(http_t
*http
, http_state_t request
,
112 static int http_upgrade(http_t
*http
);
113 static int http_setup_ssl(http_t
*http
);
114 static void http_shutdown_ssl(http_t
*http
);
115 static int http_read_ssl(http_t
*http
, char *buf
, int len
);
116 static int http_write_ssl(http_t
*http
, const char *buf
, int len
);
118 static OSStatus
CDSAReadFunc(SSLConnectionRef connection
, void *data
, size_t *dataLength
);
119 static OSStatus
CDSAWriteFunc(SSLConnectionRef connection
, const void *data
, size_t *dataLength
);
120 # endif /* HAVE_CDSASSL */
121 #endif /* HAVE_SSL */
128 static const char * const http_fields
[] =
145 "If-Unmodified-since",
158 static const char * const days
[7] =
168 static const char * const months
[12] =
186 * 'httpInitialize()' - Initialize the HTTP interface library and set the
187 * default HTTP proxy (if any).
195 struct timeval curtime
; /* Current time in microseconds */
197 int i
; /* Looping var */
198 unsigned char data
[1024]; /* Seed data */
199 #endif /* HAVE_LIBSSL */
202 WSADATA winsockdata
; /* WinSock data */
203 static int initialized
= 0;/* Has WinSock been initialized? */
207 WSAStartup(MAKEWORD(1,1), &winsockdata
);
208 #elif defined(HAVE_SIGSET)
209 sigset(SIGPIPE
, SIG_IGN
);
210 #elif defined(HAVE_SIGACTION)
211 struct sigaction action
; /* POSIX sigaction data */
215 * Ignore SIGPIPE signals...
218 memset(&action
, 0, sizeof(action
));
219 action
.sa_handler
= SIG_IGN
;
220 sigaction(SIGPIPE
, &action
, NULL
);
222 signal(SIGPIPE
, SIG_IGN
);
226 gnutls_global_init();
227 #endif /* HAVE_GNUTLS */
230 SSL_load_error_strings();
234 * Using the current time is a dubious random seed, but on some systems
235 * it is the best we can do (on others, this seed isn't even used...)
240 gettimeofday(&curtime
, NULL
);
241 srand(curtime
.tv_sec
+ curtime
.tv_usec
);
244 for (i
= 0; i
< sizeof(data
); i
++)
245 data
[i
] = rand(); /* Yes, this is a poor source of random data... */
247 RAND_seed(&data
, sizeof(data
));
248 #endif /* HAVE_LIBSSL */
253 * 'httpCheck()' - Check to see if there is a pending response from the server.
256 int /* O - 0 = no data, 1 = data available */
257 httpCheck(http_t
*http
) /* I - HTTP connection */
259 return (httpWait(http
, 0));
264 * 'httpClose()' - Close an HTTP connection...
268 httpClose(http_t
*http
) /* I - Connection to close */
274 free(http
->input_set
);
278 http_shutdown_ssl(http
);
279 #endif /* HAVE_SSL */
282 closesocket(http
->fd
);
292 * 'httpConnect()' - Connect to a HTTP server.
295 http_t
* /* O - New HTTP connection */
296 httpConnect(const char *host
, /* I - Host to connect to */
297 int port
) /* I - Port number */
299 http_encryption_t encrypt
;/* Type of encryption to use */
303 * Set the default encryption status...
307 encrypt
= HTTP_ENCRYPT_ALWAYS
;
309 encrypt
= HTTP_ENCRYPT_IF_REQUESTED
;
311 return (httpConnectEncrypt(host
, port
, encrypt
));
316 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
319 http_t
* /* O - New HTTP connection */
320 httpConnectEncrypt(const char *host
, /* I - Host to connect to */
321 int port
, /* I - Port number */
322 http_encryption_t encrypt
)
323 /* I - Type of encryption to use */
325 int i
; /* Looping var */
326 http_t
*http
; /* New HTTP connection */
327 struct hostent
*hostaddr
; /* Host address data */
339 if ((hostaddr
= httpGetHostByName(host
)) == NULL
)
342 * This hack to make users that don't have a localhost entry in
343 * their hosts file or DNS happy...
346 if (strcasecmp(host
, "localhost") != 0)
348 else if ((hostaddr
= httpGetHostByName("127.0.0.1")) == NULL
)
353 * Verify that it is an IPv4 address (IPv6 support will come in CUPS 1.2...)
356 if (hostaddr
->h_addrtype
!= AF_INET
|| hostaddr
->h_length
!= 4)
360 * Allocate memory for the structure...
363 http
= calloc(sizeof(http_t
), 1);
367 http
->version
= HTTP_1_1
;
369 http
->activity
= time(NULL
);
373 * Copy the hostname and port and then "reconnect"...
376 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
377 http
->hostaddr
.sin_family
= hostaddr
->h_addrtype
;
379 http
->hostaddr
.sin_port
= htons((u_short
)port
);
381 http
->hostaddr
.sin_port
= htons(port
);
385 * Set the encryption status...
388 if (port
== 443) /* Always use encryption for https */
389 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
391 http
->encryption
= encrypt
;
394 * Loop through the addresses we have until one of them connects...
397 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
399 for (i
= 0; hostaddr
->h_addr_list
[i
]; i
++)
402 * Load the address...
405 memcpy((char *)&(http
->hostaddr
.sin_addr
), hostaddr
->h_addr_list
[i
],
409 * Connect to the remote system...
412 if (!httpReconnect(http
))
417 * Could not connect to any known address - bail out!
426 * 'httpEncryption()' - Set the required encryption on the link.
429 int /* O - -1 on error, 0 on success */
430 httpEncryption(http_t
*http
, /* I - HTTP data */
431 http_encryption_t e
) /* I - New encryption preference */
437 http
->encryption
= e
;
439 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
440 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
441 return (httpReconnect(http
));
442 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
443 return (http_upgrade(http
));
447 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
451 #endif /* HAVE_SSL */
456 * 'httpReconnect()' - Reconnect to a HTTP server...
459 int /* O - 0 on success, non-zero on failure */
460 httpReconnect(http_t
*http
) /* I - HTTP data */
462 int val
; /* Socket option value */
466 http_shutdown_ssl(http
);
467 #endif /* HAVE_SSL */
470 * Close any previously open socket...
475 closesocket(http
->fd
);
481 * Create the socket and set options to allow reuse.
484 if ((http
->fd
= socket(AF_INET
, SOCK_STREAM
, 0)) < 0)
487 http
->error
= WSAGetLastError();
491 http
->status
= HTTP_ERROR
;
496 fcntl(http
->fd
, F_SETFD
, FD_CLOEXEC
); /* Close this socket when starting *
497 * other processes... */
498 #endif /* FD_CLOEXEC */
501 setsockopt(http
->fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *)&val
, sizeof(val
));
505 setsockopt(http
->fd
, SOL_SOCKET
, SO_REUSEPORT
, &val
, sizeof(val
));
506 #endif /* SO_REUSEPORT */
509 * Using TCP_NODELAY improves responsiveness, especially on systems
510 * with a slow loopback interface... Since we write large buffers
511 * when sending print files and requests, there shouldn't be any
512 * performance penalty for this...
516 setsockopt(http
->fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
519 * Connect to the server...
522 if (connect(http
->fd
, (struct sockaddr
*)&(http
->hostaddr
),
523 sizeof(http
->hostaddr
)) < 0)
526 http
->error
= WSAGetLastError();
530 http
->status
= HTTP_ERROR
;
533 closesocket(http
->fd
);
544 http
->status
= HTTP_CONTINUE
;
547 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
550 * Always do encryption via SSL.
553 if (http_setup_ssl(http
) != 0)
556 closesocket(http
->fd
);
564 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
565 return (http_upgrade(http
));
566 #endif /* HAVE_SSL */
573 * 'httpGetSubField()' - Get a sub-field value.
576 char * /* O - Value or NULL */
577 httpGetSubField(http_t
*http
, /* I - HTTP data */
578 http_field_t field
, /* I - Field index */
579 const char *name
, /* I - Name of sub-field */
580 char *value
) /* O - Value string */
582 const char *fptr
; /* Pointer into field */
583 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
584 *ptr
; /* Pointer into string buffer */
588 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
589 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
590 name
== NULL
|| value
== NULL
)
593 DEBUG_printf(("httpGetSubField(%p, %d, \"%s\", %p)\n",
594 http
, field
, name
, value
));
596 for (fptr
= http
->fields
[field
]; *fptr
;)
599 * Skip leading whitespace...
602 while (isspace(*fptr
))
612 * Get the sub-field name...
616 *fptr
&& *fptr
!= '=' && !isspace(*fptr
) && ptr
< (temp
+ sizeof(temp
) - 1);
621 DEBUG_printf(("name = \"%s\"\n", temp
));
624 * Skip trailing chars up to the '='...
627 while (isspace(*fptr
))
637 * Skip = and leading whitespace...
642 while (isspace(*fptr
))
648 * Read quoted string...
651 for (ptr
= value
, fptr
++;
652 *fptr
&& *fptr
!= '\"' && ptr
< (value
+ HTTP_MAX_VALUE
- 1);
657 while (*fptr
&& *fptr
!= '\"')
666 * Read unquoted string...
670 *fptr
&& !isspace(*fptr
) && *fptr
!= ',' && ptr
< (value
+ HTTP_MAX_VALUE
- 1);
675 while (*fptr
&& !isspace(*fptr
) && *fptr
!= ',')
679 DEBUG_printf(("value = \"%s\"\n", value
));
682 * See if this is the one...
685 if (strcmp(name
, temp
) == 0)
696 * 'httpSetField()' - Set the value of an HTTP header.
700 httpSetField(http_t
*http
, /* I - HTTP data */
701 http_field_t field
, /* I - Field index */
702 const char *value
) /* I - Value */
705 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
706 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
710 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
715 * 'httpDelete()' - Send a DELETE request to the server.
718 int /* O - Status of call (0 = success) */
719 httpDelete(http_t
*http
, /* I - HTTP data */
720 const char *uri
) /* I - URI to delete */
722 return (http_send(http
, HTTP_DELETE
, uri
));
727 * 'httpGet()' - Send a GET request to the server.
730 int /* O - Status of call (0 = success) */
731 httpGet(http_t
*http
, /* I - HTTP data */
732 const char *uri
) /* I - URI to get */
734 return (http_send(http
, HTTP_GET
, uri
));
739 * 'httpHead()' - Send a HEAD request to the server.
742 int /* O - Status of call (0 = success) */
743 httpHead(http_t
*http
, /* I - HTTP data */
744 const char *uri
) /* I - URI for head */
746 return (http_send(http
, HTTP_HEAD
, uri
));
751 * 'httpOptions()' - Send an OPTIONS request to the server.
754 int /* O - Status of call (0 = success) */
755 httpOptions(http_t
*http
, /* I - HTTP data */
756 const char *uri
) /* I - URI for options */
758 return (http_send(http
, HTTP_OPTIONS
, uri
));
763 * 'httpPost()' - Send a POST request to the server.
766 int /* O - Status of call (0 = success) */
767 httpPost(http_t
*http
, /* I - HTTP data */
768 const char *uri
) /* I - URI for post */
772 return (http_send(http
, HTTP_POST
, uri
));
777 * 'httpPut()' - Send a PUT request to the server.
780 int /* O - Status of call (0 = success) */
781 httpPut(http_t
*http
, /* I - HTTP data */
782 const char *uri
) /* I - URI to put */
786 return (http_send(http
, HTTP_PUT
, uri
));
791 * 'httpTrace()' - Send an TRACE request to the server.
794 int /* O - Status of call (0 = success) */
795 httpTrace(http_t
*http
, /* I - HTTP data */
796 const char *uri
) /* I - URI for trace */
798 return (http_send(http
, HTTP_TRACE
, uri
));
803 * 'httpFlush()' - Flush data from a HTTP connection.
807 httpFlush(http_t
*http
) /* I - HTTP data */
809 char buffer
[8192]; /* Junk buffer */
812 while (httpRead(http
, buffer
, sizeof(buffer
)) > 0);
817 * 'httpRead()' - Read data from a HTTP connection.
820 int /* O - Number of bytes read */
821 httpRead(http_t
*http
, /* I - HTTP data */
822 char *buffer
, /* I - Buffer for data */
823 int length
) /* I - Maximum number of bytes */
825 int bytes
; /* Bytes read */
826 char len
[32]; /* Length string */
829 DEBUG_printf(("httpRead(%p, %p, %d)\n", http
, buffer
, length
));
831 if (http
== NULL
|| buffer
== NULL
)
834 http
->activity
= time(NULL
);
839 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
840 http
->data_remaining
<= 0)
842 DEBUG_puts("httpRead: Getting chunk length...");
844 if (httpGets(len
, sizeof(len
), http
) == NULL
)
846 DEBUG_puts("httpRead: Could not get length!");
850 http
->data_remaining
= strtol(len
, NULL
, 16);
851 if (http
->data_remaining
< 0)
853 DEBUG_puts("httpRead: Negative chunk length!");
858 DEBUG_printf(("httpRead: data_remaining = %d\n", http
->data_remaining
));
860 if (http
->data_remaining
<= 0)
863 * A zero-length chunk ends a transfer; unless we are reading POST
867 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
868 httpGets(len
, sizeof(len
), http
);
870 if (http
->state
== HTTP_POST_RECV
)
873 http
->state
= HTTP_WAITING
;
877 else if (length
> http
->data_remaining
)
878 length
= http
->data_remaining
;
880 if (http
->used
== 0 && length
<= 256)
883 * Buffer small reads for better performance...
886 if (http
->data_remaining
> sizeof(http
->buffer
))
887 bytes
= sizeof(http
->buffer
);
889 bytes
= http
->data_remaining
;
893 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
895 #endif /* HAVE_SSL */
897 DEBUG_printf(("httpRead: reading %d bytes from socket into buffer...\n",
900 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
902 DEBUG_printf(("httpRead: read %d bytes from socket into buffer...\n",
911 http
->error
= WSAGetLastError();
927 if (length
> http
->used
)
932 DEBUG_printf(("httpRead: grabbing %d bytes from input buffer...\n", bytes
));
934 memcpy(buffer
, http
->buffer
, length
);
935 http
->used
-= length
;
938 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
942 bytes
= http_read_ssl(http
, buffer
, length
);
943 #endif /* HAVE_SSL */
946 DEBUG_printf(("httpRead: reading %d bytes from socket...\n", length
));
947 bytes
= recv(http
->fd
, buffer
, length
, 0);
948 DEBUG_printf(("httpRead: read %d bytes from socket...\n", bytes
));
952 http
->data_remaining
-= bytes
;
956 http
->error
= WSAGetLastError();
965 if (http
->data_remaining
== 0)
967 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
968 httpGets(len
, sizeof(len
), http
);
970 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
972 if (http
->state
== HTTP_POST_RECV
)
975 http
->state
= HTTP_WAITING
;
982 printf("httpRead: Read %d bytes:\n", bytes
);
983 for (i
= 0; i
< bytes
; i
+= 16)
987 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
988 printf(" %02X", buffer
[i
+ j
] & 255);
997 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
999 ch
= buffer
[i
+ j
] & 255;
1001 if (ch
< ' ' || ch
== 127)
1016 * 'httpWait()' - Wait for data available on a connection.
1019 int /* O - 1 if data is available, 0 otherwise */
1020 httpWait(http_t
*http
, /* I - HTTP data */
1021 int msec
) /* I - Milliseconds to wait */
1023 struct rlimit limit
; /* Runtime limit */
1024 struct timeval timeout
; /* Timeout */
1028 * First see if there is data in the buffer...
1038 * Then try doing a select() to poll the socket...
1041 if (!http
->input_set
)
1044 * Allocate the select() input set based upon the max number of file
1045 * descriptors available for this process...
1048 getrlimit(RLIMIT_NOFILE
, &limit
);
1050 http
->input_set
= calloc(1, (limit
.rlim_cur
+ 7) / 8);
1052 if (!http
->input_set
)
1056 FD_SET(http
->fd
, http
->input_set
);
1060 timeout
.tv_sec
= msec
/ 1000;
1061 timeout
.tv_usec
= (msec
% 1000) * 1000;
1063 return (select(http
->fd
+ 1, http
->input_set
, NULL
, NULL
, &timeout
) > 0);
1066 return (select(http
->fd
+ 1, http
->input_set
, NULL
, NULL
, NULL
) > 0);
1071 * 'httpWrite()' - Write data to a HTTP connection.
1074 int /* O - Number of bytes written */
1075 httpWrite(http_t
*http
, /* I - HTTP data */
1076 const char *buffer
, /* I - Buffer for data */
1077 int length
) /* I - Number of bytes to write */
1079 int tbytes
, /* Total bytes sent */
1080 bytes
; /* Bytes sent */
1083 if (http
== NULL
|| buffer
== NULL
)
1086 http
->activity
= time(NULL
);
1088 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1090 if (httpPrintf(http
, "%x\r\n", length
) < 0)
1096 * A zero-length chunk ends a transfer; unless we are sending POST
1100 DEBUG_puts("httpWrite: changing states...");
1102 if (http
->state
== HTTP_POST_RECV
)
1104 else if (http
->state
== HTTP_PUT_RECV
)
1105 http
->state
= HTTP_STATUS
;
1107 http
->state
= HTTP_WAITING
;
1109 if (httpPrintf(http
, "\r\n") < 0)
1122 bytes
= http_write_ssl(http
, buffer
, length
);
1124 #endif /* HAVE_SSL */
1125 bytes
= send(http
->fd
, buffer
, length
, 0);
1130 if (WSAGetLastError() != http
->error
)
1132 http
->error
= WSAGetLastError();
1138 else if (errno
!= http
->error
)
1140 http
->error
= errno
;
1145 DEBUG_puts("httpWrite: error writing data...\n");
1153 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1154 http
->data_remaining
-= bytes
;
1157 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1158 if (httpPrintf(http
, "\r\n") < 0)
1161 if (http
->data_remaining
== 0 && http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1164 * Finished with the transfer; unless we are sending POST data, go idle...
1167 DEBUG_puts("httpWrite: changing states...");
1169 if (http
->state
== HTTP_POST_RECV
)
1172 http
->state
= HTTP_WAITING
;
1178 printf("httpWrite: wrote %d bytes: \n", tbytes
);
1179 for (i
= 0, buffer
-= tbytes
; i
< tbytes
; i
+= 16)
1183 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
1184 printf(" %02X", buffer
[i
+ j
] & 255);
1193 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
1195 ch
= buffer
[i
+ j
] & 255;
1197 if (ch
< ' ' || ch
== 127)
1211 * 'httpGets()' - Get a line of text from a HTTP connection.
1214 char * /* O - Line or NULL */
1215 httpGets(char *line
, /* I - Line to read into */
1216 int length
, /* I - Max length of buffer */
1217 http_t
*http
) /* I - HTTP data */
1219 char *lineptr
, /* Pointer into line */
1220 *bufptr
, /* Pointer into input buffer */
1221 *bufend
; /* Pointer to end of buffer */
1222 int bytes
; /* Number of bytes read */
1225 DEBUG_printf(("httpGets(%p, %d, %p)\n", line
, length
, http
));
1227 if (http
== NULL
|| line
== NULL
)
1231 * Pre-scan the buffer and see if there is a newline in there...
1242 bufptr
= http
->buffer
;
1243 bufend
= http
->buffer
+ http
->used
;
1245 while (bufptr
< bufend
)
1246 if (*bufptr
== 0x0a)
1251 if (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
)
1254 * No newline; see if there is more data to be read...
1257 if (!http
->blocking
&& !httpWait(http
, 1000))
1262 bytes
= http_read_ssl(http
, bufend
, HTTP_MAX_BUFFER
- http
->used
);
1264 #endif /* HAVE_SSL */
1265 bytes
= recv(http
->fd
, bufend
, HTTP_MAX_BUFFER
- http
->used
, 0);
1270 * Nope, can't get a line this time...
1274 if (WSAGetLastError() != http
->error
)
1276 http
->error
= WSAGetLastError();
1280 DEBUG_printf(("httpGets(): recv() error %d!\n", WSAGetLastError()));
1284 else if (errno
!= http
->error
)
1286 http
->error
= errno
;
1290 DEBUG_printf(("httpGets(): recv() error %d!\n", errno
));
1295 else if (bytes
== 0)
1298 http
->error
= EPIPE
;
1304 * Yup, update the amount used and the end pointer...
1307 http
->used
+= bytes
;
1312 while (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
);
1314 http
->activity
= time(NULL
);
1317 * Read a line from the buffer...
1321 bufptr
= http
->buffer
;
1325 while (bufptr
< bufend
&& bytes
< length
)
1329 if (*bufptr
== 0x0a)
1334 else if (*bufptr
== 0x0d)
1337 *lineptr
++ = *bufptr
++;
1344 http
->used
-= bytes
;
1346 memmove(http
->buffer
, bufptr
, http
->used
);
1348 DEBUG_printf(("httpGets(): Returning \"%s\"\n", line
));
1352 DEBUG_puts("httpGets(): No new line available!");
1359 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1362 int /* O - Number of bytes written */
1363 httpPrintf(http_t
*http
, /* I - HTTP data */
1364 const char *format
, /* I - printf-style format string */
1365 ...) /* I - Additional args as needed */
1367 int bytes
, /* Number of bytes to write */
1368 nbytes
, /* Number of bytes written */
1369 tbytes
; /* Number of bytes all together */
1370 char buf
[HTTP_MAX_BUFFER
], /* Buffer for formatted string */
1371 *bufptr
; /* Pointer into buffer */
1372 va_list ap
; /* Variable argument pointer */
1375 va_start(ap
, format
);
1376 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1379 DEBUG_printf(("httpPrintf: %s", buf
));
1381 for (tbytes
= 0, bufptr
= buf
; tbytes
< bytes
; tbytes
+= nbytes
, bufptr
+= nbytes
)
1385 nbytes
= http_write_ssl(http
, bufptr
, bytes
- tbytes
);
1387 #endif /* HAVE_SSL */
1388 nbytes
= send(http
->fd
, bufptr
, bytes
- tbytes
, 0);
1395 if (WSAGetLastError() != http
->error
)
1397 http
->error
= WSAGetLastError();
1403 else if (errno
!= http
->error
)
1405 http
->error
= errno
;
1419 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
1422 const char * /* O - Date/time string */
1423 httpGetDateString(time_t t
) /* I - UNIX time */
1426 static char datetime
[256];
1430 snprintf(datetime
, sizeof(datetime
), "%s, %02d %s %d %02d:%02d:%02d GMT",
1431 days
[tdate
->tm_wday
], tdate
->tm_mday
, months
[tdate
->tm_mon
],
1432 tdate
->tm_year
+ 1900, tdate
->tm_hour
, tdate
->tm_min
, tdate
->tm_sec
);
1439 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
1442 time_t /* O - UNIX time */
1443 httpGetDateTime(const char *s
) /* I - Date/time string */
1445 int i
; /* Looping var */
1446 struct tm tdate
; /* Time/date structure */
1447 char mon
[16]; /* Abbreviated month name */
1448 int day
, year
; /* Day of month and year */
1449 int hour
, min
, sec
; /* Time */
1452 if (sscanf(s
, "%*s%d%15s%d%d:%d:%d", &day
, mon
, &year
, &hour
, &min
, &sec
) < 6)
1455 for (i
= 0; i
< 12; i
++)
1456 if (strcasecmp(mon
, months
[i
]) == 0)
1463 tdate
.tm_mday
= day
;
1464 tdate
.tm_year
= year
- 1900;
1465 tdate
.tm_hour
= hour
;
1470 return (mktime(&tdate
));
1475 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1478 http_status_t
/* O - HTTP status */
1479 httpUpdate(http_t
*http
) /* I - HTTP data */
1481 char line
[1024], /* Line from connection... */
1482 *value
; /* Pointer to value on line */
1483 http_field_t field
; /* Field index */
1484 int major
, minor
; /* HTTP version numbers */
1485 http_status_t status
; /* Authorization status */
1488 DEBUG_printf(("httpUpdate(%p)\n", http
));
1491 * If we haven't issued any commands, then there is nothing to "update"...
1494 if (http
->state
== HTTP_WAITING
)
1495 return (HTTP_CONTINUE
);
1498 * Grab all of the lines we can from the connection...
1501 while (httpGets(line
, sizeof(line
), http
) != NULL
)
1505 if (line
[0] == '\0')
1508 * Blank line means the start of the data section (if any). Return
1509 * the result code, too...
1511 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
1512 * Instead, we just return HTTP_CONTINUE to the caller and keep on
1516 if (http
->status
== HTTP_CONTINUE
)
1517 return (http
->status
);
1520 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
1522 if (http_setup_ssl(http
) != 0)
1525 closesocket(http
->fd
);
1530 return (HTTP_ERROR
);
1533 return (HTTP_CONTINUE
);
1535 #endif /* HAVE_SSL */
1537 httpGetLength(http
);
1539 switch (http
->state
)
1543 case HTTP_POST_RECV
:
1549 http
->state
= HTTP_WAITING
;
1553 return (http
->status
);
1555 else if (strncmp(line
, "HTTP/", 5) == 0)
1558 * Got the beginning of a response...
1561 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, (int *)&status
) != 3)
1562 return (HTTP_ERROR
);
1564 http
->version
= (http_version_t
)(major
* 100 + minor
);
1565 http
->status
= status
;
1567 else if ((value
= strchr(line
, ':')) != NULL
)
1574 while (isspace(*value
))
1578 * Be tolerants of servers that send unknown attribute fields...
1581 if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
1583 DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line
));
1587 httpSetField(http
, field
, value
);
1591 http
->status
= HTTP_ERROR
;
1592 return (HTTP_ERROR
);
1597 * See if there was an error...
1602 http
->status
= HTTP_ERROR
;
1603 return (HTTP_ERROR
);
1607 * If we haven't already returned, then there is nothing new...
1610 return (HTTP_CONTINUE
);
1615 * 'httpDecode64()' - Base64-decode a string.
1618 char * /* O - Decoded string */
1619 httpDecode64(char *out
, /* I - String to write to */
1620 const char *in
) /* I - String to read from */
1622 int pos
, /* Bit position */
1623 base64
; /* Value of this character */
1624 char *outptr
; /* Output pointer */
1627 for (outptr
= out
, pos
= 0; *in
!= '\0'; in
++)
1630 * Decode this character into a number from 0 to 63...
1633 if (*in
>= 'A' && *in
<= 'Z')
1635 else if (*in
>= 'a' && *in
<= 'z')
1636 base64
= *in
- 'a' + 26;
1637 else if (*in
>= '0' && *in
<= '9')
1638 base64
= *in
- '0' + 52;
1639 else if (*in
== '+')
1641 else if (*in
== '/')
1643 else if (*in
== '=')
1649 * Store the result in the appropriate chars...
1655 *outptr
= base64
<< 2;
1659 *outptr
++ |= (base64
>> 4) & 3;
1660 *outptr
= (base64
<< 4) & 255;
1664 *outptr
++ |= (base64
>> 2) & 15;
1665 *outptr
= (base64
<< 6) & 255;
1669 *outptr
++ |= base64
;
1678 * Return the decoded string...
1686 * 'httpEncode64()' - Base64-encode a string.
1689 char * /* O - Encoded string */
1690 httpEncode64(char *out
, /* I - String to write to */
1691 const char *in
) /* I - String to read from */
1693 char *outptr
; /* Output pointer */
1694 static const char base64
[] = /* Base64 characters... */
1696 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1697 "abcdefghijklmnopqrstuvwxyz"
1703 for (outptr
= out
; *in
!= '\0'; in
++)
1706 * Encode the up to 3 characters as 4 Base64 numbers...
1709 *outptr
++ = base64
[in
[0] >> 2];
1710 *outptr
++ = base64
[((in
[0] << 4) | (in
[1] >> 4)) & 63];
1719 *outptr
++ = base64
[((in
[0] << 2) | (in
[1] >> 6)) & 63];
1725 *outptr
++ = base64
[in
[0] & 63];
1732 * Return the encoded string...
1740 * 'httpGetLength()' - Get the amount of data remaining from the
1741 * content-length or transfer-encoding fields.
1744 int /* O - Content length */
1745 httpGetLength(http_t
*http
) /* I - HTTP data */
1747 DEBUG_printf(("httpGetLength(%p)\n", http
));
1749 if (strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked") == 0)
1751 DEBUG_puts("httpGetLength: chunked request!");
1753 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
1754 http
->data_remaining
= 0;
1758 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1761 * The following is a hack for HTTP servers that don't send a
1762 * content-length or transfer-encoding field...
1764 * If there is no content-length then the connection must close
1765 * after the transfer is complete...
1768 if (http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] == '\0')
1769 http
->data_remaining
= 2147483647;
1771 http
->data_remaining
= atoi(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
]);
1773 DEBUG_printf(("httpGetLength: content_length = %d\n", http
->data_remaining
));
1776 return (http
->data_remaining
);
1781 * 'http_field()' - Return the field index for a field name.
1784 static http_field_t
/* O - Field index */
1785 http_field(const char *name
) /* I - String name */
1787 int i
; /* Looping var */
1790 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
1791 if (strcasecmp(name
, http_fields
[i
]) == 0)
1792 return ((http_field_t
)i
);
1794 return (HTTP_FIELD_UNKNOWN
);
1799 * 'http_send()' - Send a request with all fields and the trailing blank line.
1802 static int /* O - 0 on success, non-zero on error */
1803 http_send(http_t
*http
, /* I - HTTP data */
1804 http_state_t request
, /* I - Request code */
1805 const char *uri
) /* I - URI */
1807 int i
; /* Looping var */
1808 char *ptr
, /* Pointer in buffer */
1809 buf
[1024]; /* Encoded URI buffer */
1810 static const char * const codes
[] =
1811 { /* Request code strings */
1826 static const char hex
[] = "0123456789ABCDEF";
1830 if (http
== NULL
|| uri
== NULL
)
1834 * Encode the URI as needed...
1837 for (ptr
= buf
; *uri
!= '\0' && ptr
< (buf
+ sizeof(buf
) - 1); uri
++)
1838 if (*uri
<= ' ' || *uri
>= 127)
1840 if (ptr
< (buf
+ sizeof(buf
) - 1))
1842 if (ptr
< (buf
+ sizeof(buf
) - 1))
1843 *ptr
++ = hex
[(*uri
>> 4) & 15];
1844 if (ptr
< (buf
+ sizeof(buf
) - 1))
1845 *ptr
++ = hex
[*uri
& 15];
1853 * See if we had an error the last time around; if so, reconnect...
1856 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
1857 httpReconnect(http
);
1860 * Send the request header...
1863 http
->state
= request
;
1864 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
1867 http
->status
= HTTP_CONTINUE
;
1870 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
1872 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
1873 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
1875 #endif /* HAVE_SSL */
1877 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
1879 http
->status
= HTTP_ERROR
;
1883 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
1884 if (http
->fields
[i
][0] != '\0')
1886 DEBUG_printf(("%s: %s\n", http_fields
[i
], http
->fields
[i
]));
1888 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], http
->fields
[i
]) < 1)
1890 http
->status
= HTTP_ERROR
;
1895 if (httpPrintf(http
, "\r\n") < 1)
1897 http
->status
= HTTP_ERROR
;
1901 httpClearFields(http
);
1909 * 'http_upgrade()' - Force upgrade to TLS encryption.
1912 static int /* O - Status of connection */
1913 http_upgrade(http_t
*http
) /* I - HTTP data */
1915 int ret
; /* Return value */
1916 http_t myhttp
; /* Local copy of HTTP data */
1919 DEBUG_printf(("http_upgrade(%p)\n", http
));
1922 * Copy the HTTP data to a local variable so we can do the OPTIONS
1923 * request without interfering with the existing request data...
1926 memcpy(&myhttp
, http
, sizeof(myhttp
));
1929 * Send an OPTIONS request to the server, requiring SSL or TLS
1930 * encryption on the link...
1933 httpClearFields(&myhttp
);
1934 httpSetField(&myhttp
, HTTP_FIELD_CONNECTION
, "upgrade");
1935 httpSetField(&myhttp
, HTTP_FIELD_UPGRADE
, "TLS/1.0, SSL/2.0, SSL/3.0");
1937 if ((ret
= httpOptions(&myhttp
, "*")) == 0)
1940 * Wait for the secure connection...
1943 while (httpUpdate(&myhttp
) == HTTP_CONTINUE
);
1949 * Copy the HTTP data back over, if any...
1952 http
->fd
= myhttp
.fd
;
1953 http
->error
= myhttp
.error
;
1954 http
->activity
= myhttp
.activity
;
1955 http
->status
= myhttp
.status
;
1956 http
->version
= myhttp
.version
;
1957 http
->keep_alive
= myhttp
.keep_alive
;
1958 http
->used
= myhttp
.used
;
1961 memcpy(http
->buffer
, myhttp
.buffer
, http
->used
);
1963 http
->auth_type
= myhttp
.auth_type
;
1964 http
->nonce_count
= myhttp
.nonce_count
;
1966 memcpy(http
->nonce
, myhttp
.nonce
, sizeof(http
->nonce
));
1968 http
->tls
= myhttp
.tls
;
1969 http
->encryption
= myhttp
.encryption
;
1972 * See if we actually went secure...
1978 * Server does not support HTTP upgrade...
1981 DEBUG_puts("Server does not support HTTP upgrade!");
1984 closesocket(http
->fd
);
1999 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
2002 static int /* O - Status of connection */
2003 http_setup_ssl(http_t
*http
) /* I - HTTP data */
2006 SSL_CTX
*context
; /* Context for encryption */
2007 SSL
*conn
; /* Connection for encryption */
2008 # elif defined(HAVE_GNUTLS)
2009 http_tls_t
*conn
; /* TLS session object */
2010 gnutls_certificate_client_credentials
*credentials
;
2011 /* TLS credentials */
2012 # elif defined(HAVE_CDSASSL)
2013 SSLContextRef conn
; /* Context for encryption */
2014 OSStatus error
; /* Error info */
2015 # endif /* HAVE_LIBSSL */
2019 context
= SSL_CTX_new(SSLv23_client_method());
2020 conn
= SSL_new(context
);
2022 SSL_set_fd(conn
, http
->fd
);
2023 if (SSL_connect(conn
) != 1)
2025 SSL_CTX_free(context
);
2029 http
->error
= WSAGetLastError();
2031 http
->error
= errno
;
2033 http
->status
= HTTP_ERROR
;
2035 return (HTTP_ERROR
);
2038 # elif defined(HAVE_GNUTLS)
2039 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
2043 http
->error
= errno
;
2044 http
->status
= HTTP_ERROR
;
2049 credentials
= (gnutls_certificate_client_credentials
*)
2050 malloc(sizeof(gnutls_certificate_client_credentials
));
2051 if (credentials
== NULL
)
2055 http
->error
= errno
;
2056 http
->status
= HTTP_ERROR
;
2061 gnutls_certificate_allocate_credentials(credentials
);
2063 gnutls_init(&(conn
->session
), GNUTLS_CLIENT
);
2064 gnutls_set_default_priority(conn
->session
);
2065 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
2066 gnutls_transport_set_ptr(conn
->session
, http
->fd
);
2068 if ((gnutls_handshake(conn
->session
)) != GNUTLS_E_SUCCESS
)
2070 http
->error
= errno
;
2071 http
->status
= HTTP_ERROR
;
2076 conn
->credentials
= credentials
;
2078 # elif defined(HAVE_CDSASSL)
2079 error
= SSLNewContext(false, &conn
);
2082 error
= SSLSetIOFuncs(conn
, CDSAReadFunc
, CDSAWriteFunc
);
2085 error
= SSLSetConnection(conn
, (SSLConnectionRef
)http
->fd
);
2088 error
= SSLSetAllowsExpiredCerts(conn
, true);
2091 error
= SSLSetAllowsAnyRoot(conn
, true);
2094 error
= SSLHandshake(conn
);
2098 http
->error
= error
;
2099 http
->status
= HTTP_ERROR
;
2101 SSLDisposeContext(conn
);
2107 # endif /* HAVE_CDSASSL */
2115 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
2119 http_shutdown_ssl(http_t
*http
) /* I - HTTP data */
2122 SSL_CTX
*context
; /* Context for encryption */
2123 SSL
*conn
; /* Connection for encryption */
2126 conn
= (SSL
*)(http
->tls
);
2127 context
= SSL_get_SSL_CTX(conn
);
2130 SSL_CTX_free(context
);
2133 # elif defined(HAVE_GNUTLS)
2134 http_tls_t
*conn
; /* Encryption session */
2135 gnutls_certificate_client_credentials
*credentials
;
2136 /* TLS credentials */
2139 conn
= (http_tls_t
*)(http
->tls
);
2140 credentials
= (gnutls_certificate_client_credentials
*)(conn
->credentials
);
2142 gnutls_bye(conn
->session
, GNUTLS_SHUT_RDWR
);
2143 gnutls_deinit(conn
->session
);
2144 gnutls_certificate_free_credentials(*credentials
);
2148 # elif defined(HAVE_CDSASSL)
2149 SSLClose((SSLContextRef
)http
->tls
);
2150 SSLDisposeContext((SSLContextRef
)http
->tls
);
2151 # endif /* HAVE_LIBSSL */
2158 * 'http_read_ssl()' - Read from a SSL/TLS connection.
2161 static int /* O - Bytes read */
2162 http_read_ssl(http_t
*http
, /* I - HTTP data */
2163 char *buf
, /* I - Buffer to store data */
2164 int len
) /* I - Length of buffer */
2166 # if defined(HAVE_LIBSSL)
2167 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
2169 # elif defined(HAVE_GNUTLS)
2170 return (gnutls_record_recv(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
2172 # elif defined(HAVE_CDSASSL)
2173 OSStatus error
; /* Error info */
2174 size_t processed
; /* Number of bytes processed */
2177 error
= SSLRead((SSLContextRef
)http
->tls
, buf
, len
, &processed
);
2183 http
->error
= error
;
2187 # endif /* HAVE_LIBSSL */
2192 * 'http_write_ssl()' - Write to a SSL/TLS connection.
2195 static int /* O - Bytes written */
2196 http_write_ssl(http_t
*http
, /* I - HTTP data */
2197 const char *buf
, /* I - Buffer holding data */
2198 int len
) /* I - Length of buffer */
2200 # if defined(HAVE_LIBSSL)
2201 return (SSL_write((SSL
*)(http
->tls
), buf
, len
));
2203 # elif defined(HAVE_GNUTLS)
2204 return (gnutls_record_send(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
2205 # elif defined(HAVE_CDSASSL)
2206 OSStatus error
; /* Error info */
2207 size_t processed
; /* Number of bytes processed */
2210 error
= SSLWrite((SSLContextRef
)http
->tls
, buf
, len
, &processed
);
2216 http
->error
= error
;
2219 # endif /* HAVE_LIBSSL */
2223 # if defined(HAVE_CDSASSL)
2225 * 'CDSAReadFunc()' - Read function for CDSA decryption code.
2228 static OSStatus
/* O - -1 on error, 0 on success */
2229 CDSAReadFunc(SSLConnectionRef connection
, /* I - SSL/TLS connection */
2230 void *data
, /* I - Data buffer */
2231 size_t *dataLength
) /* IO - Number of bytes */
2233 ssize_t bytes
; /* Number of bytes read */
2236 bytes
= recv((int)connection
, data
, *dataLength
, 0);
2239 *dataLength
= bytes
;
2248 * 'CDSAWriteFunc()' - Write function for CDSA encryption code.
2251 static OSStatus
/* O - -1 on error, 0 on success */
2252 CDSAWriteFunc(SSLConnectionRef connection
, /* I - SSL/TLS connection */
2253 const void *data
, /* I - Data buffer */
2254 size_t *dataLength
) /* IO - Number of bytes */
2259 bytes
= write((int)connection
, data
, *dataLength
);
2262 *dataLength
= bytes
;
2268 # endif /* HAVE_CDSASSL */
2269 #endif /* HAVE_SSL */
2273 * End of "$Id: http.c,v 1.112 2003/02/11 16:23:53 mike Exp $".