2 * "$Id: http.c,v 1.89 2001/10/30 20:58:56 mike Exp $"
4 * HTTP routines for the Common UNIX Printing System (CUPS) scheduler.
6 * Copyright 1997-2001 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
26 * httpInitialize() - Initialize the HTTP interface library and set the
27 * default HTTP proxy (if any).
28 * httpCheck() - Check to see if there is a pending response from
30 * httpClose() - Close an HTTP connection...
31 * httpConnect() - Connect to a HTTP server.
32 * httpConnectEncrypt() - Connect to a HTTP server using encryption.
33 * httpEncryption() - Set the required encryption on the link.
34 * httpReconnect() - Reconnect to a HTTP server...
35 * httpGetHostByName() - Lookup a hostname or IP address, and return
36 * address records for the specified name.
37 * httpSeparate() - Separate a Universal Resource Identifier into its
39 * httpGetSubField() - Get a sub-field value.
40 * httpSetField() - Set the value of an HTTP header.
41 * httpDelete() - Send a DELETE request to the server.
42 * httpGet() - Send a GET request to the server.
43 * httpHead() - Send a HEAD request to the server.
44 * httpOptions() - Send an OPTIONS request to the server.
45 * httpPost() - Send a POST request to the server.
46 * httpPut() - Send a PUT request to the server.
47 * httpTrace() - Send an TRACE request to the server.
48 * httpFlush() - Flush data from a HTTP connection.
49 * httpRead() - Read data from a HTTP connection.
50 * httpWrite() - Write data to a HTTP connection.
51 * httpGets() - Get a line of text from a HTTP connection.
52 * httpPrintf() - Print a formatted string to a HTTP connection.
53 * httpStatus() - Return a short string describing a HTTP status code.
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 * httpEncode64() - Base64-encode a string.
59 * httpGetLength() - Get the amount of data remaining from the
60 * content-length or transfer-encoding fields.
61 * http_field() - Return the field index for a field name.
62 * http_send() - Send a request with all fields and the trailing
64 * http_upgrade() - Force upgrade to TLS encryption.
68 * Include necessary headers...
83 #if !defined(WIN32) && !defined(__EMX__)
85 #endif /* !WIN32 && !__EMX__ */
88 # include <openssl/err.h>
89 # include <openssl/rand.h>
90 # include <openssl/ssl.h>
91 #endif /* HAVE_LIBSSL */
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 #endif /* HAVE_LIBSSL */
120 static const char *http_fields
[] =
137 "If-Unmodified-since",
150 static const char *days
[7] =
160 static const char *months
[12] =
178 * 'httpInitialize()' - Initialize the HTTP interface library and set the
179 * default HTTP proxy (if any).
186 struct timeval curtime
; /* Current time in microseconds */
187 int i
; /* Looping var */
188 unsigned char data
[1024]; /* Seed data */
189 #endif /* HAVE_LIBSSL */
191 #if defined(WIN32) || defined(__EMX__)
192 WSADATA winsockdata
; /* WinSock data */
193 static int initialized
= 0;/* Has WinSock been initialized? */
197 WSAStartup(MAKEWORD(1,1), &winsockdata
);
198 #elif defined(HAVE_SIGSET)
199 sigset(SIGPIPE
, SIG_IGN
);
200 #elif defined(HAVE_SIGACTION)
201 struct sigaction action
; /* POSIX sigaction data */
205 * Ignore SIGPIPE signals...
208 memset(&action
, 0, sizeof(action
));
209 action
.sa_handler
= SIG_IGN
;
210 sigaction(SIGPIPE
, &action
, NULL
);
212 signal(SIGPIPE
, SIG_IGN
);
213 #endif /* WIN32 || __EMX__ */
216 SSL_load_error_strings();
220 * Using the current time is a dubious random seed, but on some systems
221 * it is the best we can do (on others, this seed isn't even used...)
224 gettimeofday(&curtime
, NULL
);
225 srand(curtime
.tv_sec
+ curtime
.tv_usec
);
227 for (i
= 0; i
< sizeof(data
); i
++)
228 data
[i
] = rand(); /* Yes, this is a poor source of random data... */
230 RAND_seed(&data
, sizeof(data
));
231 #endif /* HAVE_LIBSSL */
236 * 'httpCheck()' - Check to see if there is a pending response from the server.
239 int /* O - 0 = no data, 1 = data available */
240 httpCheck(http_t
*http
) /* I - HTTP connection */
242 fd_set input
; /* Input set for select() */
243 struct timeval timeout
; /* Timeout */
247 * First see if there is data in the buffer...
257 * Then try doing a select() to poll the socket...
261 FD_SET(http
->fd
, &input
);
266 return (select(http
->fd
+ 1, &input
, NULL
, NULL
, &timeout
) > 0);
271 * 'httpClose()' - Close an HTTP connection...
275 httpClose(http_t
*http
) /* I - Connection to close */
278 SSL_CTX
*context
; /* Context for encryption */
279 SSL
*conn
; /* Connection for encryption */
280 #endif /* HAVE_LIBSSL */
289 conn
= (SSL
*)(http
->tls
);
290 context
= SSL_get_SSL_CTX(conn
);
293 SSL_CTX_free(context
);
298 #endif /* HAVE_LIBSSL */
301 closesocket(http
->fd
);
311 * 'httpConnect()' - Connect to a HTTP server.
314 http_t
* /* O - New HTTP connection */
315 httpConnect(const char *host
, /* I - Host to connect to */
316 int port
) /* I - Port number */
318 http_encryption_t encrypt
;/* Type of encryption to use */
322 * Set the default encryption status...
326 encrypt
= HTTP_ENCRYPT_ALWAYS
;
328 encrypt
= HTTP_ENCRYPT_IF_REQUESTED
;
330 return (httpConnectEncrypt(host
, port
, encrypt
));
335 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
338 http_t
* /* O - New HTTP connection */
339 httpConnectEncrypt(const char *host
, /* I - Host to connect to */
340 int port
, /* I - Port number */
341 http_encryption_t encrypt
)
342 /* I - Type of encryption to use */
344 int i
; /* Looping var */
345 http_t
*http
; /* New HTTP connection */
346 struct hostent
*hostaddr
; /* Host address data */
358 if ((hostaddr
= httpGetHostByName(host
)) == NULL
)
361 * This hack to make users that don't have a localhost entry in
362 * their hosts file or DNS happy...
365 if (strcasecmp(host
, "localhost") != 0)
367 else if ((hostaddr
= httpGetHostByName("127.0.0.1")) == NULL
)
372 * Verify that it is an IPv4 address (IPv6 support will come in CUPS 1.2...)
375 if (hostaddr
->h_addrtype
!= AF_INET
|| hostaddr
->h_length
!= 4)
379 * Allocate memory for the structure...
382 http
= calloc(sizeof(http_t
), 1);
386 http
->version
= HTTP_1_1
;
388 http
->activity
= time(NULL
);
392 * Copy the hostname and port and then "reconnect"...
395 strncpy(http
->hostname
, host
, sizeof(http
->hostname
) - 1);
396 http
->hostaddr
.sin_family
= hostaddr
->h_addrtype
;
398 http
->hostaddr
.sin_port
= htons((u_short
)port
);
400 http
->hostaddr
.sin_port
= htons(port
);
404 * Set the encryption status...
407 http
->encryption
= encrypt
;
410 * Loop through the addresses we have until one of them connects...
413 strncpy(http
->hostname
, host
, sizeof(http
->hostname
) - 1);
415 for (i
= 0; hostaddr
->h_addr_list
[i
]; i
++)
418 * Load the address...
421 memcpy((char *)&(http
->hostaddr
.sin_addr
), hostaddr
->h_addr_list
[i
],
425 * Connect to the remote system...
428 if (!httpReconnect(http
))
433 * Could not connect to any known address - bail out!
442 * 'httpEncryption()' - Set the required encryption on the link.
445 int /* O - -1 on error, 0 on success */
446 httpEncryption(http_t
*http
, /* I - HTTP data */
447 http_encryption_t e
) /* I - New encryption preference */
453 http
->encryption
= e
;
455 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
456 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
457 return (httpReconnect(http
));
458 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
459 return (http_upgrade(http
));
463 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
467 #endif /* HAVE_LIBSSL */
472 * 'httpReconnect()' - Reconnect to a HTTP server...
475 int /* O - 0 on success, non-zero on failure */
476 httpReconnect(http_t
*http
) /* I - HTTP data */
478 int val
; /* Socket option value */
480 SSL_CTX
*context
; /* Context for encryption */
481 SSL
*conn
; /* Connection for encryption */
486 conn
= (SSL
*)(http
->tls
);
487 context
= SSL_get_SSL_CTX(conn
);
490 SSL_CTX_free(context
);
495 #endif /* HAVE_LIBSSL */
498 * Close any previously open socket...
503 closesocket(http
->fd
);
509 * Create the socket and set options to allow reuse.
512 if ((http
->fd
= socket(AF_INET
, SOCK_STREAM
, 0)) < 0)
514 #if defined(WIN32) || defined(__EMX__)
515 http
->error
= WSAGetLastError();
518 #endif /* WIN32 || __EMX__ */
519 http
->status
= HTTP_ERROR
;
524 fcntl(http
->fd
, F_SETFD
, FD_CLOEXEC
); /* Close this socket when starting *
525 * other processes... */
526 #endif /* FD_CLOEXEC */
529 setsockopt(http
->fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *)&val
, sizeof(val
));
533 setsockopt(http
->fd
, SOL_SOCKET
, SO_REUSEPORT
, &val
, sizeof(val
));
534 #endif /* SO_REUSEPORT */
537 * Connect to the server...
540 if (connect(http
->fd
, (struct sockaddr
*)&(http
->hostaddr
),
541 sizeof(http
->hostaddr
)) < 0)
543 #if defined(WIN32) || defined(__EMX__)
544 http
->error
= WSAGetLastError();
547 #endif /* WIN32 || __EMX__ */
548 http
->status
= HTTP_ERROR
;
551 closesocket(http
->fd
);
562 http
->status
= HTTP_CONTINUE
;
565 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
568 * Always do encryption via SSL.
571 context
= SSL_CTX_new(SSLv23_method());
572 conn
= SSL_new(context
);
574 SSL_set_fd(conn
, http
->fd
);
575 if (SSL_connect(conn
) != 1)
577 SSL_CTX_free(context
);
580 #if defined(WIN32) || defined(__EMX__)
581 http
->error
= WSAGetLastError();
584 #endif /* WIN32 || __EMX__ */
585 http
->status
= HTTP_ERROR
;
588 closesocket(http
->fd
);
598 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
599 return (http_upgrade(http
));
600 #endif /* HAVE_LIBSSL */
607 * 'httpGetHostByName()' - Lookup a hostname or IP address, and return
608 * address records for the specified name.
611 struct hostent
* /* O - Host entry */
612 httpGetHostByName(const char *name
) /* I - Hostname or IP address */
614 unsigned ip
[4]; /* IP address components */
615 static unsigned packed_ip
; /* Packed IPv4 address */
616 static char *packed_ptr
[2]; /* Pointer to packed address */
617 static struct hostent host_ip
; /* Host entry for IP address */
621 * This function is needed because some operating systems have a
622 * buggy implementation of httpGetHostByName() that does not support
623 * IP addresses. If the first character of the name string is a
624 * number, then sscanf() is used to extract the IP components.
625 * We then pack the components into an IPv4 address manually,
626 * since the inet_aton() function is deprecated. We use the
627 * htonl() macro to get the right byte order for the address.
630 if (isdigit(name
[0]))
633 * We have an IP address; break it up and provide the host entry
634 * to the caller. Currently only supports IPv4 addresses, although
635 * it should be trivial to support IPv6 in CUPS 1.2.
638 if (sscanf(name
, "%u.%u.%u.%u", ip
, ip
+ 1, ip
+ 2, ip
+ 3) != 4)
639 return (NULL
); /* Must have 4 numbers */
641 packed_ip
= htonl(((((((ip
[0] << 8) | ip
[1]) << 8) | ip
[2]) << 8) | ip
[3]));
644 * Fill in the host entry and return it...
647 host_ip
.h_name
= (char *)name
;
648 host_ip
.h_aliases
= NULL
;
649 host_ip
.h_addrtype
= AF_INET
;
650 host_ip
.h_length
= 4;
651 host_ip
.h_addr_list
= packed_ptr
;
652 packed_ptr
[0] = (char *)(&packed_ip
);
653 packed_ptr
[1] = NULL
;
660 * Use the gethostbyname() function to get the IP address for
664 return (gethostbyname(name
));
670 * 'httpSeparate()' - Separate a Universal Resource Identifier into its
675 httpSeparate(const char *uri
, /* I - Universal Resource Identifier */
676 char *method
, /* O - Method [32] (http, https, etc.) */
677 char *username
, /* O - Username [32] */
678 char *host
, /* O - Hostname [32] */
679 int *port
, /* O - Port number to use */
680 char *resource
) /* O - Resource/filename [1024] */
682 char *ptr
; /* Pointer into string... */
683 const char *atsign
, /* @ sign */
684 *slash
; /* Separator */
685 char safeuri
[HTTP_MAX_URI
]; /* "Safe" local copy of URI */
689 * Range check input...
692 if (uri
== NULL
|| method
== NULL
|| username
== NULL
|| host
== NULL
||
693 port
== NULL
|| resource
== NULL
)
697 * Copy the URL to a local string to make sure we don't have a URL
698 * longer than HTTP_MAX_URI characters long...
701 strncpy(safeuri
, uri
, sizeof(safeuri
));
702 safeuri
[sizeof(safeuri
) - 1] = '\0';
707 * Grab the method portion of the URI...
710 if (strncmp(uri
, "//", 2) == 0)
713 * Workaround for HP IPP client bug...
716 strcpy(method
, "ipp");
721 * Standard URI with method...
724 for (ptr
= host
; *uri
!= ':' && *uri
!= '\0'; uri
++)
725 if (ptr
< (host
+ HTTP_MAX_URI
- 1))
733 * If the method contains a period or slash, then it's probably
734 * hostname/filename...
737 if (strchr(host
, '.') != NULL
|| strchr(host
, '/') != NULL
|| *uri
== '\0')
739 if ((ptr
= strchr(host
, '/')) != NULL
)
741 strncpy(resource
, ptr
, HTTP_MAX_URI
);
742 resource
[HTTP_MAX_URI
- 1] = '\0';
751 * OK, we have "hostname:port[/resource]"...
754 *port
= strtol(uri
, (char **)&uri
, 10);
758 strncpy(resource
, uri
, HTTP_MAX_URI
);
759 resource
[HTTP_MAX_URI
- 1] = '\0';
765 strcpy(method
, "http");
771 strncpy(method
, host
, 31);
777 * If the method starts with less than 2 slashes then it is a local resource...
780 if (strncmp(uri
, "//", 2) != 0)
782 strncpy(resource
, uri
, 1023);
783 resource
[1023] = '\0';
792 * Grab the username, if any...
798 if ((slash
= strchr(uri
, '/')) == NULL
)
799 slash
= uri
+ strlen(uri
);
801 if ((atsign
= strchr(uri
, '@')) != NULL
&& atsign
< slash
)
804 * Got a username:password combo...
807 for (ptr
= username
; uri
< atsign
; uri
++)
808 if (ptr
< (username
+ HTTP_MAX_URI
- 1))
819 * Grab the hostname...
822 for (ptr
= host
; *uri
!= ':' && *uri
!= '/' && *uri
!= '\0'; uri
++)
823 if (ptr
< (host
+ HTTP_MAX_URI
- 1))
830 if (strcasecmp(method
, "http") == 0)
832 else if (strcasecmp(method
, "https") == 0)
834 else if (strcasecmp(method
, "ipp") == 0)
836 else if (strcasecmp(method
, "socket") == 0) /* Not registered yet... */
844 * Parse port number...
849 while (isdigit(*uri
))
851 *port
= (*port
* 10) + *uri
- '0';
859 * Hostname but no port or path...
868 * The remaining portion is the resource string...
871 strncpy(resource
, uri
, HTTP_MAX_URI
);
872 resource
[HTTP_MAX_URI
- 1] = '\0';
877 * 'httpGetSubField()' - Get a sub-field value.
880 char * /* O - Value or NULL */
881 httpGetSubField(http_t
*http
, /* I - HTTP data */
882 http_field_t field
, /* I - Field index */
883 const char *name
, /* I - Name of sub-field */
884 char *value
) /* O - Value string */
886 const char *fptr
; /* Pointer into field */
887 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
888 *ptr
; /* Pointer into string buffer */
892 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
893 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
894 name
== NULL
|| value
== NULL
)
897 DEBUG_printf(("httpGetSubField(%p, %d, \"%s\", %p)\n",
898 http
, field
, name
, value
));
900 for (fptr
= http
->fields
[field
]; *fptr
;)
903 * Skip leading whitespace...
906 while (isspace(*fptr
))
916 * Get the sub-field name...
920 *fptr
&& *fptr
!= '=' && !isspace(*fptr
) && ptr
< (temp
+ sizeof(temp
) - 1);
925 DEBUG_printf(("name = \"%s\"\n", temp
));
928 * Skip trailing chars up to the '='...
931 while (isspace(*fptr
))
941 * Skip = and leading whitespace...
946 while (isspace(*fptr
))
952 * Read quoted string...
955 for (ptr
= value
, fptr
++;
956 *fptr
&& *fptr
!= '\"' && ptr
< (value
+ HTTP_MAX_VALUE
- 1);
961 while (*fptr
&& *fptr
!= '\"')
970 * Read unquoted string...
974 *fptr
&& !isspace(*fptr
) && *fptr
!= ',' && ptr
< (value
+ HTTP_MAX_VALUE
- 1);
979 while (*fptr
&& !isspace(*fptr
) && *fptr
!= ',')
983 DEBUG_printf(("value = \"%s\"\n", value
));
986 * See if this is the one...
989 if (strcmp(name
, temp
) == 0)
1000 * 'httpSetField()' - Set the value of an HTTP header.
1004 httpSetField(http_t
*http
, /* I - HTTP data */
1005 http_field_t field
, /* I - Field index */
1006 const char *value
) /* I - Value */
1009 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
1010 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
1014 strncpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
- 1);
1015 http
->fields
[field
][HTTP_MAX_VALUE
- 1] = '\0';
1020 * 'httpDelete()' - Send a DELETE request to the server.
1023 int /* O - Status of call (0 = success) */
1024 httpDelete(http_t
*http
, /* I - HTTP data */
1025 const char *uri
) /* I - URI to delete */
1027 return (http_send(http
, HTTP_DELETE
, uri
));
1032 * 'httpGet()' - Send a GET request to the server.
1035 int /* O - Status of call (0 = success) */
1036 httpGet(http_t
*http
, /* I - HTTP data */
1037 const char *uri
) /* I - URI to get */
1039 return (http_send(http
, HTTP_GET
, uri
));
1044 * 'httpHead()' - Send a HEAD request to the server.
1047 int /* O - Status of call (0 = success) */
1048 httpHead(http_t
*http
, /* I - HTTP data */
1049 const char *uri
) /* I - URI for head */
1051 return (http_send(http
, HTTP_HEAD
, uri
));
1056 * 'httpOptions()' - Send an OPTIONS request to the server.
1059 int /* O - Status of call (0 = success) */
1060 httpOptions(http_t
*http
, /* I - HTTP data */
1061 const char *uri
) /* I - URI for options */
1063 return (http_send(http
, HTTP_OPTIONS
, uri
));
1068 * 'httpPost()' - Send a POST request to the server.
1071 int /* O - Status of call (0 = success) */
1072 httpPost(http_t
*http
, /* I - HTTP data */
1073 const char *uri
) /* I - URI for post */
1075 httpGetLength(http
);
1077 return (http_send(http
, HTTP_POST
, uri
));
1082 * 'httpPut()' - Send a PUT request to the server.
1085 int /* O - Status of call (0 = success) */
1086 httpPut(http_t
*http
, /* I - HTTP data */
1087 const char *uri
) /* I - URI to put */
1089 httpGetLength(http
);
1091 return (http_send(http
, HTTP_PUT
, uri
));
1096 * 'httpTrace()' - Send an TRACE request to the server.
1099 int /* O - Status of call (0 = success) */
1100 httpTrace(http_t
*http
, /* I - HTTP data */
1101 const char *uri
) /* I - URI for trace */
1103 return (http_send(http
, HTTP_TRACE
, uri
));
1108 * 'httpFlush()' - Flush data from a HTTP connection.
1112 httpFlush(http_t
*http
) /* I - HTTP data */
1114 char buffer
[8192]; /* Junk buffer */
1117 while (httpRead(http
, buffer
, sizeof(buffer
)) > 0);
1122 * 'httpRead()' - Read data from a HTTP connection.
1125 int /* O - Number of bytes read */
1126 httpRead(http_t
*http
, /* I - HTTP data */
1127 char *buffer
, /* I - Buffer for data */
1128 int length
) /* I - Maximum number of bytes */
1130 int bytes
; /* Bytes read */
1131 char len
[32]; /* Length string */
1134 DEBUG_printf(("httpRead(%08x, %08x, %d)\n", http
, buffer
, length
));
1136 if (http
== NULL
|| buffer
== NULL
)
1139 http
->activity
= time(NULL
);
1144 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1145 http
->data_remaining
<= 0)
1147 DEBUG_puts("httpRead: Getting chunk length...");
1149 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1151 DEBUG_puts("httpRead: Could not get length!");
1155 http
->data_remaining
= strtol(len
, NULL
, 16);
1158 DEBUG_printf(("httpRead: data_remaining = %d\n", http
->data_remaining
));
1160 if (http
->data_remaining
== 0)
1163 * A zero-length chunk ends a transfer; unless we are reading POST
1167 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1168 httpGets(len
, sizeof(len
), http
);
1170 if (http
->state
== HTTP_POST_RECV
)
1173 http
->state
= HTTP_WAITING
;
1177 else if (length
> http
->data_remaining
)
1178 length
= http
->data_remaining
;
1180 if (http
->used
== 0 && length
<= 256)
1183 * Buffer small reads for better performance...
1186 if (http
->data_remaining
> sizeof(http
->buffer
))
1187 bytes
= sizeof(http
->buffer
);
1189 bytes
= http
->data_remaining
;
1193 bytes
= SSL_read((SSL
*)(http
->tls
), http
->buffer
, bytes
);
1195 #endif /* HAVE_LIBSSL */
1197 DEBUG_printf(("httpRead: reading %d bytes from socket into buffer...\n",
1200 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1202 DEBUG_printf(("httpRead: read %d bytes from socket into buffer...\n",
1210 #if defined(WIN32) || defined(__EMX__)
1211 http
->error
= WSAGetLastError();
1213 http
->error
= errno
;
1214 #endif /* WIN32 || __EMX__ */
1223 if (length
> http
->used
)
1224 length
= http
->used
;
1228 DEBUG_printf(("httpRead: grabbing %d bytes from input buffer...\n", bytes
));
1230 memcpy(buffer
, http
->buffer
, length
);
1231 http
->used
-= length
;
1234 memcpy(http
->buffer
, http
->buffer
+ length
, http
->used
);
1238 bytes
= SSL_read((SSL
*)(http
->tls
), buffer
, length
);
1239 #endif /* HAVE_LIBSSL */
1242 DEBUG_printf(("httpRead: reading %d bytes from socket...\n", length
));
1243 bytes
= recv(http
->fd
, buffer
, length
, 0);
1244 DEBUG_printf(("httpRead: read %d bytes from socket...\n", bytes
));
1248 http
->data_remaining
-= bytes
;
1250 #if defined(WIN32) || defined(__EMX__)
1251 http
->error
= WSAGetLastError();
1253 http
->error
= errno
;
1254 #endif /* WIN32 || __EMX__ */
1256 if (http
->data_remaining
== 0)
1258 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1259 httpGets(len
, sizeof(len
), http
);
1261 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
1263 if (http
->state
== HTTP_POST_RECV
)
1266 http
->state
= HTTP_WAITING
;
1275 * 'httpWrite()' - Write data to a HTTP connection.
1278 int /* O - Number of bytes written */
1279 httpWrite(http_t
*http
, /* I - HTTP data */
1280 const char *buffer
, /* I - Buffer for data */
1281 int length
) /* I - Number of bytes to write */
1283 int tbytes
, /* Total bytes sent */
1284 bytes
; /* Bytes sent */
1287 if (http
== NULL
|| buffer
== NULL
)
1290 http
->activity
= time(NULL
);
1292 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1294 if (httpPrintf(http
, "%x\r\n", length
) < 0)
1300 * A zero-length chunk ends a transfer; unless we are sending POST
1304 DEBUG_puts("httpWrite: changing states...");
1306 if (http
->state
== HTTP_POST_RECV
)
1308 else if (http
->state
== HTTP_PUT_RECV
)
1309 http
->state
= HTTP_STATUS
;
1311 http
->state
= HTTP_WAITING
;
1313 if (httpPrintf(http
, "\r\n") < 0)
1326 bytes
= SSL_write((SSL
*)(http
->tls
), buffer
, length
);
1328 #endif /* HAVE_LIBSSL */
1329 bytes
= send(http
->fd
, buffer
, length
, 0);
1333 DEBUG_puts("httpWrite: error writing data...\n");
1341 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1342 http
->data_remaining
-= bytes
;
1345 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1346 if (httpPrintf(http
, "\r\n") < 0)
1349 if (http
->data_remaining
== 0 && http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1352 * Finished with the transfer; unless we are sending POST data, go idle...
1355 DEBUG_puts("httpWrite: changing states...");
1357 if (http
->state
== HTTP_POST_RECV
)
1360 http
->state
= HTTP_WAITING
;
1363 DEBUG_printf(("httpWrite: wrote %d bytes...\n", tbytes
));
1370 * 'httpGets()' - Get a line of text from a HTTP connection.
1373 char * /* O - Line or NULL */
1374 httpGets(char *line
, /* I - Line to read into */
1375 int length
, /* I - Max length of buffer */
1376 http_t
*http
) /* I - HTTP data */
1378 char *lineptr
, /* Pointer into line */
1379 *bufptr
, /* Pointer into input buffer */
1380 *bufend
; /* Pointer to end of buffer */
1381 int bytes
; /* Number of bytes read */
1384 DEBUG_printf(("httpGets(%08x, %d, %08x)\n", line
, length
, http
));
1386 if (http
== NULL
|| line
== NULL
)
1390 * Pre-scan the buffer and see if there is a newline in there...
1393 #if defined(WIN32) || defined(__EMX__)
1397 #endif /* WIN32 || __EMX__ */
1401 bufptr
= http
->buffer
;
1402 bufend
= http
->buffer
+ http
->used
;
1404 while (bufptr
< bufend
)
1405 if (*bufptr
== 0x0a)
1410 if (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
)
1413 * No newline; see if there is more data to be read...
1418 bytes
= SSL_read((SSL
*)(http
->tls
), bufend
,
1419 HTTP_MAX_BUFFER
- http
->used
);
1421 #endif /* HAVE_LIBSSL */
1422 bytes
= recv(http
->fd
, bufend
, HTTP_MAX_BUFFER
- http
->used
, 0);
1427 * Nope, can't get a line this time...
1430 #if defined(WIN32) || defined(__EMX__)
1431 if (WSAGetLastError() != http
->error
)
1433 http
->error
= WSAGetLastError();
1437 DEBUG_printf(("httpGets(): recv() error %d!\n", WSAGetLastError()));
1439 if (errno
!= http
->error
)
1441 http
->error
= errno
;
1445 DEBUG_printf(("httpGets(): recv() error %d!\n", errno
));
1446 #endif /* WIN32 || __EMX__ */
1450 else if (bytes
== 0)
1453 http
->error
= EPIPE
;
1459 * Yup, update the amount used and the end pointer...
1462 http
->used
+= bytes
;
1466 while (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
);
1468 http
->activity
= time(NULL
);
1471 * Read a line from the buffer...
1475 bufptr
= http
->buffer
;
1479 while (bufptr
< bufend
&& bytes
< length
)
1483 if (*bufptr
== 0x0a)
1488 else if (*bufptr
== 0x0d)
1491 *lineptr
++ = *bufptr
++;
1498 http
->used
-= bytes
;
1500 memcpy(http
->buffer
, bufptr
, http
->used
);
1502 DEBUG_printf(("httpGets(): Returning \"%s\"\n", line
));
1506 DEBUG_puts("httpGets(): No new line available!");
1513 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1516 int /* O - Number of bytes written */
1517 httpPrintf(http_t
*http
, /* I - HTTP data */
1518 const char *format
, /* I - printf-style format string */
1519 ...) /* I - Additional args as needed */
1521 int bytes
, /* Number of bytes to write */
1522 nbytes
, /* Number of bytes written */
1523 tbytes
; /* Number of bytes all together */
1524 char buf
[HTTP_MAX_BUFFER
], /* Buffer for formatted string */
1525 *bufptr
; /* Pointer into buffer */
1526 va_list ap
; /* Variable argument pointer */
1529 va_start(ap
, format
);
1530 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1533 DEBUG_printf(("httpPrintf: %s", buf
));
1535 for (tbytes
= 0, bufptr
= buf
; tbytes
< bytes
; tbytes
+= nbytes
, bufptr
+= nbytes
)
1539 nbytes
= SSL_write((SSL
*)(http
->tls
), bufptr
, bytes
- tbytes
);
1541 #endif /* HAVE_LIBSSL */
1542 nbytes
= send(http
->fd
, bufptr
, bytes
- tbytes
, 0);
1553 * 'httpStatus()' - Return a short string describing a HTTP status code.
1556 const char * /* O - String or NULL */
1557 httpStatus(http_status_t status
) /* I - HTTP status code */
1561 case HTTP_CONTINUE
:
1562 return ("Continue");
1563 case HTTP_SWITCHING_PROTOCOLS
:
1564 return ("Switching Protocols");
1569 case HTTP_ACCEPTED
:
1570 return ("Accepted");
1571 case HTTP_NO_CONTENT
:
1572 return ("No Content");
1573 case HTTP_NOT_MODIFIED
:
1574 return ("Not Modified");
1575 case HTTP_BAD_REQUEST
:
1576 return ("Bad Request");
1577 case HTTP_UNAUTHORIZED
:
1578 return ("Unauthorized");
1579 case HTTP_FORBIDDEN
:
1580 return ("Forbidden");
1581 case HTTP_NOT_FOUND
:
1582 return ("Not Found");
1583 case HTTP_REQUEST_TOO_LARGE
:
1584 return ("Request Entity Too Large");
1585 case HTTP_URI_TOO_LONG
:
1586 return ("URI Too Long");
1587 case HTTP_UPGRADE_REQUIRED
:
1588 return ("Upgrade Required");
1589 case HTTP_NOT_IMPLEMENTED
:
1590 return ("Not Implemented");
1591 case HTTP_NOT_SUPPORTED
:
1592 return ("Not Supported");
1600 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
1603 const char * /* O - Date/time string */
1604 httpGetDateString(time_t t
) /* I - UNIX time */
1607 static char datetime
[256];
1611 snprintf(datetime
, sizeof(datetime
), "%s, %02d %s %d %02d:%02d:%02d GMT",
1612 days
[tdate
->tm_wday
], tdate
->tm_mday
, months
[tdate
->tm_mon
],
1613 tdate
->tm_year
+ 1900, tdate
->tm_hour
, tdate
->tm_min
, tdate
->tm_sec
);
1620 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
1623 time_t /* O - UNIX time */
1624 httpGetDateTime(const char *s
) /* I - Date/time string */
1626 int i
; /* Looping var */
1627 struct tm tdate
; /* Time/date structure */
1628 char mon
[16]; /* Abbreviated month name */
1629 int day
, year
; /* Day of month and year */
1630 int hour
, min
, sec
; /* Time */
1633 if (sscanf(s
, "%*s%d%15s%d%d:%d:%d", &day
, mon
, &year
, &hour
, &min
, &sec
) < 6)
1636 for (i
= 0; i
< 12; i
++)
1637 if (strcasecmp(mon
, months
[i
]) == 0)
1644 tdate
.tm_mday
= day
;
1645 tdate
.tm_year
= year
- 1900;
1646 tdate
.tm_hour
= hour
;
1651 return (mktime(&tdate
));
1656 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1659 http_status_t
/* O - HTTP status */
1660 httpUpdate(http_t
*http
) /* I - HTTP data */
1662 char line
[1024], /* Line from connection... */
1663 *value
; /* Pointer to value on line */
1664 http_field_t field
; /* Field index */
1665 int major
, minor
; /* HTTP version numbers */
1666 http_status_t status
; /* Authorization status */
1668 SSL_CTX
*context
; /* Context for encryption */
1669 SSL
*conn
; /* Connection for encryption */
1670 #endif /* HAVE_LIBSSL */
1673 DEBUG_printf(("httpUpdate(%08x)\n", http
));
1676 * If we haven't issued any commands, then there is nothing to "update"...
1679 if (http
->state
== HTTP_WAITING
)
1680 return (HTTP_CONTINUE
);
1683 * Grab all of the lines we can from the connection...
1686 while (httpGets(line
, sizeof(line
), http
) != NULL
)
1690 if (line
[0] == '\0')
1693 * Blank line means the start of the data section (if any). Return
1694 * the result code, too...
1696 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
1697 * Instead, we just return HTTP_CONTINUE to the caller and keep on
1701 if (http
->status
== HTTP_CONTINUE
)
1702 return (http
->status
);
1705 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
1707 context
= SSL_CTX_new(SSLv23_method());
1708 conn
= SSL_new(context
);
1710 SSL_set_fd(conn
, http
->fd
);
1711 if (SSL_connect(conn
) != 1)
1713 SSL_CTX_free(context
);
1716 #if defined(WIN32) || defined(__EMX__)
1717 http
->error
= WSAGetLastError();
1719 http
->error
= errno
;
1720 #endif /* WIN32 || __EMX__ */
1721 http
->status
= HTTP_ERROR
;
1724 closesocket(http
->fd
);
1729 return (HTTP_ERROR
);
1734 return (HTTP_CONTINUE
);
1736 #endif /* HAVE_LIBSSL */
1738 httpGetLength(http
);
1740 switch (http
->state
)
1744 case HTTP_POST_RECV
:
1750 http
->state
= HTTP_WAITING
;
1754 return (http
->status
);
1756 else if (strncmp(line
, "HTTP/", 5) == 0)
1759 * Got the beginning of a response...
1762 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, (int *)&status
) != 3)
1763 return (HTTP_ERROR
);
1765 http
->version
= (http_version_t
)(major
* 100 + minor
);
1766 http
->status
= status
;
1768 else if ((value
= strchr(line
, ':')) != NULL
)
1775 while (isspace(*value
))
1779 * Be tolerants of servers that send unknown attribute fields...
1782 if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
1784 DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line
));
1788 httpSetField(http
, field
, value
);
1792 http
->status
= HTTP_ERROR
;
1793 return (HTTP_ERROR
);
1798 * See if there was an error...
1803 http
->status
= HTTP_ERROR
;
1804 return (HTTP_ERROR
);
1808 * If we haven't already returned, then there is nothing new...
1811 return (HTTP_CONTINUE
);
1816 * 'httpDecode64()' - Base64-decode a string.
1819 char * /* O - Decoded string */
1820 httpDecode64(char *out
, /* I - String to write to */
1821 const char *in
) /* I - String to read from */
1823 int pos
, /* Bit position */
1824 base64
; /* Value of this character */
1825 char *outptr
; /* Output pointer */
1828 for (outptr
= out
, pos
= 0; *in
!= '\0'; in
++)
1831 * Decode this character into a number from 0 to 63...
1834 if (*in
>= 'A' && *in
<= 'Z')
1836 else if (*in
>= 'a' && *in
<= 'z')
1837 base64
= *in
- 'a' + 26;
1838 else if (*in
>= '0' && *in
<= '9')
1839 base64
= *in
- '0' + 52;
1840 else if (*in
== '+')
1842 else if (*in
== '/')
1844 else if (*in
== '=')
1850 * Store the result in the appropriate chars...
1856 *outptr
= base64
<< 2;
1860 *outptr
++ |= (base64
>> 4) & 3;
1861 *outptr
= (base64
<< 4) & 255;
1865 *outptr
++ |= (base64
>> 2) & 15;
1866 *outptr
= (base64
<< 6) & 255;
1870 *outptr
++ |= base64
;
1879 * Return the decoded string...
1887 * 'httpEncode64()' - Base64-encode a string.
1890 char * /* O - Encoded string */
1891 httpEncode64(char *out
, /* I - String to write to */
1892 const char *in
) /* I - String to read from */
1894 char *outptr
; /* Output pointer */
1895 static char base64
[] = /* Base64 characters... */
1897 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1898 "abcdefghijklmnopqrstuvwxyz"
1904 for (outptr
= out
; *in
!= '\0'; in
++)
1907 * Encode the up to 3 characters as 4 Base64 numbers...
1910 *outptr
++ = base64
[in
[0] >> 2];
1911 *outptr
++ = base64
[((in
[0] << 4) | (in
[1] >> 4)) & 63];
1920 *outptr
++ = base64
[((in
[0] << 2) | (in
[1] >> 6)) & 63];
1926 *outptr
++ = base64
[in
[0] & 63];
1933 * Return the encoded string...
1941 * 'httpGetLength()' - Get the amount of data remaining from the
1942 * content-length or transfer-encoding fields.
1945 int /* O - Content length */
1946 httpGetLength(http_t
*http
) /* I - HTTP data */
1948 DEBUG_printf(("httpGetLength(%08x)\n", http
));
1950 if (strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked") == 0)
1952 DEBUG_puts("httpGetLength: chunked request!");
1954 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
1955 http
->data_remaining
= 0;
1959 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1962 * The following is a hack for HTTP servers that don't send a
1963 * content-length or transfer-encoding field...
1965 * If there is no content-length then the connection must close
1966 * after the transfer is complete...
1969 if (http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] == '\0')
1970 http
->data_remaining
= 2147483647;
1972 http
->data_remaining
= atoi(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
]);
1974 DEBUG_printf(("httpGetLength: content_length = %d\n", http
->data_remaining
));
1977 return (http
->data_remaining
);
1982 * 'http_field()' - Return the field index for a field name.
1985 static http_field_t
/* O - Field index */
1986 http_field(const char *name
) /* I - String name */
1988 int i
; /* Looping var */
1991 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
1992 if (strcasecmp(name
, http_fields
[i
]) == 0)
1993 return ((http_field_t
)i
);
1995 return (HTTP_FIELD_UNKNOWN
);
2000 * 'http_send()' - Send a request with all fields and the trailing blank line.
2003 static int /* O - 0 on success, non-zero on error */
2004 http_send(http_t
*http
, /* I - HTTP data */
2005 http_state_t request
, /* I - Request code */
2006 const char *uri
) /* I - URI */
2008 int i
; /* Looping var */
2009 char *ptr
, /* Pointer in buffer */
2010 buf
[1024]; /* Encoded URI buffer */
2011 static const char *codes
[] = /* Request code strings */
2027 static const char *hex
= "0123456789ABCDEF";
2031 if (http
== NULL
|| uri
== NULL
)
2035 * Encode the URI as needed...
2038 for (ptr
= buf
; *uri
!= '\0' && ptr
< (buf
+ sizeof(buf
) - 1); uri
++)
2039 if (*uri
<= ' ' || *uri
>= 127)
2041 if (ptr
< (buf
+ sizeof(buf
) - 1))
2043 if (ptr
< (buf
+ sizeof(buf
) - 1))
2044 *ptr
++ = hex
[(*uri
>> 4) & 15];
2045 if (ptr
< (buf
+ sizeof(buf
) - 1))
2046 *ptr
++ = hex
[*uri
& 15];
2054 * See if we had an error the last time around; if so, reconnect...
2057 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
2058 httpReconnect(http
);
2061 * Send the request header...
2064 http
->state
= request
;
2065 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
2068 http
->status
= HTTP_CONTINUE
;
2071 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
2073 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
2074 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
2076 #endif /* HAVE_LIBSSL */
2078 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
2080 http
->status
= HTTP_ERROR
;
2084 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2085 if (http
->fields
[i
][0] != '\0')
2087 DEBUG_printf(("%s: %s\n", http_fields
[i
], http
->fields
[i
]));
2089 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], http
->fields
[i
]) < 1)
2091 http
->status
= HTTP_ERROR
;
2096 if (httpPrintf(http
, "\r\n") < 1)
2098 http
->status
= HTTP_ERROR
;
2102 httpClearFields(http
);
2110 * 'http_upgrade()' - Force upgrade to TLS encryption.
2113 static int /* O - Status of connection */
2114 http_upgrade(http_t
*http
) /* I - HTTP data */
2116 int ret
; /* Return value */
2117 http_t myhttp
; /* Local copy of HTTP data */
2120 DEBUG_printf(("http_upgrade(%p)\n", http
));
2123 * Copy the HTTP data to a local variable so we can do the OPTIONS
2124 * request without interfering with the existing request data...
2127 memcpy(&myhttp
, http
, sizeof(myhttp
));
2130 * Send an OPTIONS request to the server, requiring SSL or TLS
2131 * encryption on the link...
2134 httpClearFields(&myhttp
);
2135 httpSetField(&myhttp
, HTTP_FIELD_CONNECTION
, "upgrade");
2136 httpSetField(&myhttp
, HTTP_FIELD_UPGRADE
, "TLS/1.0, SSL/2.0, SSL/3.0");
2138 if ((ret
= httpOptions(&myhttp
, "*")) == 0)
2141 * Wait for the secure connection...
2144 while (httpUpdate(&myhttp
) == HTTP_CONTINUE
);
2150 * Copy the HTTP data back over, if any...
2153 http
->fd
= myhttp
.fd
;
2154 http
->error
= myhttp
.error
;
2155 http
->activity
= myhttp
.activity
;
2156 http
->status
= myhttp
.status
;
2157 http
->version
= myhttp
.version
;
2158 http
->keep_alive
= myhttp
.keep_alive
;
2159 http
->used
= myhttp
.used
;
2162 memcpy(http
->buffer
, myhttp
.buffer
, http
->used
);
2164 http
->auth_type
= myhttp
.auth_type
;
2165 http
->nonce_count
= myhttp
.nonce_count
;
2167 memcpy(http
->nonce
, myhttp
.nonce
, sizeof(http
->nonce
));
2169 http
->tls
= myhttp
.tls
;
2170 http
->encryption
= myhttp
.encryption
;
2173 * See if we actually went secure...
2179 * Server does not support HTTP upgrade...
2182 DEBUG_puts("Server does not support HTTP upgrade!");
2185 closesocket(http
->fd
);
2197 #endif /* HAVE_LIBSSL */
2201 * End of "$Id: http.c,v 1.89 2001/10/30 20:58:56 mike Exp $".