2 * "$Id: http.c,v 1.82.2.9 2002/02/12 19:23:07 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 */
632 #if defined(__APPLE__)
633 /* OS X hack to avoid it's ocassional long delay in lookupd */
634 static char sLoopback
[] = "127.0.0.1";
635 if (strcmp(name
, "localhost") == 0)
637 #endif /* __APPLE__ */
640 * This function is needed because some operating systems have a
641 * buggy implementation of httpGetHostByName() that does not support
642 * IP addresses. If the first character of the name string is a
643 * number, then sscanf() is used to extract the IP components.
644 * We then pack the components into an IPv4 address manually,
645 * since the inet_aton() function is deprecated. We use the
646 * htonl() macro to get the right byte order for the address.
649 if (isdigit(name
[0]))
652 * We have an IP address; break it up and provide the host entry
653 * to the caller. Currently only supports IPv4 addresses, although
654 * it should be trivial to support IPv6 in CUPS 1.2.
657 if (sscanf(name
, "%u.%u.%u.%u", ip
, ip
+ 1, ip
+ 2, ip
+ 3) != 4)
658 return (NULL
); /* Must have 4 numbers */
660 packed_ip
= htonl(((((((ip
[0] << 8) | ip
[1]) << 8) | ip
[2]) << 8) | ip
[3]));
663 * Fill in the host entry and return it...
666 host_ip
.h_name
= (char *)name
;
667 host_ip
.h_aliases
= NULL
;
668 host_ip
.h_addrtype
= AF_INET
;
669 host_ip
.h_length
= 4;
670 host_ip
.h_addr_list
= packed_ptr
;
671 packed_ptr
[0] = (char *)(&packed_ip
);
672 packed_ptr
[1] = NULL
;
679 * Use the gethostbyname() function to get the IP address for
683 return (gethostbyname(name
));
689 * 'httpSeparate()' - Separate a Universal Resource Identifier into its
694 httpSeparate(const char *uri
, /* I - Universal Resource Identifier */
695 char *method
, /* O - Method [32] (http, https, etc.) */
696 char *username
, /* O - Username [32] */
697 char *host
, /* O - Hostname [32] */
698 int *port
, /* O - Port number to use */
699 char *resource
) /* O - Resource/filename [1024] */
701 char *ptr
; /* Pointer into string... */
702 const char *atsign
, /* @ sign */
703 *slash
; /* Separator */
704 char safeuri
[HTTP_MAX_URI
]; /* "Safe" local copy of URI */
708 * Range check input...
711 if (uri
== NULL
|| method
== NULL
|| username
== NULL
|| host
== NULL
||
712 port
== NULL
|| resource
== NULL
)
716 * Copy the URL to a local string to make sure we don't have a URL
717 * longer than HTTP_MAX_URI characters long...
720 strncpy(safeuri
, uri
, sizeof(safeuri
));
721 safeuri
[sizeof(safeuri
) - 1] = '\0';
726 * Grab the method portion of the URI...
729 if (strncmp(uri
, "//", 2) == 0)
732 * Workaround for HP IPP client bug...
735 strcpy(method
, "ipp");
740 * Standard URI with method...
743 for (ptr
= host
; *uri
!= ':' && *uri
!= '\0'; uri
++)
744 if (ptr
< (host
+ HTTP_MAX_URI
- 1))
752 * If the method contains a period or slash, then it's probably
753 * hostname/filename...
756 if (strchr(host
, '.') != NULL
|| strchr(host
, '/') != NULL
|| *uri
== '\0')
758 if ((ptr
= strchr(host
, '/')) != NULL
)
760 strncpy(resource
, ptr
, HTTP_MAX_URI
);
761 resource
[HTTP_MAX_URI
- 1] = '\0';
770 * OK, we have "hostname:port[/resource]"...
773 *port
= strtol(uri
, (char **)&uri
, 10);
777 strncpy(resource
, uri
, HTTP_MAX_URI
);
778 resource
[HTTP_MAX_URI
- 1] = '\0';
784 strcpy(method
, "http");
790 strncpy(method
, host
, 31);
796 * If the method starts with less than 2 slashes then it is a local resource...
799 if (strncmp(uri
, "//", 2) != 0)
801 strncpy(resource
, uri
, 1023);
802 resource
[1023] = '\0';
811 * Grab the username, if any...
817 if ((slash
= strchr(uri
, '/')) == NULL
)
818 slash
= uri
+ strlen(uri
);
820 if ((atsign
= strchr(uri
, '@')) != NULL
&& atsign
< slash
)
823 * Got a username:password combo...
826 for (ptr
= username
; uri
< atsign
; uri
++)
827 if (ptr
< (username
+ HTTP_MAX_URI
- 1))
838 * Grab the hostname...
841 for (ptr
= host
; *uri
!= ':' && *uri
!= '/' && *uri
!= '\0'; uri
++)
842 if (ptr
< (host
+ HTTP_MAX_URI
- 1))
849 if (strcasecmp(method
, "http") == 0)
851 else if (strcasecmp(method
, "https") == 0)
853 else if (strcasecmp(method
, "ipp") == 0)
855 else if (strcasecmp(method
, "socket") == 0) /* Not registered yet... */
863 * Parse port number...
868 while (isdigit(*uri
))
870 *port
= (*port
* 10) + *uri
- '0';
878 * Hostname but no port or path...
887 * The remaining portion is the resource string...
890 strncpy(resource
, uri
, HTTP_MAX_URI
);
891 resource
[HTTP_MAX_URI
- 1] = '\0';
896 * 'httpGetSubField()' - Get a sub-field value.
899 char * /* O - Value or NULL */
900 httpGetSubField(http_t
*http
, /* I - HTTP data */
901 http_field_t field
, /* I - Field index */
902 const char *name
, /* I - Name of sub-field */
903 char *value
) /* O - Value string */
905 const char *fptr
; /* Pointer into field */
906 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
907 *ptr
; /* Pointer into string buffer */
911 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
912 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
913 name
== NULL
|| value
== NULL
)
916 for (fptr
= http
->fields
[field
]; *fptr
;)
919 * Skip leading whitespace...
922 while (isspace(*fptr
))
932 * Get the sub-field name...
936 *fptr
&& *fptr
!= '=' && !isspace(*fptr
) && ptr
< (temp
+ sizeof(temp
) - 1);
942 * Skip trailing chars up to the '='...
945 while (*fptr
&& *fptr
!= '=')
952 * Skip = and leading whitespace...
957 while (isspace(*fptr
))
963 * Read quoted string...
966 for (ptr
= value
, fptr
++;
967 *fptr
&& *fptr
!= '\"' && ptr
< (value
+ HTTP_MAX_VALUE
- 1);
972 while (*fptr
&& *fptr
!= '\"')
981 * Read unquoted string...
985 *fptr
&& !isspace(*fptr
) && *fptr
!= ',' && ptr
< (value
+ HTTP_MAX_VALUE
- 1);
990 while (*fptr
&& !isspace(*fptr
) && *fptr
!= ',')
995 * See if this is the one...
998 if (strcmp(name
, temp
) == 0)
1009 * 'httpSetField()' - Set the value of an HTTP header.
1013 httpSetField(http_t
*http
, /* I - HTTP data */
1014 http_field_t field
, /* I - Field index */
1015 const char *value
) /* I - Value */
1018 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
1019 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
1023 strncpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
- 1);
1024 http
->fields
[field
][HTTP_MAX_VALUE
- 1] = '\0';
1029 * 'httpDelete()' - Send a DELETE request to the server.
1032 int /* O - Status of call (0 = success) */
1033 httpDelete(http_t
*http
, /* I - HTTP data */
1034 const char *uri
) /* I - URI to delete */
1036 return (http_send(http
, HTTP_DELETE
, uri
));
1041 * 'httpGet()' - Send a GET request to the server.
1044 int /* O - Status of call (0 = success) */
1045 httpGet(http_t
*http
, /* I - HTTP data */
1046 const char *uri
) /* I - URI to get */
1048 return (http_send(http
, HTTP_GET
, uri
));
1053 * 'httpHead()' - Send a HEAD request to the server.
1056 int /* O - Status of call (0 = success) */
1057 httpHead(http_t
*http
, /* I - HTTP data */
1058 const char *uri
) /* I - URI for head */
1060 return (http_send(http
, HTTP_HEAD
, uri
));
1065 * 'httpOptions()' - Send an OPTIONS request to the server.
1068 int /* O - Status of call (0 = success) */
1069 httpOptions(http_t
*http
, /* I - HTTP data */
1070 const char *uri
) /* I - URI for options */
1072 return (http_send(http
, HTTP_OPTIONS
, uri
));
1077 * 'httpPost()' - Send a POST request to the server.
1080 int /* O - Status of call (0 = success) */
1081 httpPost(http_t
*http
, /* I - HTTP data */
1082 const char *uri
) /* I - URI for post */
1084 httpGetLength(http
);
1086 return (http_send(http
, HTTP_POST
, uri
));
1091 * 'httpPut()' - Send a PUT request to the server.
1094 int /* O - Status of call (0 = success) */
1095 httpPut(http_t
*http
, /* I - HTTP data */
1096 const char *uri
) /* I - URI to put */
1098 httpGetLength(http
);
1100 return (http_send(http
, HTTP_PUT
, uri
));
1105 * 'httpTrace()' - Send an TRACE request to the server.
1108 int /* O - Status of call (0 = success) */
1109 httpTrace(http_t
*http
, /* I - HTTP data */
1110 const char *uri
) /* I - URI for trace */
1112 return (http_send(http
, HTTP_TRACE
, uri
));
1117 * 'httpFlush()' - Flush data from a HTTP connection.
1121 httpFlush(http_t
*http
) /* I - HTTP data */
1123 char buffer
[8192]; /* Junk buffer */
1126 while (httpRead(http
, buffer
, sizeof(buffer
)) > 0);
1131 * 'httpRead()' - Read data from a HTTP connection.
1134 int /* O - Number of bytes read */
1135 httpRead(http_t
*http
, /* I - HTTP data */
1136 char *buffer
, /* I - Buffer for data */
1137 int length
) /* I - Maximum number of bytes */
1139 int bytes
; /* Bytes read */
1140 char len
[32]; /* Length string */
1143 DEBUG_printf(("httpRead(%08x, %08x, %d)\n", http
, buffer
, length
));
1145 if (http
== NULL
|| buffer
== NULL
)
1148 http
->activity
= time(NULL
);
1153 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1154 http
->data_remaining
<= 0)
1156 DEBUG_puts("httpRead: Getting chunk length...");
1158 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1160 DEBUG_puts("httpRead: Could not get length!");
1164 http
->data_remaining
= strtol(len
, NULL
, 16);
1167 DEBUG_printf(("httpRead: data_remaining = %d\n", http
->data_remaining
));
1169 if (http
->data_remaining
== 0)
1172 * A zero-length chunk ends a transfer; unless we are reading POST
1176 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1177 httpGets(len
, sizeof(len
), http
);
1179 if (http
->state
== HTTP_POST_RECV
)
1182 http
->state
= HTTP_WAITING
;
1186 else if (length
> http
->data_remaining
)
1187 length
= http
->data_remaining
;
1189 if (http
->used
== 0 && length
<= 256)
1192 * Buffer small reads for better performance...
1195 if (http
->data_remaining
> sizeof(http
->buffer
))
1196 bytes
= sizeof(http
->buffer
);
1198 bytes
= http
->data_remaining
;
1202 bytes
= SSL_read((SSL
*)(http
->tls
), http
->buffer
, bytes
);
1204 #endif /* HAVE_LIBSSL */
1206 DEBUG_printf(("httpRead: reading %d bytes from socket into buffer...\n",
1209 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1211 DEBUG_printf(("httpRead: read %d bytes from socket into buffer...\n",
1220 http
->error
= WSAGetLastError();
1222 http
->error
= errno
;
1232 if (length
> http
->used
)
1233 length
= http
->used
;
1237 DEBUG_printf(("httpRead: grabbing %d bytes from input buffer...\n", bytes
));
1239 memcpy(buffer
, http
->buffer
, length
);
1240 http
->used
-= length
;
1243 memcpy(http
->buffer
, http
->buffer
+ length
, http
->used
);
1247 bytes
= SSL_read((SSL
*)(http
->tls
), buffer
, length
);
1248 #endif /* HAVE_LIBSSL */
1251 DEBUG_printf(("httpRead: reading %d bytes from socket...\n", length
));
1252 bytes
= recv(http
->fd
, buffer
, length
, 0);
1253 DEBUG_printf(("httpRead: read %d bytes from socket...\n", bytes
));
1257 http
->data_remaining
-= bytes
;
1260 http
->error
= WSAGetLastError();
1262 http
->error
= errno
;
1265 if (http
->data_remaining
== 0)
1267 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1268 httpGets(len
, sizeof(len
), http
);
1270 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
1272 if (http
->state
== HTTP_POST_RECV
)
1275 http
->state
= HTTP_WAITING
;
1284 * 'httpWrite()' - Write data to a HTTP connection.
1287 int /* O - Number of bytes written */
1288 httpWrite(http_t
*http
, /* I - HTTP data */
1289 const char *buffer
, /* I - Buffer for data */
1290 int length
) /* I - Number of bytes to write */
1292 int tbytes
, /* Total bytes sent */
1293 bytes
; /* Bytes sent */
1296 if (http
== NULL
|| buffer
== NULL
)
1299 http
->activity
= time(NULL
);
1301 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1303 if (httpPrintf(http
, "%x\r\n", length
) < 0)
1309 * A zero-length chunk ends a transfer; unless we are sending POST
1313 DEBUG_puts("httpWrite: changing states...");
1315 if (http
->state
== HTTP_POST_RECV
)
1317 else if (http
->state
== HTTP_PUT_RECV
)
1318 http
->state
= HTTP_STATUS
;
1320 http
->state
= HTTP_WAITING
;
1322 if (httpPrintf(http
, "\r\n") < 0)
1335 bytes
= SSL_write((SSL
*)(http
->tls
), buffer
, length
);
1337 #endif /* HAVE_LIBSSL */
1338 bytes
= send(http
->fd
, buffer
, length
, 0);
1342 DEBUG_puts("httpWrite: error writing data...\n");
1350 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1351 http
->data_remaining
-= bytes
;
1354 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1355 if (httpPrintf(http
, "\r\n") < 0)
1358 if (http
->data_remaining
== 0 && http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1361 * Finished with the transfer; unless we are sending POST data, go idle...
1364 DEBUG_puts("httpWrite: changing states...");
1366 if (http
->state
== HTTP_POST_RECV
)
1369 http
->state
= HTTP_WAITING
;
1372 DEBUG_printf(("httpWrite: wrote %d bytes...\n", tbytes
));
1379 * 'httpGets()' - Get a line of text from a HTTP connection.
1382 char * /* O - Line or NULL */
1383 httpGets(char *line
, /* I - Line to read into */
1384 int length
, /* I - Max length of buffer */
1385 http_t
*http
) /* I - HTTP data */
1387 char *lineptr
, /* Pointer into line */
1388 *bufptr
, /* Pointer into input buffer */
1389 *bufend
; /* Pointer to end of buffer */
1390 int bytes
; /* Number of bytes read */
1393 DEBUG_printf(("httpGets(%08x, %d, %08x)\n", line
, length
, http
));
1395 if (http
== NULL
|| line
== NULL
)
1399 * Pre-scan the buffer and see if there is a newline in there...
1410 bufptr
= http
->buffer
;
1411 bufend
= http
->buffer
+ http
->used
;
1413 while (bufptr
< bufend
)
1414 if (*bufptr
== 0x0a)
1419 if (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
)
1422 * No newline; see if there is more data to be read...
1427 bytes
= SSL_read((SSL
*)(http
->tls
), bufend
,
1428 HTTP_MAX_BUFFER
- http
->used
);
1430 #endif /* HAVE_LIBSSL */
1431 bytes
= recv(http
->fd
, bufend
, HTTP_MAX_BUFFER
- http
->used
, 0);
1436 * Nope, can't get a line this time...
1440 if (WSAGetLastError() != http
->error
)
1442 http
->error
= WSAGetLastError();
1446 DEBUG_printf(("httpGets(): recv() error %d!\n", WSAGetLastError()));
1448 if (errno
!= http
->error
)
1450 http
->error
= errno
;
1454 DEBUG_printf(("httpGets(): recv() error %d!\n", errno
));
1459 else if (bytes
== 0)
1462 http
->error
= EPIPE
;
1468 * Yup, update the amount used and the end pointer...
1471 http
->used
+= bytes
;
1475 while (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
);
1477 http
->activity
= time(NULL
);
1480 * Read a line from the buffer...
1484 bufptr
= http
->buffer
;
1488 while (bufptr
< bufend
&& bytes
< length
)
1492 if (*bufptr
== 0x0a)
1497 else if (*bufptr
== 0x0d)
1500 *lineptr
++ = *bufptr
++;
1507 http
->used
-= bytes
;
1509 memcpy(http
->buffer
, bufptr
, http
->used
);
1511 DEBUG_printf(("httpGets(): Returning \"%s\"\n", line
));
1515 DEBUG_puts("httpGets(): No new line available!");
1522 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1525 int /* O - Number of bytes written */
1526 httpPrintf(http_t
*http
, /* I - HTTP data */
1527 const char *format
, /* I - printf-style format string */
1528 ...) /* I - Additional args as needed */
1530 int bytes
, /* Number of bytes to write */
1531 nbytes
, /* Number of bytes written */
1532 tbytes
; /* Number of bytes all together */
1533 char buf
[HTTP_MAX_BUFFER
], /* Buffer for formatted string */
1534 *bufptr
; /* Pointer into buffer */
1535 va_list ap
; /* Variable argument pointer */
1538 va_start(ap
, format
);
1539 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1542 DEBUG_printf(("httpPrintf: %s", buf
));
1544 for (tbytes
= 0, bufptr
= buf
; tbytes
< bytes
; tbytes
+= nbytes
, bufptr
+= nbytes
)
1548 nbytes
= SSL_write((SSL
*)(http
->tls
), bufptr
, bytes
- tbytes
);
1550 #endif /* HAVE_LIBSSL */
1551 nbytes
= send(http
->fd
, bufptr
, bytes
- tbytes
, 0);
1562 * 'httpStatus()' - Return a short string describing a HTTP status code.
1565 const char * /* O - String or NULL */
1566 httpStatus(http_status_t status
) /* I - HTTP status code */
1570 case HTTP_CONTINUE
:
1571 return ("Continue");
1572 case HTTP_SWITCHING_PROTOCOLS
:
1573 return ("Switching Protocols");
1578 case HTTP_ACCEPTED
:
1579 return ("Accepted");
1580 case HTTP_NO_CONTENT
:
1581 return ("No Content");
1582 case HTTP_NOT_MODIFIED
:
1583 return ("Not Modified");
1584 case HTTP_BAD_REQUEST
:
1585 return ("Bad Request");
1586 case HTTP_UNAUTHORIZED
:
1587 return ("Unauthorized");
1588 case HTTP_FORBIDDEN
:
1589 return ("Forbidden");
1590 case HTTP_NOT_FOUND
:
1591 return ("Not Found");
1592 case HTTP_REQUEST_TOO_LARGE
:
1593 return ("Request Entity Too Large");
1594 case HTTP_URI_TOO_LONG
:
1595 return ("URI Too Long");
1596 case HTTP_UPGRADE_REQUIRED
:
1597 return ("Upgrade Required");
1598 case HTTP_NOT_IMPLEMENTED
:
1599 return ("Not Implemented");
1600 case HTTP_NOT_SUPPORTED
:
1601 return ("Not Supported");
1609 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
1612 const char * /* O - Date/time string */
1613 httpGetDateString(time_t t
) /* I - UNIX time */
1616 static char datetime
[256];
1620 snprintf(datetime
, sizeof(datetime
), "%s, %02d %s %d %02d:%02d:%02d GMT",
1621 days
[tdate
->tm_wday
], tdate
->tm_mday
, months
[tdate
->tm_mon
],
1622 tdate
->tm_year
+ 1900, tdate
->tm_hour
, tdate
->tm_min
, tdate
->tm_sec
);
1629 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
1632 time_t /* O - UNIX time */
1633 httpGetDateTime(const char *s
) /* I - Date/time string */
1635 int i
; /* Looping var */
1636 struct tm tdate
; /* Time/date structure */
1637 char mon
[16]; /* Abbreviated month name */
1638 int day
, year
; /* Day of month and year */
1639 int hour
, min
, sec
; /* Time */
1642 if (sscanf(s
, "%*s%d%15s%d%d:%d:%d", &day
, mon
, &year
, &hour
, &min
, &sec
) < 6)
1645 for (i
= 0; i
< 12; i
++)
1646 if (strcasecmp(mon
, months
[i
]) == 0)
1653 tdate
.tm_mday
= day
;
1654 tdate
.tm_year
= year
- 1900;
1655 tdate
.tm_hour
= hour
;
1660 return (mktime(&tdate
));
1665 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1668 http_status_t
/* O - HTTP status */
1669 httpUpdate(http_t
*http
) /* I - HTTP data */
1671 char line
[1024], /* Line from connection... */
1672 *value
; /* Pointer to value on line */
1673 http_field_t field
; /* Field index */
1674 int major
, minor
; /* HTTP version numbers */
1675 http_status_t status
; /* Authorization status */
1677 SSL_CTX
*context
; /* Context for encryption */
1678 SSL
*conn
; /* Connection for encryption */
1679 #endif /* HAVE_LIBSSL */
1682 DEBUG_printf(("httpUpdate(%08x)\n", http
));
1685 * If we haven't issued any commands, then there is nothing to "update"...
1688 if (http
->state
== HTTP_WAITING
)
1689 return (HTTP_CONTINUE
);
1692 * Grab all of the lines we can from the connection...
1695 while (httpGets(line
, sizeof(line
), http
) != NULL
)
1699 if (line
[0] == '\0')
1702 * Blank line means the start of the data section (if any). Return
1703 * the result code, too...
1705 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
1706 * Instead, we just return HTTP_CONTINUE to the caller and keep on
1710 if (http
->status
== HTTP_CONTINUE
)
1711 return (http
->status
);
1714 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
1716 context
= SSL_CTX_new(SSLv23_method());
1717 conn
= SSL_new(context
);
1719 SSL_set_fd(conn
, http
->fd
);
1720 if (SSL_connect(conn
) != 1)
1722 SSL_CTX_free(context
);
1726 http
->error
= WSAGetLastError();
1728 http
->error
= errno
;
1730 http
->status
= HTTP_ERROR
;
1733 closesocket(http
->fd
);
1738 return (HTTP_ERROR
);
1743 return (HTTP_CONTINUE
);
1745 else if (http
->status
== HTTP_UPGRADE_REQUIRED
&&
1746 http
->encryption
!= HTTP_ENCRYPT_NEVER
)
1747 http
->encryption
= HTTP_ENCRYPT_REQUIRED
;
1748 #endif /* HAVE_LIBSSL */
1750 httpGetLength(http
);
1752 switch (http
->state
)
1756 case HTTP_POST_RECV
:
1762 http
->state
= HTTP_WAITING
;
1766 return (http
->status
);
1768 else if (strncmp(line
, "HTTP/", 5) == 0)
1771 * Got the beginning of a response...
1774 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, (int *)&status
) != 3)
1775 return (HTTP_ERROR
);
1777 http
->version
= (http_version_t
)(major
* 100 + minor
);
1778 http
->status
= status
;
1780 else if ((value
= strchr(line
, ':')) != NULL
)
1787 while (isspace(*value
))
1791 * Be tolerants of servers that send unknown attribute fields...
1794 if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
1796 DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line
));
1800 httpSetField(http
, field
, value
);
1804 http
->status
= HTTP_ERROR
;
1805 return (HTTP_ERROR
);
1810 * See if there was an error...
1815 http
->status
= HTTP_ERROR
;
1816 return (HTTP_ERROR
);
1820 * If we haven't already returned, then there is nothing new...
1823 return (HTTP_CONTINUE
);
1828 * 'httpDecode64()' - Base64-decode a string.
1831 char * /* O - Decoded string */
1832 httpDecode64(char *out
, /* I - String to write to */
1833 const char *in
) /* I - String to read from */
1835 int pos
, /* Bit position */
1836 base64
; /* Value of this character */
1837 char *outptr
; /* Output pointer */
1840 for (outptr
= out
, pos
= 0; *in
!= '\0'; in
++)
1843 * Decode this character into a number from 0 to 63...
1846 if (*in
>= 'A' && *in
<= 'Z')
1848 else if (*in
>= 'a' && *in
<= 'z')
1849 base64
= *in
- 'a' + 26;
1850 else if (*in
>= '0' && *in
<= '9')
1851 base64
= *in
- '0' + 52;
1852 else if (*in
== '+')
1854 else if (*in
== '/')
1856 else if (*in
== '=')
1862 * Store the result in the appropriate chars...
1868 *outptr
= base64
<< 2;
1872 *outptr
++ |= (base64
>> 4) & 3;
1873 *outptr
= (base64
<< 4) & 255;
1877 *outptr
++ |= (base64
>> 2) & 15;
1878 *outptr
= (base64
<< 6) & 255;
1882 *outptr
++ |= base64
;
1891 * Return the decoded string...
1899 * 'httpEncode64()' - Base64-encode a string.
1902 char * /* O - Encoded string */
1903 httpEncode64(char *out
, /* I - String to write to */
1904 const char *in
) /* I - String to read from */
1906 char *outptr
; /* Output pointer */
1907 static char base64
[] = /* Base64 characters... */
1909 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1910 "abcdefghijklmnopqrstuvwxyz"
1916 for (outptr
= out
; *in
!= '\0'; in
++)
1919 * Encode the up to 3 characters as 4 Base64 numbers...
1922 *outptr
++ = base64
[in
[0] >> 2];
1923 *outptr
++ = base64
[((in
[0] << 4) | (in
[1] >> 4)) & 63];
1932 *outptr
++ = base64
[((in
[0] << 2) | (in
[1] >> 6)) & 63];
1938 *outptr
++ = base64
[in
[0] & 63];
1945 * Return the encoded string...
1953 * 'httpGetLength()' - Get the amount of data remaining from the
1954 * content-length or transfer-encoding fields.
1957 int /* O - Content length */
1958 httpGetLength(http_t
*http
) /* I - HTTP data */
1960 DEBUG_printf(("httpGetLength(%08x)\n", http
));
1962 if (strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked") == 0)
1964 DEBUG_puts("httpGetLength: chunked request!");
1966 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
1967 http
->data_remaining
= 0;
1971 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1974 * The following is a hack for HTTP servers that don't send a
1975 * content-length or transfer-encoding field...
1977 * If there is no content-length then the connection must close
1978 * after the transfer is complete...
1981 if (http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] == '\0')
1982 http
->data_remaining
= 2147483647;
1984 http
->data_remaining
= atoi(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
]);
1986 DEBUG_printf(("httpGetLength: content_length = %d\n", http
->data_remaining
));
1989 return (http
->data_remaining
);
1994 * 'http_field()' - Return the field index for a field name.
1997 static http_field_t
/* O - Field index */
1998 http_field(const char *name
) /* I - String name */
2000 int i
; /* Looping var */
2003 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2004 if (strcasecmp(name
, http_fields
[i
]) == 0)
2005 return ((http_field_t
)i
);
2007 return (HTTP_FIELD_UNKNOWN
);
2012 * 'http_send()' - Send a request with all fields and the trailing blank line.
2015 static int /* O - 0 on success, non-zero on error */
2016 http_send(http_t
*http
, /* I - HTTP data */
2017 http_state_t request
, /* I - Request code */
2018 const char *uri
) /* I - URI */
2020 int i
; /* Looping var */
2021 char *ptr
, /* Pointer in buffer */
2022 buf
[1024]; /* Encoded URI buffer */
2023 static const char *codes
[] = /* Request code strings */
2039 static const char *hex
= "0123456789ABCDEF";
2043 if (http
== NULL
|| uri
== NULL
)
2047 * Encode the URI as needed...
2050 for (ptr
= buf
; *uri
!= '\0' && ptr
< (buf
+ sizeof(buf
) - 1); uri
++)
2051 if (*uri
<= ' ' || *uri
>= 127)
2053 if (ptr
< (buf
+ sizeof(buf
) - 1))
2055 if (ptr
< (buf
+ sizeof(buf
) - 1))
2056 *ptr
++ = hex
[(*uri
>> 4) & 15];
2057 if (ptr
< (buf
+ sizeof(buf
) - 1))
2058 *ptr
++ = hex
[*uri
& 15];
2066 * See if we had an error the last time around; if so, reconnect...
2069 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
2070 httpReconnect(http
);
2073 * Send the request header...
2076 http
->state
= request
;
2077 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
2080 http
->status
= HTTP_CONTINUE
;
2083 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
2085 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
2086 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
2088 #endif /* HAVE_LIBSSL */
2090 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
2092 http
->status
= HTTP_ERROR
;
2096 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2097 if (http
->fields
[i
][0] != '\0')
2099 DEBUG_printf(("%s: %s\n", http_fields
[i
], http
->fields
[i
]));
2101 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], http
->fields
[i
]) < 1)
2103 http
->status
= HTTP_ERROR
;
2108 if (httpPrintf(http
, "\r\n") < 1)
2110 http
->status
= HTTP_ERROR
;
2114 httpClearFields(http
);
2122 * 'http_upgrade()' - Force upgrade to TLS encryption.
2125 static int /* O - Status of connection */
2126 http_upgrade(http_t
*http
) /* I - HTTP data */
2128 int ret
; /* Return value */
2129 http_t myhttp
; /* Local copy of HTTP data */
2132 DEBUG_printf(("http_upgrade(%p)\n", http
));
2135 * Copy the HTTP data to a local variable so we can do the OPTIONS
2136 * request without interfering with the existing request data...
2139 memcpy(&myhttp
, http
, sizeof(myhttp
));
2142 * Send an OPTIONS request to the server, requiring SSL or TLS
2143 * encryption on the link...
2146 httpClearFields(&myhttp
);
2147 httpSetField(&myhttp
, HTTP_FIELD_CONNECTION
, "upgrade");
2148 httpSetField(&myhttp
, HTTP_FIELD_UPGRADE
, "TLS/1.0, SSL/2.0, SSL/3.0");
2150 if ((ret
= httpOptions(&myhttp
, "*")) == 0)
2153 * Wait for the secure connection...
2156 while (httpUpdate(&myhttp
) == HTTP_CONTINUE
);
2162 * Copy the HTTP data back over, if any...
2165 http
->fd
= myhttp
.fd
;
2166 http
->error
= myhttp
.error
;
2167 http
->activity
= myhttp
.activity
;
2168 http
->status
= myhttp
.status
;
2169 http
->version
= myhttp
.version
;
2170 http
->keep_alive
= myhttp
.keep_alive
;
2171 http
->used
= myhttp
.used
;
2174 memcpy(http
->buffer
, myhttp
.buffer
, http
->used
);
2176 http
->auth_type
= myhttp
.auth_type
;
2177 http
->nonce_count
= myhttp
.nonce_count
;
2179 memcpy(http
->nonce
, myhttp
.nonce
, sizeof(http
->nonce
));
2181 http
->tls
= myhttp
.tls
;
2182 http
->encryption
= myhttp
.encryption
;
2185 * See if we actually went secure...
2191 * Server does not support HTTP upgrade...
2194 DEBUG_puts("Server does not support HTTP upgrade!");
2197 closesocket(http
->fd
);
2209 #endif /* HAVE_LIBSSL */
2213 * End of "$Id: http.c,v 1.82.2.9 2002/02/12 19:23:07 mike Exp $".