2 * "$Id: http.c,v 1.105 2002/10/30 20:04:56 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
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 * httpGetSubField() - Get a sub-field value.
38 * httpSetField() - Set the value of an HTTP header.
39 * httpDelete() - Send a DELETE request to the server.
40 * httpGet() - Send a GET request to the server.
41 * httpHead() - Send a HEAD request to the server.
42 * httpOptions() - Send an OPTIONS request to the server.
43 * httpPost() - Send a POST request to the server.
44 * httpPut() - Send a PUT request to the server.
45 * httpTrace() - Send an TRACE request to the server.
46 * httpFlush() - Flush data from a HTTP connection.
47 * httpRead() - Read data from a HTTP connection.
48 * httpWrite() - Write data to a HTTP connection.
49 * httpGets() - Get a line of text from a HTTP connection.
50 * httpPrintf() - Print a formatted string to a HTTP connection.
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...
84 # include <openssl/err.h>
85 # include <openssl/rand.h>
86 # include <openssl/ssl.h>
87 #endif /* HAVE_LIBSSL */
91 * Some operating systems have done away with the Fxxxx constants for
92 * the fcntl() call; this works around that "feature"...
96 # define FNONBLK O_NONBLOCK
104 static http_field_t
http_field(const char *name
);
105 static int http_send(http_t
*http
, http_state_t request
,
108 static int http_upgrade(http_t
*http
);
109 #endif /* HAVE_LIBSSL */
116 static const char *http_fields
[] =
133 "If-Unmodified-since",
146 static const char *days
[7] =
156 static const char *months
[12] =
174 * 'httpInitialize()' - Initialize the HTTP interface library and set the
175 * default HTTP proxy (if any).
183 struct timeval curtime
; /* Current time in microseconds */
185 int i
; /* Looping var */
186 unsigned char data
[1024]; /* Seed data */
187 #endif /* HAVE_LIBSSL */
190 WSADATA winsockdata
; /* WinSock data */
191 static int initialized
= 0;/* Has WinSock been initialized? */
195 WSAStartup(MAKEWORD(1,1), &winsockdata
);
196 #elif defined(HAVE_SIGSET)
197 sigset(SIGPIPE
, SIG_IGN
);
198 #elif defined(HAVE_SIGACTION)
199 struct sigaction action
; /* POSIX sigaction data */
203 * Ignore SIGPIPE signals...
206 memset(&action
, 0, sizeof(action
));
207 action
.sa_handler
= SIG_IGN
;
208 sigaction(SIGPIPE
, &action
, NULL
);
210 signal(SIGPIPE
, SIG_IGN
);
214 SSL_load_error_strings();
218 * Using the current time is a dubious random seed, but on some systems
219 * it is the best we can do (on others, this seed isn't even used...)
224 gettimeofday(&curtime
, NULL
);
225 srand(curtime
.tv_sec
+ curtime
.tv_usec
);
228 for (i
= 0; i
< sizeof(data
); i
++)
229 data
[i
] = rand(); /* Yes, this is a poor source of random data... */
231 RAND_seed(&data
, sizeof(data
));
232 #endif /* HAVE_LIBSSL */
237 * 'httpCheck()' - Check to see if there is a pending response from the server.
240 int /* O - 0 = no data, 1 = data available */
241 httpCheck(http_t
*http
) /* I - HTTP connection */
243 fd_set input
; /* Input set for select() */
244 struct timeval timeout
; /* Timeout */
248 * First see if there is data in the buffer...
258 * Then try doing a select() to poll the socket...
262 FD_SET(http
->fd
, &input
);
267 return (select(http
->fd
+ 1, &input
, NULL
, NULL
, &timeout
) > 0);
272 * 'httpClose()' - Close an HTTP connection...
276 httpClose(http_t
*http
) /* I - Connection to close */
279 SSL_CTX
*context
; /* Context for encryption */
280 SSL
*conn
; /* Connection for encryption */
281 #endif /* HAVE_LIBSSL */
290 conn
= (SSL
*)(http
->tls
);
291 context
= SSL_get_SSL_CTX(conn
);
294 SSL_CTX_free(context
);
299 #endif /* HAVE_LIBSSL */
302 closesocket(http
->fd
);
312 * 'httpConnect()' - Connect to a HTTP server.
315 http_t
* /* O - New HTTP connection */
316 httpConnect(const char *host
, /* I - Host to connect to */
317 int port
) /* I - Port number */
319 http_encryption_t encrypt
;/* Type of encryption to use */
323 * Set the default encryption status...
327 encrypt
= HTTP_ENCRYPT_ALWAYS
;
329 encrypt
= HTTP_ENCRYPT_IF_REQUESTED
;
331 return (httpConnectEncrypt(host
, port
, encrypt
));
336 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
339 http_t
* /* O - New HTTP connection */
340 httpConnectEncrypt(const char *host
, /* I - Host to connect to */
341 int port
, /* I - Port number */
342 http_encryption_t encrypt
)
343 /* I - Type of encryption to use */
345 int i
; /* Looping var */
346 http_t
*http
; /* New HTTP connection */
347 struct hostent
*hostaddr
; /* Host address data */
359 if ((hostaddr
= httpGetHostByName(host
)) == NULL
)
362 * This hack to make users that don't have a localhost entry in
363 * their hosts file or DNS happy...
366 if (strcasecmp(host
, "localhost") != 0)
368 else if ((hostaddr
= httpGetHostByName("127.0.0.1")) == NULL
)
373 * Verify that it is an IPv4 address (IPv6 support will come in CUPS 1.2...)
376 if (hostaddr
->h_addrtype
!= AF_INET
|| hostaddr
->h_length
!= 4)
380 * Allocate memory for the structure...
383 http
= calloc(sizeof(http_t
), 1);
387 http
->version
= HTTP_1_1
;
389 http
->activity
= time(NULL
);
393 * Copy the hostname and port and then "reconnect"...
396 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
397 http
->hostaddr
.sin_family
= hostaddr
->h_addrtype
;
399 http
->hostaddr
.sin_port
= htons((u_short
)port
);
401 http
->hostaddr
.sin_port
= htons(port
);
405 * Set the encryption status...
408 if (port
== 443) /* Always use encryption for https */
409 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
411 http
->encryption
= encrypt
;
414 * Loop through the addresses we have until one of them connects...
417 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
419 for (i
= 0; hostaddr
->h_addr_list
[i
]; i
++)
422 * Load the address...
425 memcpy((char *)&(http
->hostaddr
.sin_addr
), hostaddr
->h_addr_list
[i
],
429 * Connect to the remote system...
432 if (!httpReconnect(http
))
437 * Could not connect to any known address - bail out!
446 * 'httpEncryption()' - Set the required encryption on the link.
449 int /* O - -1 on error, 0 on success */
450 httpEncryption(http_t
*http
, /* I - HTTP data */
451 http_encryption_t e
) /* I - New encryption preference */
457 http
->encryption
= e
;
459 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
460 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
461 return (httpReconnect(http
));
462 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
463 return (http_upgrade(http
));
467 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
471 #endif /* HAVE_LIBSSL */
476 * 'httpReconnect()' - Reconnect to a HTTP server...
479 int /* O - 0 on success, non-zero on failure */
480 httpReconnect(http_t
*http
) /* I - HTTP data */
482 int val
; /* Socket option value */
484 SSL_CTX
*context
; /* Context for encryption */
485 SSL
*conn
; /* Connection for encryption */
490 conn
= (SSL
*)(http
->tls
);
491 context
= SSL_get_SSL_CTX(conn
);
494 SSL_CTX_free(context
);
499 #endif /* HAVE_LIBSSL */
502 * Close any previously open socket...
507 closesocket(http
->fd
);
513 * Create the socket and set options to allow reuse.
516 if ((http
->fd
= socket(AF_INET
, SOCK_STREAM
, 0)) < 0)
519 http
->error
= WSAGetLastError();
523 http
->status
= HTTP_ERROR
;
528 fcntl(http
->fd
, F_SETFD
, FD_CLOEXEC
); /* Close this socket when starting *
529 * other processes... */
530 #endif /* FD_CLOEXEC */
533 setsockopt(http
->fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *)&val
, sizeof(val
));
537 setsockopt(http
->fd
, SOL_SOCKET
, SO_REUSEPORT
, &val
, sizeof(val
));
538 #endif /* SO_REUSEPORT */
541 * Using TCP_NODELAY improves responsiveness, especially on systems
542 * with a slow loopback interface... Since we write large buffers
543 * when sending print files and requests, there shouldn't be any
544 * performance penalty for this...
548 setsockopt(http
->fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
551 * Connect to the server...
554 if (connect(http
->fd
, (struct sockaddr
*)&(http
->hostaddr
),
555 sizeof(http
->hostaddr
)) < 0)
558 http
->error
= WSAGetLastError();
562 http
->status
= HTTP_ERROR
;
565 closesocket(http
->fd
);
576 http
->status
= HTTP_CONTINUE
;
579 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
582 * Always do encryption via SSL.
585 context
= SSL_CTX_new(SSLv23_method());
586 conn
= SSL_new(context
);
588 SSL_set_fd(conn
, http
->fd
);
589 if (SSL_connect(conn
) != 1)
591 SSL_CTX_free(context
);
595 http
->error
= WSAGetLastError();
599 http
->status
= HTTP_ERROR
;
602 closesocket(http
->fd
);
612 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
613 return (http_upgrade(http
));
614 #endif /* HAVE_LIBSSL */
621 * 'httpGetSubField()' - Get a sub-field value.
624 char * /* O - Value or NULL */
625 httpGetSubField(http_t
*http
, /* I - HTTP data */
626 http_field_t field
, /* I - Field index */
627 const char *name
, /* I - Name of sub-field */
628 char *value
) /* O - Value string */
630 const char *fptr
; /* Pointer into field */
631 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
632 *ptr
; /* Pointer into string buffer */
636 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
637 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
638 name
== NULL
|| value
== NULL
)
641 DEBUG_printf(("httpGetSubField(%p, %d, \"%s\", %p)\n",
642 http
, field
, name
, value
));
644 for (fptr
= http
->fields
[field
]; *fptr
;)
647 * Skip leading whitespace...
650 while (isspace(*fptr
))
660 * Get the sub-field name...
664 *fptr
&& *fptr
!= '=' && !isspace(*fptr
) && ptr
< (temp
+ sizeof(temp
) - 1);
669 DEBUG_printf(("name = \"%s\"\n", temp
));
672 * Skip trailing chars up to the '='...
675 while (isspace(*fptr
))
685 * Skip = and leading whitespace...
690 while (isspace(*fptr
))
696 * Read quoted string...
699 for (ptr
= value
, fptr
++;
700 *fptr
&& *fptr
!= '\"' && ptr
< (value
+ HTTP_MAX_VALUE
- 1);
705 while (*fptr
&& *fptr
!= '\"')
714 * Read unquoted string...
718 *fptr
&& !isspace(*fptr
) && *fptr
!= ',' && ptr
< (value
+ HTTP_MAX_VALUE
- 1);
723 while (*fptr
&& !isspace(*fptr
) && *fptr
!= ',')
727 DEBUG_printf(("value = \"%s\"\n", value
));
730 * See if this is the one...
733 if (strcmp(name
, temp
) == 0)
744 * 'httpSetField()' - Set the value of an HTTP header.
748 httpSetField(http_t
*http
, /* I - HTTP data */
749 http_field_t field
, /* I - Field index */
750 const char *value
) /* I - Value */
753 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
754 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
758 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
763 * 'httpDelete()' - Send a DELETE request to the server.
766 int /* O - Status of call (0 = success) */
767 httpDelete(http_t
*http
, /* I - HTTP data */
768 const char *uri
) /* I - URI to delete */
770 return (http_send(http
, HTTP_DELETE
, uri
));
775 * 'httpGet()' - Send a GET request to the server.
778 int /* O - Status of call (0 = success) */
779 httpGet(http_t
*http
, /* I - HTTP data */
780 const char *uri
) /* I - URI to get */
782 return (http_send(http
, HTTP_GET
, uri
));
787 * 'httpHead()' - Send a HEAD request to the server.
790 int /* O - Status of call (0 = success) */
791 httpHead(http_t
*http
, /* I - HTTP data */
792 const char *uri
) /* I - URI for head */
794 return (http_send(http
, HTTP_HEAD
, uri
));
799 * 'httpOptions()' - Send an OPTIONS request to the server.
802 int /* O - Status of call (0 = success) */
803 httpOptions(http_t
*http
, /* I - HTTP data */
804 const char *uri
) /* I - URI for options */
806 return (http_send(http
, HTTP_OPTIONS
, uri
));
811 * 'httpPost()' - Send a POST request to the server.
814 int /* O - Status of call (0 = success) */
815 httpPost(http_t
*http
, /* I - HTTP data */
816 const char *uri
) /* I - URI for post */
820 return (http_send(http
, HTTP_POST
, uri
));
825 * 'httpPut()' - Send a PUT request to the server.
828 int /* O - Status of call (0 = success) */
829 httpPut(http_t
*http
, /* I - HTTP data */
830 const char *uri
) /* I - URI to put */
834 return (http_send(http
, HTTP_PUT
, uri
));
839 * 'httpTrace()' - Send an TRACE request to the server.
842 int /* O - Status of call (0 = success) */
843 httpTrace(http_t
*http
, /* I - HTTP data */
844 const char *uri
) /* I - URI for trace */
846 return (http_send(http
, HTTP_TRACE
, uri
));
851 * 'httpFlush()' - Flush data from a HTTP connection.
855 httpFlush(http_t
*http
) /* I - HTTP data */
857 char buffer
[8192]; /* Junk buffer */
860 while (httpRead(http
, buffer
, sizeof(buffer
)) > 0);
865 * 'httpRead()' - Read data from a HTTP connection.
868 int /* O - Number of bytes read */
869 httpRead(http_t
*http
, /* I - HTTP data */
870 char *buffer
, /* I - Buffer for data */
871 int length
) /* I - Maximum number of bytes */
873 int bytes
; /* Bytes read */
874 char len
[32]; /* Length string */
877 DEBUG_printf(("httpRead(%p, %p, %d)\n", http
, buffer
, length
));
879 if (http
== NULL
|| buffer
== NULL
)
882 http
->activity
= time(NULL
);
887 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
888 http
->data_remaining
<= 0)
890 DEBUG_puts("httpRead: Getting chunk length...");
892 if (httpGets(len
, sizeof(len
), http
) == NULL
)
894 DEBUG_puts("httpRead: Could not get length!");
898 http
->data_remaining
= strtol(len
, NULL
, 16);
901 DEBUG_printf(("httpRead: data_remaining = %d\n", http
->data_remaining
));
903 if (http
->data_remaining
== 0)
906 * A zero-length chunk ends a transfer; unless we are reading POST
910 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
911 httpGets(len
, sizeof(len
), http
);
913 if (http
->state
== HTTP_POST_RECV
)
916 http
->state
= HTTP_WAITING
;
920 else if (length
> http
->data_remaining
)
921 length
= http
->data_remaining
;
923 if (http
->used
== 0 && length
<= 256)
926 * Buffer small reads for better performance...
929 if (http
->data_remaining
> sizeof(http
->buffer
))
930 bytes
= sizeof(http
->buffer
);
932 bytes
= http
->data_remaining
;
936 bytes
= SSL_read((SSL
*)(http
->tls
), http
->buffer
, bytes
);
938 #endif /* HAVE_LIBSSL */
940 DEBUG_printf(("httpRead: reading %d bytes from socket into buffer...\n",
943 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
945 DEBUG_printf(("httpRead: read %d bytes from socket into buffer...\n",
954 http
->error
= WSAGetLastError();
970 if (length
> http
->used
)
975 DEBUG_printf(("httpRead: grabbing %d bytes from input buffer...\n", bytes
));
977 memcpy(buffer
, http
->buffer
, length
);
978 http
->used
-= length
;
981 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
985 bytes
= SSL_read((SSL
*)(http
->tls
), buffer
, length
);
986 #endif /* HAVE_LIBSSL */
989 DEBUG_printf(("httpRead: reading %d bytes from socket...\n", length
));
990 bytes
= recv(http
->fd
, buffer
, length
, 0);
991 DEBUG_printf(("httpRead: read %d bytes from socket...\n", bytes
));
995 http
->data_remaining
-= bytes
;
999 http
->error
= WSAGetLastError();
1004 http
->error
= errno
;
1008 if (http
->data_remaining
== 0)
1010 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1011 httpGets(len
, sizeof(len
), http
);
1013 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
1015 if (http
->state
== HTTP_POST_RECV
)
1018 http
->state
= HTTP_WAITING
;
1025 printf("httpRead: Read %d bytes:\n", bytes
);
1026 for (i
= 0; i
< bytes
; i
+= 16)
1030 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1031 printf(" %02X", buffer
[i
+ j
] & 255);
1040 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1042 ch
= buffer
[i
+ j
] & 255;
1044 if (ch
< ' ' || ch
== 127)
1059 * 'httpWrite()' - Write data to a HTTP connection.
1062 int /* O - Number of bytes written */
1063 httpWrite(http_t
*http
, /* I - HTTP data */
1064 const char *buffer
, /* I - Buffer for data */
1065 int length
) /* I - Number of bytes to write */
1067 int tbytes
, /* Total bytes sent */
1068 bytes
; /* Bytes sent */
1071 if (http
== NULL
|| buffer
== NULL
)
1074 http
->activity
= time(NULL
);
1076 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1078 if (httpPrintf(http
, "%x\r\n", length
) < 0)
1084 * A zero-length chunk ends a transfer; unless we are sending POST
1088 DEBUG_puts("httpWrite: changing states...");
1090 if (http
->state
== HTTP_POST_RECV
)
1092 else if (http
->state
== HTTP_PUT_RECV
)
1093 http
->state
= HTTP_STATUS
;
1095 http
->state
= HTTP_WAITING
;
1097 if (httpPrintf(http
, "\r\n") < 0)
1110 bytes
= SSL_write((SSL
*)(http
->tls
), buffer
, length
);
1112 #endif /* HAVE_LIBSSL */
1113 bytes
= send(http
->fd
, buffer
, length
, 0);
1118 if (WSAGetLastError() != http
->error
)
1120 http
->error
= WSAGetLastError();
1126 else if (errno
!= http
->error
)
1128 http
->error
= errno
;
1133 DEBUG_puts("httpWrite: error writing data...\n");
1141 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1142 http
->data_remaining
-= bytes
;
1145 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1146 if (httpPrintf(http
, "\r\n") < 0)
1149 if (http
->data_remaining
== 0 && http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1152 * Finished with the transfer; unless we are sending POST data, go idle...
1155 DEBUG_puts("httpWrite: changing states...");
1157 if (http
->state
== HTTP_POST_RECV
)
1160 http
->state
= HTTP_WAITING
;
1166 printf("httpWrite: wrote %d bytes: \n", tbytes
);
1167 for (i
= 0, buffer
-= tbytes
; i
< tbytes
; i
+= 16)
1171 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
1172 printf(" %02X", buffer
[i
+ j
] & 255);
1181 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
1183 ch
= buffer
[i
+ j
] & 255;
1185 if (ch
< ' ' || ch
== 127)
1199 * 'httpGets()' - Get a line of text from a HTTP connection.
1202 char * /* O - Line or NULL */
1203 httpGets(char *line
, /* I - Line to read into */
1204 int length
, /* I - Max length of buffer */
1205 http_t
*http
) /* I - HTTP data */
1207 char *lineptr
, /* Pointer into line */
1208 *bufptr
, /* Pointer into input buffer */
1209 *bufend
; /* Pointer to end of buffer */
1210 int bytes
; /* Number of bytes read */
1213 DEBUG_printf(("httpGets(%p, %d, %p)\n", line
, length
, http
));
1215 if (http
== NULL
|| line
== NULL
)
1219 * Pre-scan the buffer and see if there is a newline in there...
1230 bufptr
= http
->buffer
;
1231 bufend
= http
->buffer
+ http
->used
;
1233 while (bufptr
< bufend
)
1234 if (*bufptr
== 0x0a)
1239 if (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
)
1242 * No newline; see if there is more data to be read...
1247 bytes
= SSL_read((SSL
*)(http
->tls
), bufend
,
1248 HTTP_MAX_BUFFER
- http
->used
);
1250 #endif /* HAVE_LIBSSL */
1251 bytes
= recv(http
->fd
, bufend
, HTTP_MAX_BUFFER
- http
->used
, 0);
1256 * Nope, can't get a line this time...
1260 if (WSAGetLastError() != http
->error
)
1262 http
->error
= WSAGetLastError();
1266 DEBUG_printf(("httpGets(): recv() error %d!\n", WSAGetLastError()));
1270 else if (errno
!= http
->error
)
1272 http
->error
= errno
;
1276 DEBUG_printf(("httpGets(): recv() error %d!\n", errno
));
1281 else if (bytes
== 0)
1284 http
->error
= EPIPE
;
1290 * Yup, update the amount used and the end pointer...
1293 http
->used
+= bytes
;
1298 while (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
);
1300 http
->activity
= time(NULL
);
1303 * Read a line from the buffer...
1307 bufptr
= http
->buffer
;
1311 while (bufptr
< bufend
&& bytes
< length
)
1315 if (*bufptr
== 0x0a)
1320 else if (*bufptr
== 0x0d)
1323 *lineptr
++ = *bufptr
++;
1330 http
->used
-= bytes
;
1332 memmove(http
->buffer
, bufptr
, http
->used
);
1334 DEBUG_printf(("httpGets(): Returning \"%s\"\n", line
));
1338 DEBUG_puts("httpGets(): No new line available!");
1345 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1348 int /* O - Number of bytes written */
1349 httpPrintf(http_t
*http
, /* I - HTTP data */
1350 const char *format
, /* I - printf-style format string */
1351 ...) /* I - Additional args as needed */
1353 int bytes
, /* Number of bytes to write */
1354 nbytes
, /* Number of bytes written */
1355 tbytes
; /* Number of bytes all together */
1356 char buf
[HTTP_MAX_BUFFER
], /* Buffer for formatted string */
1357 *bufptr
; /* Pointer into buffer */
1358 va_list ap
; /* Variable argument pointer */
1361 va_start(ap
, format
);
1362 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1365 DEBUG_printf(("httpPrintf: %s", buf
));
1367 for (tbytes
= 0, bufptr
= buf
; tbytes
< bytes
; tbytes
+= nbytes
, bufptr
+= nbytes
)
1371 nbytes
= SSL_write((SSL
*)(http
->tls
), bufptr
, bytes
- tbytes
);
1373 #endif /* HAVE_LIBSSL */
1374 nbytes
= send(http
->fd
, bufptr
, bytes
- tbytes
, 0);
1381 if (WSAGetLastError() != http
->error
)
1383 http
->error
= WSAGetLastError();
1389 else if (errno
!= http
->error
)
1391 http
->error
= errno
;
1405 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
1408 const char * /* O - Date/time string */
1409 httpGetDateString(time_t t
) /* I - UNIX time */
1412 static char datetime
[256];
1416 snprintf(datetime
, sizeof(datetime
), "%s, %02d %s %d %02d:%02d:%02d GMT",
1417 days
[tdate
->tm_wday
], tdate
->tm_mday
, months
[tdate
->tm_mon
],
1418 tdate
->tm_year
+ 1900, tdate
->tm_hour
, tdate
->tm_min
, tdate
->tm_sec
);
1425 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
1428 time_t /* O - UNIX time */
1429 httpGetDateTime(const char *s
) /* I - Date/time string */
1431 int i
; /* Looping var */
1432 struct tm tdate
; /* Time/date structure */
1433 char mon
[16]; /* Abbreviated month name */
1434 int day
, year
; /* Day of month and year */
1435 int hour
, min
, sec
; /* Time */
1438 if (sscanf(s
, "%*s%d%15s%d%d:%d:%d", &day
, mon
, &year
, &hour
, &min
, &sec
) < 6)
1441 for (i
= 0; i
< 12; i
++)
1442 if (strcasecmp(mon
, months
[i
]) == 0)
1449 tdate
.tm_mday
= day
;
1450 tdate
.tm_year
= year
- 1900;
1451 tdate
.tm_hour
= hour
;
1456 return (mktime(&tdate
));
1461 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1464 http_status_t
/* O - HTTP status */
1465 httpUpdate(http_t
*http
) /* I - HTTP data */
1467 char line
[1024], /* Line from connection... */
1468 *value
; /* Pointer to value on line */
1469 http_field_t field
; /* Field index */
1470 int major
, minor
; /* HTTP version numbers */
1471 http_status_t status
; /* Authorization status */
1473 SSL_CTX
*context
; /* Context for encryption */
1474 SSL
*conn
; /* Connection for encryption */
1475 #endif /* HAVE_LIBSSL */
1478 DEBUG_printf(("httpUpdate(%p)\n", http
));
1481 * If we haven't issued any commands, then there is nothing to "update"...
1484 if (http
->state
== HTTP_WAITING
)
1485 return (HTTP_CONTINUE
);
1488 * Grab all of the lines we can from the connection...
1491 while (httpGets(line
, sizeof(line
), http
) != NULL
)
1495 if (line
[0] == '\0')
1498 * Blank line means the start of the data section (if any). Return
1499 * the result code, too...
1501 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
1502 * Instead, we just return HTTP_CONTINUE to the caller and keep on
1506 if (http
->status
== HTTP_CONTINUE
)
1507 return (http
->status
);
1510 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
1512 context
= SSL_CTX_new(SSLv23_method());
1513 conn
= SSL_new(context
);
1515 SSL_set_fd(conn
, http
->fd
);
1516 if (SSL_connect(conn
) != 1)
1518 SSL_CTX_free(context
);
1522 http
->error
= WSAGetLastError();
1524 http
->error
= errno
;
1526 http
->status
= HTTP_ERROR
;
1529 closesocket(http
->fd
);
1534 return (HTTP_ERROR
);
1539 return (HTTP_CONTINUE
);
1541 #endif /* HAVE_LIBSSL */
1543 httpGetLength(http
);
1545 switch (http
->state
)
1549 case HTTP_POST_RECV
:
1555 http
->state
= HTTP_WAITING
;
1559 return (http
->status
);
1561 else if (strncmp(line
, "HTTP/", 5) == 0)
1564 * Got the beginning of a response...
1567 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, (int *)&status
) != 3)
1568 return (HTTP_ERROR
);
1570 http
->version
= (http_version_t
)(major
* 100 + minor
);
1571 http
->status
= status
;
1573 else if ((value
= strchr(line
, ':')) != NULL
)
1580 while (isspace(*value
))
1584 * Be tolerants of servers that send unknown attribute fields...
1587 if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
1589 DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line
));
1593 httpSetField(http
, field
, value
);
1597 http
->status
= HTTP_ERROR
;
1598 return (HTTP_ERROR
);
1603 * See if there was an error...
1608 http
->status
= HTTP_ERROR
;
1609 return (HTTP_ERROR
);
1613 * If we haven't already returned, then there is nothing new...
1616 return (HTTP_CONTINUE
);
1621 * 'httpDecode64()' - Base64-decode a string.
1624 char * /* O - Decoded string */
1625 httpDecode64(char *out
, /* I - String to write to */
1626 const char *in
) /* I - String to read from */
1628 int pos
, /* Bit position */
1629 base64
; /* Value of this character */
1630 char *outptr
; /* Output pointer */
1633 for (outptr
= out
, pos
= 0; *in
!= '\0'; in
++)
1636 * Decode this character into a number from 0 to 63...
1639 if (*in
>= 'A' && *in
<= 'Z')
1641 else if (*in
>= 'a' && *in
<= 'z')
1642 base64
= *in
- 'a' + 26;
1643 else if (*in
>= '0' && *in
<= '9')
1644 base64
= *in
- '0' + 52;
1645 else if (*in
== '+')
1647 else if (*in
== '/')
1649 else if (*in
== '=')
1655 * Store the result in the appropriate chars...
1661 *outptr
= base64
<< 2;
1665 *outptr
++ |= (base64
>> 4) & 3;
1666 *outptr
= (base64
<< 4) & 255;
1670 *outptr
++ |= (base64
>> 2) & 15;
1671 *outptr
= (base64
<< 6) & 255;
1675 *outptr
++ |= base64
;
1684 * Return the decoded string...
1692 * 'httpEncode64()' - Base64-encode a string.
1695 char * /* O - Encoded string */
1696 httpEncode64(char *out
, /* I - String to write to */
1697 const char *in
) /* I - String to read from */
1699 char *outptr
; /* Output pointer */
1700 static char base64
[] = /* Base64 characters... */
1702 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1703 "abcdefghijklmnopqrstuvwxyz"
1709 for (outptr
= out
; *in
!= '\0'; in
++)
1712 * Encode the up to 3 characters as 4 Base64 numbers...
1715 *outptr
++ = base64
[in
[0] >> 2];
1716 *outptr
++ = base64
[((in
[0] << 4) | (in
[1] >> 4)) & 63];
1725 *outptr
++ = base64
[((in
[0] << 2) | (in
[1] >> 6)) & 63];
1731 *outptr
++ = base64
[in
[0] & 63];
1738 * Return the encoded string...
1746 * 'httpGetLength()' - Get the amount of data remaining from the
1747 * content-length or transfer-encoding fields.
1750 int /* O - Content length */
1751 httpGetLength(http_t
*http
) /* I - HTTP data */
1753 DEBUG_printf(("httpGetLength(%p)\n", http
));
1755 if (strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked") == 0)
1757 DEBUG_puts("httpGetLength: chunked request!");
1759 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
1760 http
->data_remaining
= 0;
1764 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1767 * The following is a hack for HTTP servers that don't send a
1768 * content-length or transfer-encoding field...
1770 * If there is no content-length then the connection must close
1771 * after the transfer is complete...
1774 if (http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] == '\0')
1775 http
->data_remaining
= 2147483647;
1777 http
->data_remaining
= atoi(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
]);
1779 DEBUG_printf(("httpGetLength: content_length = %d\n", http
->data_remaining
));
1782 return (http
->data_remaining
);
1787 * 'http_field()' - Return the field index for a field name.
1790 static http_field_t
/* O - Field index */
1791 http_field(const char *name
) /* I - String name */
1793 int i
; /* Looping var */
1796 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
1797 if (strcasecmp(name
, http_fields
[i
]) == 0)
1798 return ((http_field_t
)i
);
1800 return (HTTP_FIELD_UNKNOWN
);
1805 * 'http_send()' - Send a request with all fields and the trailing blank line.
1808 static int /* O - 0 on success, non-zero on error */
1809 http_send(http_t
*http
, /* I - HTTP data */
1810 http_state_t request
, /* I - Request code */
1811 const char *uri
) /* I - URI */
1813 int i
; /* Looping var */
1814 char *ptr
, /* Pointer in buffer */
1815 buf
[1024]; /* Encoded URI buffer */
1816 static const char *codes
[] = /* Request code strings */
1832 static const char *hex
= "0123456789ABCDEF";
1836 if (http
== NULL
|| uri
== NULL
)
1840 * Encode the URI as needed...
1843 for (ptr
= buf
; *uri
!= '\0' && ptr
< (buf
+ sizeof(buf
) - 1); uri
++)
1844 if (*uri
<= ' ' || *uri
>= 127)
1846 if (ptr
< (buf
+ sizeof(buf
) - 1))
1848 if (ptr
< (buf
+ sizeof(buf
) - 1))
1849 *ptr
++ = hex
[(*uri
>> 4) & 15];
1850 if (ptr
< (buf
+ sizeof(buf
) - 1))
1851 *ptr
++ = hex
[*uri
& 15];
1859 * See if we had an error the last time around; if so, reconnect...
1862 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
1863 httpReconnect(http
);
1866 * Send the request header...
1869 http
->state
= request
;
1870 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
1873 http
->status
= HTTP_CONTINUE
;
1876 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
1878 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
1879 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
1881 #endif /* HAVE_LIBSSL */
1883 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
1885 http
->status
= HTTP_ERROR
;
1889 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
1890 if (http
->fields
[i
][0] != '\0')
1892 DEBUG_printf(("%s: %s\n", http_fields
[i
], http
->fields
[i
]));
1894 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], http
->fields
[i
]) < 1)
1896 http
->status
= HTTP_ERROR
;
1901 if (httpPrintf(http
, "\r\n") < 1)
1903 http
->status
= HTTP_ERROR
;
1907 httpClearFields(http
);
1915 * 'http_upgrade()' - Force upgrade to TLS encryption.
1918 static int /* O - Status of connection */
1919 http_upgrade(http_t
*http
) /* I - HTTP data */
1921 int ret
; /* Return value */
1922 http_t myhttp
; /* Local copy of HTTP data */
1925 DEBUG_printf(("http_upgrade(%p)\n", http
));
1928 * Copy the HTTP data to a local variable so we can do the OPTIONS
1929 * request without interfering with the existing request data...
1932 memcpy(&myhttp
, http
, sizeof(myhttp
));
1935 * Send an OPTIONS request to the server, requiring SSL or TLS
1936 * encryption on the link...
1939 httpClearFields(&myhttp
);
1940 httpSetField(&myhttp
, HTTP_FIELD_CONNECTION
, "upgrade");
1941 httpSetField(&myhttp
, HTTP_FIELD_UPGRADE
, "TLS/1.0, SSL/2.0, SSL/3.0");
1943 if ((ret
= httpOptions(&myhttp
, "*")) == 0)
1946 * Wait for the secure connection...
1949 while (httpUpdate(&myhttp
) == HTTP_CONTINUE
);
1955 * Copy the HTTP data back over, if any...
1958 http
->fd
= myhttp
.fd
;
1959 http
->error
= myhttp
.error
;
1960 http
->activity
= myhttp
.activity
;
1961 http
->status
= myhttp
.status
;
1962 http
->version
= myhttp
.version
;
1963 http
->keep_alive
= myhttp
.keep_alive
;
1964 http
->used
= myhttp
.used
;
1967 memcpy(http
->buffer
, myhttp
.buffer
, http
->used
);
1969 http
->auth_type
= myhttp
.auth_type
;
1970 http
->nonce_count
= myhttp
.nonce_count
;
1972 memcpy(http
->nonce
, myhttp
.nonce
, sizeof(http
->nonce
));
1974 http
->tls
= myhttp
.tls
;
1975 http
->encryption
= myhttp
.encryption
;
1978 * See if we actually went secure...
1984 * Server does not support HTTP upgrade...
1987 DEBUG_puts("Server does not support HTTP upgrade!");
1990 closesocket(http
->fd
);
2002 #endif /* HAVE_LIBSSL */
2006 * End of "$Id: http.c,v 1.105 2002/10/30 20:04:56 mike Exp $".