2 * "$Id: http.c,v 1.82.2.22 2003/01/14 14:34:15 mike Exp $"
4 * HTTP routines for the Common UNIX Printing System (CUPS).
6 * Copyright 1997-2003 by Easy Software Products, all rights reserved.
8 * These coded instructions, statements, and computer programs are the
9 * property of Easy Software Products and are protected by Federal
10 * copyright law. Distribution and use rights are outlined in the file
11 * "LICENSE.txt" which should have been included with this file. If this
12 * file is missing or damaged please contact Easy Software Products
15 * Attn: CUPS Licensing Information
16 * Easy Software Products
17 * 44141 Airport View Drive, Suite 204
18 * Hollywood, Maryland 20636-3111 USA
20 * Voice: (301) 373-9603
21 * EMail: cups-info@cups.org
22 * WWW: http://www.cups.org
24 * This file is subject to the Apple OS-Developed Software exception.
28 * httpInitialize() - Initialize the HTTP interface library and set the
29 * default HTTP proxy (if any).
30 * httpCheck() - Check to see if there is a pending response from
32 * httpClose() - Close an HTTP connection...
33 * httpConnect() - Connect to a HTTP server.
34 * httpConnectEncrypt() - Connect to a HTTP server using encryption.
35 * httpEncryption() - Set the required encryption on the link.
36 * httpReconnect() - Reconnect to a HTTP server...
37 * httpSetField() - Set the value of an HTTP header.
38 * httpDelete() - Send a DELETE request to the server.
39 * httpGet() - Send a GET request to the server.
40 * httpHead() - Send a HEAD request to the server.
41 * httpOptions() - Send an OPTIONS request to the server.
42 * httpPost() - Send a POST request to the server.
43 * httpPut() - Send a PUT request to the server.
44 * httpTrace() - Send an TRACE request to the server.
45 * httpFlush() - Flush data from a HTTP connection.
46 * httpRead() - Read data from a HTTP connection.
47 * httpWrite() - Write data to a HTTP connection.
48 * httpGets() - Get a line of text from a HTTP connection.
49 * httpPrintf() - Print a formatted string to a HTTP connection.
50 * httpStatus() - Return a short string describing a HTTP status code.
51 * httpGetDateString() - Get a formatted date/time string from a time value.
52 * httpGetDateTime() - Get a time value from a formatted date/time string.
53 * httpUpdate() - Update the current HTTP state for incoming data.
54 * httpDecode64() - Base64-decode a string.
55 * httpEncode64() - Base64-encode a string.
56 * httpGetLength() - Get the amount of data remaining from the
57 * content-length or transfer-encoding fields.
58 * http_field() - Return the field index for a field name.
59 * http_send() - Send a request with all fields and the trailing
61 * http_upgrade() - Force upgrade to TLS encryption.
65 * Include necessary headers...
85 # include <openssl/err.h>
86 # include <openssl/rand.h>
87 # include <openssl/ssl.h>
88 #endif /* HAVE_LIBSSL */
92 * Some operating systems have done away with the Fxxxx constants for
93 * the fcntl() call; this works around that "feature"...
97 # define FNONBLK O_NONBLOCK
105 static http_field_t
http_field(const char *name
);
106 static int http_send(http_t
*http
, http_state_t request
,
109 static int http_upgrade(http_t
*http
);
110 #endif /* HAVE_LIBSSL */
117 static const char *http_fields
[] =
134 "If-Unmodified-since",
147 static const char *days
[7] =
157 static const char *months
[12] =
175 * 'httpInitialize()' - Initialize the HTTP interface library and set the
176 * default HTTP proxy (if any).
183 struct timeval curtime
; /* Current time in microseconds */
184 int i
; /* Looping var */
185 unsigned char data
[1024]; /* Seed data */
186 #endif /* HAVE_LIBSSL */
189 WSADATA winsockdata
; /* WinSock data */
190 static int initialized
= 0;/* Has WinSock been initialized? */
194 WSAStartup(MAKEWORD(1,1), &winsockdata
);
195 #elif defined(HAVE_SIGSET)
196 sigset(SIGPIPE
, SIG_IGN
);
197 #elif defined(HAVE_SIGACTION)
198 struct sigaction action
; /* POSIX sigaction data */
202 * Ignore SIGPIPE signals...
205 memset(&action
, 0, sizeof(action
));
206 action
.sa_handler
= SIG_IGN
;
207 sigaction(SIGPIPE
, &action
, NULL
);
209 signal(SIGPIPE
, SIG_IGN
);
213 SSL_load_error_strings();
217 * Using the current time is a dubious random seed, but on some systems
218 * it is the best we can do (on others, this seed isn't even used...)
221 gettimeofday(&curtime
, NULL
);
222 srand(curtime
.tv_sec
+ curtime
.tv_usec
);
224 for (i
= 0; i
< sizeof(data
); i
++)
225 data
[i
] = rand(); /* Yes, this is a poor source of random data... */
227 RAND_seed(&data
, sizeof(data
));
228 #endif /* HAVE_LIBSSL */
233 * 'httpCheck()' - Check to see if there is a pending response from the server.
236 int /* O - 0 = no data, 1 = data available */
237 httpCheck(http_t
*http
) /* I - HTTP connection */
239 fd_set input
; /* Input set for select() */
240 struct timeval timeout
; /* Timeout */
244 * First see if there is data in the buffer...
254 * Then try doing a select() to poll the socket...
258 FD_SET(http
->fd
, &input
);
263 return (select(http
->fd
+ 1, &input
, NULL
, NULL
, &timeout
) > 0);
268 * 'httpClose()' - Close an HTTP connection...
272 httpClose(http_t
*http
) /* I - Connection to close */
275 SSL_CTX
*context
; /* Context for encryption */
276 SSL
*conn
; /* Connection for encryption */
277 #endif /* HAVE_LIBSSL */
286 conn
= (SSL
*)(http
->tls
);
287 context
= SSL_get_SSL_CTX(conn
);
290 SSL_CTX_free(context
);
295 #endif /* HAVE_LIBSSL */
298 closesocket(http
->fd
);
308 * 'httpConnect()' - Connect to a HTTP server.
311 http_t
* /* O - New HTTP connection */
312 httpConnect(const char *host
, /* I - Host to connect to */
313 int port
) /* I - Port number */
315 http_encryption_t encrypt
;/* Type of encryption to use */
319 * Set the default encryption status...
323 encrypt
= HTTP_ENCRYPT_ALWAYS
;
325 encrypt
= HTTP_ENCRYPT_IF_REQUESTED
;
327 return (httpConnectEncrypt(host
, port
, encrypt
));
332 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
335 http_t
* /* O - New HTTP connection */
336 httpConnectEncrypt(const char *host
, /* I - Host to connect to */
337 int port
, /* I - Port number */
338 http_encryption_t encrypt
)
339 /* I - Type of encryption to use */
341 int i
; /* Looping var */
342 http_t
*http
; /* New HTTP connection */
343 struct hostent
*hostaddr
; /* Host address data */
355 if ((hostaddr
= httpGetHostByName(host
)) == NULL
)
358 * This hack to make users that don't have a localhost entry in
359 * their hosts file or DNS happy...
362 if (strcasecmp(host
, "localhost") != 0)
364 else if ((hostaddr
= httpGetHostByName("127.0.0.1")) == NULL
)
369 * Verify that it is an IPv4 address (IPv6 support will come in CUPS 1.2...)
373 if ((hostaddr
->h_addrtype
!= AF_INET
|| hostaddr
->h_length
!= 4) &&
374 (hostaddr
->h_addrtype
!= AF_INET6
|| hostaddr
->h_length
!= 16))
377 if (hostaddr
->h_addrtype
!= AF_INET
|| hostaddr
->h_length
!= 4)
379 #endif /* AF_INET6 */
382 * Allocate memory for the structure...
385 http
= calloc(sizeof(http_t
), 1);
389 http
->version
= HTTP_1_1
;
391 http
->activity
= time(NULL
);
395 * Set the encryption status...
398 if (port
== 443) /* Always use encryption for https */
399 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
401 http
->encryption
= encrypt
;
404 * Loop through the addresses we have until one of them connects...
407 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
409 for (i
= 0; hostaddr
->h_addr_list
[i
]; i
++)
412 * Load the address...
415 httpAddrLoad(hostaddr
, port
, i
, &(http
->hostaddr
));
418 * Connect to the remote system...
421 if (!httpReconnect(http
))
426 * Return the new structure if we could connect; otherwise, bail out...
429 if (hostaddr
->h_addr_list
[i
])
440 * 'httpEncryption()' - Set the required encryption on the link.
443 int /* O - -1 on error, 0 on success */
444 httpEncryption(http_t
*http
, /* I - HTTP data */
445 http_encryption_t e
) /* I - New encryption preference */
451 http
->encryption
= e
;
453 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
454 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
455 return (httpReconnect(http
));
456 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
457 return (http_upgrade(http
));
461 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
465 #endif /* HAVE_LIBSSL */
470 * 'httpReconnect()' - Reconnect to a HTTP server...
473 int /* O - 0 on success, non-zero on failure */
474 httpReconnect(http_t
*http
) /* I - HTTP data */
476 int val
; /* Socket option value */
478 SSL_CTX
*context
; /* Context for encryption */
479 SSL
*conn
; /* Connection for encryption */
484 conn
= (SSL
*)(http
->tls
);
485 context
= SSL_get_SSL_CTX(conn
);
488 SSL_CTX_free(context
);
493 #endif /* HAVE_LIBSSL */
496 * Close any previously open socket...
501 closesocket(http
->fd
);
507 * Create the socket and set options to allow reuse.
510 if ((http
->fd
= socket(http
->hostaddr
.addr
.sa_family
, SOCK_STREAM
, 0)) < 0)
513 http
->error
= WSAGetLastError();
517 http
->status
= HTTP_ERROR
;
522 fcntl(http
->fd
, F_SETFD
, FD_CLOEXEC
); /* Close this socket when starting *
523 * other processes... */
524 #endif /* FD_CLOEXEC */
527 setsockopt(http
->fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *)&val
, sizeof(val
));
531 setsockopt(http
->fd
, SOL_SOCKET
, SO_REUSEPORT
, &val
, sizeof(val
));
532 #endif /* SO_REUSEPORT */
535 * Using TCP_NODELAY improves responsiveness, especially on systems
536 * with a slow loopback interface... Since we write large buffers
537 * when sending print files and requests, there shouldn't be any
538 * performance penalty for this...
542 setsockopt(http
->fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
545 * Connect to the server...
548 if (connect(http
->fd
, (struct sockaddr
*)&(http
->hostaddr
),
549 sizeof(http
->hostaddr
)) < 0)
552 http
->error
= WSAGetLastError();
556 http
->status
= HTTP_ERROR
;
559 closesocket(http
->fd
);
570 http
->status
= HTTP_CONTINUE
;
573 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
576 * Always do encryption via SSL.
579 context
= SSL_CTX_new(SSLv23_method());
580 conn
= SSL_new(context
);
582 SSL_set_fd(conn
, http
->fd
);
583 if (SSL_connect(conn
) != 1)
585 SSL_CTX_free(context
);
589 http
->error
= WSAGetLastError();
593 http
->status
= HTTP_ERROR
;
596 closesocket(http
->fd
);
606 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
607 return (http_upgrade(http
));
608 #endif /* HAVE_LIBSSL */
615 * 'httpGetSubField()' - Get a sub-field value.
618 char * /* O - Value or NULL */
619 httpGetSubField(http_t
*http
, /* I - HTTP data */
620 http_field_t field
, /* I - Field index */
621 const char *name
, /* I - Name of sub-field */
622 char *value
) /* O - Value string */
624 const char *fptr
; /* Pointer into field */
625 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
626 *ptr
; /* Pointer into string buffer */
630 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
631 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
632 name
== NULL
|| value
== NULL
)
635 for (fptr
= http
->fields
[field
]; *fptr
;)
638 * Skip leading whitespace...
641 while (isspace(*fptr
))
651 * Get the sub-field name...
655 *fptr
&& *fptr
!= '=' && !isspace(*fptr
) && ptr
< (temp
+ sizeof(temp
) - 1);
661 * Skip trailing chars up to the '='...
664 while (*fptr
&& *fptr
!= '=')
671 * Skip = and leading whitespace...
676 while (isspace(*fptr
))
682 * Read quoted string...
685 for (ptr
= value
, fptr
++;
686 *fptr
&& *fptr
!= '\"' && ptr
< (value
+ HTTP_MAX_VALUE
- 1);
691 while (*fptr
&& *fptr
!= '\"')
700 * Read unquoted string...
704 *fptr
&& !isspace(*fptr
) && *fptr
!= ',' && ptr
< (value
+ HTTP_MAX_VALUE
- 1);
709 while (*fptr
&& !isspace(*fptr
) && *fptr
!= ',')
714 * See if this is the one...
717 if (strcmp(name
, temp
) == 0)
728 * 'httpSetField()' - Set the value of an HTTP header.
732 httpSetField(http_t
*http
, /* I - HTTP data */
733 http_field_t field
, /* I - Field index */
734 const char *value
) /* I - Value */
737 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
738 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
742 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
747 * 'httpDelete()' - Send a DELETE request to the server.
750 int /* O - Status of call (0 = success) */
751 httpDelete(http_t
*http
, /* I - HTTP data */
752 const char *uri
) /* I - URI to delete */
754 return (http_send(http
, HTTP_DELETE
, uri
));
759 * 'httpGet()' - Send a GET request to the server.
762 int /* O - Status of call (0 = success) */
763 httpGet(http_t
*http
, /* I - HTTP data */
764 const char *uri
) /* I - URI to get */
766 return (http_send(http
, HTTP_GET
, uri
));
771 * 'httpHead()' - Send a HEAD request to the server.
774 int /* O - Status of call (0 = success) */
775 httpHead(http_t
*http
, /* I - HTTP data */
776 const char *uri
) /* I - URI for head */
778 return (http_send(http
, HTTP_HEAD
, uri
));
783 * 'httpOptions()' - Send an OPTIONS request to the server.
786 int /* O - Status of call (0 = success) */
787 httpOptions(http_t
*http
, /* I - HTTP data */
788 const char *uri
) /* I - URI for options */
790 return (http_send(http
, HTTP_OPTIONS
, uri
));
795 * 'httpPost()' - Send a POST request to the server.
798 int /* O - Status of call (0 = success) */
799 httpPost(http_t
*http
, /* I - HTTP data */
800 const char *uri
) /* I - URI for post */
804 return (http_send(http
, HTTP_POST
, uri
));
809 * 'httpPut()' - Send a PUT request to the server.
812 int /* O - Status of call (0 = success) */
813 httpPut(http_t
*http
, /* I - HTTP data */
814 const char *uri
) /* I - URI to put */
818 return (http_send(http
, HTTP_PUT
, uri
));
823 * 'httpTrace()' - Send an TRACE request to the server.
826 int /* O - Status of call (0 = success) */
827 httpTrace(http_t
*http
, /* I - HTTP data */
828 const char *uri
) /* I - URI for trace */
830 return (http_send(http
, HTTP_TRACE
, uri
));
835 * 'httpFlush()' - Flush data from a HTTP connection.
839 httpFlush(http_t
*http
) /* I - HTTP data */
841 char buffer
[8192]; /* Junk buffer */
844 while (httpRead(http
, buffer
, sizeof(buffer
)) > 0);
849 * 'httpRead()' - Read data from a HTTP connection.
852 int /* O - Number of bytes read */
853 httpRead(http_t
*http
, /* I - HTTP data */
854 char *buffer
, /* I - Buffer for data */
855 int length
) /* I - Maximum number of bytes */
857 int bytes
; /* Bytes read */
858 char len
[32]; /* Length string */
861 DEBUG_printf(("httpRead(%p, %p, %d)\n", http
, buffer
, length
));
863 if (http
== NULL
|| buffer
== NULL
)
866 http
->activity
= time(NULL
);
871 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
872 http
->data_remaining
<= 0)
874 DEBUG_puts("httpRead: Getting chunk length...");
876 if (httpGets(len
, sizeof(len
), http
) == NULL
)
878 DEBUG_puts("httpRead: Could not get length!");
882 http
->data_remaining
= strtol(len
, NULL
, 16);
883 if (http
->data_remaining
< 0)
885 DEBUG_puts("httpRead: Negative chunk length!");
890 DEBUG_printf(("httpRead: data_remaining = %d\n", http
->data_remaining
));
892 if (http
->data_remaining
<= 0)
895 * A zero-length chunk ends a transfer; unless we are reading POST
899 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
900 httpGets(len
, sizeof(len
), http
);
902 if (http
->state
== HTTP_POST_RECV
)
905 http
->state
= HTTP_WAITING
;
909 else if (length
> http
->data_remaining
)
910 length
= http
->data_remaining
;
912 if (http
->used
== 0 && length
<= 256)
915 * Buffer small reads for better performance...
918 if (http
->data_remaining
> sizeof(http
->buffer
))
919 bytes
= sizeof(http
->buffer
);
921 bytes
= http
->data_remaining
;
925 bytes
= SSL_read((SSL
*)(http
->tls
), http
->buffer
, bytes
);
927 #endif /* HAVE_LIBSSL */
929 DEBUG_printf(("httpRead: reading %d bytes from socket into buffer...\n",
932 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
934 DEBUG_printf(("httpRead: read %d bytes from socket into buffer...\n",
943 http
->error
= WSAGetLastError();
959 if (length
> http
->used
)
964 DEBUG_printf(("httpRead: grabbing %d bytes from input buffer...\n", bytes
));
966 memcpy(buffer
, http
->buffer
, length
);
967 http
->used
-= length
;
970 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
974 bytes
= SSL_read((SSL
*)(http
->tls
), buffer
, length
);
975 #endif /* HAVE_LIBSSL */
978 DEBUG_printf(("httpRead: reading %d bytes from socket...\n", length
));
979 bytes
= recv(http
->fd
, buffer
, length
, 0);
980 DEBUG_printf(("httpRead: read %d bytes from socket...\n", bytes
));
984 http
->data_remaining
-= bytes
;
988 http
->error
= WSAGetLastError();
997 if (http
->data_remaining
== 0)
999 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1000 httpGets(len
, sizeof(len
), http
);
1002 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
1004 if (http
->state
== HTTP_POST_RECV
)
1007 http
->state
= HTTP_WAITING
;
1014 printf("httpRead: Read %d bytes:\n", bytes
);
1015 for (i
= 0; i
< bytes
; i
+= 16)
1019 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1020 printf(" %02X", buffer
[i
+ j
] & 255);
1029 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1031 ch
= buffer
[i
+ j
] & 255;
1033 if (ch
< ' ' || ch
== 127)
1048 * 'httpWrite()' - Write data to a HTTP connection.
1051 int /* O - Number of bytes written */
1052 httpWrite(http_t
*http
, /* I - HTTP data */
1053 const char *buffer
, /* I - Buffer for data */
1054 int length
) /* I - Number of bytes to write */
1056 int tbytes
, /* Total bytes sent */
1057 bytes
; /* Bytes sent */
1060 if (http
== NULL
|| buffer
== NULL
)
1063 http
->activity
= time(NULL
);
1065 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1067 if (httpPrintf(http
, "%x\r\n", length
) < 0)
1073 * A zero-length chunk ends a transfer; unless we are sending POST
1077 DEBUG_puts("httpWrite: changing states...");
1079 if (http
->state
== HTTP_POST_RECV
)
1081 else if (http
->state
== HTTP_PUT_RECV
)
1082 http
->state
= HTTP_STATUS
;
1084 http
->state
= HTTP_WAITING
;
1086 if (httpPrintf(http
, "\r\n") < 0)
1099 bytes
= SSL_write((SSL
*)(http
->tls
), buffer
, length
);
1101 #endif /* HAVE_LIBSSL */
1102 bytes
= send(http
->fd
, buffer
, length
, 0);
1107 if (WSAGetLastError() != http
->error
)
1109 http
->error
= WSAGetLastError();
1115 else if (errno
!= http
->error
)
1117 http
->error
= errno
;
1122 DEBUG_puts("httpWrite: error writing data...\n");
1130 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1131 http
->data_remaining
-= bytes
;
1134 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1135 if (httpPrintf(http
, "\r\n") < 0)
1138 if (http
->data_remaining
== 0 && http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1141 * Finished with the transfer; unless we are sending POST data, go idle...
1144 DEBUG_puts("httpWrite: changing states...");
1146 if (http
->state
== HTTP_POST_RECV
)
1149 http
->state
= HTTP_WAITING
;
1155 printf("httpWrite: wrote %d bytes: \n", tbytes
);
1156 for (i
= 0, buffer
-= tbytes
; i
< tbytes
; i
+= 16)
1160 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
1161 printf(" %02X", buffer
[i
+ j
] & 255);
1170 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
1172 ch
= buffer
[i
+ j
] & 255;
1174 if (ch
< ' ' || ch
== 127)
1188 * 'httpGets()' - Get a line of text from a HTTP connection.
1191 char * /* O - Line or NULL */
1192 httpGets(char *line
, /* I - Line to read into */
1193 int length
, /* I - Max length of buffer */
1194 http_t
*http
) /* I - HTTP data */
1196 char *lineptr
, /* Pointer into line */
1197 *bufptr
, /* Pointer into input buffer */
1198 *bufend
; /* Pointer to end of buffer */
1199 int bytes
; /* Number of bytes read */
1202 DEBUG_printf(("httpGets(%p, %d, %p)\n", line
, length
, http
));
1204 if (http
== NULL
|| line
== NULL
)
1208 * Pre-scan the buffer and see if there is a newline in there...
1219 bufptr
= http
->buffer
;
1220 bufend
= http
->buffer
+ http
->used
;
1222 while (bufptr
< bufend
)
1223 if (*bufptr
== 0x0a)
1228 if (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
)
1231 * No newline; see if there is more data to be read...
1236 bytes
= SSL_read((SSL
*)(http
->tls
), bufend
,
1237 HTTP_MAX_BUFFER
- http
->used
);
1239 #endif /* HAVE_LIBSSL */
1240 bytes
= recv(http
->fd
, bufend
, HTTP_MAX_BUFFER
- http
->used
, 0);
1245 * Nope, can't get a line this time...
1249 if (WSAGetLastError() != http
->error
)
1251 http
->error
= WSAGetLastError();
1255 DEBUG_printf(("httpGets(): recv() error %d!\n", WSAGetLastError()));
1259 else if (errno
!= http
->error
)
1261 http
->error
= errno
;
1265 DEBUG_printf(("httpGets(): recv() error %d!\n", errno
));
1270 else if (bytes
== 0)
1273 http
->error
= EPIPE
;
1279 * Yup, update the amount used and the end pointer...
1282 http
->used
+= bytes
;
1287 while (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
);
1289 http
->activity
= time(NULL
);
1292 * Read a line from the buffer...
1296 bufptr
= http
->buffer
;
1300 while (bufptr
< bufend
&& bytes
< length
)
1304 if (*bufptr
== 0x0a)
1309 else if (*bufptr
== 0x0d)
1312 *lineptr
++ = *bufptr
++;
1319 http
->used
-= bytes
;
1321 memmove(http
->buffer
, bufptr
, http
->used
);
1323 DEBUG_printf(("httpGets(): Returning \"%s\"\n", line
));
1327 DEBUG_puts("httpGets(): No new line available!");
1334 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1337 int /* O - Number of bytes written */
1338 httpPrintf(http_t
*http
, /* I - HTTP data */
1339 const char *format
, /* I - printf-style format string */
1340 ...) /* I - Additional args as needed */
1342 int bytes
, /* Number of bytes to write */
1343 nbytes
, /* Number of bytes written */
1344 tbytes
; /* Number of bytes all together */
1345 char buf
[HTTP_MAX_BUFFER
], /* Buffer for formatted string */
1346 *bufptr
; /* Pointer into buffer */
1347 va_list ap
; /* Variable argument pointer */
1350 va_start(ap
, format
);
1351 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1354 DEBUG_printf(("httpPrintf: %s", buf
));
1356 for (tbytes
= 0, bufptr
= buf
; tbytes
< bytes
; tbytes
+= nbytes
, bufptr
+= nbytes
)
1360 nbytes
= SSL_write((SSL
*)(http
->tls
), bufptr
, bytes
- tbytes
);
1362 #endif /* HAVE_LIBSSL */
1363 nbytes
= send(http
->fd
, bufptr
, bytes
- tbytes
, 0);
1370 if (WSAGetLastError() != http
->error
)
1372 http
->error
= WSAGetLastError();
1378 else if (errno
!= http
->error
)
1380 http
->error
= errno
;
1394 * 'httpStatus()' - Return a short string describing a HTTP status code.
1397 const char * /* O - String or NULL */
1398 httpStatus(http_status_t status
) /* I - HTTP status code */
1402 case HTTP_CONTINUE
:
1403 return ("Continue");
1404 case HTTP_SWITCHING_PROTOCOLS
:
1405 return ("Switching Protocols");
1410 case HTTP_ACCEPTED
:
1411 return ("Accepted");
1412 case HTTP_NO_CONTENT
:
1413 return ("No Content");
1414 case HTTP_NOT_MODIFIED
:
1415 return ("Not Modified");
1416 case HTTP_BAD_REQUEST
:
1417 return ("Bad Request");
1418 case HTTP_UNAUTHORIZED
:
1419 return ("Unauthorized");
1420 case HTTP_FORBIDDEN
:
1421 return ("Forbidden");
1422 case HTTP_NOT_FOUND
:
1423 return ("Not Found");
1424 case HTTP_REQUEST_TOO_LARGE
:
1425 return ("Request Entity Too Large");
1426 case HTTP_URI_TOO_LONG
:
1427 return ("URI Too Long");
1428 case HTTP_UPGRADE_REQUIRED
:
1429 return ("Upgrade Required");
1430 case HTTP_NOT_IMPLEMENTED
:
1431 return ("Not Implemented");
1432 case HTTP_NOT_SUPPORTED
:
1433 return ("Not Supported");
1441 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
1444 const char * /* O - Date/time string */
1445 httpGetDateString(time_t t
) /* I - UNIX time */
1448 static char datetime
[256];
1452 snprintf(datetime
, sizeof(datetime
), "%s, %02d %s %d %02d:%02d:%02d GMT",
1453 days
[tdate
->tm_wday
], tdate
->tm_mday
, months
[tdate
->tm_mon
],
1454 tdate
->tm_year
+ 1900, tdate
->tm_hour
, tdate
->tm_min
, tdate
->tm_sec
);
1461 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
1464 time_t /* O - UNIX time */
1465 httpGetDateTime(const char *s
) /* I - Date/time string */
1467 int i
; /* Looping var */
1468 struct tm tdate
; /* Time/date structure */
1469 char mon
[16]; /* Abbreviated month name */
1470 int day
, year
; /* Day of month and year */
1471 int hour
, min
, sec
; /* Time */
1474 if (sscanf(s
, "%*s%d%15s%d%d:%d:%d", &day
, mon
, &year
, &hour
, &min
, &sec
) < 6)
1477 for (i
= 0; i
< 12; i
++)
1478 if (strcasecmp(mon
, months
[i
]) == 0)
1485 tdate
.tm_mday
= day
;
1486 tdate
.tm_year
= year
- 1900;
1487 tdate
.tm_hour
= hour
;
1492 return (mktime(&tdate
));
1497 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1500 http_status_t
/* O - HTTP status */
1501 httpUpdate(http_t
*http
) /* I - HTTP data */
1503 char line
[1024], /* Line from connection... */
1504 *value
; /* Pointer to value on line */
1505 http_field_t field
; /* Field index */
1506 int major
, minor
; /* HTTP version numbers */
1507 http_status_t status
; /* Authorization status */
1509 SSL_CTX
*context
; /* Context for encryption */
1510 SSL
*conn
; /* Connection for encryption */
1511 #endif /* HAVE_LIBSSL */
1514 DEBUG_printf(("httpUpdate(%p)\n", http
));
1517 * If we haven't issued any commands, then there is nothing to "update"...
1520 if (http
->state
== HTTP_WAITING
)
1521 return (HTTP_CONTINUE
);
1524 * Grab all of the lines we can from the connection...
1527 while (httpGets(line
, sizeof(line
), http
) != NULL
)
1531 if (line
[0] == '\0')
1534 * Blank line means the start of the data section (if any). Return
1535 * the result code, too...
1537 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
1538 * Instead, we just return HTTP_CONTINUE to the caller and keep on
1542 if (http
->status
== HTTP_CONTINUE
)
1543 return (http
->status
);
1546 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
1548 context
= SSL_CTX_new(SSLv23_method());
1549 conn
= SSL_new(context
);
1551 SSL_set_fd(conn
, http
->fd
);
1552 if (SSL_connect(conn
) != 1)
1554 SSL_CTX_free(context
);
1558 http
->error
= WSAGetLastError();
1560 http
->error
= errno
;
1562 http
->status
= HTTP_ERROR
;
1565 closesocket(http
->fd
);
1570 return (HTTP_ERROR
);
1575 return (HTTP_CONTINUE
);
1577 else if (http
->status
== HTTP_UPGRADE_REQUIRED
&&
1578 http
->encryption
!= HTTP_ENCRYPT_NEVER
)
1579 http
->encryption
= HTTP_ENCRYPT_REQUIRED
;
1580 #endif /* HAVE_LIBSSL */
1582 httpGetLength(http
);
1584 switch (http
->state
)
1588 case HTTP_POST_RECV
:
1594 http
->state
= HTTP_WAITING
;
1598 return (http
->status
);
1600 else if (strncmp(line
, "HTTP/", 5) == 0)
1603 * Got the beginning of a response...
1606 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, (int *)&status
) != 3)
1607 return (HTTP_ERROR
);
1609 http
->version
= (http_version_t
)(major
* 100 + minor
);
1610 http
->status
= status
;
1612 else if ((value
= strchr(line
, ':')) != NULL
)
1619 while (isspace(*value
))
1623 * Be tolerants of servers that send unknown attribute fields...
1626 if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
1628 DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line
));
1632 httpSetField(http
, field
, value
);
1636 http
->status
= HTTP_ERROR
;
1637 return (HTTP_ERROR
);
1642 * See if there was an error...
1647 http
->status
= HTTP_ERROR
;
1648 return (HTTP_ERROR
);
1652 * If we haven't already returned, then there is nothing new...
1655 return (HTTP_CONTINUE
);
1660 * 'httpDecode64()' - Base64-decode a string.
1663 char * /* O - Decoded string */
1664 httpDecode64(char *out
, /* I - String to write to */
1665 const char *in
) /* I - String to read from */
1667 int pos
, /* Bit position */
1668 base64
; /* Value of this character */
1669 char *outptr
; /* Output pointer */
1672 for (outptr
= out
, pos
= 0; *in
!= '\0'; in
++)
1675 * Decode this character into a number from 0 to 63...
1678 if (*in
>= 'A' && *in
<= 'Z')
1680 else if (*in
>= 'a' && *in
<= 'z')
1681 base64
= *in
- 'a' + 26;
1682 else if (*in
>= '0' && *in
<= '9')
1683 base64
= *in
- '0' + 52;
1684 else if (*in
== '+')
1686 else if (*in
== '/')
1688 else if (*in
== '=')
1694 * Store the result in the appropriate chars...
1700 *outptr
= base64
<< 2;
1704 *outptr
++ |= (base64
>> 4) & 3;
1705 *outptr
= (base64
<< 4) & 255;
1709 *outptr
++ |= (base64
>> 2) & 15;
1710 *outptr
= (base64
<< 6) & 255;
1714 *outptr
++ |= base64
;
1723 * Return the decoded string...
1731 * 'httpEncode64()' - Base64-encode a string.
1734 char * /* O - Encoded string */
1735 httpEncode64(char *out
, /* I - String to write to */
1736 const char *in
) /* I - String to read from */
1738 char *outptr
; /* Output pointer */
1739 static char base64
[] = /* Base64 characters... */
1741 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1742 "abcdefghijklmnopqrstuvwxyz"
1748 for (outptr
= out
; *in
!= '\0'; in
++)
1751 * Encode the up to 3 characters as 4 Base64 numbers...
1754 *outptr
++ = base64
[in
[0] >> 2];
1755 *outptr
++ = base64
[((in
[0] << 4) | (in
[1] >> 4)) & 63];
1764 *outptr
++ = base64
[((in
[0] << 2) | (in
[1] >> 6)) & 63];
1770 *outptr
++ = base64
[in
[0] & 63];
1777 * Return the encoded string...
1785 * 'httpGetLength()' - Get the amount of data remaining from the
1786 * content-length or transfer-encoding fields.
1789 int /* O - Content length */
1790 httpGetLength(http_t
*http
) /* I - HTTP data */
1792 DEBUG_printf(("httpGetLength(%p)\n", http
));
1794 if (strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked") == 0)
1796 DEBUG_puts("httpGetLength: chunked request!");
1798 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
1799 http
->data_remaining
= 0;
1803 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1806 * The following is a hack for HTTP servers that don't send a
1807 * content-length or transfer-encoding field...
1809 * If there is no content-length then the connection must close
1810 * after the transfer is complete...
1813 if (http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] == '\0')
1814 http
->data_remaining
= 2147483647;
1816 http
->data_remaining
= atoi(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
]);
1818 DEBUG_printf(("httpGetLength: content_length = %d\n", http
->data_remaining
));
1821 return (http
->data_remaining
);
1826 * 'http_field()' - Return the field index for a field name.
1829 static http_field_t
/* O - Field index */
1830 http_field(const char *name
) /* I - String name */
1832 int i
; /* Looping var */
1835 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
1836 if (strcasecmp(name
, http_fields
[i
]) == 0)
1837 return ((http_field_t
)i
);
1839 return (HTTP_FIELD_UNKNOWN
);
1844 * 'http_send()' - Send a request with all fields and the trailing blank line.
1847 static int /* O - 0 on success, non-zero on error */
1848 http_send(http_t
*http
, /* I - HTTP data */
1849 http_state_t request
, /* I - Request code */
1850 const char *uri
) /* I - URI */
1852 int i
; /* Looping var */
1853 char *ptr
, /* Pointer in buffer */
1854 buf
[1024]; /* Encoded URI buffer */
1855 static const char *codes
[] = /* Request code strings */
1871 static const char *hex
= "0123456789ABCDEF";
1875 if (http
== NULL
|| uri
== NULL
)
1879 * Encode the URI as needed...
1882 for (ptr
= buf
; *uri
!= '\0' && ptr
< (buf
+ sizeof(buf
) - 1); uri
++)
1883 if (*uri
<= ' ' || *uri
>= 127)
1885 if (ptr
< (buf
+ sizeof(buf
) - 1))
1887 if (ptr
< (buf
+ sizeof(buf
) - 1))
1888 *ptr
++ = hex
[(*uri
>> 4) & 15];
1889 if (ptr
< (buf
+ sizeof(buf
) - 1))
1890 *ptr
++ = hex
[*uri
& 15];
1898 * See if we had an error the last time around; if so, reconnect...
1901 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
1902 httpReconnect(http
);
1905 * Send the request header...
1908 http
->state
= request
;
1909 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
1912 http
->status
= HTTP_CONTINUE
;
1915 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
1917 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
1918 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
1920 #endif /* HAVE_LIBSSL */
1922 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
1924 http
->status
= HTTP_ERROR
;
1928 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
1929 if (http
->fields
[i
][0] != '\0')
1931 DEBUG_printf(("%s: %s\n", http_fields
[i
], http
->fields
[i
]));
1933 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], http
->fields
[i
]) < 1)
1935 http
->status
= HTTP_ERROR
;
1940 if (httpPrintf(http
, "\r\n") < 1)
1942 http
->status
= HTTP_ERROR
;
1946 httpClearFields(http
);
1954 * 'http_upgrade()' - Force upgrade to TLS encryption.
1957 static int /* O - Status of connection */
1958 http_upgrade(http_t
*http
) /* I - HTTP data */
1960 int ret
; /* Return value */
1961 http_t myhttp
; /* Local copy of HTTP data */
1964 DEBUG_printf(("http_upgrade(%p)\n", http
));
1967 * Copy the HTTP data to a local variable so we can do the OPTIONS
1968 * request without interfering with the existing request data...
1971 memcpy(&myhttp
, http
, sizeof(myhttp
));
1974 * Send an OPTIONS request to the server, requiring SSL or TLS
1975 * encryption on the link...
1978 httpClearFields(&myhttp
);
1979 httpSetField(&myhttp
, HTTP_FIELD_CONNECTION
, "upgrade");
1980 httpSetField(&myhttp
, HTTP_FIELD_UPGRADE
, "TLS/1.0, SSL/2.0, SSL/3.0");
1982 if ((ret
= httpOptions(&myhttp
, "*")) == 0)
1985 * Wait for the secure connection...
1988 while (httpUpdate(&myhttp
) == HTTP_CONTINUE
);
1994 * Copy the HTTP data back over, if any...
1997 http
->fd
= myhttp
.fd
;
1998 http
->error
= myhttp
.error
;
1999 http
->activity
= myhttp
.activity
;
2000 http
->status
= myhttp
.status
;
2001 http
->version
= myhttp
.version
;
2002 http
->keep_alive
= myhttp
.keep_alive
;
2003 http
->used
= myhttp
.used
;
2006 memcpy(http
->buffer
, myhttp
.buffer
, http
->used
);
2008 http
->auth_type
= myhttp
.auth_type
;
2009 http
->nonce_count
= myhttp
.nonce_count
;
2011 memcpy(http
->nonce
, myhttp
.nonce
, sizeof(http
->nonce
));
2013 http
->tls
= myhttp
.tls
;
2014 http
->encryption
= myhttp
.encryption
;
2017 * See if we actually went secure...
2023 * Server does not support HTTP upgrade...
2026 DEBUG_puts("Server does not support HTTP upgrade!");
2029 closesocket(http
->fd
);
2041 #endif /* HAVE_LIBSSL */
2045 * End of "$Id: http.c,v 1.82.2.22 2003/01/14 14:34:15 mike Exp $".