2 * "$Id: http.c,v 1.102 2002/09/05 21:12:00 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).
182 struct timeval curtime
; /* Current time in microseconds */
183 int i
; /* Looping var */
184 unsigned char data
[1024]; /* Seed data */
185 #endif /* HAVE_LIBSSL */
188 WSADATA winsockdata
; /* WinSock data */
189 static int initialized
= 0;/* Has WinSock been initialized? */
193 WSAStartup(MAKEWORD(1,1), &winsockdata
);
194 #elif defined(HAVE_SIGSET)
195 sigset(SIGPIPE
, SIG_IGN
);
196 #elif defined(HAVE_SIGACTION)
197 struct sigaction action
; /* POSIX sigaction data */
201 * Ignore SIGPIPE signals...
204 memset(&action
, 0, sizeof(action
));
205 action
.sa_handler
= SIG_IGN
;
206 sigaction(SIGPIPE
, &action
, NULL
);
208 signal(SIGPIPE
, SIG_IGN
);
212 SSL_load_error_strings();
216 * Using the current time is a dubious random seed, but on some systems
217 * it is the best we can do (on others, this seed isn't even used...)
220 gettimeofday(&curtime
, NULL
);
221 srand(curtime
.tv_sec
+ curtime
.tv_usec
);
223 for (i
= 0; i
< sizeof(data
); i
++)
224 data
[i
] = rand(); /* Yes, this is a poor source of random data... */
226 RAND_seed(&data
, sizeof(data
));
227 #endif /* HAVE_LIBSSL */
232 * 'httpCheck()' - Check to see if there is a pending response from the server.
235 int /* O - 0 = no data, 1 = data available */
236 httpCheck(http_t
*http
) /* I - HTTP connection */
238 fd_set input
; /* Input set for select() */
239 struct timeval timeout
; /* Timeout */
243 * First see if there is data in the buffer...
253 * Then try doing a select() to poll the socket...
257 FD_SET(http
->fd
, &input
);
262 return (select(http
->fd
+ 1, &input
, NULL
, NULL
, &timeout
) > 0);
267 * 'httpClose()' - Close an HTTP connection...
271 httpClose(http_t
*http
) /* I - Connection to close */
274 SSL_CTX
*context
; /* Context for encryption */
275 SSL
*conn
; /* Connection for encryption */
276 #endif /* HAVE_LIBSSL */
285 conn
= (SSL
*)(http
->tls
);
286 context
= SSL_get_SSL_CTX(conn
);
289 SSL_CTX_free(context
);
294 #endif /* HAVE_LIBSSL */
297 closesocket(http
->fd
);
307 * 'httpConnect()' - Connect to a HTTP server.
310 http_t
* /* O - New HTTP connection */
311 httpConnect(const char *host
, /* I - Host to connect to */
312 int port
) /* I - Port number */
314 http_encryption_t encrypt
;/* Type of encryption to use */
318 * Set the default encryption status...
322 encrypt
= HTTP_ENCRYPT_ALWAYS
;
324 encrypt
= HTTP_ENCRYPT_IF_REQUESTED
;
326 return (httpConnectEncrypt(host
, port
, encrypt
));
331 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
334 http_t
* /* O - New HTTP connection */
335 httpConnectEncrypt(const char *host
, /* I - Host to connect to */
336 int port
, /* I - Port number */
337 http_encryption_t encrypt
)
338 /* I - Type of encryption to use */
340 int i
; /* Looping var */
341 http_t
*http
; /* New HTTP connection */
342 struct hostent
*hostaddr
; /* Host address data */
354 if ((hostaddr
= httpGetHostByName(host
)) == NULL
)
357 * This hack to make users that don't have a localhost entry in
358 * their hosts file or DNS happy...
361 if (strcasecmp(host
, "localhost") != 0)
363 else if ((hostaddr
= httpGetHostByName("127.0.0.1")) == NULL
)
368 * Verify that it is an IPv4 address (IPv6 support will come in CUPS 1.2...)
371 if (hostaddr
->h_addrtype
!= AF_INET
|| hostaddr
->h_length
!= 4)
375 * Allocate memory for the structure...
378 http
= calloc(sizeof(http_t
), 1);
382 http
->version
= HTTP_1_1
;
384 http
->activity
= time(NULL
);
388 * Copy the hostname and port and then "reconnect"...
391 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
392 http
->hostaddr
.sin_family
= hostaddr
->h_addrtype
;
394 http
->hostaddr
.sin_port
= htons((u_short
)port
);
396 http
->hostaddr
.sin_port
= htons(port
);
400 * Set the encryption status...
403 if (port
== 443) /* Always use encryption for https */
404 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
406 http
->encryption
= encrypt
;
409 * Loop through the addresses we have until one of them connects...
412 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
414 for (i
= 0; hostaddr
->h_addr_list
[i
]; i
++)
417 * Load the address...
420 memcpy((char *)&(http
->hostaddr
.sin_addr
), hostaddr
->h_addr_list
[i
],
424 * Connect to the remote system...
427 if (!httpReconnect(http
))
432 * Could not connect to any known address - bail out!
441 * 'httpEncryption()' - Set the required encryption on the link.
444 int /* O - -1 on error, 0 on success */
445 httpEncryption(http_t
*http
, /* I - HTTP data */
446 http_encryption_t e
) /* I - New encryption preference */
452 http
->encryption
= e
;
454 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
455 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
456 return (httpReconnect(http
));
457 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
458 return (http_upgrade(http
));
462 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
466 #endif /* HAVE_LIBSSL */
471 * 'httpReconnect()' - Reconnect to a HTTP server...
474 int /* O - 0 on success, non-zero on failure */
475 httpReconnect(http_t
*http
) /* I - HTTP data */
477 int val
; /* Socket option value */
479 SSL_CTX
*context
; /* Context for encryption */
480 SSL
*conn
; /* Connection for encryption */
485 conn
= (SSL
*)(http
->tls
);
486 context
= SSL_get_SSL_CTX(conn
);
489 SSL_CTX_free(context
);
494 #endif /* HAVE_LIBSSL */
497 * Close any previously open socket...
502 closesocket(http
->fd
);
508 * Create the socket and set options to allow reuse.
511 if ((http
->fd
= socket(AF_INET
, SOCK_STREAM
, 0)) < 0)
514 http
->error
= WSAGetLastError();
518 http
->status
= HTTP_ERROR
;
523 fcntl(http
->fd
, F_SETFD
, FD_CLOEXEC
); /* Close this socket when starting *
524 * other processes... */
525 #endif /* FD_CLOEXEC */
528 setsockopt(http
->fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *)&val
, sizeof(val
));
532 setsockopt(http
->fd
, SOL_SOCKET
, SO_REUSEPORT
, &val
, sizeof(val
));
533 #endif /* SO_REUSEPORT */
536 * Using TCP_NODELAY improves responsiveness, especially on systems
537 * with a slow loopback interface... Since we write large buffers
538 * when sending print files and requests, there shouldn't be any
539 * performance penalty for this...
543 setsockopt(http
->fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
546 * Connect to the server...
549 if (connect(http
->fd
, (struct sockaddr
*)&(http
->hostaddr
),
550 sizeof(http
->hostaddr
)) < 0)
553 http
->error
= WSAGetLastError();
557 http
->status
= HTTP_ERROR
;
560 closesocket(http
->fd
);
571 http
->status
= HTTP_CONTINUE
;
574 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
577 * Always do encryption via SSL.
580 context
= SSL_CTX_new(SSLv23_method());
581 conn
= SSL_new(context
);
583 SSL_set_fd(conn
, http
->fd
);
584 if (SSL_connect(conn
) != 1)
586 SSL_CTX_free(context
);
590 http
->error
= WSAGetLastError();
594 http
->status
= HTTP_ERROR
;
597 closesocket(http
->fd
);
607 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
608 return (http_upgrade(http
));
609 #endif /* HAVE_LIBSSL */
616 * 'httpGetSubField()' - Get a sub-field value.
619 char * /* O - Value or NULL */
620 httpGetSubField(http_t
*http
, /* I - HTTP data */
621 http_field_t field
, /* I - Field index */
622 const char *name
, /* I - Name of sub-field */
623 char *value
) /* O - Value string */
625 const char *fptr
; /* Pointer into field */
626 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
627 *ptr
; /* Pointer into string buffer */
631 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
632 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
633 name
== NULL
|| value
== NULL
)
636 DEBUG_printf(("httpGetSubField(%p, %d, \"%s\", %p)\n",
637 http
, field
, name
, value
));
639 for (fptr
= http
->fields
[field
]; *fptr
;)
642 * Skip leading whitespace...
645 while (isspace(*fptr
))
655 * Get the sub-field name...
659 *fptr
&& *fptr
!= '=' && !isspace(*fptr
) && ptr
< (temp
+ sizeof(temp
) - 1);
664 DEBUG_printf(("name = \"%s\"\n", temp
));
667 * Skip trailing chars up to the '='...
670 while (isspace(*fptr
))
680 * Skip = and leading whitespace...
685 while (isspace(*fptr
))
691 * Read quoted string...
694 for (ptr
= value
, fptr
++;
695 *fptr
&& *fptr
!= '\"' && ptr
< (value
+ HTTP_MAX_VALUE
- 1);
700 while (*fptr
&& *fptr
!= '\"')
709 * Read unquoted string...
713 *fptr
&& !isspace(*fptr
) && *fptr
!= ',' && ptr
< (value
+ HTTP_MAX_VALUE
- 1);
718 while (*fptr
&& !isspace(*fptr
) && *fptr
!= ',')
722 DEBUG_printf(("value = \"%s\"\n", value
));
725 * See if this is the one...
728 if (strcmp(name
, temp
) == 0)
739 * 'httpSetField()' - Set the value of an HTTP header.
743 httpSetField(http_t
*http
, /* I - HTTP data */
744 http_field_t field
, /* I - Field index */
745 const char *value
) /* I - Value */
748 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
749 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
753 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
758 * 'httpDelete()' - Send a DELETE request to the server.
761 int /* O - Status of call (0 = success) */
762 httpDelete(http_t
*http
, /* I - HTTP data */
763 const char *uri
) /* I - URI to delete */
765 return (http_send(http
, HTTP_DELETE
, uri
));
770 * 'httpGet()' - Send a GET request to the server.
773 int /* O - Status of call (0 = success) */
774 httpGet(http_t
*http
, /* I - HTTP data */
775 const char *uri
) /* I - URI to get */
777 return (http_send(http
, HTTP_GET
, uri
));
782 * 'httpHead()' - Send a HEAD request to the server.
785 int /* O - Status of call (0 = success) */
786 httpHead(http_t
*http
, /* I - HTTP data */
787 const char *uri
) /* I - URI for head */
789 return (http_send(http
, HTTP_HEAD
, uri
));
794 * 'httpOptions()' - Send an OPTIONS request to the server.
797 int /* O - Status of call (0 = success) */
798 httpOptions(http_t
*http
, /* I - HTTP data */
799 const char *uri
) /* I - URI for options */
801 return (http_send(http
, HTTP_OPTIONS
, uri
));
806 * 'httpPost()' - Send a POST request to the server.
809 int /* O - Status of call (0 = success) */
810 httpPost(http_t
*http
, /* I - HTTP data */
811 const char *uri
) /* I - URI for post */
815 return (http_send(http
, HTTP_POST
, uri
));
820 * 'httpPut()' - Send a PUT request to the server.
823 int /* O - Status of call (0 = success) */
824 httpPut(http_t
*http
, /* I - HTTP data */
825 const char *uri
) /* I - URI to put */
829 return (http_send(http
, HTTP_PUT
, uri
));
834 * 'httpTrace()' - Send an TRACE request to the server.
837 int /* O - Status of call (0 = success) */
838 httpTrace(http_t
*http
, /* I - HTTP data */
839 const char *uri
) /* I - URI for trace */
841 return (http_send(http
, HTTP_TRACE
, uri
));
846 * 'httpFlush()' - Flush data from a HTTP connection.
850 httpFlush(http_t
*http
) /* I - HTTP data */
852 char buffer
[8192]; /* Junk buffer */
855 while (httpRead(http
, buffer
, sizeof(buffer
)) > 0);
860 * 'httpRead()' - Read data from a HTTP connection.
863 int /* O - Number of bytes read */
864 httpRead(http_t
*http
, /* I - HTTP data */
865 char *buffer
, /* I - Buffer for data */
866 int length
) /* I - Maximum number of bytes */
868 int bytes
; /* Bytes read */
869 char len
[32]; /* Length string */
872 DEBUG_printf(("httpRead(%p, %p, %d)\n", http
, buffer
, length
));
874 if (http
== NULL
|| buffer
== NULL
)
877 http
->activity
= time(NULL
);
882 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
883 http
->data_remaining
<= 0)
885 DEBUG_puts("httpRead: Getting chunk length...");
887 if (httpGets(len
, sizeof(len
), http
) == NULL
)
889 DEBUG_puts("httpRead: Could not get length!");
893 http
->data_remaining
= strtol(len
, NULL
, 16);
896 DEBUG_printf(("httpRead: data_remaining = %d\n", http
->data_remaining
));
898 if (http
->data_remaining
== 0)
901 * A zero-length chunk ends a transfer; unless we are reading POST
905 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
906 httpGets(len
, sizeof(len
), http
);
908 if (http
->state
== HTTP_POST_RECV
)
911 http
->state
= HTTP_WAITING
;
915 else if (length
> http
->data_remaining
)
916 length
= http
->data_remaining
;
918 if (http
->used
== 0 && length
<= 256)
921 * Buffer small reads for better performance...
924 if (http
->data_remaining
> sizeof(http
->buffer
))
925 bytes
= sizeof(http
->buffer
);
927 bytes
= http
->data_remaining
;
931 bytes
= SSL_read((SSL
*)(http
->tls
), http
->buffer
, bytes
);
933 #endif /* HAVE_LIBSSL */
935 DEBUG_printf(("httpRead: reading %d bytes from socket into buffer...\n",
938 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
940 DEBUG_printf(("httpRead: read %d bytes from socket into buffer...\n",
949 http
->error
= WSAGetLastError();
961 if (length
> http
->used
)
966 DEBUG_printf(("httpRead: grabbing %d bytes from input buffer...\n", bytes
));
968 memcpy(buffer
, http
->buffer
, length
);
969 http
->used
-= length
;
972 memcpy(http
->buffer
, http
->buffer
+ length
, http
->used
);
976 bytes
= SSL_read((SSL
*)(http
->tls
), buffer
, length
);
977 #endif /* HAVE_LIBSSL */
980 DEBUG_printf(("httpRead: reading %d bytes from socket...\n", length
));
981 bytes
= recv(http
->fd
, buffer
, length
, 0);
982 DEBUG_printf(("httpRead: read %d bytes from socket...\n", bytes
));
986 http
->data_remaining
-= bytes
;
989 http
->error
= WSAGetLastError();
994 if (http
->data_remaining
== 0)
996 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
997 httpGets(len
, sizeof(len
), http
);
999 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
1001 if (http
->state
== HTTP_POST_RECV
)
1004 http
->state
= HTTP_WAITING
;
1011 printf("httpRead: Read %d bytes:\n", bytes
);
1012 for (i
= 0; i
< bytes
; i
+= 16)
1016 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1017 printf(" %02X", buffer
[i
+ j
] & 255);
1026 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1028 ch
= buffer
[i
+ j
] & 255;
1030 if (ch
< ' ' || ch
== 127)
1045 * 'httpWrite()' - Write data to a HTTP connection.
1048 int /* O - Number of bytes written */
1049 httpWrite(http_t
*http
, /* I - HTTP data */
1050 const char *buffer
, /* I - Buffer for data */
1051 int length
) /* I - Number of bytes to write */
1053 int tbytes
, /* Total bytes sent */
1054 bytes
; /* Bytes sent */
1057 if (http
== NULL
|| buffer
== NULL
)
1060 http
->activity
= time(NULL
);
1062 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1064 if (httpPrintf(http
, "%x\r\n", length
) < 0)
1070 * A zero-length chunk ends a transfer; unless we are sending POST
1074 DEBUG_puts("httpWrite: changing states...");
1076 if (http
->state
== HTTP_POST_RECV
)
1078 else if (http
->state
== HTTP_PUT_RECV
)
1079 http
->state
= HTTP_STATUS
;
1081 http
->state
= HTTP_WAITING
;
1083 if (httpPrintf(http
, "\r\n") < 0)
1096 bytes
= SSL_write((SSL
*)(http
->tls
), buffer
, length
);
1098 #endif /* HAVE_LIBSSL */
1099 bytes
= send(http
->fd
, buffer
, length
, 0);
1103 DEBUG_puts("httpWrite: error writing data...\n");
1111 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1112 http
->data_remaining
-= bytes
;
1115 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1116 if (httpPrintf(http
, "\r\n") < 0)
1119 if (http
->data_remaining
== 0 && http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1122 * Finished with the transfer; unless we are sending POST data, go idle...
1125 DEBUG_puts("httpWrite: changing states...");
1127 if (http
->state
== HTTP_POST_RECV
)
1130 http
->state
= HTTP_WAITING
;
1136 printf("httpWrite: wrote %d bytes: \n", tbytes
);
1137 for (i
= 0, buffer
-= tbytes
; i
< tbytes
; i
+= 16)
1141 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
1142 printf(" %02X", buffer
[i
+ j
] & 255);
1151 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
1153 ch
= buffer
[i
+ j
] & 255;
1155 if (ch
< ' ' || ch
== 127)
1169 * 'httpGets()' - Get a line of text from a HTTP connection.
1172 char * /* O - Line or NULL */
1173 httpGets(char *line
, /* I - Line to read into */
1174 int length
, /* I - Max length of buffer */
1175 http_t
*http
) /* I - HTTP data */
1177 char *lineptr
, /* Pointer into line */
1178 *bufptr
, /* Pointer into input buffer */
1179 *bufend
; /* Pointer to end of buffer */
1180 int bytes
; /* Number of bytes read */
1183 DEBUG_printf(("httpGets(%p, %d, %p)\n", line
, length
, http
));
1185 if (http
== NULL
|| line
== NULL
)
1189 * Pre-scan the buffer and see if there is a newline in there...
1200 bufptr
= http
->buffer
;
1201 bufend
= http
->buffer
+ http
->used
;
1203 while (bufptr
< bufend
)
1204 if (*bufptr
== 0x0a)
1209 if (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
)
1212 * No newline; see if there is more data to be read...
1217 bytes
= SSL_read((SSL
*)(http
->tls
), bufend
,
1218 HTTP_MAX_BUFFER
- http
->used
);
1220 #endif /* HAVE_LIBSSL */
1221 bytes
= recv(http
->fd
, bufend
, HTTP_MAX_BUFFER
- http
->used
, 0);
1226 * Nope, can't get a line this time...
1230 if (WSAGetLastError() != http
->error
)
1232 http
->error
= WSAGetLastError();
1236 DEBUG_printf(("httpGets(): recv() error %d!\n", WSAGetLastError()));
1238 if (errno
!= http
->error
)
1240 http
->error
= errno
;
1244 DEBUG_printf(("httpGets(): recv() error %d!\n", errno
));
1249 else if (bytes
== 0)
1252 http
->error
= EPIPE
;
1258 * Yup, update the amount used and the end pointer...
1261 http
->used
+= bytes
;
1265 while (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
);
1267 http
->activity
= time(NULL
);
1270 * Read a line from the buffer...
1274 bufptr
= http
->buffer
;
1278 while (bufptr
< bufend
&& bytes
< length
)
1282 if (*bufptr
== 0x0a)
1287 else if (*bufptr
== 0x0d)
1290 *lineptr
++ = *bufptr
++;
1297 http
->used
-= bytes
;
1299 memcpy(http
->buffer
, bufptr
, http
->used
);
1301 DEBUG_printf(("httpGets(): Returning \"%s\"\n", line
));
1305 DEBUG_puts("httpGets(): No new line available!");
1312 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1315 int /* O - Number of bytes written */
1316 httpPrintf(http_t
*http
, /* I - HTTP data */
1317 const char *format
, /* I - printf-style format string */
1318 ...) /* I - Additional args as needed */
1320 int bytes
, /* Number of bytes to write */
1321 nbytes
, /* Number of bytes written */
1322 tbytes
; /* Number of bytes all together */
1323 char buf
[HTTP_MAX_BUFFER
], /* Buffer for formatted string */
1324 *bufptr
; /* Pointer into buffer */
1325 va_list ap
; /* Variable argument pointer */
1328 va_start(ap
, format
);
1329 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1332 DEBUG_printf(("httpPrintf: %s", buf
));
1334 for (tbytes
= 0, bufptr
= buf
; tbytes
< bytes
; tbytes
+= nbytes
, bufptr
+= nbytes
)
1338 nbytes
= SSL_write((SSL
*)(http
->tls
), bufptr
, bytes
- tbytes
);
1340 #endif /* HAVE_LIBSSL */
1341 nbytes
= send(http
->fd
, bufptr
, bytes
- tbytes
, 0);
1352 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
1355 const char * /* O - Date/time string */
1356 httpGetDateString(time_t t
) /* I - UNIX time */
1359 static char datetime
[256];
1363 snprintf(datetime
, sizeof(datetime
), "%s, %02d %s %d %02d:%02d:%02d GMT",
1364 days
[tdate
->tm_wday
], tdate
->tm_mday
, months
[tdate
->tm_mon
],
1365 tdate
->tm_year
+ 1900, tdate
->tm_hour
, tdate
->tm_min
, tdate
->tm_sec
);
1372 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
1375 time_t /* O - UNIX time */
1376 httpGetDateTime(const char *s
) /* I - Date/time string */
1378 int i
; /* Looping var */
1379 struct tm tdate
; /* Time/date structure */
1380 char mon
[16]; /* Abbreviated month name */
1381 int day
, year
; /* Day of month and year */
1382 int hour
, min
, sec
; /* Time */
1385 if (sscanf(s
, "%*s%d%15s%d%d:%d:%d", &day
, mon
, &year
, &hour
, &min
, &sec
) < 6)
1388 for (i
= 0; i
< 12; i
++)
1389 if (strcasecmp(mon
, months
[i
]) == 0)
1396 tdate
.tm_mday
= day
;
1397 tdate
.tm_year
= year
- 1900;
1398 tdate
.tm_hour
= hour
;
1403 return (mktime(&tdate
));
1408 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1411 http_status_t
/* O - HTTP status */
1412 httpUpdate(http_t
*http
) /* I - HTTP data */
1414 char line
[1024], /* Line from connection... */
1415 *value
; /* Pointer to value on line */
1416 http_field_t field
; /* Field index */
1417 int major
, minor
; /* HTTP version numbers */
1418 http_status_t status
; /* Authorization status */
1420 SSL_CTX
*context
; /* Context for encryption */
1421 SSL
*conn
; /* Connection for encryption */
1422 #endif /* HAVE_LIBSSL */
1425 DEBUG_printf(("httpUpdate(%p)\n", http
));
1428 * If we haven't issued any commands, then there is nothing to "update"...
1431 if (http
->state
== HTTP_WAITING
)
1432 return (HTTP_CONTINUE
);
1435 * Grab all of the lines we can from the connection...
1438 while (httpGets(line
, sizeof(line
), http
) != NULL
)
1442 if (line
[0] == '\0')
1445 * Blank line means the start of the data section (if any). Return
1446 * the result code, too...
1448 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
1449 * Instead, we just return HTTP_CONTINUE to the caller and keep on
1453 if (http
->status
== HTTP_CONTINUE
)
1454 return (http
->status
);
1457 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
1459 context
= SSL_CTX_new(SSLv23_method());
1460 conn
= SSL_new(context
);
1462 SSL_set_fd(conn
, http
->fd
);
1463 if (SSL_connect(conn
) != 1)
1465 SSL_CTX_free(context
);
1469 http
->error
= WSAGetLastError();
1471 http
->error
= errno
;
1473 http
->status
= HTTP_ERROR
;
1476 closesocket(http
->fd
);
1481 return (HTTP_ERROR
);
1486 return (HTTP_CONTINUE
);
1488 #endif /* HAVE_LIBSSL */
1490 httpGetLength(http
);
1492 switch (http
->state
)
1496 case HTTP_POST_RECV
:
1502 http
->state
= HTTP_WAITING
;
1506 return (http
->status
);
1508 else if (strncmp(line
, "HTTP/", 5) == 0)
1511 * Got the beginning of a response...
1514 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, (int *)&status
) != 3)
1515 return (HTTP_ERROR
);
1517 http
->version
= (http_version_t
)(major
* 100 + minor
);
1518 http
->status
= status
;
1520 else if ((value
= strchr(line
, ':')) != NULL
)
1527 while (isspace(*value
))
1531 * Be tolerants of servers that send unknown attribute fields...
1534 if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
1536 DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line
));
1540 httpSetField(http
, field
, value
);
1544 http
->status
= HTTP_ERROR
;
1545 return (HTTP_ERROR
);
1550 * See if there was an error...
1555 http
->status
= HTTP_ERROR
;
1556 return (HTTP_ERROR
);
1560 * If we haven't already returned, then there is nothing new...
1563 return (HTTP_CONTINUE
);
1568 * 'httpDecode64()' - Base64-decode a string.
1571 char * /* O - Decoded string */
1572 httpDecode64(char *out
, /* I - String to write to */
1573 const char *in
) /* I - String to read from */
1575 int pos
, /* Bit position */
1576 base64
; /* Value of this character */
1577 char *outptr
; /* Output pointer */
1580 for (outptr
= out
, pos
= 0; *in
!= '\0'; in
++)
1583 * Decode this character into a number from 0 to 63...
1586 if (*in
>= 'A' && *in
<= 'Z')
1588 else if (*in
>= 'a' && *in
<= 'z')
1589 base64
= *in
- 'a' + 26;
1590 else if (*in
>= '0' && *in
<= '9')
1591 base64
= *in
- '0' + 52;
1592 else if (*in
== '+')
1594 else if (*in
== '/')
1596 else if (*in
== '=')
1602 * Store the result in the appropriate chars...
1608 *outptr
= base64
<< 2;
1612 *outptr
++ |= (base64
>> 4) & 3;
1613 *outptr
= (base64
<< 4) & 255;
1617 *outptr
++ |= (base64
>> 2) & 15;
1618 *outptr
= (base64
<< 6) & 255;
1622 *outptr
++ |= base64
;
1631 * Return the decoded string...
1639 * 'httpEncode64()' - Base64-encode a string.
1642 char * /* O - Encoded string */
1643 httpEncode64(char *out
, /* I - String to write to */
1644 const char *in
) /* I - String to read from */
1646 char *outptr
; /* Output pointer */
1647 static char base64
[] = /* Base64 characters... */
1649 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1650 "abcdefghijklmnopqrstuvwxyz"
1656 for (outptr
= out
; *in
!= '\0'; in
++)
1659 * Encode the up to 3 characters as 4 Base64 numbers...
1662 *outptr
++ = base64
[in
[0] >> 2];
1663 *outptr
++ = base64
[((in
[0] << 4) | (in
[1] >> 4)) & 63];
1672 *outptr
++ = base64
[((in
[0] << 2) | (in
[1] >> 6)) & 63];
1678 *outptr
++ = base64
[in
[0] & 63];
1685 * Return the encoded string...
1693 * 'httpGetLength()' - Get the amount of data remaining from the
1694 * content-length or transfer-encoding fields.
1697 int /* O - Content length */
1698 httpGetLength(http_t
*http
) /* I - HTTP data */
1700 DEBUG_printf(("httpGetLength(%p)\n", http
));
1702 if (strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked") == 0)
1704 DEBUG_puts("httpGetLength: chunked request!");
1706 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
1707 http
->data_remaining
= 0;
1711 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1714 * The following is a hack for HTTP servers that don't send a
1715 * content-length or transfer-encoding field...
1717 * If there is no content-length then the connection must close
1718 * after the transfer is complete...
1721 if (http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] == '\0')
1722 http
->data_remaining
= 2147483647;
1724 http
->data_remaining
= atoi(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
]);
1726 DEBUG_printf(("httpGetLength: content_length = %d\n", http
->data_remaining
));
1729 return (http
->data_remaining
);
1734 * 'http_field()' - Return the field index for a field name.
1737 static http_field_t
/* O - Field index */
1738 http_field(const char *name
) /* I - String name */
1740 int i
; /* Looping var */
1743 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
1744 if (strcasecmp(name
, http_fields
[i
]) == 0)
1745 return ((http_field_t
)i
);
1747 return (HTTP_FIELD_UNKNOWN
);
1752 * 'http_send()' - Send a request with all fields and the trailing blank line.
1755 static int /* O - 0 on success, non-zero on error */
1756 http_send(http_t
*http
, /* I - HTTP data */
1757 http_state_t request
, /* I - Request code */
1758 const char *uri
) /* I - URI */
1760 int i
; /* Looping var */
1761 char *ptr
, /* Pointer in buffer */
1762 buf
[1024]; /* Encoded URI buffer */
1763 static const char *codes
[] = /* Request code strings */
1779 static const char *hex
= "0123456789ABCDEF";
1783 if (http
== NULL
|| uri
== NULL
)
1787 * Encode the URI as needed...
1790 for (ptr
= buf
; *uri
!= '\0' && ptr
< (buf
+ sizeof(buf
) - 1); uri
++)
1791 if (*uri
<= ' ' || *uri
>= 127)
1793 if (ptr
< (buf
+ sizeof(buf
) - 1))
1795 if (ptr
< (buf
+ sizeof(buf
) - 1))
1796 *ptr
++ = hex
[(*uri
>> 4) & 15];
1797 if (ptr
< (buf
+ sizeof(buf
) - 1))
1798 *ptr
++ = hex
[*uri
& 15];
1806 * See if we had an error the last time around; if so, reconnect...
1809 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
1810 httpReconnect(http
);
1813 * Send the request header...
1816 http
->state
= request
;
1817 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
1820 http
->status
= HTTP_CONTINUE
;
1823 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
1825 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
1826 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
1828 #endif /* HAVE_LIBSSL */
1830 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
1832 http
->status
= HTTP_ERROR
;
1836 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
1837 if (http
->fields
[i
][0] != '\0')
1839 DEBUG_printf(("%s: %s\n", http_fields
[i
], http
->fields
[i
]));
1841 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], http
->fields
[i
]) < 1)
1843 http
->status
= HTTP_ERROR
;
1848 if (httpPrintf(http
, "\r\n") < 1)
1850 http
->status
= HTTP_ERROR
;
1854 httpClearFields(http
);
1862 * 'http_upgrade()' - Force upgrade to TLS encryption.
1865 static int /* O - Status of connection */
1866 http_upgrade(http_t
*http
) /* I - HTTP data */
1868 int ret
; /* Return value */
1869 http_t myhttp
; /* Local copy of HTTP data */
1872 DEBUG_printf(("http_upgrade(%p)\n", http
));
1875 * Copy the HTTP data to a local variable so we can do the OPTIONS
1876 * request without interfering with the existing request data...
1879 memcpy(&myhttp
, http
, sizeof(myhttp
));
1882 * Send an OPTIONS request to the server, requiring SSL or TLS
1883 * encryption on the link...
1886 httpClearFields(&myhttp
);
1887 httpSetField(&myhttp
, HTTP_FIELD_CONNECTION
, "upgrade");
1888 httpSetField(&myhttp
, HTTP_FIELD_UPGRADE
, "TLS/1.0, SSL/2.0, SSL/3.0");
1890 if ((ret
= httpOptions(&myhttp
, "*")) == 0)
1893 * Wait for the secure connection...
1896 while (httpUpdate(&myhttp
) == HTTP_CONTINUE
);
1902 * Copy the HTTP data back over, if any...
1905 http
->fd
= myhttp
.fd
;
1906 http
->error
= myhttp
.error
;
1907 http
->activity
= myhttp
.activity
;
1908 http
->status
= myhttp
.status
;
1909 http
->version
= myhttp
.version
;
1910 http
->keep_alive
= myhttp
.keep_alive
;
1911 http
->used
= myhttp
.used
;
1914 memcpy(http
->buffer
, myhttp
.buffer
, http
->used
);
1916 http
->auth_type
= myhttp
.auth_type
;
1917 http
->nonce_count
= myhttp
.nonce_count
;
1919 memcpy(http
->nonce
, myhttp
.nonce
, sizeof(http
->nonce
));
1921 http
->tls
= myhttp
.tls
;
1922 http
->encryption
= myhttp
.encryption
;
1925 * See if we actually went secure...
1931 * Server does not support HTTP upgrade...
1934 DEBUG_puts("Server does not support HTTP upgrade!");
1937 closesocket(http
->fd
);
1949 #endif /* HAVE_LIBSSL */
1953 * End of "$Id: http.c,v 1.102 2002/09/05 21:12:00 mike Exp $".