2 * "$Id: http.c,v 1.82.2.8 2002/01/27 21:20:28 mike Exp $"
4 * HTTP routines for the Common UNIX Printing System (CUPS).
6 * Copyright 1997-2002 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 * httpSetField() - Set the value of an HTTP header.
40 * httpDelete() - Send a DELETE request to the server.
41 * httpGet() - Send a GET request to the server.
42 * httpHead() - Send a HEAD request to the server.
43 * httpOptions() - Send an OPTIONS request to the server.
44 * httpPost() - Send a POST request to the server.
45 * httpPut() - Send a PUT request to the server.
46 * httpTrace() - Send an TRACE request to the server.
47 * httpFlush() - Flush data from a HTTP connection.
48 * httpRead() - Read data from a HTTP connection.
49 * 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 * httpStatus() - Return a short string describing a HTTP status code.
53 * httpGetDateString() - Get a formatted date/time string from a time value.
54 * httpGetDateTime() - Get a time value from a formatted date/time string.
55 * httpUpdate() - Update the current HTTP state for incoming data.
56 * httpDecode64() - Base64-decode a string.
57 * httpEncode64() - Base64-encode a string.
58 * httpGetLength() - Get the amount of data remaining from the
59 * content-length or transfer-encoding fields.
60 * http_field() - Return the field index for a field name.
61 * http_send() - Send a request with all fields and the trailing
63 * http_upgrade() - Force upgrade to TLS encryption.
67 * Include necessary headers...
87 # include <openssl/err.h>
88 # include <openssl/rand.h>
89 # include <openssl/ssl.h>
90 #endif /* HAVE_LIBSSL */
94 * Some operating systems have done away with the Fxxxx constants for
95 * the fcntl() call; this works around that "feature"...
99 # define FNONBLK O_NONBLOCK
100 #endif /* !FNONBLK */
107 static http_field_t
http_field(const char *name
);
108 static int http_send(http_t
*http
, http_state_t request
,
111 static int http_upgrade(http_t
*http
);
112 #endif /* HAVE_LIBSSL */
119 static const char *http_fields
[] =
138 "If-Unmodified-since",
152 static const char *days
[7] =
162 static const char *months
[12] =
180 * 'httpInitialize()' - Initialize the HTTP interface library and set the
181 * default HTTP proxy (if any).
188 struct timeval curtime
; /* Current time in microseconds */
189 int i
; /* Looping var */
190 unsigned char data
[1024]; /* Seed data */
191 #endif /* HAVE_LIBSSL */
194 WSADATA winsockdata
; /* WinSock data */
195 static int initialized
= 0;/* Has WinSock been initialized? */
199 WSAStartup(MAKEWORD(1,1), &winsockdata
);
200 #elif defined(HAVE_SIGSET)
201 sigset(SIGPIPE
, SIG_IGN
);
202 #elif defined(HAVE_SIGACTION)
203 struct sigaction action
; /* POSIX sigaction data */
207 * Ignore SIGPIPE signals...
210 memset(&action
, 0, sizeof(action
));
211 action
.sa_handler
= SIG_IGN
;
212 sigaction(SIGPIPE
, &action
, NULL
);
214 signal(SIGPIPE
, SIG_IGN
);
218 SSL_load_error_strings();
222 * Using the current time is a dubious random seed, but on some systems
223 * it is the best we can do (on others, this seed isn't even used...)
226 gettimeofday(&curtime
, NULL
);
227 srand(curtime
.tv_sec
+ curtime
.tv_usec
);
229 for (i
= 0; i
< sizeof(data
); i
++)
230 data
[i
] = rand(); /* Yes, this is a poor source of random data... */
232 RAND_seed(&data
, sizeof(data
));
233 #endif /* HAVE_LIBSSL */
238 * 'httpCheck()' - Check to see if there is a pending response from the server.
241 int /* O - 0 = no data, 1 = data available */
242 httpCheck(http_t
*http
) /* I - HTTP connection */
244 fd_set input
; /* Input set for select() */
245 struct timeval timeout
; /* Timeout */
249 * First see if there is data in the buffer...
259 * Then try doing a select() to poll the socket...
263 FD_SET(http
->fd
, &input
);
268 return (select(http
->fd
+ 1, &input
, NULL
, NULL
, &timeout
) > 0);
273 * 'httpClose()' - Close an HTTP connection...
277 httpClose(http_t
*http
) /* I - Connection to close */
280 SSL_CTX
*context
; /* Context for encryption */
281 SSL
*conn
; /* Connection for encryption */
282 #endif /* HAVE_LIBSSL */
291 conn
= (SSL
*)(http
->tls
);
292 context
= SSL_get_SSL_CTX(conn
);
295 SSL_CTX_free(context
);
300 #endif /* HAVE_LIBSSL */
303 closesocket(http
->fd
);
313 * 'httpConnect()' - Connect to a HTTP server.
316 http_t
* /* O - New HTTP connection */
317 httpConnect(const char *host
, /* I - Host to connect to */
318 int port
) /* I - Port number */
320 http_encryption_t encrypt
;/* Type of encryption to use */
324 * Set the default encryption status...
328 encrypt
= HTTP_ENCRYPT_ALWAYS
;
330 encrypt
= HTTP_ENCRYPT_IF_REQUESTED
;
332 return (httpConnectEncrypt(host
, port
, encrypt
));
337 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
340 http_t
* /* O - New HTTP connection */
341 httpConnectEncrypt(const char *host
, /* I - Host to connect to */
342 int port
, /* I - Port number */
343 http_encryption_t encrypt
)
344 /* I - Type of encryption to use */
346 int i
; /* Looping var */
347 http_t
*http
; /* New HTTP connection */
348 struct hostent
*hostaddr
; /* Host address data */
360 if ((hostaddr
= httpGetHostByName(host
)) == NULL
)
363 * This hack to make users that don't have a localhost entry in
364 * their hosts file or DNS happy...
367 if (strcasecmp(host
, "localhost") != 0)
369 else if ((hostaddr
= httpGetHostByName("127.0.0.1")) == NULL
)
374 * Verify that it is an IPv4 address (IPv6 support will come in CUPS 1.2...)
378 if ((hostaddr
->h_addrtype
!= AF_INET
|| hostaddr
->h_length
!= 4) &&
379 (hostaddr
->h_addrtype
!= AF_INET6
|| hostaddr
->h_length
!= 16))
382 if (hostaddr
->h_addrtype
!= AF_INET
|| hostaddr
->h_length
!= 4)
384 #endif /* AF_INET6 */
387 * Allocate memory for the structure...
390 http
= calloc(sizeof(http_t
), 1);
394 http
->version
= HTTP_1_1
;
396 http
->activity
= time(NULL
);
400 * Set the encryption status...
403 if (port
== 443) /* Always use encryption for https */
404 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
406 http
->encryption
= encrypt
;
409 * Loop through the addresses we have until one of them connects...
412 strncpy(http
->hostname
, host
, sizeof(http
->hostname
) - 1);
414 for (i
= 0; hostaddr
->h_addr_list
[i
]; i
++)
417 * Load the address...
420 httpAddrLoad(hostaddr
, port
, i
, &(http
->hostaddr
));
423 * Connect to the remote system...
426 if (!httpReconnect(http
))
431 * Return the new structure if we could connect; otherwise, bail out...
434 if (hostaddr
->h_addr_list
[i
])
445 * 'httpEncryption()' - Set the required encryption on the link.
448 int /* O - -1 on error, 0 on success */
449 httpEncryption(http_t
*http
, /* I - HTTP data */
450 http_encryption_t e
) /* I - New encryption preference */
456 http
->encryption
= e
;
458 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
459 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
460 return (httpReconnect(http
));
461 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
462 return (http_upgrade(http
));
466 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
470 #endif /* HAVE_LIBSSL */
475 * 'httpReconnect()' - Reconnect to a HTTP server...
478 int /* O - 0 on success, non-zero on failure */
479 httpReconnect(http_t
*http
) /* I - HTTP data */
481 int val
; /* Socket option value */
483 SSL_CTX
*context
; /* Context for encryption */
484 SSL
*conn
; /* Connection for encryption */
489 conn
= (SSL
*)(http
->tls
);
490 context
= SSL_get_SSL_CTX(conn
);
493 SSL_CTX_free(context
);
498 #endif /* HAVE_LIBSSL */
501 * Close any previously open socket...
506 closesocket(http
->fd
);
512 * Create the socket and set options to allow reuse.
515 if ((http
->fd
= socket(http
->hostaddr
.addr
.sa_family
, SOCK_STREAM
, 0)) < 0)
518 http
->error
= WSAGetLastError();
522 http
->status
= HTTP_ERROR
;
527 fcntl(http
->fd
, F_SETFD
, FD_CLOEXEC
); /* Close this socket when starting *
528 * other processes... */
529 #endif /* FD_CLOEXEC */
532 setsockopt(http
->fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *)&val
, sizeof(val
));
536 setsockopt(http
->fd
, SOL_SOCKET
, SO_REUSEPORT
, &val
, sizeof(val
));
537 #endif /* SO_REUSEPORT */
540 * Using TCP_NODELAY improves responsiveness, especially on systems
541 * with a slow loopback interface... Since we write large buffers
542 * when sending print files and requests, there shouldn't be any
543 * performance penalty for this...
547 setsockopt(http
->fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
550 * Connect to the server...
553 if (connect(http
->fd
, (struct sockaddr
*)&(http
->hostaddr
),
554 sizeof(http
->hostaddr
)) < 0)
557 http
->error
= WSAGetLastError();
561 http
->status
= HTTP_ERROR
;
564 closesocket(http
->fd
);
575 http
->status
= HTTP_CONTINUE
;
578 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
581 * Always do encryption via SSL.
584 context
= SSL_CTX_new(SSLv23_method());
585 conn
= SSL_new(context
);
587 SSL_set_fd(conn
, http
->fd
);
588 if (SSL_connect(conn
) != 1)
590 SSL_CTX_free(context
);
594 http
->error
= WSAGetLastError();
598 http
->status
= HTTP_ERROR
;
601 closesocket(http
->fd
);
611 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
612 return (http_upgrade(http
));
613 #endif /* HAVE_LIBSSL */
620 * 'httpGetHostByName()' - Lookup a hostname or IP address, and return
621 * address records for the specified name.
624 struct hostent
* /* O - Host entry */
625 httpGetHostByName(const char *name
) /* I - Hostname or IP address */
627 unsigned ip
[4]; /* IP address components */
628 static unsigned packed_ip
; /* Packed IPv4 address */
629 static char *packed_ptr
[2]; /* Pointer to packed address */
630 static struct hostent host_ip
; /* Host entry for IP address */
634 * This function is needed because some operating systems have a
635 * buggy implementation of httpGetHostByName() that does not support
636 * IP addresses. If the first character of the name string is a
637 * number, then sscanf() is used to extract the IP components.
638 * We then pack the components into an IPv4 address manually,
639 * since the inet_aton() function is deprecated. We use the
640 * htonl() macro to get the right byte order for the address.
643 if (isdigit(name
[0]))
646 * We have an IP address; break it up and provide the host entry
647 * to the caller. Currently only supports IPv4 addresses, although
648 * it should be trivial to support IPv6 in CUPS 1.2.
651 if (sscanf(name
, "%u.%u.%u.%u", ip
, ip
+ 1, ip
+ 2, ip
+ 3) != 4)
652 return (NULL
); /* Must have 4 numbers */
654 packed_ip
= htonl(((((((ip
[0] << 8) | ip
[1]) << 8) | ip
[2]) << 8) | ip
[3]));
657 * Fill in the host entry and return it...
660 host_ip
.h_name
= (char *)name
;
661 host_ip
.h_aliases
= NULL
;
662 host_ip
.h_addrtype
= AF_INET
;
663 host_ip
.h_length
= 4;
664 host_ip
.h_addr_list
= packed_ptr
;
665 packed_ptr
[0] = (char *)(&packed_ip
);
666 packed_ptr
[1] = NULL
;
673 * Use the gethostbyname() function to get the IP address for
677 return (gethostbyname(name
));
683 * 'httpSeparate()' - Separate a Universal Resource Identifier into its
688 httpSeparate(const char *uri
, /* I - Universal Resource Identifier */
689 char *method
, /* O - Method [32] (http, https, etc.) */
690 char *username
, /* O - Username [32] */
691 char *host
, /* O - Hostname [32] */
692 int *port
, /* O - Port number to use */
693 char *resource
) /* O - Resource/filename [1024] */
695 char *ptr
; /* Pointer into string... */
696 const char *atsign
, /* @ sign */
697 *slash
; /* Separator */
698 char safeuri
[HTTP_MAX_URI
]; /* "Safe" local copy of URI */
702 * Range check input...
705 if (uri
== NULL
|| method
== NULL
|| username
== NULL
|| host
== NULL
||
706 port
== NULL
|| resource
== NULL
)
710 * Copy the URL to a local string to make sure we don't have a URL
711 * longer than HTTP_MAX_URI characters long...
714 strncpy(safeuri
, uri
, sizeof(safeuri
));
715 safeuri
[sizeof(safeuri
) - 1] = '\0';
720 * Grab the method portion of the URI...
723 if (strncmp(uri
, "//", 2) == 0)
726 * Workaround for HP IPP client bug...
729 strcpy(method
, "ipp");
734 * Standard URI with method...
737 for (ptr
= host
; *uri
!= ':' && *uri
!= '\0'; uri
++)
738 if (ptr
< (host
+ HTTP_MAX_URI
- 1))
746 * If the method contains a period or slash, then it's probably
747 * hostname/filename...
750 if (strchr(host
, '.') != NULL
|| strchr(host
, '/') != NULL
|| *uri
== '\0')
752 if ((ptr
= strchr(host
, '/')) != NULL
)
754 strncpy(resource
, ptr
, HTTP_MAX_URI
);
755 resource
[HTTP_MAX_URI
- 1] = '\0';
764 * OK, we have "hostname:port[/resource]"...
767 *port
= strtol(uri
, (char **)&uri
, 10);
771 strncpy(resource
, uri
, HTTP_MAX_URI
);
772 resource
[HTTP_MAX_URI
- 1] = '\0';
778 strcpy(method
, "http");
784 strncpy(method
, host
, 31);
790 * If the method starts with less than 2 slashes then it is a local resource...
793 if (strncmp(uri
, "//", 2) != 0)
795 strncpy(resource
, uri
, 1023);
796 resource
[1023] = '\0';
805 * Grab the username, if any...
811 if ((slash
= strchr(uri
, '/')) == NULL
)
812 slash
= uri
+ strlen(uri
);
814 if ((atsign
= strchr(uri
, '@')) != NULL
&& atsign
< slash
)
817 * Got a username:password combo...
820 for (ptr
= username
; uri
< atsign
; uri
++)
821 if (ptr
< (username
+ HTTP_MAX_URI
- 1))
832 * Grab the hostname...
835 for (ptr
= host
; *uri
!= ':' && *uri
!= '/' && *uri
!= '\0'; uri
++)
836 if (ptr
< (host
+ HTTP_MAX_URI
- 1))
843 if (strcasecmp(method
, "http") == 0)
845 else if (strcasecmp(method
, "https") == 0)
847 else if (strcasecmp(method
, "ipp") == 0)
849 else if (strcasecmp(method
, "socket") == 0) /* Not registered yet... */
857 * Parse port number...
862 while (isdigit(*uri
))
864 *port
= (*port
* 10) + *uri
- '0';
872 * Hostname but no port or path...
881 * The remaining portion is the resource string...
884 strncpy(resource
, uri
, HTTP_MAX_URI
);
885 resource
[HTTP_MAX_URI
- 1] = '\0';
890 * 'httpGetSubField()' - Get a sub-field value.
893 char * /* O - Value or NULL */
894 httpGetSubField(http_t
*http
, /* I - HTTP data */
895 http_field_t field
, /* I - Field index */
896 const char *name
, /* I - Name of sub-field */
897 char *value
) /* O - Value string */
899 const char *fptr
; /* Pointer into field */
900 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
901 *ptr
; /* Pointer into string buffer */
905 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
906 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
907 name
== NULL
|| value
== NULL
)
910 for (fptr
= http
->fields
[field
]; *fptr
;)
913 * Skip leading whitespace...
916 while (isspace(*fptr
))
926 * Get the sub-field name...
930 *fptr
&& *fptr
!= '=' && !isspace(*fptr
) && ptr
< (temp
+ sizeof(temp
) - 1);
936 * Skip trailing chars up to the '='...
939 while (*fptr
&& *fptr
!= '=')
946 * Skip = and leading whitespace...
951 while (isspace(*fptr
))
957 * Read quoted string...
960 for (ptr
= value
, fptr
++;
961 *fptr
&& *fptr
!= '\"' && ptr
< (value
+ HTTP_MAX_VALUE
- 1);
966 while (*fptr
&& *fptr
!= '\"')
975 * Read unquoted string...
979 *fptr
&& !isspace(*fptr
) && *fptr
!= ',' && ptr
< (value
+ HTTP_MAX_VALUE
- 1);
984 while (*fptr
&& !isspace(*fptr
) && *fptr
!= ',')
989 * See if this is the one...
992 if (strcmp(name
, temp
) == 0)
1003 * 'httpSetField()' - Set the value of an HTTP header.
1007 httpSetField(http_t
*http
, /* I - HTTP data */
1008 http_field_t field
, /* I - Field index */
1009 const char *value
) /* I - Value */
1012 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
1013 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
1017 strncpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
- 1);
1018 http
->fields
[field
][HTTP_MAX_VALUE
- 1] = '\0';
1023 * 'httpDelete()' - Send a DELETE request to the server.
1026 int /* O - Status of call (0 = success) */
1027 httpDelete(http_t
*http
, /* I - HTTP data */
1028 const char *uri
) /* I - URI to delete */
1030 return (http_send(http
, HTTP_DELETE
, uri
));
1035 * 'httpGet()' - Send a GET request to the server.
1038 int /* O - Status of call (0 = success) */
1039 httpGet(http_t
*http
, /* I - HTTP data */
1040 const char *uri
) /* I - URI to get */
1042 return (http_send(http
, HTTP_GET
, uri
));
1047 * 'httpHead()' - Send a HEAD request to the server.
1050 int /* O - Status of call (0 = success) */
1051 httpHead(http_t
*http
, /* I - HTTP data */
1052 const char *uri
) /* I - URI for head */
1054 return (http_send(http
, HTTP_HEAD
, uri
));
1059 * 'httpOptions()' - Send an OPTIONS request to the server.
1062 int /* O - Status of call (0 = success) */
1063 httpOptions(http_t
*http
, /* I - HTTP data */
1064 const char *uri
) /* I - URI for options */
1066 return (http_send(http
, HTTP_OPTIONS
, uri
));
1071 * 'httpPost()' - Send a POST request to the server.
1074 int /* O - Status of call (0 = success) */
1075 httpPost(http_t
*http
, /* I - HTTP data */
1076 const char *uri
) /* I - URI for post */
1078 httpGetLength(http
);
1080 return (http_send(http
, HTTP_POST
, uri
));
1085 * 'httpPut()' - Send a PUT request to the server.
1088 int /* O - Status of call (0 = success) */
1089 httpPut(http_t
*http
, /* I - HTTP data */
1090 const char *uri
) /* I - URI to put */
1092 httpGetLength(http
);
1094 return (http_send(http
, HTTP_PUT
, uri
));
1099 * 'httpTrace()' - Send an TRACE request to the server.
1102 int /* O - Status of call (0 = success) */
1103 httpTrace(http_t
*http
, /* I - HTTP data */
1104 const char *uri
) /* I - URI for trace */
1106 return (http_send(http
, HTTP_TRACE
, uri
));
1111 * 'httpFlush()' - Flush data from a HTTP connection.
1115 httpFlush(http_t
*http
) /* I - HTTP data */
1117 char buffer
[8192]; /* Junk buffer */
1120 while (httpRead(http
, buffer
, sizeof(buffer
)) > 0);
1125 * 'httpRead()' - Read data from a HTTP connection.
1128 int /* O - Number of bytes read */
1129 httpRead(http_t
*http
, /* I - HTTP data */
1130 char *buffer
, /* I - Buffer for data */
1131 int length
) /* I - Maximum number of bytes */
1133 int bytes
; /* Bytes read */
1134 char len
[32]; /* Length string */
1137 DEBUG_printf(("httpRead(%08x, %08x, %d)\n", http
, buffer
, length
));
1139 if (http
== NULL
|| buffer
== NULL
)
1142 http
->activity
= time(NULL
);
1147 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1148 http
->data_remaining
<= 0)
1150 DEBUG_puts("httpRead: Getting chunk length...");
1152 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1154 DEBUG_puts("httpRead: Could not get length!");
1158 http
->data_remaining
= strtol(len
, NULL
, 16);
1161 DEBUG_printf(("httpRead: data_remaining = %d\n", http
->data_remaining
));
1163 if (http
->data_remaining
== 0)
1166 * A zero-length chunk ends a transfer; unless we are reading POST
1170 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1171 httpGets(len
, sizeof(len
), http
);
1173 if (http
->state
== HTTP_POST_RECV
)
1176 http
->state
= HTTP_WAITING
;
1180 else if (length
> http
->data_remaining
)
1181 length
= http
->data_remaining
;
1183 if (http
->used
== 0 && length
<= 256)
1186 * Buffer small reads for better performance...
1189 if (http
->data_remaining
> sizeof(http
->buffer
))
1190 bytes
= sizeof(http
->buffer
);
1192 bytes
= http
->data_remaining
;
1196 bytes
= SSL_read((SSL
*)(http
->tls
), http
->buffer
, bytes
);
1198 #endif /* HAVE_LIBSSL */
1200 DEBUG_printf(("httpRead: reading %d bytes from socket into buffer...\n",
1203 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1205 DEBUG_printf(("httpRead: read %d bytes from socket into buffer...\n",
1214 http
->error
= WSAGetLastError();
1216 http
->error
= errno
;
1226 if (length
> http
->used
)
1227 length
= http
->used
;
1231 DEBUG_printf(("httpRead: grabbing %d bytes from input buffer...\n", bytes
));
1233 memcpy(buffer
, http
->buffer
, length
);
1234 http
->used
-= length
;
1237 memcpy(http
->buffer
, http
->buffer
+ length
, http
->used
);
1241 bytes
= SSL_read((SSL
*)(http
->tls
), buffer
, length
);
1242 #endif /* HAVE_LIBSSL */
1245 DEBUG_printf(("httpRead: reading %d bytes from socket...\n", length
));
1246 bytes
= recv(http
->fd
, buffer
, length
, 0);
1247 DEBUG_printf(("httpRead: read %d bytes from socket...\n", bytes
));
1251 http
->data_remaining
-= bytes
;
1254 http
->error
= WSAGetLastError();
1256 http
->error
= errno
;
1259 if (http
->data_remaining
== 0)
1261 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1262 httpGets(len
, sizeof(len
), http
);
1264 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
1266 if (http
->state
== HTTP_POST_RECV
)
1269 http
->state
= HTTP_WAITING
;
1278 * 'httpWrite()' - Write data to a HTTP connection.
1281 int /* O - Number of bytes written */
1282 httpWrite(http_t
*http
, /* I - HTTP data */
1283 const char *buffer
, /* I - Buffer for data */
1284 int length
) /* I - Number of bytes to write */
1286 int tbytes
, /* Total bytes sent */
1287 bytes
; /* Bytes sent */
1290 if (http
== NULL
|| buffer
== NULL
)
1293 http
->activity
= time(NULL
);
1295 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1297 if (httpPrintf(http
, "%x\r\n", length
) < 0)
1303 * A zero-length chunk ends a transfer; unless we are sending POST
1307 DEBUG_puts("httpWrite: changing states...");
1309 if (http
->state
== HTTP_POST_RECV
)
1311 else if (http
->state
== HTTP_PUT_RECV
)
1312 http
->state
= HTTP_STATUS
;
1314 http
->state
= HTTP_WAITING
;
1316 if (httpPrintf(http
, "\r\n") < 0)
1329 bytes
= SSL_write((SSL
*)(http
->tls
), buffer
, length
);
1331 #endif /* HAVE_LIBSSL */
1332 bytes
= send(http
->fd
, buffer
, length
, 0);
1336 DEBUG_puts("httpWrite: error writing data...\n");
1344 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1345 http
->data_remaining
-= bytes
;
1348 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1349 if (httpPrintf(http
, "\r\n") < 0)
1352 if (http
->data_remaining
== 0 && http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1355 * Finished with the transfer; unless we are sending POST data, go idle...
1358 DEBUG_puts("httpWrite: changing states...");
1360 if (http
->state
== HTTP_POST_RECV
)
1363 http
->state
= HTTP_WAITING
;
1366 DEBUG_printf(("httpWrite: wrote %d bytes...\n", tbytes
));
1373 * 'httpGets()' - Get a line of text from a HTTP connection.
1376 char * /* O - Line or NULL */
1377 httpGets(char *line
, /* I - Line to read into */
1378 int length
, /* I - Max length of buffer */
1379 http_t
*http
) /* I - HTTP data */
1381 char *lineptr
, /* Pointer into line */
1382 *bufptr
, /* Pointer into input buffer */
1383 *bufend
; /* Pointer to end of buffer */
1384 int bytes
; /* Number of bytes read */
1387 DEBUG_printf(("httpGets(%08x, %d, %08x)\n", line
, length
, http
));
1389 if (http
== NULL
|| line
== NULL
)
1393 * Pre-scan the buffer and see if there is a newline in there...
1404 bufptr
= http
->buffer
;
1405 bufend
= http
->buffer
+ http
->used
;
1407 while (bufptr
< bufend
)
1408 if (*bufptr
== 0x0a)
1413 if (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
)
1416 * No newline; see if there is more data to be read...
1421 bytes
= SSL_read((SSL
*)(http
->tls
), bufend
,
1422 HTTP_MAX_BUFFER
- http
->used
);
1424 #endif /* HAVE_LIBSSL */
1425 bytes
= recv(http
->fd
, bufend
, HTTP_MAX_BUFFER
- http
->used
, 0);
1430 * Nope, can't get a line this time...
1434 if (WSAGetLastError() != http
->error
)
1436 http
->error
= WSAGetLastError();
1440 DEBUG_printf(("httpGets(): recv() error %d!\n", WSAGetLastError()));
1442 if (errno
!= http
->error
)
1444 http
->error
= errno
;
1448 DEBUG_printf(("httpGets(): recv() error %d!\n", errno
));
1453 else if (bytes
== 0)
1456 http
->error
= EPIPE
;
1462 * Yup, update the amount used and the end pointer...
1465 http
->used
+= bytes
;
1469 while (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
);
1471 http
->activity
= time(NULL
);
1474 * Read a line from the buffer...
1478 bufptr
= http
->buffer
;
1482 while (bufptr
< bufend
&& bytes
< length
)
1486 if (*bufptr
== 0x0a)
1491 else if (*bufptr
== 0x0d)
1494 *lineptr
++ = *bufptr
++;
1501 http
->used
-= bytes
;
1503 memcpy(http
->buffer
, bufptr
, http
->used
);
1505 DEBUG_printf(("httpGets(): Returning \"%s\"\n", line
));
1509 DEBUG_puts("httpGets(): No new line available!");
1516 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1519 int /* O - Number of bytes written */
1520 httpPrintf(http_t
*http
, /* I - HTTP data */
1521 const char *format
, /* I - printf-style format string */
1522 ...) /* I - Additional args as needed */
1524 int bytes
, /* Number of bytes to write */
1525 nbytes
, /* Number of bytes written */
1526 tbytes
; /* Number of bytes all together */
1527 char buf
[HTTP_MAX_BUFFER
], /* Buffer for formatted string */
1528 *bufptr
; /* Pointer into buffer */
1529 va_list ap
; /* Variable argument pointer */
1532 va_start(ap
, format
);
1533 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1536 DEBUG_printf(("httpPrintf: %s", buf
));
1538 for (tbytes
= 0, bufptr
= buf
; tbytes
< bytes
; tbytes
+= nbytes
, bufptr
+= nbytes
)
1542 nbytes
= SSL_write((SSL
*)(http
->tls
), bufptr
, bytes
- tbytes
);
1544 #endif /* HAVE_LIBSSL */
1545 nbytes
= send(http
->fd
, bufptr
, bytes
- tbytes
, 0);
1556 * 'httpStatus()' - Return a short string describing a HTTP status code.
1559 const char * /* O - String or NULL */
1560 httpStatus(http_status_t status
) /* I - HTTP status code */
1564 case HTTP_CONTINUE
:
1565 return ("Continue");
1566 case HTTP_SWITCHING_PROTOCOLS
:
1567 return ("Switching Protocols");
1572 case HTTP_ACCEPTED
:
1573 return ("Accepted");
1574 case HTTP_NO_CONTENT
:
1575 return ("No Content");
1576 case HTTP_NOT_MODIFIED
:
1577 return ("Not Modified");
1578 case HTTP_BAD_REQUEST
:
1579 return ("Bad Request");
1580 case HTTP_UNAUTHORIZED
:
1581 return ("Unauthorized");
1582 case HTTP_FORBIDDEN
:
1583 return ("Forbidden");
1584 case HTTP_NOT_FOUND
:
1585 return ("Not Found");
1586 case HTTP_REQUEST_TOO_LARGE
:
1587 return ("Request Entity Too Large");
1588 case HTTP_URI_TOO_LONG
:
1589 return ("URI Too Long");
1590 case HTTP_UPGRADE_REQUIRED
:
1591 return ("Upgrade Required");
1592 case HTTP_NOT_IMPLEMENTED
:
1593 return ("Not Implemented");
1594 case HTTP_NOT_SUPPORTED
:
1595 return ("Not Supported");
1603 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
1606 const char * /* O - Date/time string */
1607 httpGetDateString(time_t t
) /* I - UNIX time */
1610 static char datetime
[256];
1614 snprintf(datetime
, sizeof(datetime
), "%s, %02d %s %d %02d:%02d:%02d GMT",
1615 days
[tdate
->tm_wday
], tdate
->tm_mday
, months
[tdate
->tm_mon
],
1616 tdate
->tm_year
+ 1900, tdate
->tm_hour
, tdate
->tm_min
, tdate
->tm_sec
);
1623 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
1626 time_t /* O - UNIX time */
1627 httpGetDateTime(const char *s
) /* I - Date/time string */
1629 int i
; /* Looping var */
1630 struct tm tdate
; /* Time/date structure */
1631 char mon
[16]; /* Abbreviated month name */
1632 int day
, year
; /* Day of month and year */
1633 int hour
, min
, sec
; /* Time */
1636 if (sscanf(s
, "%*s%d%15s%d%d:%d:%d", &day
, mon
, &year
, &hour
, &min
, &sec
) < 6)
1639 for (i
= 0; i
< 12; i
++)
1640 if (strcasecmp(mon
, months
[i
]) == 0)
1647 tdate
.tm_mday
= day
;
1648 tdate
.tm_year
= year
- 1900;
1649 tdate
.tm_hour
= hour
;
1654 return (mktime(&tdate
));
1659 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1662 http_status_t
/* O - HTTP status */
1663 httpUpdate(http_t
*http
) /* I - HTTP data */
1665 char line
[1024], /* Line from connection... */
1666 *value
; /* Pointer to value on line */
1667 http_field_t field
; /* Field index */
1668 int major
, minor
; /* HTTP version numbers */
1669 http_status_t status
; /* Authorization status */
1671 SSL_CTX
*context
; /* Context for encryption */
1672 SSL
*conn
; /* Connection for encryption */
1673 #endif /* HAVE_LIBSSL */
1676 DEBUG_printf(("httpUpdate(%08x)\n", http
));
1679 * If we haven't issued any commands, then there is nothing to "update"...
1682 if (http
->state
== HTTP_WAITING
)
1683 return (HTTP_CONTINUE
);
1686 * Grab all of the lines we can from the connection...
1689 while (httpGets(line
, sizeof(line
), http
) != NULL
)
1693 if (line
[0] == '\0')
1696 * Blank line means the start of the data section (if any). Return
1697 * the result code, too...
1699 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
1700 * Instead, we just return HTTP_CONTINUE to the caller and keep on
1704 if (http
->status
== HTTP_CONTINUE
)
1705 return (http
->status
);
1708 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
1710 context
= SSL_CTX_new(SSLv23_method());
1711 conn
= SSL_new(context
);
1713 SSL_set_fd(conn
, http
->fd
);
1714 if (SSL_connect(conn
) != 1)
1716 SSL_CTX_free(context
);
1720 http
->error
= WSAGetLastError();
1722 http
->error
= errno
;
1724 http
->status
= HTTP_ERROR
;
1727 closesocket(http
->fd
);
1732 return (HTTP_ERROR
);
1737 return (HTTP_CONTINUE
);
1739 else if (http
->status
== HTTP_UPGRADE_REQUIRED
&&
1740 http
->encryption
!= HTTP_ENCRYPT_NEVER
)
1741 http
->encryption
= HTTP_ENCRYPT_REQUIRED
;
1742 #endif /* HAVE_LIBSSL */
1744 httpGetLength(http
);
1746 switch (http
->state
)
1750 case HTTP_POST_RECV
:
1756 http
->state
= HTTP_WAITING
;
1760 return (http
->status
);
1762 else if (strncmp(line
, "HTTP/", 5) == 0)
1765 * Got the beginning of a response...
1768 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, (int *)&status
) != 3)
1769 return (HTTP_ERROR
);
1771 http
->version
= (http_version_t
)(major
* 100 + minor
);
1772 http
->status
= status
;
1774 else if ((value
= strchr(line
, ':')) != NULL
)
1781 while (isspace(*value
))
1785 * Be tolerants of servers that send unknown attribute fields...
1788 if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
1790 DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line
));
1794 httpSetField(http
, field
, value
);
1798 http
->status
= HTTP_ERROR
;
1799 return (HTTP_ERROR
);
1804 * See if there was an error...
1809 http
->status
= HTTP_ERROR
;
1810 return (HTTP_ERROR
);
1814 * If we haven't already returned, then there is nothing new...
1817 return (HTTP_CONTINUE
);
1822 * 'httpDecode64()' - Base64-decode a string.
1825 char * /* O - Decoded string */
1826 httpDecode64(char *out
, /* I - String to write to */
1827 const char *in
) /* I - String to read from */
1829 int pos
, /* Bit position */
1830 base64
; /* Value of this character */
1831 char *outptr
; /* Output pointer */
1834 for (outptr
= out
, pos
= 0; *in
!= '\0'; in
++)
1837 * Decode this character into a number from 0 to 63...
1840 if (*in
>= 'A' && *in
<= 'Z')
1842 else if (*in
>= 'a' && *in
<= 'z')
1843 base64
= *in
- 'a' + 26;
1844 else if (*in
>= '0' && *in
<= '9')
1845 base64
= *in
- '0' + 52;
1846 else if (*in
== '+')
1848 else if (*in
== '/')
1850 else if (*in
== '=')
1856 * Store the result in the appropriate chars...
1862 *outptr
= base64
<< 2;
1866 *outptr
++ |= (base64
>> 4) & 3;
1867 *outptr
= (base64
<< 4) & 255;
1871 *outptr
++ |= (base64
>> 2) & 15;
1872 *outptr
= (base64
<< 6) & 255;
1876 *outptr
++ |= base64
;
1885 * Return the decoded string...
1893 * 'httpEncode64()' - Base64-encode a string.
1896 char * /* O - Encoded string */
1897 httpEncode64(char *out
, /* I - String to write to */
1898 const char *in
) /* I - String to read from */
1900 char *outptr
; /* Output pointer */
1901 static char base64
[] = /* Base64 characters... */
1903 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1904 "abcdefghijklmnopqrstuvwxyz"
1910 for (outptr
= out
; *in
!= '\0'; in
++)
1913 * Encode the up to 3 characters as 4 Base64 numbers...
1916 *outptr
++ = base64
[in
[0] >> 2];
1917 *outptr
++ = base64
[((in
[0] << 4) | (in
[1] >> 4)) & 63];
1926 *outptr
++ = base64
[((in
[0] << 2) | (in
[1] >> 6)) & 63];
1932 *outptr
++ = base64
[in
[0] & 63];
1939 * Return the encoded string...
1947 * 'httpGetLength()' - Get the amount of data remaining from the
1948 * content-length or transfer-encoding fields.
1951 int /* O - Content length */
1952 httpGetLength(http_t
*http
) /* I - HTTP data */
1954 DEBUG_printf(("httpGetLength(%08x)\n", http
));
1956 if (strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked") == 0)
1958 DEBUG_puts("httpGetLength: chunked request!");
1960 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
1961 http
->data_remaining
= 0;
1965 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1968 * The following is a hack for HTTP servers that don't send a
1969 * content-length or transfer-encoding field...
1971 * If there is no content-length then the connection must close
1972 * after the transfer is complete...
1975 if (http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] == '\0')
1976 http
->data_remaining
= 2147483647;
1978 http
->data_remaining
= atoi(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
]);
1980 DEBUG_printf(("httpGetLength: content_length = %d\n", http
->data_remaining
));
1983 return (http
->data_remaining
);
1988 * 'http_field()' - Return the field index for a field name.
1991 static http_field_t
/* O - Field index */
1992 http_field(const char *name
) /* I - String name */
1994 int i
; /* Looping var */
1997 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
1998 if (strcasecmp(name
, http_fields
[i
]) == 0)
1999 return ((http_field_t
)i
);
2001 return (HTTP_FIELD_UNKNOWN
);
2006 * 'http_send()' - Send a request with all fields and the trailing blank line.
2009 static int /* O - 0 on success, non-zero on error */
2010 http_send(http_t
*http
, /* I - HTTP data */
2011 http_state_t request
, /* I - Request code */
2012 const char *uri
) /* I - URI */
2014 int i
; /* Looping var */
2015 char *ptr
, /* Pointer in buffer */
2016 buf
[1024]; /* Encoded URI buffer */
2017 static const char *codes
[] = /* Request code strings */
2033 static const char *hex
= "0123456789ABCDEF";
2037 if (http
== NULL
|| uri
== NULL
)
2041 * Encode the URI as needed...
2044 for (ptr
= buf
; *uri
!= '\0' && ptr
< (buf
+ sizeof(buf
) - 1); uri
++)
2045 if (*uri
<= ' ' || *uri
>= 127)
2047 if (ptr
< (buf
+ sizeof(buf
) - 1))
2049 if (ptr
< (buf
+ sizeof(buf
) - 1))
2050 *ptr
++ = hex
[(*uri
>> 4) & 15];
2051 if (ptr
< (buf
+ sizeof(buf
) - 1))
2052 *ptr
++ = hex
[*uri
& 15];
2060 * See if we had an error the last time around; if so, reconnect...
2063 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
2064 httpReconnect(http
);
2067 * Send the request header...
2070 http
->state
= request
;
2071 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
2074 http
->status
= HTTP_CONTINUE
;
2077 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
2079 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
2080 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
2082 #endif /* HAVE_LIBSSL */
2084 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
2086 http
->status
= HTTP_ERROR
;
2090 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2091 if (http
->fields
[i
][0] != '\0')
2093 DEBUG_printf(("%s: %s\n", http_fields
[i
], http
->fields
[i
]));
2095 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], http
->fields
[i
]) < 1)
2097 http
->status
= HTTP_ERROR
;
2102 if (httpPrintf(http
, "\r\n") < 1)
2104 http
->status
= HTTP_ERROR
;
2108 httpClearFields(http
);
2116 * 'http_upgrade()' - Force upgrade to TLS encryption.
2119 static int /* O - Status of connection */
2120 http_upgrade(http_t
*http
) /* I - HTTP data */
2122 int ret
; /* Return value */
2123 http_t myhttp
; /* Local copy of HTTP data */
2126 DEBUG_printf(("http_upgrade(%p)\n", http
));
2129 * Copy the HTTP data to a local variable so we can do the OPTIONS
2130 * request without interfering with the existing request data...
2133 memcpy(&myhttp
, http
, sizeof(myhttp
));
2136 * Send an OPTIONS request to the server, requiring SSL or TLS
2137 * encryption on the link...
2140 httpClearFields(&myhttp
);
2141 httpSetField(&myhttp
, HTTP_FIELD_CONNECTION
, "upgrade");
2142 httpSetField(&myhttp
, HTTP_FIELD_UPGRADE
, "TLS/1.0, SSL/2.0, SSL/3.0");
2144 if ((ret
= httpOptions(&myhttp
, "*")) == 0)
2147 * Wait for the secure connection...
2150 while (httpUpdate(&myhttp
) == HTTP_CONTINUE
);
2156 * Copy the HTTP data back over, if any...
2159 http
->fd
= myhttp
.fd
;
2160 http
->error
= myhttp
.error
;
2161 http
->activity
= myhttp
.activity
;
2162 http
->status
= myhttp
.status
;
2163 http
->version
= myhttp
.version
;
2164 http
->keep_alive
= myhttp
.keep_alive
;
2165 http
->used
= myhttp
.used
;
2168 memcpy(http
->buffer
, myhttp
.buffer
, http
->used
);
2170 http
->auth_type
= myhttp
.auth_type
;
2171 http
->nonce_count
= myhttp
.nonce_count
;
2173 memcpy(http
->nonce
, myhttp
.nonce
, sizeof(http
->nonce
));
2175 http
->tls
= myhttp
.tls
;
2176 http
->encryption
= myhttp
.encryption
;
2179 * See if we actually went secure...
2185 * Server does not support HTTP upgrade...
2188 DEBUG_puts("Server does not support HTTP upgrade!");
2191 closesocket(http
->fd
);
2203 #endif /* HAVE_LIBSSL */
2207 * End of "$Id: http.c,v 1.82.2.8 2002/01/27 21:20:28 mike Exp $".