2 * "$Id: http.c,v 1.96 2002/04/09 19:27:06 mike Exp $"
4 * HTTP routines for the Common UNIX Printing System (CUPS) scheduler.
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
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 * httpGetHostByName() - Lookup a hostname or IP address, and return
38 * address records for the specified name.
39 * httpSeparate() - Separate a Universal Resource Identifier into its
41 * httpGetSubField() - Get a sub-field value.
42 * httpSetField() - Set the value of an HTTP header.
43 * httpDelete() - Send a DELETE request to the server.
44 * httpGet() - Send a GET request to the server.
45 * httpHead() - Send a HEAD request to the server.
46 * httpOptions() - Send an OPTIONS request to the server.
47 * httpPost() - Send a POST request to the server.
48 * httpPut() - Send a PUT request to the server.
49 * httpTrace() - Send an TRACE request to the server.
50 * httpFlush() - Flush data from a HTTP connection.
51 * httpRead() - Read data from a HTTP connection.
52 * httpWrite() - Write data to a HTTP connection.
53 * httpGets() - Get a line of text from a HTTP connection.
54 * httpPrintf() - Print a formatted string to a HTTP connection.
55 * httpStatus() - Return a short string describing a HTTP status code.
56 * httpGetDateString() - Get a formatted date/time string from a time value.
57 * httpGetDateTime() - Get a time value from a formatted date/time string.
58 * httpUpdate() - Update the current HTTP state for incoming data.
59 * httpDecode64() - Base64-decode a string.
60 * httpEncode64() - Base64-encode a string.
61 * httpGetLength() - Get the amount of data remaining from the
62 * content-length or transfer-encoding fields.
63 * http_field() - Return the field index for a field name.
64 * http_send() - Send a request with all fields and the trailing
66 * http_upgrade() - Force upgrade to TLS encryption.
70 * Include necessary headers...
90 # include <openssl/err.h>
91 # include <openssl/rand.h>
92 # include <openssl/ssl.h>
93 #endif /* HAVE_LIBSSL */
97 * Some operating systems have done away with the Fxxxx constants for
98 * the fcntl() call; this works around that "feature"...
102 # define FNONBLK O_NONBLOCK
103 #endif /* !FNONBLK */
110 static http_field_t
http_field(const char *name
);
111 static int http_send(http_t
*http
, http_state_t request
,
114 static int http_upgrade(http_t
*http
);
115 #endif /* HAVE_LIBSSL */
122 static const char *http_fields
[] =
139 "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...)
377 if (hostaddr
->h_addrtype
!= AF_INET
|| hostaddr
->h_length
!= 4)
381 * Allocate memory for the structure...
384 http
= calloc(sizeof(http_t
), 1);
388 http
->version
= HTTP_1_1
;
390 http
->activity
= time(NULL
);
394 * Copy the hostname and port and then "reconnect"...
397 strncpy(http
->hostname
, host
, sizeof(http
->hostname
) - 1);
398 http
->hostaddr
.sin_family
= hostaddr
->h_addrtype
;
400 http
->hostaddr
.sin_port
= htons((u_short
)port
);
402 http
->hostaddr
.sin_port
= htons(port
);
406 * Set the encryption status...
409 if (port
== 443) /* Always use encryption for https */
410 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
412 http
->encryption
= encrypt
;
415 * Loop through the addresses we have until one of them connects...
418 strncpy(http
->hostname
, host
, sizeof(http
->hostname
) - 1);
420 for (i
= 0; hostaddr
->h_addr_list
[i
]; i
++)
423 * Load the address...
426 memcpy((char *)&(http
->hostaddr
.sin_addr
), hostaddr
->h_addr_list
[i
],
430 * Connect to the remote system...
433 if (!httpReconnect(http
))
438 * Could not connect to any known address - bail out!
447 * 'httpEncryption()' - Set the required encryption on the link.
450 int /* O - -1 on error, 0 on success */
451 httpEncryption(http_t
*http
, /* I - HTTP data */
452 http_encryption_t e
) /* I - New encryption preference */
458 http
->encryption
= e
;
460 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
461 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
462 return (httpReconnect(http
));
463 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
464 return (http_upgrade(http
));
468 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
472 #endif /* HAVE_LIBSSL */
477 * 'httpReconnect()' - Reconnect to a HTTP server...
480 int /* O - 0 on success, non-zero on failure */
481 httpReconnect(http_t
*http
) /* I - HTTP data */
483 int val
; /* Socket option value */
485 SSL_CTX
*context
; /* Context for encryption */
486 SSL
*conn
; /* Connection for encryption */
491 conn
= (SSL
*)(http
->tls
);
492 context
= SSL_get_SSL_CTX(conn
);
495 SSL_CTX_free(context
);
500 #endif /* HAVE_LIBSSL */
503 * Close any previously open socket...
508 closesocket(http
->fd
);
514 * Create the socket and set options to allow reuse.
517 if ((http
->fd
= socket(AF_INET
, SOCK_STREAM
, 0)) < 0)
520 http
->error
= WSAGetLastError();
524 http
->status
= HTTP_ERROR
;
529 fcntl(http
->fd
, F_SETFD
, FD_CLOEXEC
); /* Close this socket when starting *
530 * other processes... */
531 #endif /* FD_CLOEXEC */
534 setsockopt(http
->fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *)&val
, sizeof(val
));
538 setsockopt(http
->fd
, SOL_SOCKET
, SO_REUSEPORT
, &val
, sizeof(val
));
539 #endif /* SO_REUSEPORT */
542 * Using TCP_NODELAY improves responsiveness, especially on systems
543 * with a slow loopback interface... Since we write large buffers
544 * when sending print files and requests, there shouldn't be any
545 * performance penalty for this...
549 setsockopt(http
->fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
552 * Connect to the server...
555 if (connect(http
->fd
, (struct sockaddr
*)&(http
->hostaddr
),
556 sizeof(http
->hostaddr
)) < 0)
559 http
->error
= WSAGetLastError();
563 http
->status
= HTTP_ERROR
;
566 closesocket(http
->fd
);
577 http
->status
= HTTP_CONTINUE
;
580 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
583 * Always do encryption via SSL.
586 context
= SSL_CTX_new(SSLv23_method());
587 conn
= SSL_new(context
);
589 SSL_set_fd(conn
, http
->fd
);
590 if (SSL_connect(conn
) != 1)
592 SSL_CTX_free(context
);
596 http
->error
= WSAGetLastError();
600 http
->status
= HTTP_ERROR
;
603 closesocket(http
->fd
);
613 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
614 return (http_upgrade(http
));
615 #endif /* HAVE_LIBSSL */
622 * 'httpGetHostByName()' - Lookup a hostname or IP address, and return
623 * address records for the specified name.
626 struct hostent
* /* O - Host entry */
627 httpGetHostByName(const char *name
) /* I - Hostname or IP address */
629 unsigned ip
[4]; /* IP address components */
630 static unsigned packed_ip
; /* Packed IPv4 address */
631 static char *packed_ptr
[2]; /* Pointer to packed address */
632 static struct hostent host_ip
; /* Host entry for IP address */
634 #if defined(__APPLE__)
635 /* OS X hack to avoid it's ocassional long delay in lookupd */
636 static char sLoopback
[] = "127.0.0.1";
637 if (strcmp(name
, "localhost") == 0)
639 #endif /* __APPLE__ */
642 * This function is needed because some operating systems have a
643 * buggy implementation of httpGetHostByName() that does not support
644 * IP addresses. If the first character of the name string is a
645 * number, then sscanf() is used to extract the IP components.
646 * We then pack the components into an IPv4 address manually,
647 * since the inet_aton() function is deprecated. We use the
648 * htonl() macro to get the right byte order for the address.
651 if (isdigit(name
[0]))
654 * We have an IP address; break it up and provide the host entry
655 * to the caller. Currently only supports IPv4 addresses, although
656 * it should be trivial to support IPv6 in CUPS 1.2.
659 if (sscanf(name
, "%u.%u.%u.%u", ip
, ip
+ 1, ip
+ 2, ip
+ 3) != 4)
660 return (NULL
); /* Must have 4 numbers */
662 packed_ip
= htonl(((((((ip
[0] << 8) | ip
[1]) << 8) | ip
[2]) << 8) | ip
[3]));
665 * Fill in the host entry and return it...
668 host_ip
.h_name
= (char *)name
;
669 host_ip
.h_aliases
= NULL
;
670 host_ip
.h_addrtype
= AF_INET
;
671 host_ip
.h_length
= 4;
672 host_ip
.h_addr_list
= packed_ptr
;
673 packed_ptr
[0] = (char *)(&packed_ip
);
674 packed_ptr
[1] = NULL
;
681 * Use the gethostbyname() function to get the IP address for
685 return (gethostbyname(name
));
691 * 'httpSeparate()' - Separate a Universal Resource Identifier into its
696 httpSeparate(const char *uri
, /* I - Universal Resource Identifier */
697 char *method
, /* O - Method [32] (http, https, etc.) */
698 char *username
, /* O - Username [32] */
699 char *host
, /* O - Hostname [32] */
700 int *port
, /* O - Port number to use */
701 char *resource
) /* O - Resource/filename [1024] */
703 char *ptr
; /* Pointer into string... */
704 const char *atsign
, /* @ sign */
705 *slash
; /* Separator */
706 char safeuri
[HTTP_MAX_URI
]; /* "Safe" local copy of URI */
710 * Range check input...
713 if (uri
== NULL
|| method
== NULL
|| username
== NULL
|| host
== NULL
||
714 port
== NULL
|| resource
== NULL
)
718 * Copy the URL to a local string to make sure we don't have a URL
719 * longer than HTTP_MAX_URI characters long...
722 strncpy(safeuri
, uri
, sizeof(safeuri
));
723 safeuri
[sizeof(safeuri
) - 1] = '\0';
728 * Grab the method portion of the URI...
731 if (strncmp(uri
, "//", 2) == 0)
734 * Workaround for HP IPP client bug...
737 strcpy(method
, "ipp");
742 * Standard URI with method...
745 for (ptr
= host
; *uri
!= ':' && *uri
!= '\0'; uri
++)
746 if (ptr
< (host
+ HTTP_MAX_URI
- 1))
754 * If the method contains a period or slash, then it's probably
755 * hostname/filename...
758 if (strchr(host
, '.') != NULL
|| strchr(host
, '/') != NULL
|| *uri
== '\0')
760 if ((ptr
= strchr(host
, '/')) != NULL
)
762 strncpy(resource
, ptr
, HTTP_MAX_URI
);
763 resource
[HTTP_MAX_URI
- 1] = '\0';
772 * OK, we have "hostname:port[/resource]"...
775 *port
= strtol(uri
, (char **)&uri
, 10);
779 strncpy(resource
, uri
, HTTP_MAX_URI
);
780 resource
[HTTP_MAX_URI
- 1] = '\0';
786 strcpy(method
, "http");
792 strncpy(method
, host
, 31);
798 * If the method starts with less than 2 slashes then it is a local resource...
801 if (strncmp(uri
, "//", 2) != 0)
803 strncpy(resource
, uri
, 1023);
804 resource
[1023] = '\0';
813 * Grab the username, if any...
819 if ((slash
= strchr(uri
, '/')) == NULL
)
820 slash
= uri
+ strlen(uri
);
822 if ((atsign
= strchr(uri
, '@')) != NULL
&& atsign
< slash
)
825 * Got a username:password combo...
828 for (ptr
= username
; uri
< atsign
; uri
++)
829 if (ptr
< (username
+ HTTP_MAX_URI
- 1))
840 * Grab the hostname...
843 for (ptr
= host
; *uri
!= ':' && *uri
!= '/' && *uri
!= '\0'; uri
++)
844 if (ptr
< (host
+ HTTP_MAX_URI
- 1))
851 if (strcasecmp(method
, "http") == 0)
853 else if (strcasecmp(method
, "https") == 0)
855 else if (strcasecmp(method
, "ipp") == 0)
857 else if (strcasecmp(method
, "socket") == 0) /* Not registered yet... */
865 * Parse port number...
870 while (isdigit(*uri
))
872 *port
= (*port
* 10) + *uri
- '0';
880 * Hostname but no port or path...
889 * The remaining portion is the resource string...
892 strncpy(resource
, uri
, HTTP_MAX_URI
);
893 resource
[HTTP_MAX_URI
- 1] = '\0';
898 * 'httpGetSubField()' - Get a sub-field value.
901 char * /* O - Value or NULL */
902 httpGetSubField(http_t
*http
, /* I - HTTP data */
903 http_field_t field
, /* I - Field index */
904 const char *name
, /* I - Name of sub-field */
905 char *value
) /* O - Value string */
907 const char *fptr
; /* Pointer into field */
908 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
909 *ptr
; /* Pointer into string buffer */
913 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
914 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
915 name
== NULL
|| value
== NULL
)
918 DEBUG_printf(("httpGetSubField(%p, %d, \"%s\", %p)\n",
919 http
, field
, name
, value
));
921 for (fptr
= http
->fields
[field
]; *fptr
;)
924 * Skip leading whitespace...
927 while (isspace(*fptr
))
937 * Get the sub-field name...
941 *fptr
&& *fptr
!= '=' && !isspace(*fptr
) && ptr
< (temp
+ sizeof(temp
) - 1);
946 DEBUG_printf(("name = \"%s\"\n", temp
));
949 * Skip trailing chars up to the '='...
952 while (isspace(*fptr
))
962 * Skip = and leading whitespace...
967 while (isspace(*fptr
))
973 * Read quoted string...
976 for (ptr
= value
, fptr
++;
977 *fptr
&& *fptr
!= '\"' && ptr
< (value
+ HTTP_MAX_VALUE
- 1);
982 while (*fptr
&& *fptr
!= '\"')
991 * Read unquoted string...
995 *fptr
&& !isspace(*fptr
) && *fptr
!= ',' && ptr
< (value
+ HTTP_MAX_VALUE
- 1);
1000 while (*fptr
&& !isspace(*fptr
) && *fptr
!= ',')
1004 DEBUG_printf(("value = \"%s\"\n", value
));
1007 * See if this is the one...
1010 if (strcmp(name
, temp
) == 0)
1021 * 'httpSetField()' - Set the value of an HTTP header.
1025 httpSetField(http_t
*http
, /* I - HTTP data */
1026 http_field_t field
, /* I - Field index */
1027 const char *value
) /* I - Value */
1030 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
1031 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
1035 strncpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
- 1);
1036 http
->fields
[field
][HTTP_MAX_VALUE
- 1] = '\0';
1041 * 'httpDelete()' - Send a DELETE request to the server.
1044 int /* O - Status of call (0 = success) */
1045 httpDelete(http_t
*http
, /* I - HTTP data */
1046 const char *uri
) /* I - URI to delete */
1048 return (http_send(http
, HTTP_DELETE
, uri
));
1053 * 'httpGet()' - Send a GET request to the server.
1056 int /* O - Status of call (0 = success) */
1057 httpGet(http_t
*http
, /* I - HTTP data */
1058 const char *uri
) /* I - URI to get */
1060 return (http_send(http
, HTTP_GET
, uri
));
1065 * 'httpHead()' - Send a HEAD request to the server.
1068 int /* O - Status of call (0 = success) */
1069 httpHead(http_t
*http
, /* I - HTTP data */
1070 const char *uri
) /* I - URI for head */
1072 return (http_send(http
, HTTP_HEAD
, uri
));
1077 * 'httpOptions()' - Send an OPTIONS request to the server.
1080 int /* O - Status of call (0 = success) */
1081 httpOptions(http_t
*http
, /* I - HTTP data */
1082 const char *uri
) /* I - URI for options */
1084 return (http_send(http
, HTTP_OPTIONS
, uri
));
1089 * 'httpPost()' - Send a POST request to the server.
1092 int /* O - Status of call (0 = success) */
1093 httpPost(http_t
*http
, /* I - HTTP data */
1094 const char *uri
) /* I - URI for post */
1096 httpGetLength(http
);
1098 return (http_send(http
, HTTP_POST
, uri
));
1103 * 'httpPut()' - Send a PUT request to the server.
1106 int /* O - Status of call (0 = success) */
1107 httpPut(http_t
*http
, /* I - HTTP data */
1108 const char *uri
) /* I - URI to put */
1110 httpGetLength(http
);
1112 return (http_send(http
, HTTP_PUT
, uri
));
1117 * 'httpTrace()' - Send an TRACE request to the server.
1120 int /* O - Status of call (0 = success) */
1121 httpTrace(http_t
*http
, /* I - HTTP data */
1122 const char *uri
) /* I - URI for trace */
1124 return (http_send(http
, HTTP_TRACE
, uri
));
1129 * 'httpFlush()' - Flush data from a HTTP connection.
1133 httpFlush(http_t
*http
) /* I - HTTP data */
1135 char buffer
[8192]; /* Junk buffer */
1138 while (httpRead(http
, buffer
, sizeof(buffer
)) > 0);
1143 * 'httpRead()' - Read data from a HTTP connection.
1146 int /* O - Number of bytes read */
1147 httpRead(http_t
*http
, /* I - HTTP data */
1148 char *buffer
, /* I - Buffer for data */
1149 int length
) /* I - Maximum number of bytes */
1151 int bytes
; /* Bytes read */
1152 char len
[32]; /* Length string */
1155 DEBUG_printf(("httpRead(%p, %p, %d)\n", http
, buffer
, length
));
1157 if (http
== NULL
|| buffer
== NULL
)
1160 http
->activity
= time(NULL
);
1165 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1166 http
->data_remaining
<= 0)
1168 DEBUG_puts("httpRead: Getting chunk length...");
1170 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1172 DEBUG_puts("httpRead: Could not get length!");
1176 http
->data_remaining
= strtol(len
, NULL
, 16);
1179 DEBUG_printf(("httpRead: data_remaining = %d\n", http
->data_remaining
));
1181 if (http
->data_remaining
== 0)
1184 * A zero-length chunk ends a transfer; unless we are reading POST
1188 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1189 httpGets(len
, sizeof(len
), http
);
1191 if (http
->state
== HTTP_POST_RECV
)
1194 http
->state
= HTTP_WAITING
;
1198 else if (length
> http
->data_remaining
)
1199 length
= http
->data_remaining
;
1201 if (http
->used
== 0 && length
<= 256)
1204 * Buffer small reads for better performance...
1207 if (http
->data_remaining
> sizeof(http
->buffer
))
1208 bytes
= sizeof(http
->buffer
);
1210 bytes
= http
->data_remaining
;
1214 bytes
= SSL_read((SSL
*)(http
->tls
), http
->buffer
, bytes
);
1216 #endif /* HAVE_LIBSSL */
1218 DEBUG_printf(("httpRead: reading %d bytes from socket into buffer...\n",
1221 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1223 DEBUG_printf(("httpRead: read %d bytes from socket into buffer...\n",
1232 http
->error
= WSAGetLastError();
1234 http
->error
= errno
;
1244 if (length
> http
->used
)
1245 length
= http
->used
;
1249 DEBUG_printf(("httpRead: grabbing %d bytes from input buffer...\n", bytes
));
1251 memcpy(buffer
, http
->buffer
, length
);
1252 http
->used
-= length
;
1255 memcpy(http
->buffer
, http
->buffer
+ length
, http
->used
);
1259 bytes
= SSL_read((SSL
*)(http
->tls
), buffer
, length
);
1260 #endif /* HAVE_LIBSSL */
1263 DEBUG_printf(("httpRead: reading %d bytes from socket...\n", length
));
1264 bytes
= recv(http
->fd
, buffer
, length
, 0);
1265 DEBUG_printf(("httpRead: read %d bytes from socket...\n", bytes
));
1269 http
->data_remaining
-= bytes
;
1272 http
->error
= WSAGetLastError();
1274 http
->error
= errno
;
1277 if (http
->data_remaining
== 0)
1279 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1280 httpGets(len
, sizeof(len
), http
);
1282 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
1284 if (http
->state
== HTTP_POST_RECV
)
1287 http
->state
= HTTP_WAITING
;
1294 printf("httpRead: Read %d bytes:\n", bytes
);
1295 for (i
= 0; i
< bytes
; i
+= 16)
1299 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1300 printf(" %02X", buffer
[i
+ j
] & 255);
1309 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1311 ch
= buffer
[i
+ j
] & 255;
1313 if (ch
< ' ' || ch
== 127)
1328 * 'httpWrite()' - Write data to a HTTP connection.
1331 int /* O - Number of bytes written */
1332 httpWrite(http_t
*http
, /* I - HTTP data */
1333 const char *buffer
, /* I - Buffer for data */
1334 int length
) /* I - Number of bytes to write */
1336 int tbytes
, /* Total bytes sent */
1337 bytes
; /* Bytes sent */
1340 if (http
== NULL
|| buffer
== NULL
)
1343 http
->activity
= time(NULL
);
1345 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1347 if (httpPrintf(http
, "%x\r\n", length
) < 0)
1353 * A zero-length chunk ends a transfer; unless we are sending POST
1357 DEBUG_puts("httpWrite: changing states...");
1359 if (http
->state
== HTTP_POST_RECV
)
1361 else if (http
->state
== HTTP_PUT_RECV
)
1362 http
->state
= HTTP_STATUS
;
1364 http
->state
= HTTP_WAITING
;
1366 if (httpPrintf(http
, "\r\n") < 0)
1379 bytes
= SSL_write((SSL
*)(http
->tls
), buffer
, length
);
1381 #endif /* HAVE_LIBSSL */
1382 bytes
= send(http
->fd
, buffer
, length
, 0);
1386 DEBUG_puts("httpWrite: error writing data...\n");
1394 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1395 http
->data_remaining
-= bytes
;
1398 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1399 if (httpPrintf(http
, "\r\n") < 0)
1402 if (http
->data_remaining
== 0 && http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1405 * Finished with the transfer; unless we are sending POST data, go idle...
1408 DEBUG_puts("httpWrite: changing states...");
1410 if (http
->state
== HTTP_POST_RECV
)
1413 http
->state
= HTTP_WAITING
;
1419 printf("httpWrite: wrote %d bytes: \n", tbytes
);
1420 for (i
= 0, buffer
-= tbytes
; i
< tbytes
; i
+= 16)
1424 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
1425 printf(" %02X", buffer
[i
+ j
] & 255);
1434 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
1436 ch
= buffer
[i
+ j
] & 255;
1438 if (ch
< ' ' || ch
== 127)
1452 * 'httpGets()' - Get a line of text from a HTTP connection.
1455 char * /* O - Line or NULL */
1456 httpGets(char *line
, /* I - Line to read into */
1457 int length
, /* I - Max length of buffer */
1458 http_t
*http
) /* I - HTTP data */
1460 char *lineptr
, /* Pointer into line */
1461 *bufptr
, /* Pointer into input buffer */
1462 *bufend
; /* Pointer to end of buffer */
1463 int bytes
; /* Number of bytes read */
1466 DEBUG_printf(("httpGets(%p, %d, %p)\n", line
, length
, http
));
1468 if (http
== NULL
|| line
== NULL
)
1472 * Pre-scan the buffer and see if there is a newline in there...
1483 bufptr
= http
->buffer
;
1484 bufend
= http
->buffer
+ http
->used
;
1486 while (bufptr
< bufend
)
1487 if (*bufptr
== 0x0a)
1492 if (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
)
1495 * No newline; see if there is more data to be read...
1500 bytes
= SSL_read((SSL
*)(http
->tls
), bufend
,
1501 HTTP_MAX_BUFFER
- http
->used
);
1503 #endif /* HAVE_LIBSSL */
1504 bytes
= recv(http
->fd
, bufend
, HTTP_MAX_BUFFER
- http
->used
, 0);
1509 * Nope, can't get a line this time...
1513 if (WSAGetLastError() != http
->error
)
1515 http
->error
= WSAGetLastError();
1519 DEBUG_printf(("httpGets(): recv() error %d!\n", WSAGetLastError()));
1521 if (errno
!= http
->error
)
1523 http
->error
= errno
;
1527 DEBUG_printf(("httpGets(): recv() error %d!\n", errno
));
1532 else if (bytes
== 0)
1535 http
->error
= EPIPE
;
1541 * Yup, update the amount used and the end pointer...
1544 http
->used
+= bytes
;
1548 while (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
);
1550 http
->activity
= time(NULL
);
1553 * Read a line from the buffer...
1557 bufptr
= http
->buffer
;
1561 while (bufptr
< bufend
&& bytes
< length
)
1565 if (*bufptr
== 0x0a)
1570 else if (*bufptr
== 0x0d)
1573 *lineptr
++ = *bufptr
++;
1580 http
->used
-= bytes
;
1582 memcpy(http
->buffer
, bufptr
, http
->used
);
1584 DEBUG_printf(("httpGets(): Returning \"%s\"\n", line
));
1588 DEBUG_puts("httpGets(): No new line available!");
1595 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1598 int /* O - Number of bytes written */
1599 httpPrintf(http_t
*http
, /* I - HTTP data */
1600 const char *format
, /* I - printf-style format string */
1601 ...) /* I - Additional args as needed */
1603 int bytes
, /* Number of bytes to write */
1604 nbytes
, /* Number of bytes written */
1605 tbytes
; /* Number of bytes all together */
1606 char buf
[HTTP_MAX_BUFFER
], /* Buffer for formatted string */
1607 *bufptr
; /* Pointer into buffer */
1608 va_list ap
; /* Variable argument pointer */
1611 va_start(ap
, format
);
1612 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1615 DEBUG_printf(("httpPrintf: %s", buf
));
1617 for (tbytes
= 0, bufptr
= buf
; tbytes
< bytes
; tbytes
+= nbytes
, bufptr
+= nbytes
)
1621 nbytes
= SSL_write((SSL
*)(http
->tls
), bufptr
, bytes
- tbytes
);
1623 #endif /* HAVE_LIBSSL */
1624 nbytes
= send(http
->fd
, bufptr
, bytes
- tbytes
, 0);
1635 * 'httpStatus()' - Return a short string describing a HTTP status code.
1638 const char * /* O - String or NULL */
1639 httpStatus(http_status_t status
) /* I - HTTP status code */
1643 case HTTP_CONTINUE
:
1644 return ("Continue");
1645 case HTTP_SWITCHING_PROTOCOLS
:
1646 return ("Switching Protocols");
1651 case HTTP_ACCEPTED
:
1652 return ("Accepted");
1653 case HTTP_NO_CONTENT
:
1654 return ("No Content");
1655 case HTTP_NOT_MODIFIED
:
1656 return ("Not Modified");
1657 case HTTP_BAD_REQUEST
:
1658 return ("Bad Request");
1659 case HTTP_UNAUTHORIZED
:
1660 return ("Unauthorized");
1661 case HTTP_FORBIDDEN
:
1662 return ("Forbidden");
1663 case HTTP_NOT_FOUND
:
1664 return ("Not Found");
1665 case HTTP_REQUEST_TOO_LARGE
:
1666 return ("Request Entity Too Large");
1667 case HTTP_URI_TOO_LONG
:
1668 return ("URI Too Long");
1669 case HTTP_UPGRADE_REQUIRED
:
1670 return ("Upgrade Required");
1671 case HTTP_NOT_IMPLEMENTED
:
1672 return ("Not Implemented");
1673 case HTTP_NOT_SUPPORTED
:
1674 return ("Not Supported");
1682 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
1685 const char * /* O - Date/time string */
1686 httpGetDateString(time_t t
) /* I - UNIX time */
1689 static char datetime
[256];
1693 snprintf(datetime
, sizeof(datetime
), "%s, %02d %s %d %02d:%02d:%02d GMT",
1694 days
[tdate
->tm_wday
], tdate
->tm_mday
, months
[tdate
->tm_mon
],
1695 tdate
->tm_year
+ 1900, tdate
->tm_hour
, tdate
->tm_min
, tdate
->tm_sec
);
1702 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
1705 time_t /* O - UNIX time */
1706 httpGetDateTime(const char *s
) /* I - Date/time string */
1708 int i
; /* Looping var */
1709 struct tm tdate
; /* Time/date structure */
1710 char mon
[16]; /* Abbreviated month name */
1711 int day
, year
; /* Day of month and year */
1712 int hour
, min
, sec
; /* Time */
1715 if (sscanf(s
, "%*s%d%15s%d%d:%d:%d", &day
, mon
, &year
, &hour
, &min
, &sec
) < 6)
1718 for (i
= 0; i
< 12; i
++)
1719 if (strcasecmp(mon
, months
[i
]) == 0)
1726 tdate
.tm_mday
= day
;
1727 tdate
.tm_year
= year
- 1900;
1728 tdate
.tm_hour
= hour
;
1733 return (mktime(&tdate
));
1738 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1741 http_status_t
/* O - HTTP status */
1742 httpUpdate(http_t
*http
) /* I - HTTP data */
1744 char line
[1024], /* Line from connection... */
1745 *value
; /* Pointer to value on line */
1746 http_field_t field
; /* Field index */
1747 int major
, minor
; /* HTTP version numbers */
1748 http_status_t status
; /* Authorization status */
1750 SSL_CTX
*context
; /* Context for encryption */
1751 SSL
*conn
; /* Connection for encryption */
1752 #endif /* HAVE_LIBSSL */
1755 DEBUG_printf(("httpUpdate(%p)\n", http
));
1758 * If we haven't issued any commands, then there is nothing to "update"...
1761 if (http
->state
== HTTP_WAITING
)
1762 return (HTTP_CONTINUE
);
1765 * Grab all of the lines we can from the connection...
1768 while (httpGets(line
, sizeof(line
), http
) != NULL
)
1772 if (line
[0] == '\0')
1775 * Blank line means the start of the data section (if any). Return
1776 * the result code, too...
1778 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
1779 * Instead, we just return HTTP_CONTINUE to the caller and keep on
1783 if (http
->status
== HTTP_CONTINUE
)
1784 return (http
->status
);
1787 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
1789 context
= SSL_CTX_new(SSLv23_method());
1790 conn
= SSL_new(context
);
1792 SSL_set_fd(conn
, http
->fd
);
1793 if (SSL_connect(conn
) != 1)
1795 SSL_CTX_free(context
);
1799 http
->error
= WSAGetLastError();
1801 http
->error
= errno
;
1803 http
->status
= HTTP_ERROR
;
1806 closesocket(http
->fd
);
1811 return (HTTP_ERROR
);
1816 return (HTTP_CONTINUE
);
1818 #endif /* HAVE_LIBSSL */
1820 httpGetLength(http
);
1822 switch (http
->state
)
1826 case HTTP_POST_RECV
:
1832 http
->state
= HTTP_WAITING
;
1836 return (http
->status
);
1838 else if (strncmp(line
, "HTTP/", 5) == 0)
1841 * Got the beginning of a response...
1844 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, (int *)&status
) != 3)
1845 return (HTTP_ERROR
);
1847 http
->version
= (http_version_t
)(major
* 100 + minor
);
1848 http
->status
= status
;
1850 else if ((value
= strchr(line
, ':')) != NULL
)
1857 while (isspace(*value
))
1861 * Be tolerants of servers that send unknown attribute fields...
1864 if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
1866 DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line
));
1870 httpSetField(http
, field
, value
);
1874 http
->status
= HTTP_ERROR
;
1875 return (HTTP_ERROR
);
1880 * See if there was an error...
1885 http
->status
= HTTP_ERROR
;
1886 return (HTTP_ERROR
);
1890 * If we haven't already returned, then there is nothing new...
1893 return (HTTP_CONTINUE
);
1898 * 'httpDecode64()' - Base64-decode a string.
1901 char * /* O - Decoded string */
1902 httpDecode64(char *out
, /* I - String to write to */
1903 const char *in
) /* I - String to read from */
1905 int pos
, /* Bit position */
1906 base64
; /* Value of this character */
1907 char *outptr
; /* Output pointer */
1910 for (outptr
= out
, pos
= 0; *in
!= '\0'; in
++)
1913 * Decode this character into a number from 0 to 63...
1916 if (*in
>= 'A' && *in
<= 'Z')
1918 else if (*in
>= 'a' && *in
<= 'z')
1919 base64
= *in
- 'a' + 26;
1920 else if (*in
>= '0' && *in
<= '9')
1921 base64
= *in
- '0' + 52;
1922 else if (*in
== '+')
1924 else if (*in
== '/')
1926 else if (*in
== '=')
1932 * Store the result in the appropriate chars...
1938 *outptr
= base64
<< 2;
1942 *outptr
++ |= (base64
>> 4) & 3;
1943 *outptr
= (base64
<< 4) & 255;
1947 *outptr
++ |= (base64
>> 2) & 15;
1948 *outptr
= (base64
<< 6) & 255;
1952 *outptr
++ |= base64
;
1961 * Return the decoded string...
1969 * 'httpEncode64()' - Base64-encode a string.
1972 char * /* O - Encoded string */
1973 httpEncode64(char *out
, /* I - String to write to */
1974 const char *in
) /* I - String to read from */
1976 char *outptr
; /* Output pointer */
1977 static char base64
[] = /* Base64 characters... */
1979 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1980 "abcdefghijklmnopqrstuvwxyz"
1986 for (outptr
= out
; *in
!= '\0'; in
++)
1989 * Encode the up to 3 characters as 4 Base64 numbers...
1992 *outptr
++ = base64
[in
[0] >> 2];
1993 *outptr
++ = base64
[((in
[0] << 4) | (in
[1] >> 4)) & 63];
2002 *outptr
++ = base64
[((in
[0] << 2) | (in
[1] >> 6)) & 63];
2008 *outptr
++ = base64
[in
[0] & 63];
2015 * Return the encoded string...
2023 * 'httpGetLength()' - Get the amount of data remaining from the
2024 * content-length or transfer-encoding fields.
2027 int /* O - Content length */
2028 httpGetLength(http_t
*http
) /* I - HTTP data */
2030 DEBUG_printf(("httpGetLength(%p)\n", http
));
2032 if (strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked") == 0)
2034 DEBUG_puts("httpGetLength: chunked request!");
2036 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
2037 http
->data_remaining
= 0;
2041 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
2044 * The following is a hack for HTTP servers that don't send a
2045 * content-length or transfer-encoding field...
2047 * If there is no content-length then the connection must close
2048 * after the transfer is complete...
2051 if (http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] == '\0')
2052 http
->data_remaining
= 2147483647;
2054 http
->data_remaining
= atoi(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
]);
2056 DEBUG_printf(("httpGetLength: content_length = %d\n", http
->data_remaining
));
2059 return (http
->data_remaining
);
2064 * 'http_field()' - Return the field index for a field name.
2067 static http_field_t
/* O - Field index */
2068 http_field(const char *name
) /* I - String name */
2070 int i
; /* Looping var */
2073 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2074 if (strcasecmp(name
, http_fields
[i
]) == 0)
2075 return ((http_field_t
)i
);
2077 return (HTTP_FIELD_UNKNOWN
);
2082 * 'http_send()' - Send a request with all fields and the trailing blank line.
2085 static int /* O - 0 on success, non-zero on error */
2086 http_send(http_t
*http
, /* I - HTTP data */
2087 http_state_t request
, /* I - Request code */
2088 const char *uri
) /* I - URI */
2090 int i
; /* Looping var */
2091 char *ptr
, /* Pointer in buffer */
2092 buf
[1024]; /* Encoded URI buffer */
2093 static const char *codes
[] = /* Request code strings */
2109 static const char *hex
= "0123456789ABCDEF";
2113 if (http
== NULL
|| uri
== NULL
)
2117 * Encode the URI as needed...
2120 for (ptr
= buf
; *uri
!= '\0' && ptr
< (buf
+ sizeof(buf
) - 1); uri
++)
2121 if (*uri
<= ' ' || *uri
>= 127)
2123 if (ptr
< (buf
+ sizeof(buf
) - 1))
2125 if (ptr
< (buf
+ sizeof(buf
) - 1))
2126 *ptr
++ = hex
[(*uri
>> 4) & 15];
2127 if (ptr
< (buf
+ sizeof(buf
) - 1))
2128 *ptr
++ = hex
[*uri
& 15];
2136 * See if we had an error the last time around; if so, reconnect...
2139 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
2140 httpReconnect(http
);
2143 * Send the request header...
2146 http
->state
= request
;
2147 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
2150 http
->status
= HTTP_CONTINUE
;
2153 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
2155 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
2156 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
2158 #endif /* HAVE_LIBSSL */
2160 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
2162 http
->status
= HTTP_ERROR
;
2166 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2167 if (http
->fields
[i
][0] != '\0')
2169 DEBUG_printf(("%s: %s\n", http_fields
[i
], http
->fields
[i
]));
2171 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], http
->fields
[i
]) < 1)
2173 http
->status
= HTTP_ERROR
;
2178 if (httpPrintf(http
, "\r\n") < 1)
2180 http
->status
= HTTP_ERROR
;
2184 httpClearFields(http
);
2192 * 'http_upgrade()' - Force upgrade to TLS encryption.
2195 static int /* O - Status of connection */
2196 http_upgrade(http_t
*http
) /* I - HTTP data */
2198 int ret
; /* Return value */
2199 http_t myhttp
; /* Local copy of HTTP data */
2202 DEBUG_printf(("http_upgrade(%p)\n", http
));
2205 * Copy the HTTP data to a local variable so we can do the OPTIONS
2206 * request without interfering with the existing request data...
2209 memcpy(&myhttp
, http
, sizeof(myhttp
));
2212 * Send an OPTIONS request to the server, requiring SSL or TLS
2213 * encryption on the link...
2216 httpClearFields(&myhttp
);
2217 httpSetField(&myhttp
, HTTP_FIELD_CONNECTION
, "upgrade");
2218 httpSetField(&myhttp
, HTTP_FIELD_UPGRADE
, "TLS/1.0, SSL/2.0, SSL/3.0");
2220 if ((ret
= httpOptions(&myhttp
, "*")) == 0)
2223 * Wait for the secure connection...
2226 while (httpUpdate(&myhttp
) == HTTP_CONTINUE
);
2232 * Copy the HTTP data back over, if any...
2235 http
->fd
= myhttp
.fd
;
2236 http
->error
= myhttp
.error
;
2237 http
->activity
= myhttp
.activity
;
2238 http
->status
= myhttp
.status
;
2239 http
->version
= myhttp
.version
;
2240 http
->keep_alive
= myhttp
.keep_alive
;
2241 http
->used
= myhttp
.used
;
2244 memcpy(http
->buffer
, myhttp
.buffer
, http
->used
);
2246 http
->auth_type
= myhttp
.auth_type
;
2247 http
->nonce_count
= myhttp
.nonce_count
;
2249 memcpy(http
->nonce
, myhttp
.nonce
, sizeof(http
->nonce
));
2251 http
->tls
= myhttp
.tls
;
2252 http
->encryption
= myhttp
.encryption
;
2255 * See if we actually went secure...
2261 * Server does not support HTTP upgrade...
2264 DEBUG_puts("Server does not support HTTP upgrade!");
2267 closesocket(http
->fd
);
2279 #endif /* HAVE_LIBSSL */
2283 * End of "$Id: http.c,v 1.96 2002/04/09 19:27:06 mike Exp $".