2 * "$Id: http.c,v 1.114 2003/03/03 17:59:56 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...
84 #include "http-private.h"
89 # include <sys/time.h>
90 # include <sys/resource.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 */
1024 struct rlimit limit
; /* Runtime limit */
1026 struct timeval timeout
; /* Timeout */
1027 int nfds
; /* Result from select() */
1031 * First see if there is data in the buffer...
1041 * Then try doing a select() to poll the socket...
1044 if (!http
->input_set
)
1048 * Windows has a fixed-size select() structure, different (surprise,
1049 * surprise!) from all UNIX implementations. Just allocate this
1050 * fixed structure...
1053 http
->input_set
= calloc(1, sizeof(fd_set
));
1056 * Allocate the select() input set based upon the max number of file
1057 * descriptors available for this process...
1060 getrlimit(RLIMIT_NOFILE
, &limit
);
1062 http
->input_set
= calloc(1, (limit
.rlim_cur
+ 7) / 8);
1065 if (!http
->input_set
)
1069 FD_SET(http
->fd
, http
->input_set
);
1073 timeout
.tv_sec
= msec
/ 1000;
1074 timeout
.tv_usec
= (msec
% 1000) * 1000;
1076 nfds
= select(http
->fd
+ 1, http
->input_set
, NULL
, NULL
, &timeout
);
1079 nfds
= select(http
->fd
+ 1, http
->input_set
, NULL
, NULL
, NULL
);
1081 FD_CLR(http
->fd
, http
->input_set
);
1088 * 'httpWrite()' - Write data to a HTTP connection.
1091 int /* O - Number of bytes written */
1092 httpWrite(http_t
*http
, /* I - HTTP data */
1093 const char *buffer
, /* I - Buffer for data */
1094 int length
) /* I - Number of bytes to write */
1096 int tbytes
, /* Total bytes sent */
1097 bytes
; /* Bytes sent */
1100 if (http
== NULL
|| buffer
== NULL
)
1103 http
->activity
= time(NULL
);
1105 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1107 if (httpPrintf(http
, "%x\r\n", length
) < 0)
1113 * A zero-length chunk ends a transfer; unless we are sending POST
1117 DEBUG_puts("httpWrite: changing states...");
1119 if (http
->state
== HTTP_POST_RECV
)
1121 else if (http
->state
== HTTP_PUT_RECV
)
1122 http
->state
= HTTP_STATUS
;
1124 http
->state
= HTTP_WAITING
;
1126 if (httpPrintf(http
, "\r\n") < 0)
1139 bytes
= http_write_ssl(http
, buffer
, length
);
1141 #endif /* HAVE_SSL */
1142 bytes
= send(http
->fd
, buffer
, length
, 0);
1147 if (WSAGetLastError() != http
->error
)
1149 http
->error
= WSAGetLastError();
1155 else if (errno
!= http
->error
)
1157 http
->error
= errno
;
1162 DEBUG_puts("httpWrite: error writing data...\n");
1170 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1171 http
->data_remaining
-= bytes
;
1174 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1175 if (httpPrintf(http
, "\r\n") < 0)
1178 if (http
->data_remaining
== 0 && http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1181 * Finished with the transfer; unless we are sending POST data, go idle...
1184 DEBUG_puts("httpWrite: changing states...");
1186 if (http
->state
== HTTP_POST_RECV
)
1189 http
->state
= HTTP_WAITING
;
1195 printf("httpWrite: wrote %d bytes: \n", tbytes
);
1196 for (i
= 0, buffer
-= tbytes
; i
< tbytes
; i
+= 16)
1200 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
1201 printf(" %02X", buffer
[i
+ j
] & 255);
1210 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
1212 ch
= buffer
[i
+ j
] & 255;
1214 if (ch
< ' ' || ch
== 127)
1228 * 'httpGets()' - Get a line of text from a HTTP connection.
1231 char * /* O - Line or NULL */
1232 httpGets(char *line
, /* I - Line to read into */
1233 int length
, /* I - Max length of buffer */
1234 http_t
*http
) /* I - HTTP data */
1236 char *lineptr
, /* Pointer into line */
1237 *bufptr
, /* Pointer into input buffer */
1238 *bufend
; /* Pointer to end of buffer */
1239 int bytes
; /* Number of bytes read */
1242 DEBUG_printf(("httpGets(%p, %d, %p)\n", line
, length
, http
));
1244 if (http
== NULL
|| line
== NULL
)
1248 * Pre-scan the buffer and see if there is a newline in there...
1259 bufptr
= http
->buffer
;
1260 bufend
= http
->buffer
+ http
->used
;
1262 while (bufptr
< bufend
)
1263 if (*bufptr
== 0x0a)
1268 if (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
)
1271 * No newline; see if there is more data to be read...
1274 if (!http
->blocking
&& !httpWait(http
, 1000))
1279 bytes
= http_read_ssl(http
, bufend
, HTTP_MAX_BUFFER
- http
->used
);
1281 #endif /* HAVE_SSL */
1282 bytes
= recv(http
->fd
, bufend
, HTTP_MAX_BUFFER
- http
->used
, 0);
1287 * Nope, can't get a line this time...
1291 if (WSAGetLastError() != http
->error
)
1293 http
->error
= WSAGetLastError();
1297 DEBUG_printf(("httpGets(): recv() error %d!\n", WSAGetLastError()));
1301 else if (errno
!= http
->error
)
1303 http
->error
= errno
;
1307 DEBUG_printf(("httpGets(): recv() error %d!\n", errno
));
1312 else if (bytes
== 0)
1315 http
->error
= EPIPE
;
1321 * Yup, update the amount used and the end pointer...
1324 http
->used
+= bytes
;
1329 while (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
);
1331 http
->activity
= time(NULL
);
1334 * Read a line from the buffer...
1338 bufptr
= http
->buffer
;
1342 while (bufptr
< bufend
&& bytes
< length
)
1346 if (*bufptr
== 0x0a)
1351 else if (*bufptr
== 0x0d)
1354 *lineptr
++ = *bufptr
++;
1361 http
->used
-= bytes
;
1363 memmove(http
->buffer
, bufptr
, http
->used
);
1365 DEBUG_printf(("httpGets(): Returning \"%s\"\n", line
));
1369 DEBUG_puts("httpGets(): No new line available!");
1376 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1379 int /* O - Number of bytes written */
1380 httpPrintf(http_t
*http
, /* I - HTTP data */
1381 const char *format
, /* I - printf-style format string */
1382 ...) /* I - Additional args as needed */
1384 int bytes
, /* Number of bytes to write */
1385 nbytes
, /* Number of bytes written */
1386 tbytes
; /* Number of bytes all together */
1387 char buf
[HTTP_MAX_BUFFER
], /* Buffer for formatted string */
1388 *bufptr
; /* Pointer into buffer */
1389 va_list ap
; /* Variable argument pointer */
1392 va_start(ap
, format
);
1393 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1396 DEBUG_printf(("httpPrintf: %s", buf
));
1398 for (tbytes
= 0, bufptr
= buf
; tbytes
< bytes
; tbytes
+= nbytes
, bufptr
+= nbytes
)
1402 nbytes
= http_write_ssl(http
, bufptr
, bytes
- tbytes
);
1404 #endif /* HAVE_SSL */
1405 nbytes
= send(http
->fd
, bufptr
, bytes
- tbytes
, 0);
1412 if (WSAGetLastError() != http
->error
)
1414 http
->error
= WSAGetLastError();
1420 else if (errno
!= http
->error
)
1422 http
->error
= errno
;
1436 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
1439 const char * /* O - Date/time string */
1440 httpGetDateString(time_t t
) /* I - UNIX time */
1443 static char datetime
[256];
1447 snprintf(datetime
, sizeof(datetime
), "%s, %02d %s %d %02d:%02d:%02d GMT",
1448 days
[tdate
->tm_wday
], tdate
->tm_mday
, months
[tdate
->tm_mon
],
1449 tdate
->tm_year
+ 1900, tdate
->tm_hour
, tdate
->tm_min
, tdate
->tm_sec
);
1456 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
1459 time_t /* O - UNIX time */
1460 httpGetDateTime(const char *s
) /* I - Date/time string */
1462 int i
; /* Looping var */
1463 struct tm tdate
; /* Time/date structure */
1464 char mon
[16]; /* Abbreviated month name */
1465 int day
, year
; /* Day of month and year */
1466 int hour
, min
, sec
; /* Time */
1469 if (sscanf(s
, "%*s%d%15s%d%d:%d:%d", &day
, mon
, &year
, &hour
, &min
, &sec
) < 6)
1472 for (i
= 0; i
< 12; i
++)
1473 if (strcasecmp(mon
, months
[i
]) == 0)
1480 tdate
.tm_mday
= day
;
1481 tdate
.tm_year
= year
- 1900;
1482 tdate
.tm_hour
= hour
;
1487 return (mktime(&tdate
));
1492 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1495 http_status_t
/* O - HTTP status */
1496 httpUpdate(http_t
*http
) /* I - HTTP data */
1498 char line
[1024], /* Line from connection... */
1499 *value
; /* Pointer to value on line */
1500 http_field_t field
; /* Field index */
1501 int major
, minor
; /* HTTP version numbers */
1502 http_status_t status
; /* Authorization status */
1505 DEBUG_printf(("httpUpdate(%p)\n", http
));
1508 * If we haven't issued any commands, then there is nothing to "update"...
1511 if (http
->state
== HTTP_WAITING
)
1512 return (HTTP_CONTINUE
);
1515 * Grab all of the lines we can from the connection...
1518 while (httpGets(line
, sizeof(line
), http
) != NULL
)
1522 if (line
[0] == '\0')
1525 * Blank line means the start of the data section (if any). Return
1526 * the result code, too...
1528 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
1529 * Instead, we just return HTTP_CONTINUE to the caller and keep on
1533 if (http
->status
== HTTP_CONTINUE
)
1534 return (http
->status
);
1537 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
1539 if (http_setup_ssl(http
) != 0)
1542 closesocket(http
->fd
);
1547 return (HTTP_ERROR
);
1550 return (HTTP_CONTINUE
);
1552 #endif /* HAVE_SSL */
1554 httpGetLength(http
);
1556 switch (http
->state
)
1560 case HTTP_POST_RECV
:
1566 http
->state
= HTTP_WAITING
;
1570 return (http
->status
);
1572 else if (strncmp(line
, "HTTP/", 5) == 0)
1575 * Got the beginning of a response...
1578 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, (int *)&status
) != 3)
1579 return (HTTP_ERROR
);
1581 http
->version
= (http_version_t
)(major
* 100 + minor
);
1582 http
->status
= status
;
1584 else if ((value
= strchr(line
, ':')) != NULL
)
1591 while (isspace(*value
))
1595 * Be tolerants of servers that send unknown attribute fields...
1598 if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
1600 DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line
));
1604 httpSetField(http
, field
, value
);
1608 http
->status
= HTTP_ERROR
;
1609 return (HTTP_ERROR
);
1614 * See if there was an error...
1619 http
->status
= HTTP_ERROR
;
1620 return (HTTP_ERROR
);
1624 * If we haven't already returned, then there is nothing new...
1627 return (HTTP_CONTINUE
);
1632 * 'httpDecode64()' - Base64-decode a string.
1635 char * /* O - Decoded string */
1636 httpDecode64(char *out
, /* I - String to write to */
1637 const char *in
) /* I - String to read from */
1639 int pos
, /* Bit position */
1640 base64
; /* Value of this character */
1641 char *outptr
; /* Output pointer */
1644 for (outptr
= out
, pos
= 0; *in
!= '\0'; in
++)
1647 * Decode this character into a number from 0 to 63...
1650 if (*in
>= 'A' && *in
<= 'Z')
1652 else if (*in
>= 'a' && *in
<= 'z')
1653 base64
= *in
- 'a' + 26;
1654 else if (*in
>= '0' && *in
<= '9')
1655 base64
= *in
- '0' + 52;
1656 else if (*in
== '+')
1658 else if (*in
== '/')
1660 else if (*in
== '=')
1666 * Store the result in the appropriate chars...
1672 *outptr
= base64
<< 2;
1676 *outptr
++ |= (base64
>> 4) & 3;
1677 *outptr
= (base64
<< 4) & 255;
1681 *outptr
++ |= (base64
>> 2) & 15;
1682 *outptr
= (base64
<< 6) & 255;
1686 *outptr
++ |= base64
;
1695 * Return the decoded string...
1703 * 'httpEncode64()' - Base64-encode a string.
1706 char * /* O - Encoded string */
1707 httpEncode64(char *out
, /* I - String to write to */
1708 const char *in
) /* I - String to read from */
1710 char *outptr
; /* Output pointer */
1711 static const char base64
[] = /* Base64 characters... */
1713 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1714 "abcdefghijklmnopqrstuvwxyz"
1720 for (outptr
= out
; *in
!= '\0'; in
++)
1723 * Encode the up to 3 characters as 4 Base64 numbers...
1726 *outptr
++ = base64
[in
[0] >> 2];
1727 *outptr
++ = base64
[((in
[0] << 4) | (in
[1] >> 4)) & 63];
1736 *outptr
++ = base64
[((in
[0] << 2) | (in
[1] >> 6)) & 63];
1742 *outptr
++ = base64
[in
[0] & 63];
1749 * Return the encoded string...
1757 * 'httpGetLength()' - Get the amount of data remaining from the
1758 * content-length or transfer-encoding fields.
1761 int /* O - Content length */
1762 httpGetLength(http_t
*http
) /* I - HTTP data */
1764 DEBUG_printf(("httpGetLength(%p)\n", http
));
1766 if (strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked") == 0)
1768 DEBUG_puts("httpGetLength: chunked request!");
1770 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
1771 http
->data_remaining
= 0;
1775 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1778 * The following is a hack for HTTP servers that don't send a
1779 * content-length or transfer-encoding field...
1781 * If there is no content-length then the connection must close
1782 * after the transfer is complete...
1785 if (http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] == '\0')
1786 http
->data_remaining
= 2147483647;
1788 http
->data_remaining
= atoi(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
]);
1790 DEBUG_printf(("httpGetLength: content_length = %d\n", http
->data_remaining
));
1793 return (http
->data_remaining
);
1798 * 'http_field()' - Return the field index for a field name.
1801 static http_field_t
/* O - Field index */
1802 http_field(const char *name
) /* I - String name */
1804 int i
; /* Looping var */
1807 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
1808 if (strcasecmp(name
, http_fields
[i
]) == 0)
1809 return ((http_field_t
)i
);
1811 return (HTTP_FIELD_UNKNOWN
);
1816 * 'http_send()' - Send a request with all fields and the trailing blank line.
1819 static int /* O - 0 on success, non-zero on error */
1820 http_send(http_t
*http
, /* I - HTTP data */
1821 http_state_t request
, /* I - Request code */
1822 const char *uri
) /* I - URI */
1824 int i
; /* Looping var */
1825 char *ptr
, /* Pointer in buffer */
1826 buf
[1024]; /* Encoded URI buffer */
1827 static const char * const codes
[] =
1828 { /* Request code strings */
1843 static const char hex
[] = "0123456789ABCDEF";
1847 if (http
== NULL
|| uri
== NULL
)
1851 * Encode the URI as needed...
1854 for (ptr
= buf
; *uri
!= '\0' && ptr
< (buf
+ sizeof(buf
) - 1); uri
++)
1855 if (*uri
<= ' ' || *uri
>= 127)
1857 if (ptr
< (buf
+ sizeof(buf
) - 1))
1859 if (ptr
< (buf
+ sizeof(buf
) - 1))
1860 *ptr
++ = hex
[(*uri
>> 4) & 15];
1861 if (ptr
< (buf
+ sizeof(buf
) - 1))
1862 *ptr
++ = hex
[*uri
& 15];
1870 * See if we had an error the last time around; if so, reconnect...
1873 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
1874 httpReconnect(http
);
1877 * Send the request header...
1880 http
->state
= request
;
1881 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
1884 http
->status
= HTTP_CONTINUE
;
1887 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
1889 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
1890 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
1892 #endif /* HAVE_SSL */
1894 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
1896 http
->status
= HTTP_ERROR
;
1900 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
1901 if (http
->fields
[i
][0] != '\0')
1903 DEBUG_printf(("%s: %s\n", http_fields
[i
], http
->fields
[i
]));
1905 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], http
->fields
[i
]) < 1)
1907 http
->status
= HTTP_ERROR
;
1912 if (httpPrintf(http
, "\r\n") < 1)
1914 http
->status
= HTTP_ERROR
;
1918 httpClearFields(http
);
1926 * 'http_upgrade()' - Force upgrade to TLS encryption.
1929 static int /* O - Status of connection */
1930 http_upgrade(http_t
*http
) /* I - HTTP data */
1932 int ret
; /* Return value */
1933 http_t myhttp
; /* Local copy of HTTP data */
1936 DEBUG_printf(("http_upgrade(%p)\n", http
));
1939 * Copy the HTTP data to a local variable so we can do the OPTIONS
1940 * request without interfering with the existing request data...
1943 memcpy(&myhttp
, http
, sizeof(myhttp
));
1946 * Send an OPTIONS request to the server, requiring SSL or TLS
1947 * encryption on the link...
1950 httpClearFields(&myhttp
);
1951 httpSetField(&myhttp
, HTTP_FIELD_CONNECTION
, "upgrade");
1952 httpSetField(&myhttp
, HTTP_FIELD_UPGRADE
, "TLS/1.0, SSL/2.0, SSL/3.0");
1954 if ((ret
= httpOptions(&myhttp
, "*")) == 0)
1957 * Wait for the secure connection...
1960 while (httpUpdate(&myhttp
) == HTTP_CONTINUE
);
1966 * Copy the HTTP data back over, if any...
1969 http
->fd
= myhttp
.fd
;
1970 http
->error
= myhttp
.error
;
1971 http
->activity
= myhttp
.activity
;
1972 http
->status
= myhttp
.status
;
1973 http
->version
= myhttp
.version
;
1974 http
->keep_alive
= myhttp
.keep_alive
;
1975 http
->used
= myhttp
.used
;
1978 memcpy(http
->buffer
, myhttp
.buffer
, http
->used
);
1980 http
->auth_type
= myhttp
.auth_type
;
1981 http
->nonce_count
= myhttp
.nonce_count
;
1983 memcpy(http
->nonce
, myhttp
.nonce
, sizeof(http
->nonce
));
1985 http
->tls
= myhttp
.tls
;
1986 http
->encryption
= myhttp
.encryption
;
1989 * See if we actually went secure...
1995 * Server does not support HTTP upgrade...
1998 DEBUG_puts("Server does not support HTTP upgrade!");
2001 closesocket(http
->fd
);
2016 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
2019 static int /* O - Status of connection */
2020 http_setup_ssl(http_t
*http
) /* I - HTTP data */
2023 SSL_CTX
*context
; /* Context for encryption */
2024 SSL
*conn
; /* Connection for encryption */
2025 # elif defined(HAVE_GNUTLS)
2026 http_tls_t
*conn
; /* TLS session object */
2027 gnutls_certificate_client_credentials
*credentials
;
2028 /* TLS credentials */
2029 # elif defined(HAVE_CDSASSL)
2030 SSLContextRef conn
; /* Context for encryption */
2031 OSStatus error
; /* Error info */
2032 # endif /* HAVE_LIBSSL */
2036 context
= SSL_CTX_new(SSLv23_client_method());
2037 conn
= SSL_new(context
);
2039 SSL_set_fd(conn
, http
->fd
);
2040 if (SSL_connect(conn
) != 1)
2042 SSL_CTX_free(context
);
2046 http
->error
= WSAGetLastError();
2048 http
->error
= errno
;
2050 http
->status
= HTTP_ERROR
;
2052 return (HTTP_ERROR
);
2055 # elif defined(HAVE_GNUTLS)
2056 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
2060 http
->error
= errno
;
2061 http
->status
= HTTP_ERROR
;
2066 credentials
= (gnutls_certificate_client_credentials
*)
2067 malloc(sizeof(gnutls_certificate_client_credentials
));
2068 if (credentials
== NULL
)
2072 http
->error
= errno
;
2073 http
->status
= HTTP_ERROR
;
2078 gnutls_certificate_allocate_credentials(credentials
);
2080 gnutls_init(&(conn
->session
), GNUTLS_CLIENT
);
2081 gnutls_set_default_priority(conn
->session
);
2082 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
2083 gnutls_transport_set_ptr(conn
->session
, http
->fd
);
2085 if ((gnutls_handshake(conn
->session
)) != GNUTLS_E_SUCCESS
)
2087 http
->error
= errno
;
2088 http
->status
= HTTP_ERROR
;
2093 conn
->credentials
= credentials
;
2095 # elif defined(HAVE_CDSASSL)
2096 error
= SSLNewContext(false, &conn
);
2099 error
= SSLSetIOFuncs(conn
, CDSAReadFunc
, CDSAWriteFunc
);
2102 error
= SSLSetConnection(conn
, (SSLConnectionRef
)http
->fd
);
2105 error
= SSLSetAllowsExpiredCerts(conn
, true);
2108 error
= SSLSetAllowsAnyRoot(conn
, true);
2111 error
= SSLHandshake(conn
);
2115 http
->error
= error
;
2116 http
->status
= HTTP_ERROR
;
2118 SSLDisposeContext(conn
);
2124 # endif /* HAVE_CDSASSL */
2132 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
2136 http_shutdown_ssl(http_t
*http
) /* I - HTTP data */
2139 SSL_CTX
*context
; /* Context for encryption */
2140 SSL
*conn
; /* Connection for encryption */
2143 conn
= (SSL
*)(http
->tls
);
2144 context
= SSL_get_SSL_CTX(conn
);
2147 SSL_CTX_free(context
);
2150 # elif defined(HAVE_GNUTLS)
2151 http_tls_t
*conn
; /* Encryption session */
2152 gnutls_certificate_client_credentials
*credentials
;
2153 /* TLS credentials */
2156 conn
= (http_tls_t
*)(http
->tls
);
2157 credentials
= (gnutls_certificate_client_credentials
*)(conn
->credentials
);
2159 gnutls_bye(conn
->session
, GNUTLS_SHUT_RDWR
);
2160 gnutls_deinit(conn
->session
);
2161 gnutls_certificate_free_credentials(*credentials
);
2165 # elif defined(HAVE_CDSASSL)
2166 SSLClose((SSLContextRef
)http
->tls
);
2167 SSLDisposeContext((SSLContextRef
)http
->tls
);
2168 # endif /* HAVE_LIBSSL */
2175 * 'http_read_ssl()' - Read from a SSL/TLS connection.
2178 static int /* O - Bytes read */
2179 http_read_ssl(http_t
*http
, /* I - HTTP data */
2180 char *buf
, /* I - Buffer to store data */
2181 int len
) /* I - Length of buffer */
2183 # if defined(HAVE_LIBSSL)
2184 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
2186 # elif defined(HAVE_GNUTLS)
2187 return (gnutls_record_recv(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
2189 # elif defined(HAVE_CDSASSL)
2190 OSStatus error
; /* Error info */
2191 size_t processed
; /* Number of bytes processed */
2194 error
= SSLRead((SSLContextRef
)http
->tls
, buf
, len
, &processed
);
2200 http
->error
= error
;
2204 # endif /* HAVE_LIBSSL */
2209 * 'http_write_ssl()' - Write to a SSL/TLS connection.
2212 static int /* O - Bytes written */
2213 http_write_ssl(http_t
*http
, /* I - HTTP data */
2214 const char *buf
, /* I - Buffer holding data */
2215 int len
) /* I - Length of buffer */
2217 # if defined(HAVE_LIBSSL)
2218 return (SSL_write((SSL
*)(http
->tls
), buf
, len
));
2220 # elif defined(HAVE_GNUTLS)
2221 return (gnutls_record_send(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
2222 # elif defined(HAVE_CDSASSL)
2223 OSStatus error
; /* Error info */
2224 size_t processed
; /* Number of bytes processed */
2227 error
= SSLWrite((SSLContextRef
)http
->tls
, buf
, len
, &processed
);
2233 http
->error
= error
;
2236 # endif /* HAVE_LIBSSL */
2240 # if defined(HAVE_CDSASSL)
2242 * 'CDSAReadFunc()' - Read function for CDSA decryption code.
2245 static OSStatus
/* O - -1 on error, 0 on success */
2246 CDSAReadFunc(SSLConnectionRef connection
, /* I - SSL/TLS connection */
2247 void *data
, /* I - Data buffer */
2248 size_t *dataLength
) /* IO - Number of bytes */
2250 ssize_t bytes
; /* Number of bytes read */
2253 bytes
= recv((int)connection
, data
, *dataLength
, 0);
2256 *dataLength
= bytes
;
2265 * 'CDSAWriteFunc()' - Write function for CDSA encryption code.
2268 static OSStatus
/* O - -1 on error, 0 on success */
2269 CDSAWriteFunc(SSLConnectionRef connection
, /* I - SSL/TLS connection */
2270 const void *data
, /* I - Data buffer */
2271 size_t *dataLength
) /* IO - Number of bytes */
2276 bytes
= write((int)connection
, data
, *dataLength
);
2279 *dataLength
= bytes
;
2285 # endif /* HAVE_CDSASSL */
2286 #endif /* HAVE_SSL */
2290 * End of "$Id: http.c,v 1.114 2003/03/03 17:59:56 mike Exp $".