2 * "$Id: http.c,v 1.108 2002/12/17 18:56:42 swdev 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 * 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);
899 if (http
->data_remaining
< 0)
901 DEBUG_puts("httpRead: Negative chunk length!");
906 DEBUG_printf(("httpRead: data_remaining = %d\n", http
->data_remaining
));
908 if (http
->data_remaining
<= 0)
911 * A zero-length chunk ends a transfer; unless we are reading POST
915 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
916 httpGets(len
, sizeof(len
), http
);
918 if (http
->state
== HTTP_POST_RECV
)
921 http
->state
= HTTP_WAITING
;
925 else if (length
> http
->data_remaining
)
926 length
= http
->data_remaining
;
928 if (http
->used
== 0 && length
<= 256)
931 * Buffer small reads for better performance...
934 if (http
->data_remaining
> sizeof(http
->buffer
))
935 bytes
= sizeof(http
->buffer
);
937 bytes
= http
->data_remaining
;
941 bytes
= SSL_read((SSL
*)(http
->tls
), http
->buffer
, bytes
);
943 #endif /* HAVE_LIBSSL */
945 DEBUG_printf(("httpRead: reading %d bytes from socket into buffer...\n",
948 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
950 DEBUG_printf(("httpRead: read %d bytes from socket into buffer...\n",
959 http
->error
= WSAGetLastError();
975 if (length
> http
->used
)
980 DEBUG_printf(("httpRead: grabbing %d bytes from input buffer...\n", bytes
));
982 memcpy(buffer
, http
->buffer
, length
);
983 http
->used
-= length
;
986 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
990 bytes
= SSL_read((SSL
*)(http
->tls
), buffer
, length
);
991 #endif /* HAVE_LIBSSL */
994 DEBUG_printf(("httpRead: reading %d bytes from socket...\n", length
));
995 bytes
= recv(http
->fd
, buffer
, length
, 0);
996 DEBUG_printf(("httpRead: read %d bytes from socket...\n", bytes
));
1000 http
->data_remaining
-= bytes
;
1004 http
->error
= WSAGetLastError();
1009 http
->error
= errno
;
1013 if (http
->data_remaining
== 0)
1015 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1016 httpGets(len
, sizeof(len
), http
);
1018 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
1020 if (http
->state
== HTTP_POST_RECV
)
1023 http
->state
= HTTP_WAITING
;
1030 printf("httpRead: Read %d bytes:\n", bytes
);
1031 for (i
= 0; i
< bytes
; i
+= 16)
1035 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1036 printf(" %02X", buffer
[i
+ j
] & 255);
1045 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1047 ch
= buffer
[i
+ j
] & 255;
1049 if (ch
< ' ' || ch
== 127)
1064 * 'httpWrite()' - Write data to a HTTP connection.
1067 int /* O - Number of bytes written */
1068 httpWrite(http_t
*http
, /* I - HTTP data */
1069 const char *buffer
, /* I - Buffer for data */
1070 int length
) /* I - Number of bytes to write */
1072 int tbytes
, /* Total bytes sent */
1073 bytes
; /* Bytes sent */
1076 if (http
== NULL
|| buffer
== NULL
)
1079 http
->activity
= time(NULL
);
1081 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1083 if (httpPrintf(http
, "%x\r\n", length
) < 0)
1089 * A zero-length chunk ends a transfer; unless we are sending POST
1093 DEBUG_puts("httpWrite: changing states...");
1095 if (http
->state
== HTTP_POST_RECV
)
1097 else if (http
->state
== HTTP_PUT_RECV
)
1098 http
->state
= HTTP_STATUS
;
1100 http
->state
= HTTP_WAITING
;
1102 if (httpPrintf(http
, "\r\n") < 0)
1115 bytes
= SSL_write((SSL
*)(http
->tls
), buffer
, length
);
1117 #endif /* HAVE_LIBSSL */
1118 bytes
= send(http
->fd
, buffer
, length
, 0);
1123 if (WSAGetLastError() != http
->error
)
1125 http
->error
= WSAGetLastError();
1131 else if (errno
!= http
->error
)
1133 http
->error
= errno
;
1138 DEBUG_puts("httpWrite: error writing data...\n");
1146 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1147 http
->data_remaining
-= bytes
;
1150 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1151 if (httpPrintf(http
, "\r\n") < 0)
1154 if (http
->data_remaining
== 0 && http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1157 * Finished with the transfer; unless we are sending POST data, go idle...
1160 DEBUG_puts("httpWrite: changing states...");
1162 if (http
->state
== HTTP_POST_RECV
)
1165 http
->state
= HTTP_WAITING
;
1171 printf("httpWrite: wrote %d bytes: \n", tbytes
);
1172 for (i
= 0, buffer
-= tbytes
; i
< tbytes
; i
+= 16)
1176 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
1177 printf(" %02X", buffer
[i
+ j
] & 255);
1186 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
1188 ch
= buffer
[i
+ j
] & 255;
1190 if (ch
< ' ' || ch
== 127)
1204 * 'httpGets()' - Get a line of text from a HTTP connection.
1207 char * /* O - Line or NULL */
1208 httpGets(char *line
, /* I - Line to read into */
1209 int length
, /* I - Max length of buffer */
1210 http_t
*http
) /* I - HTTP data */
1212 char *lineptr
, /* Pointer into line */
1213 *bufptr
, /* Pointer into input buffer */
1214 *bufend
; /* Pointer to end of buffer */
1215 int bytes
; /* Number of bytes read */
1218 DEBUG_printf(("httpGets(%p, %d, %p)\n", line
, length
, http
));
1220 if (http
== NULL
|| line
== NULL
)
1224 * Pre-scan the buffer and see if there is a newline in there...
1235 bufptr
= http
->buffer
;
1236 bufend
= http
->buffer
+ http
->used
;
1238 while (bufptr
< bufend
)
1239 if (*bufptr
== 0x0a)
1244 if (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
)
1247 * No newline; see if there is more data to be read...
1252 bytes
= SSL_read((SSL
*)(http
->tls
), bufend
,
1253 HTTP_MAX_BUFFER
- http
->used
);
1255 #endif /* HAVE_LIBSSL */
1256 bytes
= recv(http
->fd
, bufend
, HTTP_MAX_BUFFER
- http
->used
, 0);
1261 * Nope, can't get a line this time...
1265 if (WSAGetLastError() != http
->error
)
1267 http
->error
= WSAGetLastError();
1271 DEBUG_printf(("httpGets(): recv() error %d!\n", WSAGetLastError()));
1275 else if (errno
!= http
->error
)
1277 http
->error
= errno
;
1281 DEBUG_printf(("httpGets(): recv() error %d!\n", errno
));
1286 else if (bytes
== 0)
1289 http
->error
= EPIPE
;
1295 * Yup, update the amount used and the end pointer...
1298 http
->used
+= bytes
;
1303 while (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
);
1305 http
->activity
= time(NULL
);
1308 * Read a line from the buffer...
1312 bufptr
= http
->buffer
;
1316 while (bufptr
< bufend
&& bytes
< length
)
1320 if (*bufptr
== 0x0a)
1325 else if (*bufptr
== 0x0d)
1328 *lineptr
++ = *bufptr
++;
1335 http
->used
-= bytes
;
1337 memmove(http
->buffer
, bufptr
, http
->used
);
1339 DEBUG_printf(("httpGets(): Returning \"%s\"\n", line
));
1343 DEBUG_puts("httpGets(): No new line available!");
1350 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1353 int /* O - Number of bytes written */
1354 httpPrintf(http_t
*http
, /* I - HTTP data */
1355 const char *format
, /* I - printf-style format string */
1356 ...) /* I - Additional args as needed */
1358 int bytes
, /* Number of bytes to write */
1359 nbytes
, /* Number of bytes written */
1360 tbytes
; /* Number of bytes all together */
1361 char buf
[HTTP_MAX_BUFFER
], /* Buffer for formatted string */
1362 *bufptr
; /* Pointer into buffer */
1363 va_list ap
; /* Variable argument pointer */
1366 va_start(ap
, format
);
1367 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1370 DEBUG_printf(("httpPrintf: %s", buf
));
1372 for (tbytes
= 0, bufptr
= buf
; tbytes
< bytes
; tbytes
+= nbytes
, bufptr
+= nbytes
)
1376 nbytes
= SSL_write((SSL
*)(http
->tls
), bufptr
, bytes
- tbytes
);
1378 #endif /* HAVE_LIBSSL */
1379 nbytes
= send(http
->fd
, bufptr
, bytes
- tbytes
, 0);
1386 if (WSAGetLastError() != http
->error
)
1388 http
->error
= WSAGetLastError();
1394 else if (errno
!= http
->error
)
1396 http
->error
= errno
;
1410 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
1413 const char * /* O - Date/time string */
1414 httpGetDateString(time_t t
) /* I - UNIX time */
1417 static char datetime
[256];
1421 snprintf(datetime
, sizeof(datetime
), "%s, %02d %s %d %02d:%02d:%02d GMT",
1422 days
[tdate
->tm_wday
], tdate
->tm_mday
, months
[tdate
->tm_mon
],
1423 tdate
->tm_year
+ 1900, tdate
->tm_hour
, tdate
->tm_min
, tdate
->tm_sec
);
1430 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
1433 time_t /* O - UNIX time */
1434 httpGetDateTime(const char *s
) /* I - Date/time string */
1436 int i
; /* Looping var */
1437 struct tm tdate
; /* Time/date structure */
1438 char mon
[16]; /* Abbreviated month name */
1439 int day
, year
; /* Day of month and year */
1440 int hour
, min
, sec
; /* Time */
1443 if (sscanf(s
, "%*s%d%15s%d%d:%d:%d", &day
, mon
, &year
, &hour
, &min
, &sec
) < 6)
1446 for (i
= 0; i
< 12; i
++)
1447 if (strcasecmp(mon
, months
[i
]) == 0)
1454 tdate
.tm_mday
= day
;
1455 tdate
.tm_year
= year
- 1900;
1456 tdate
.tm_hour
= hour
;
1461 return (mktime(&tdate
));
1466 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1469 http_status_t
/* O - HTTP status */
1470 httpUpdate(http_t
*http
) /* I - HTTP data */
1472 char line
[1024], /* Line from connection... */
1473 *value
; /* Pointer to value on line */
1474 http_field_t field
; /* Field index */
1475 int major
, minor
; /* HTTP version numbers */
1476 http_status_t status
; /* Authorization status */
1478 SSL_CTX
*context
; /* Context for encryption */
1479 SSL
*conn
; /* Connection for encryption */
1480 #endif /* HAVE_LIBSSL */
1483 DEBUG_printf(("httpUpdate(%p)\n", http
));
1486 * If we haven't issued any commands, then there is nothing to "update"...
1489 if (http
->state
== HTTP_WAITING
)
1490 return (HTTP_CONTINUE
);
1493 * Grab all of the lines we can from the connection...
1496 while (httpGets(line
, sizeof(line
), http
) != NULL
)
1500 if (line
[0] == '\0')
1503 * Blank line means the start of the data section (if any). Return
1504 * the result code, too...
1506 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
1507 * Instead, we just return HTTP_CONTINUE to the caller and keep on
1511 if (http
->status
== HTTP_CONTINUE
)
1512 return (http
->status
);
1515 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
1517 context
= SSL_CTX_new(SSLv23_method());
1518 conn
= SSL_new(context
);
1520 SSL_set_fd(conn
, http
->fd
);
1521 if (SSL_connect(conn
) != 1)
1523 SSL_CTX_free(context
);
1527 http
->error
= WSAGetLastError();
1529 http
->error
= errno
;
1531 http
->status
= HTTP_ERROR
;
1534 closesocket(http
->fd
);
1539 return (HTTP_ERROR
);
1544 return (HTTP_CONTINUE
);
1546 #endif /* HAVE_LIBSSL */
1548 httpGetLength(http
);
1550 switch (http
->state
)
1554 case HTTP_POST_RECV
:
1560 http
->state
= HTTP_WAITING
;
1564 return (http
->status
);
1566 else if (strncmp(line
, "HTTP/", 5) == 0)
1569 * Got the beginning of a response...
1572 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, (int *)&status
) != 3)
1573 return (HTTP_ERROR
);
1575 http
->version
= (http_version_t
)(major
* 100 + minor
);
1576 http
->status
= status
;
1578 else if ((value
= strchr(line
, ':')) != NULL
)
1585 while (isspace(*value
))
1589 * Be tolerants of servers that send unknown attribute fields...
1592 if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
1594 DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line
));
1598 httpSetField(http
, field
, value
);
1602 http
->status
= HTTP_ERROR
;
1603 return (HTTP_ERROR
);
1608 * See if there was an error...
1613 http
->status
= HTTP_ERROR
;
1614 return (HTTP_ERROR
);
1618 * If we haven't already returned, then there is nothing new...
1621 return (HTTP_CONTINUE
);
1626 * 'httpDecode64()' - Base64-decode a string.
1629 char * /* O - Decoded string */
1630 httpDecode64(char *out
, /* I - String to write to */
1631 const char *in
) /* I - String to read from */
1633 int pos
, /* Bit position */
1634 base64
; /* Value of this character */
1635 char *outptr
; /* Output pointer */
1638 for (outptr
= out
, pos
= 0; *in
!= '\0'; in
++)
1641 * Decode this character into a number from 0 to 63...
1644 if (*in
>= 'A' && *in
<= 'Z')
1646 else if (*in
>= 'a' && *in
<= 'z')
1647 base64
= *in
- 'a' + 26;
1648 else if (*in
>= '0' && *in
<= '9')
1649 base64
= *in
- '0' + 52;
1650 else if (*in
== '+')
1652 else if (*in
== '/')
1654 else if (*in
== '=')
1660 * Store the result in the appropriate chars...
1666 *outptr
= base64
<< 2;
1670 *outptr
++ |= (base64
>> 4) & 3;
1671 *outptr
= (base64
<< 4) & 255;
1675 *outptr
++ |= (base64
>> 2) & 15;
1676 *outptr
= (base64
<< 6) & 255;
1680 *outptr
++ |= base64
;
1689 * Return the decoded string...
1697 * 'httpEncode64()' - Base64-encode a string.
1700 char * /* O - Encoded string */
1701 httpEncode64(char *out
, /* I - String to write to */
1702 const char *in
) /* I - String to read from */
1704 char *outptr
; /* Output pointer */
1705 static char base64
[] = /* Base64 characters... */
1707 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1708 "abcdefghijklmnopqrstuvwxyz"
1714 for (outptr
= out
; *in
!= '\0'; in
++)
1717 * Encode the up to 3 characters as 4 Base64 numbers...
1720 *outptr
++ = base64
[in
[0] >> 2];
1721 *outptr
++ = base64
[((in
[0] << 4) | (in
[1] >> 4)) & 63];
1730 *outptr
++ = base64
[((in
[0] << 2) | (in
[1] >> 6)) & 63];
1736 *outptr
++ = base64
[in
[0] & 63];
1743 * Return the encoded string...
1751 * 'httpGetLength()' - Get the amount of data remaining from the
1752 * content-length or transfer-encoding fields.
1755 int /* O - Content length */
1756 httpGetLength(http_t
*http
) /* I - HTTP data */
1758 DEBUG_printf(("httpGetLength(%p)\n", http
));
1760 if (strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked") == 0)
1762 DEBUG_puts("httpGetLength: chunked request!");
1764 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
1765 http
->data_remaining
= 0;
1769 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1772 * The following is a hack for HTTP servers that don't send a
1773 * content-length or transfer-encoding field...
1775 * If there is no content-length then the connection must close
1776 * after the transfer is complete...
1779 if (http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] == '\0')
1780 http
->data_remaining
= 2147483647;
1782 http
->data_remaining
= atoi(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
]);
1784 DEBUG_printf(("httpGetLength: content_length = %d\n", http
->data_remaining
));
1787 return (http
->data_remaining
);
1792 * 'http_field()' - Return the field index for a field name.
1795 static http_field_t
/* O - Field index */
1796 http_field(const char *name
) /* I - String name */
1798 int i
; /* Looping var */
1801 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
1802 if (strcasecmp(name
, http_fields
[i
]) == 0)
1803 return ((http_field_t
)i
);
1805 return (HTTP_FIELD_UNKNOWN
);
1810 * 'http_send()' - Send a request with all fields and the trailing blank line.
1813 static int /* O - 0 on success, non-zero on error */
1814 http_send(http_t
*http
, /* I - HTTP data */
1815 http_state_t request
, /* I - Request code */
1816 const char *uri
) /* I - URI */
1818 int i
; /* Looping var */
1819 char *ptr
, /* Pointer in buffer */
1820 buf
[1024]; /* Encoded URI buffer */
1821 static const char *codes
[] = /* Request code strings */
1837 static const char *hex
= "0123456789ABCDEF";
1841 if (http
== NULL
|| uri
== NULL
)
1845 * Encode the URI as needed...
1848 for (ptr
= buf
; *uri
!= '\0' && ptr
< (buf
+ sizeof(buf
) - 1); uri
++)
1849 if (*uri
<= ' ' || *uri
>= 127)
1851 if (ptr
< (buf
+ sizeof(buf
) - 1))
1853 if (ptr
< (buf
+ sizeof(buf
) - 1))
1854 *ptr
++ = hex
[(*uri
>> 4) & 15];
1855 if (ptr
< (buf
+ sizeof(buf
) - 1))
1856 *ptr
++ = hex
[*uri
& 15];
1864 * See if we had an error the last time around; if so, reconnect...
1867 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
1868 httpReconnect(http
);
1871 * Send the request header...
1874 http
->state
= request
;
1875 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
1878 http
->status
= HTTP_CONTINUE
;
1881 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
1883 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
1884 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
1886 #endif /* HAVE_LIBSSL */
1888 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
1890 http
->status
= HTTP_ERROR
;
1894 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
1895 if (http
->fields
[i
][0] != '\0')
1897 DEBUG_printf(("%s: %s\n", http_fields
[i
], http
->fields
[i
]));
1899 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], http
->fields
[i
]) < 1)
1901 http
->status
= HTTP_ERROR
;
1906 if (httpPrintf(http
, "\r\n") < 1)
1908 http
->status
= HTTP_ERROR
;
1912 httpClearFields(http
);
1920 * 'http_upgrade()' - Force upgrade to TLS encryption.
1923 static int /* O - Status of connection */
1924 http_upgrade(http_t
*http
) /* I - HTTP data */
1926 int ret
; /* Return value */
1927 http_t myhttp
; /* Local copy of HTTP data */
1930 DEBUG_printf(("http_upgrade(%p)\n", http
));
1933 * Copy the HTTP data to a local variable so we can do the OPTIONS
1934 * request without interfering with the existing request data...
1937 memcpy(&myhttp
, http
, sizeof(myhttp
));
1940 * Send an OPTIONS request to the server, requiring SSL or TLS
1941 * encryption on the link...
1944 httpClearFields(&myhttp
);
1945 httpSetField(&myhttp
, HTTP_FIELD_CONNECTION
, "upgrade");
1946 httpSetField(&myhttp
, HTTP_FIELD_UPGRADE
, "TLS/1.0, SSL/2.0, SSL/3.0");
1948 if ((ret
= httpOptions(&myhttp
, "*")) == 0)
1951 * Wait for the secure connection...
1954 while (httpUpdate(&myhttp
) == HTTP_CONTINUE
);
1960 * Copy the HTTP data back over, if any...
1963 http
->fd
= myhttp
.fd
;
1964 http
->error
= myhttp
.error
;
1965 http
->activity
= myhttp
.activity
;
1966 http
->status
= myhttp
.status
;
1967 http
->version
= myhttp
.version
;
1968 http
->keep_alive
= myhttp
.keep_alive
;
1969 http
->used
= myhttp
.used
;
1972 memcpy(http
->buffer
, myhttp
.buffer
, http
->used
);
1974 http
->auth_type
= myhttp
.auth_type
;
1975 http
->nonce_count
= myhttp
.nonce_count
;
1977 memcpy(http
->nonce
, myhttp
.nonce
, sizeof(http
->nonce
));
1979 http
->tls
= myhttp
.tls
;
1980 http
->encryption
= myhttp
.encryption
;
1983 * See if we actually went secure...
1989 * Server does not support HTTP upgrade...
1992 DEBUG_puts("Server does not support HTTP upgrade!");
1995 closesocket(http
->fd
);
2007 #endif /* HAVE_LIBSSL */
2011 * End of "$Id: http.c,v 1.108 2002/12/17 18:56:42 swdev Exp $".