2 * "$Id: http.c,v 1.73 2000/12/20 13:41:13 mike Exp $"
4 * HTTP routines for the Common UNIX Printing System (CUPS) scheduler.
6 * Copyright 1997-2000 by Easy Software Products, all rights reserved.
8 * These coded instructions, statements, and computer programs are the
9 * property of Easy Software Products and are protected by Federal
10 * copyright law. Distribution and use rights are outlined in the file
11 * "LICENSE.txt" which should have been included with this file. If this
12 * file is missing or damaged please contact Easy Software Products
15 * Attn: CUPS Licensing Information
16 * Easy Software Products
17 * 44141 Airport View Drive, Suite 204
18 * Hollywood, Maryland 20636-3111 USA
20 * Voice: (301) 373-9603
21 * EMail: cups-info@cups.org
22 * WWW: http://www.cups.org
26 * httpInitialize() - Initialize the HTTP interface library and set the
27 * default HTTP proxy (if any).
28 * httpCheck() - Check to see if there is a pending response from
30 * httpClose() - Close an HTTP connection...
31 * httpConnect() - Connect to a HTTP server.
32 * httpEncryption() - Set the required encryption on the link.
33 * httpReconnect() - Reconnect to a HTTP server...
34 * httpSeparate() - Separate a Universal Resource Identifier into its
36 * httpSetField() - Set the value of an HTTP header.
37 * httpDelete() - Send a DELETE request to the server.
38 * httpGet() - Send a GET request to the server.
39 * httpHead() - Send a HEAD request to the server.
40 * httpOptions() - Send an OPTIONS request to the server.
41 * httpPost() - Send a POST request to the server.
42 * httpPut() - Send a PUT request to the server.
43 * httpTrace() - Send an TRACE request to the server.
44 * httpFlush() - Flush data from a HTTP connection.
45 * httpRead() - Read data from a HTTP connection.
46 * httpWrite() - Write data to a HTTP connection.
47 * httpGets() - Get a line of text from a HTTP connection.
48 * httpPrintf() - Print a formatted string to a HTTP connection.
49 * httpStatus() - Return a short string describing a HTTP status code.
50 * httpGetDateString() - Get a formatted date/time string from a time value.
51 * httpGetDateTime() - Get a time value from a formatted date/time string.
52 * httpUpdate() - Update the current HTTP state for incoming data.
53 * httpDecode64() - Base64-decode a string.
54 * httpEncode64() - Base64-encode a string.
55 * httpGetLength() - Get the amount of data remaining from the
56 * content-length or transfer-encoding fields.
57 * http_field() - Return the field index for a field name.
58 * http_send() - Send a request with all fields and the trailing
60 * http_upgrade() - Force upgrade to TLS encryption.
64 * Include necessary headers...
79 #if !defined(WIN32) && !defined(__EMX__)
81 #endif /* !WIN32 && !__EMX__ */
84 # include <openssl/rand.h>
85 # include <openssl/ssl.h>
86 #endif /* HAVE_LIBSSL */
90 * Some operating systems have done away with the Fxxxx constants for
91 * the fcntl() call; this works around that "feature"...
95 # define FNONBLK O_NONBLOCK
103 static http_field_t
http_field(const char *name
);
104 static int http_send(http_t
*http
, http_state_t request
,
106 static int http_upgrade(http_t
*http
);
113 static const char *http_fields
[] =
130 "If-Unmodified-since",
143 static const char *days
[7] =
153 static const char *months
[12] =
171 * 'httpInitialize()' - Initialize the HTTP interface library and set the
172 * default HTTP proxy (if any).
179 # if defined(WIN32) || defined(__EMX__)
181 struct timeval curtime
; /* Current time in microseconds */
182 # endif /* WIN32 || __EMX__ */
183 #endif /* HAVE_LIBSSL */
185 #if defined(WIN32) || defined(__EMX__)
186 WSADATA winsockdata
; /* WinSock data */
187 static int initialized
= 0;/* Has WinSock been initialized? */
191 WSAStartup(MAKEWORD(1,1), &winsockdata
);
192 #elif defined(HAVE_SIGSET)
193 sigset(SIGPIPE
, SIG_IGN
);
194 #elif defined(HAVE_SIGACTION)
195 struct sigaction action
; /* POSIX sigaction data */
199 * Ignore SIGPIPE signals...
202 memset(&action
, 0, sizeof(action
));
203 action
.sa_handler
= SIG_IGN
;
204 sigaction(SIGPIPE
, &action
, NULL
);
206 signal(SIGPIPE
, SIG_IGN
);
207 #endif /* WIN32 || __EMX__ */
213 * Using the current time is a dubious random seed, but on some systems
214 * it is the best we can do (on others, this seed isn't even used...)
217 # if defined(WIN32) || defined(__EMX__)
219 gettimeofday(&curtime
, NULL
);
220 RAND_seed(&curtime
, sizeof(curtime
));
221 # endif /* WIN32 || __EMX__ */
222 #endif /* HAVE_LIBSSL */
227 * 'httpCheck()' - Check to see if there is a pending response from the server.
230 int /* O - 0 = no data, 1 = data available */
231 httpCheck(http_t
*http
) /* I - HTTP connection */
233 fd_set input
; /* Input set for select() */
234 struct timeval timeout
; /* Timeout */
238 * First see if there is data in the buffer...
248 * Then try doing a select() to poll the socket...
252 FD_SET(http
->fd
, &input
);
257 return (select(http
->fd
+ 1, &input
, NULL
, NULL
, &timeout
) > 0);
262 * 'httpClose()' - Close an HTTP connection...
266 httpClose(http_t
*http
) /* I - Connection to close */
269 SSL_CTX
*context
; /* Context for encryption */
270 SSL
*conn
; /* Connection for encryption */
271 #endif /* HAVE_LIBSSL */
280 conn
= (SSL
*)(http
->tls
);
281 context
= SSL_get_SSL_CTX(conn
);
284 SSL_CTX_free(context
);
289 #endif /* HAVE_LIBSSL */
292 closesocket(http
->fd
);
302 * 'httpConnect()' - Connect to a HTTP server.
305 http_t
* /* O - New HTTP connection */
306 httpConnect(const char *host
, /* I - Host to connect to */
307 int port
) /* I - Port number */
309 http_t
*http
; /* New HTTP connection */
310 struct hostent
*hostaddr
; /* Host address data */
322 if ((hostaddr
= gethostbyname(host
)) == NULL
)
326 * Allocate memory for the structure...
329 http
= calloc(sizeof(http_t
), 1);
333 http
->version
= HTTP_1_1
;
335 http
->activity
= time(NULL
);
338 * Copy the hostname and port and then "reconnect"...
341 strncpy(http
->hostname
, host
, sizeof(http
->hostname
) - 1);
342 memcpy((char *)&(http
->hostaddr
.sin_addr
), hostaddr
->h_addr
, hostaddr
->h_length
);
343 http
->hostaddr
.sin_family
= hostaddr
->h_addrtype
;
345 http
->hostaddr
.sin_port
= htons((u_short
)port
);
347 http
->hostaddr
.sin_port
= htons(port
);
351 * Set the default encryption status...
355 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
358 * Connect to the remote system...
361 if (httpReconnect(http
))
372 * 'httpEncryption()' - Set the required encryption on the link.
375 int /* O - -1 on error, 0 on success */
376 httpEncryption(http_t
*http
, /* I - HTTP data */
377 http_encryption_t e
) /* I - New encryption preference */
383 http
->encryption
= e
;
385 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
386 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
387 return (httpReconnect(http
));
388 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
389 return (http_upgrade(http
));
393 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
397 #endif /* HAVE_LIBSSL */
402 * 'httpReconnect()' - Reconnect to a HTTP server...
405 int /* O - 0 on success, non-zero on failure */
406 httpReconnect(http_t
*http
) /* I - HTTP data */
408 int val
; /* Socket option value */
410 SSL_CTX
*context
; /* Context for encryption */
411 SSL
*conn
; /* Connection for encryption */
416 conn
= (SSL
*)(http
->tls
);
417 context
= SSL_get_SSL_CTX(conn
);
420 SSL_CTX_free(context
);
425 #endif /* HAVE_LIBSSL */
428 * Close any previously open socket...
433 closesocket(http
->fd
);
439 * Create the socket and set options to allow reuse.
442 if ((http
->fd
= socket(AF_INET
, SOCK_STREAM
, 0)) < 0)
444 #if defined(WIN32) || defined(__EMX__)
445 http
->error
= WSAGetLastError();
448 #endif /* WIN32 || __EMX__ */
449 http
->status
= HTTP_ERROR
;
454 fcntl(http
->fd
, F_SETFD
, FD_CLOEXEC
); /* Close this socket when starting *
455 * other processes... */
456 #endif /* FD_CLOEXEC */
459 setsockopt(http
->fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *)&val
, sizeof(val
));
463 setsockopt(http
->fd
, SOL_SOCKET
, SO_REUSEPORT
, &val
, sizeof(val
));
464 #endif /* SO_REUSEPORT */
467 * Connect to the server...
470 if (connect(http
->fd
, (struct sockaddr
*)&(http
->hostaddr
),
471 sizeof(http
->hostaddr
)) < 0)
473 #if defined(WIN32) || defined(__EMX__)
474 http
->error
= WSAGetLastError();
477 #endif /* WIN32 || __EMX__ */
478 http
->status
= HTTP_ERROR
;
481 closesocket(http
->fd
);
490 http
->status
= HTTP_CONTINUE
;
493 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
496 * Always do encryption via SSL.
499 context
= SSL_CTX_new(SSLv23_method());
500 conn
= SSL_new(context
);
502 SSL_set_fd(conn
, http
->fd
);
503 if (SSL_connect(conn
) != 1)
505 SSL_CTX_free(context
);
508 #if defined(WIN32) || defined(__EMX__)
509 http
->error
= WSAGetLastError();
512 #endif /* WIN32 || __EMX__ */
513 http
->status
= HTTP_ERROR
;
516 closesocket(http
->fd
);
526 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
527 return (http_upgrade(http
));
528 #endif /* HAVE_LIBSSL */
535 * 'httpSeparate()' - Separate a Universal Resource Identifier into its
540 httpSeparate(const char *uri
, /* I - Universal Resource Identifier */
541 char *method
, /* O - Method [32] (http, https, etc.) */
542 char *username
, /* O - Username [32] */
543 char *host
, /* O - Hostname [32] */
544 int *port
, /* O - Port number to use */
545 char *resource
) /* O - Resource/filename [1024] */
547 char *ptr
; /* Pointer into string... */
548 const char *atsign
, /* @ sign */
549 *slash
; /* Separator */
552 if (uri
== NULL
|| method
== NULL
|| username
== NULL
|| host
== NULL
||
553 port
== NULL
|| resource
== NULL
)
557 * Grab the method portion of the URI...
560 if (strncmp(uri
, "//", 2) == 0)
563 * Workaround for HP IPP client bug...
566 strcpy(method
, "ipp");
571 * Standard URI with method...
575 while (*uri
!= ':' && *uri
!= '\0')
583 * If the method contains a period or slash, then it's probably
584 * hostname/filename...
587 if (strchr(host
, '.') != NULL
|| strchr(host
, '/') != NULL
|| *uri
== '\0')
589 if ((ptr
= strchr(host
, '/')) != NULL
)
591 strncpy(resource
, ptr
, HTTP_MAX_URI
- 1);
592 resource
[HTTP_MAX_URI
- 1] = '\0';
601 * OK, we have "hostname:port[/resource]"...
604 *port
= strtol(uri
, (char **)&uri
, 10);
608 strncpy(resource
, uri
, HTTP_MAX_URI
- 1);
609 resource
[HTTP_MAX_URI
- 1] = '\0';
615 strcpy(method
, "http");
621 strncpy(method
, host
, 31);
627 * If the method starts with less than 2 slashes then it is a local resource...
630 if (strncmp(uri
, "//", 2) != 0)
632 strncpy(resource
, uri
, 1023);
633 resource
[1023] = '\0';
642 * Grab the usenname, if any...
648 if ((slash
= strchr(uri
, '/')) == NULL
)
649 slash
= uri
+ strlen(uri
);
651 if ((atsign
= strchr(uri
, '@')) != NULL
&& atsign
< slash
)
654 * Got a username:password combo...
658 uri
< atsign
&& ptr
< (username
+ sizeof(username
) - 1);
669 * Grab the hostname...
673 while (*uri
!= ':' && *uri
!= '/' && *uri
!= '\0')
680 if (strcasecmp(method
, "http") == 0)
682 else if (strcasecmp(method
, "https") == 0)
684 else if (strcasecmp(method
, "ipp") == 0)
686 else if (strcasecmp(method
, "socket") == 0) /* Not registered yet... */
694 * Parse port number...
699 while (isdigit(*uri
))
701 *port
= (*port
* 10) + *uri
- '0';
709 * Hostname but no port or path...
718 * The remaining portion is the resource string...
721 strncpy(resource
, uri
, HTTP_MAX_URI
- 1);
722 resource
[HTTP_MAX_URI
- 1] = '\0';
727 * 'httpGetSubField()' - Get a sub-field value.
730 char * /* O - Value or NULL */
731 httpGetSubField(http_t
*http
, /* I - HTTP data */
732 http_field_t field
, /* I - Field index */
733 const char *name
, /* I - Name of sub-field */
734 char *value
) /* O - Value string */
736 const char *fptr
; /* Pointer into field */
737 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
738 *ptr
; /* Pointer into string buffer */
742 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
743 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
744 name
== NULL
|| value
== NULL
)
747 for (fptr
= http
->fields
[field
]; *fptr
;)
750 * Skip leading whitespace...
753 while (isspace(*fptr
));
763 * Get the sub-field name...
767 *fptr
&& *fptr
!= '=' && !isspace(*fptr
) && ptr
< (temp
+ sizeof(temp
) - 1);
773 * Skip trailing chars up to the '='...
776 while (*fptr
&& *fptr
!= '=')
783 * Skip = and leading whitespace...
788 while (isspace(*fptr
));
794 * Read quoted string...
797 for (ptr
= value
, fptr
++;
798 *fptr
&& *fptr
!= '\"' && ptr
< (value
+ HTTP_MAX_VALUE
- 1);
803 while (*fptr
&& *fptr
!= '\"')
812 * Read unquoted string...
816 *fptr
&& !isspace(*fptr
) && *fptr
!= ',' && ptr
< (value
+ HTTP_MAX_VALUE
- 1);
821 while (*fptr
&& !isspace(*fptr
) && *fptr
!= ',')
826 * See if this is the one...
829 if (strcmp(name
, temp
) == 0)
840 * 'httpSetField()' - Set the value of an HTTP header.
844 httpSetField(http_t
*http
, /* I - HTTP data */
845 http_field_t field
, /* I - Field index */
846 const char *value
) /* I - Value */
849 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
850 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
854 strncpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
- 1);
855 http
->fields
[field
][HTTP_MAX_VALUE
- 1] = '\0';
860 * 'httpDelete()' - Send a DELETE request to the server.
863 int /* O - Status of call (0 = success) */
864 httpDelete(http_t
*http
, /* I - HTTP data */
865 const char *uri
) /* I - URI to delete */
867 return (http_send(http
, HTTP_DELETE
, uri
));
872 * 'httpGet()' - Send a GET request to the server.
875 int /* O - Status of call (0 = success) */
876 httpGet(http_t
*http
, /* I - HTTP data */
877 const char *uri
) /* I - URI to get */
879 return (http_send(http
, HTTP_GET
, uri
));
884 * 'httpHead()' - Send a HEAD request to the server.
887 int /* O - Status of call (0 = success) */
888 httpHead(http_t
*http
, /* I - HTTP data */
889 const char *uri
) /* I - URI for head */
891 return (http_send(http
, HTTP_HEAD
, uri
));
896 * 'httpOptions()' - Send an OPTIONS request to the server.
899 int /* O - Status of call (0 = success) */
900 httpOptions(http_t
*http
, /* I - HTTP data */
901 const char *uri
) /* I - URI for options */
903 return (http_send(http
, HTTP_OPTIONS
, uri
));
908 * 'httpPost()' - Send a POST request to the server.
911 int /* O - Status of call (0 = success) */
912 httpPost(http_t
*http
, /* I - HTTP data */
913 const char *uri
) /* I - URI for post */
917 return (http_send(http
, HTTP_POST
, uri
));
922 * 'httpPut()' - Send a PUT request to the server.
925 int /* O - Status of call (0 = success) */
926 httpPut(http_t
*http
, /* I - HTTP data */
927 const char *uri
) /* I - URI to put */
931 return (http_send(http
, HTTP_PUT
, uri
));
936 * 'httpTrace()' - Send an TRACE request to the server.
939 int /* O - Status of call (0 = success) */
940 httpTrace(http_t
*http
, /* I - HTTP data */
941 const char *uri
) /* I - URI for trace */
943 return (http_send(http
, HTTP_TRACE
, uri
));
948 * 'httpFlush()' - Flush data from a HTTP connection.
952 httpFlush(http_t
*http
) /* I - HTTP data */
954 char buffer
[8192]; /* Junk buffer */
957 while (httpRead(http
, buffer
, sizeof(buffer
)) > 0);
962 * 'httpRead()' - Read data from a HTTP connection.
965 int /* O - Number of bytes read */
966 httpRead(http_t
*http
, /* I - HTTP data */
967 char *buffer
, /* I - Buffer for data */
968 int length
) /* I - Maximum number of bytes */
970 int bytes
; /* Bytes read */
971 char len
[32]; /* Length string */
974 DEBUG_printf(("httpRead(%08x, %08x, %d)\n", http
, buffer
, length
));
976 if (http
== NULL
|| buffer
== NULL
)
979 http
->activity
= time(NULL
);
984 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
985 http
->data_remaining
<= 0)
987 DEBUG_puts("httpRead: Getting chunk length...");
989 if (httpGets(len
, sizeof(len
), http
) == NULL
)
991 DEBUG_puts("httpRead: Could not get length!");
995 http
->data_remaining
= strtol(len
, NULL
, 16);
998 DEBUG_printf(("httpRead: data_remaining = %d\n", http
->data_remaining
));
1000 if (http
->data_remaining
== 0)
1003 * A zero-length chunk ends a transfer; unless we are reading POST
1007 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1008 httpGets(len
, sizeof(len
), http
);
1010 if (http
->state
== HTTP_POST_RECV
)
1013 http
->state
= HTTP_WAITING
;
1017 else if (length
> http
->data_remaining
)
1018 length
= http
->data_remaining
;
1022 if (length
> http
->used
)
1023 length
= http
->used
;
1027 DEBUG_printf(("httpRead: grabbing %d bytes from input buffer...\n", bytes
));
1029 memcpy(buffer
, http
->buffer
, length
);
1030 http
->used
-= length
;
1033 memcpy(http
->buffer
, http
->buffer
+ length
, http
->used
);
1037 bytes
= SSL_read((SSL
*)(http
->tls
), buffer
, length
);
1038 #endif /* HAVE_LIBSSL */
1041 DEBUG_printf(("httpRead: reading %d bytes from socket...\n", length
));
1042 bytes
= recv(http
->fd
, buffer
, length
, 0);
1043 DEBUG_printf(("httpRead: read %d bytes from socket...\n", bytes
));
1047 http
->data_remaining
-= bytes
;
1049 #if defined(WIN32) || defined(__EMX__)
1050 http
->error
= WSAGetLastError();
1052 http
->error
= errno
;
1053 #endif /* WIN32 || __EMX__ */
1055 if (http
->data_remaining
== 0)
1057 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1058 httpGets(len
, sizeof(len
), http
);
1060 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
1062 if (http
->state
== HTTP_POST_RECV
)
1065 http
->state
= HTTP_WAITING
;
1074 * 'httpWrite()' - Write data to a HTTP connection.
1077 int /* O - Number of bytes written */
1078 httpWrite(http_t
*http
, /* I - HTTP data */
1079 const char *buffer
, /* I - Buffer for data */
1080 int length
) /* I - Number of bytes to write */
1082 int tbytes
, /* Total bytes sent */
1083 bytes
; /* Bytes sent */
1086 if (http
== NULL
|| buffer
== NULL
)
1089 http
->activity
= time(NULL
);
1091 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1093 if (httpPrintf(http
, "%x\r\n", length
) < 0)
1099 * A zero-length chunk ends a transfer; unless we are sending POST
1103 DEBUG_puts("httpWrite: changing states...");
1105 if (http
->state
== HTTP_POST_RECV
)
1108 http
->state
= HTTP_WAITING
;
1110 if (httpPrintf(http
, "\r\n") < 0)
1123 bytes
= SSL_write((SSL
*)(http
->tls
), buffer
, length
);
1125 #endif /* HAVE_LIBSSL */
1126 bytes
= send(http
->fd
, buffer
, length
, 0);
1130 DEBUG_puts("httpWrite: error writing data...\n");
1138 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1139 http
->data_remaining
-= bytes
;
1142 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1143 if (httpPrintf(http
, "\r\n") < 0)
1146 if (http
->data_remaining
== 0 && http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1149 * Finished with the transfer; unless we are sending POST data, go idle...
1152 DEBUG_puts("httpWrite: changing states...");
1154 if (http
->state
== HTTP_POST_RECV
)
1157 http
->state
= HTTP_WAITING
;
1160 DEBUG_printf(("httpWrite: wrote %d bytes...\n", tbytes
));
1167 * 'httpGets()' - Get a line of text from a HTTP connection.
1170 char * /* O - Line or NULL */
1171 httpGets(char *line
, /* I - Line to read into */
1172 int length
, /* I - Max length of buffer */
1173 http_t
*http
) /* I - HTTP data */
1175 char *lineptr
, /* Pointer into line */
1176 *bufptr
, /* Pointer into input buffer */
1177 *bufend
; /* Pointer to end of buffer */
1178 int bytes
; /* Number of bytes read */
1181 DEBUG_printf(("httpGets(%08x, %d, %08x)\n", line
, length
, http
));
1183 if (http
== NULL
|| line
== NULL
)
1187 * Pre-scan the buffer and see if there is a newline in there...
1190 #if defined(WIN32) || defined(__EMX__)
1194 #endif /* WIN32 || __EMX__ */
1198 bufptr
= http
->buffer
;
1199 bufend
= http
->buffer
+ http
->used
;
1201 while (bufptr
< bufend
)
1202 if (*bufptr
== 0x0a)
1207 if (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
)
1210 * No newline; see if there is more data to be read...
1215 bytes
= SSL_read((SSL
*)(http
->tls
), bufend
,
1216 HTTP_MAX_BUFFER
- http
->used
);
1218 #endif /* HAVE_LIBSSL */
1219 bytes
= recv(http
->fd
, bufend
, HTTP_MAX_BUFFER
- http
->used
, 0);
1224 * Nope, can't get a line this time...
1227 #if defined(WIN32) || defined(__EMX__)
1228 if (WSAGetLastError() != http
->error
)
1230 http
->error
= WSAGetLastError();
1234 DEBUG_printf(("httpGets(): recv() error %d!\n", WSAGetLastError()));
1236 if (errno
!= http
->error
)
1238 http
->error
= errno
;
1242 DEBUG_printf(("httpGets(): recv() error %d!\n", errno
));
1243 #endif /* WIN32 || __EMX__ */
1247 else if (bytes
== 0)
1250 http
->error
= EPIPE
;
1256 * Yup, update the amount used and the end pointer...
1259 http
->used
+= bytes
;
1263 while (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
);
1265 http
->activity
= time(NULL
);
1268 * Read a line from the buffer...
1272 bufptr
= http
->buffer
;
1275 while (bufptr
< bufend
&& bytes
< length
)
1279 if (*bufptr
== 0x0a)
1284 http
->used
-= bytes
;
1286 memcpy(http
->buffer
, bufptr
, http
->used
);
1288 DEBUG_printf(("httpGets(): Returning \"%s\"\n", line
));
1291 else if (*bufptr
== 0x0d)
1294 *lineptr
++ = *bufptr
++;
1297 DEBUG_puts("httpGets(): No new line available!");
1304 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1307 int /* O - Number of bytes written */
1308 httpPrintf(http_t
*http
, /* I - HTTP data */
1309 const char *format
, /* I - printf-style format string */
1310 ...) /* I - Additional args as needed */
1312 int bytes
, /* Number of bytes to write */
1313 nbytes
, /* Number of bytes written */
1314 tbytes
; /* Number of bytes all together */
1315 char buf
[HTTP_MAX_BUFFER
], /* Buffer for formatted string */
1316 *bufptr
; /* Pointer into buffer */
1317 va_list ap
; /* Variable argument pointer */
1320 va_start(ap
, format
);
1321 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1324 DEBUG_printf(("httpPrintf: %s", buf
));
1326 for (tbytes
= 0, bufptr
= buf
; tbytes
< bytes
; tbytes
+= nbytes
, bufptr
+= nbytes
)
1330 nbytes
= SSL_write((SSL
*)(http
->tls
), bufptr
, bytes
- tbytes
);
1332 #endif /* HAVE_LIBSSL */
1333 nbytes
= send(http
->fd
, bufptr
, bytes
- tbytes
, 0);
1344 * 'httpStatus()' - Return a short string describing a HTTP status code.
1347 const char * /* O - String or NULL */
1348 httpStatus(http_status_t status
) /* I - HTTP status code */
1352 case HTTP_CONTINUE
:
1353 return ("Continue");
1354 case HTTP_SWITCHING_PROTOCOLS
:
1355 return ("Switching Protocols");
1360 case HTTP_ACCEPTED
:
1361 return ("Accepted");
1362 case HTTP_NO_CONTENT
:
1363 return ("No Content");
1364 case HTTP_NOT_MODIFIED
:
1365 return ("Not Modified");
1366 case HTTP_BAD_REQUEST
:
1367 return ("Bad Request");
1368 case HTTP_UNAUTHORIZED
:
1369 return ("Unauthorized");
1370 case HTTP_FORBIDDEN
:
1371 return ("Forbidden");
1372 case HTTP_NOT_FOUND
:
1373 return ("Not Found");
1374 case HTTP_REQUEST_TOO_LARGE
:
1375 return ("Request Entity Too Large");
1376 case HTTP_URI_TOO_LONG
:
1377 return ("URI Too Long");
1378 case HTTP_UPGRADE_REQUIRED
:
1379 return ("Upgrade Required");
1380 case HTTP_NOT_IMPLEMENTED
:
1381 return ("Not Implemented");
1382 case HTTP_NOT_SUPPORTED
:
1383 return ("Not Supported");
1391 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
1394 const char * /* O - Date/time string */
1395 httpGetDateString(time_t t
) /* I - UNIX time */
1398 static char datetime
[256];
1402 snprintf(datetime
, sizeof(datetime
), "%s, %02d %s %d %02d:%02d:%02d GMT",
1403 days
[tdate
->tm_wday
], tdate
->tm_mday
, months
[tdate
->tm_mon
],
1404 tdate
->tm_year
+ 1900, tdate
->tm_hour
, tdate
->tm_min
, tdate
->tm_sec
);
1411 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
1414 time_t /* O - UNIX time */
1415 httpGetDateTime(const char *s
) /* I - Date/time string */
1417 int i
; /* Looping var */
1418 struct tm tdate
; /* Time/date structure */
1419 char mon
[16]; /* Abbreviated month name */
1420 int day
, year
; /* Day of month and year */
1421 int hour
, min
, sec
; /* Time */
1424 if (sscanf(s
, "%*s%d%15s%d%d:%d:%d", &day
, mon
, &year
, &hour
, &min
, &sec
) < 6)
1427 for (i
= 0; i
< 12; i
++)
1428 if (strcasecmp(mon
, months
[i
]) == 0)
1435 tdate
.tm_mday
= day
;
1436 tdate
.tm_year
= year
- 1900;
1437 tdate
.tm_hour
= hour
;
1442 return (mktime(&tdate
));
1447 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1450 http_status_t
/* O - HTTP status */
1451 httpUpdate(http_t
*http
) /* I - HTTP data */
1453 char line
[1024], /* Line from connection... */
1454 *value
; /* Pointer to value on line */
1455 http_field_t field
; /* Field index */
1456 int major
, minor
; /* HTTP version numbers */
1457 http_status_t status
; /* Authorization status */
1459 SSL_CTX
*context
; /* Context for encryption */
1460 SSL
*conn
; /* Connection for encryption */
1461 #endif /* HAVE_LIBSSL */
1464 DEBUG_printf(("httpUpdate(%08x)\n", http
));
1467 * If we haven't issued any commands, then there is nothing to "update"...
1470 if (http
->state
== HTTP_WAITING
)
1471 return (HTTP_CONTINUE
);
1474 * Grab all of the lines we can from the connection...
1477 while (httpGets(line
, sizeof(line
), http
) != NULL
)
1481 if (line
[0] == '\0')
1484 * Blank line means the start of the data section (if any). Return
1485 * the result code, too...
1487 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
1488 * Instead, we just return HTTP_CONTINUE to the caller and keep on
1492 if (http
->status
== HTTP_CONTINUE
)
1493 return (http
->status
);
1496 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
1498 context
= SSL_CTX_new(SSLv23_method());
1499 conn
= SSL_new(context
);
1501 SSL_set_fd(conn
, http
->fd
);
1502 if (SSL_connect(conn
) != 1)
1504 SSL_CTX_free(context
);
1507 #if defined(WIN32) || defined(__EMX__)
1508 http
->error
= WSAGetLastError();
1510 http
->error
= errno
;
1511 #endif /* WIN32 || __EMX__ */
1512 http
->status
= HTTP_ERROR
;
1515 closesocket(http
->fd
);
1520 return (HTTP_ERROR
);
1525 return (HTTP_CONTINUE
);
1527 else if (http
->status
== HTTP_UPGRADE_REQUIRED
&&
1528 http
->encryption
!= HTTP_ENCRYPT_NEVER
)
1529 http
->encryption
= HTTP_ENCRYPT_REQUIRED
;
1530 #endif /* HAVE_LIBSSL */
1532 httpGetLength(http
);
1534 switch (http
->state
)
1538 case HTTP_POST_RECV
:
1544 http
->state
= HTTP_WAITING
;
1548 return (http
->status
);
1550 else if (strncmp(line
, "HTTP/", 5) == 0)
1553 * Got the beginning of a response...
1556 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, (int *)&status
) != 3)
1557 return (HTTP_ERROR
);
1559 http
->version
= (http_version_t
)(major
* 100 + minor
);
1560 http
->status
= status
;
1562 else if ((value
= strchr(line
, ':')) != NULL
)
1569 while (isspace(*value
))
1573 * Be tolerants of servers that send unknown attribute fields...
1576 if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
1578 DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line
));
1582 httpSetField(http
, field
, value
);
1586 http
->status
= HTTP_ERROR
;
1587 return (HTTP_ERROR
);
1592 * See if there was an error...
1597 http
->status
= HTTP_ERROR
;
1598 return (HTTP_ERROR
);
1602 * If we haven't already returned, then there is nothing new...
1605 return (HTTP_CONTINUE
);
1610 * 'httpDecode64()' - Base64-decode a string.
1613 char * /* O - Decoded string */
1614 httpDecode64(char *out
, /* I - String to write to */
1615 const char *in
) /* I - String to read from */
1617 int pos
, /* Bit position */
1618 base64
; /* Value of this character */
1619 char *outptr
; /* Output pointer */
1622 for (outptr
= out
, pos
= 0; *in
!= '\0'; in
++)
1625 * Decode this character into a number from 0 to 63...
1628 if (*in
>= 'A' && *in
<= 'Z')
1630 else if (*in
>= 'a' && *in
<= 'z')
1631 base64
= *in
- 'a' + 26;
1632 else if (*in
>= '0' && *in
<= '9')
1633 base64
= *in
- '0' + 52;
1634 else if (*in
== '+')
1636 else if (*in
== '/')
1638 else if (*in
== '=')
1644 * Store the result in the appropriate chars...
1650 *outptr
= base64
<< 2;
1654 *outptr
++ |= (base64
>> 4) & 3;
1655 *outptr
= (base64
<< 4) & 255;
1659 *outptr
++ |= (base64
>> 2) & 15;
1660 *outptr
= (base64
<< 6) & 255;
1664 *outptr
++ |= base64
;
1673 * Return the decoded string...
1681 * 'httpEncode64()' - Base64-encode a string.
1684 char * /* O - Encoded string */
1685 httpEncode64(char *out
, /* I - String to write to */
1686 const char *in
) /* I - String to read from */
1688 char *outptr
; /* Output pointer */
1689 static char base64
[] = /* Base64 characters... */
1691 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1692 "abcdefghijklmnopqrstuvwxyz"
1698 for (outptr
= out
; *in
!= '\0'; in
++)
1701 * Encode the up to 3 characters as 4 Base64 numbers...
1704 *outptr
++ = base64
[in
[0] >> 2];
1705 *outptr
++ = base64
[((in
[0] << 4) | (in
[1] >> 4)) & 63];
1714 *outptr
++ = base64
[((in
[0] << 2) | (in
[1] >> 6)) & 63];
1720 *outptr
++ = base64
[in
[0] & 63];
1727 * Return the encoded string...
1735 * 'httpGetLength()' - Get the amount of data remaining from the
1736 * content-length or transfer-encoding fields.
1739 int /* O - Content length */
1740 httpGetLength(http_t
*http
) /* I - HTTP data */
1742 DEBUG_printf(("httpGetLength(%08x)\n", http
));
1744 if (strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked") == 0)
1746 DEBUG_puts("httpGetLength: chunked request!");
1748 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
1749 http
->data_remaining
= 0;
1753 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1756 * The following is a hack for HTTP servers that don't send a
1757 * content-length or transfer-encoding field...
1759 * If there is no content-length then the connection must close
1760 * after the transfer is complete...
1763 if (http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] == '\0')
1764 http
->data_remaining
= 2147483647;
1766 http
->data_remaining
= atoi(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
]);
1768 DEBUG_printf(("httpGetLength: content_length = %d\n", http
->data_remaining
));
1771 return (http
->data_remaining
);
1776 * 'http_field()' - Return the field index for a field name.
1779 static http_field_t
/* O - Field index */
1780 http_field(const char *name
) /* I - String name */
1782 int i
; /* Looping var */
1785 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
1786 if (strcasecmp(name
, http_fields
[i
]) == 0)
1787 return ((http_field_t
)i
);
1789 return (HTTP_FIELD_UNKNOWN
);
1794 * 'http_send()' - Send a request with all fields and the trailing blank line.
1797 static int /* O - 0 on success, non-zero on error */
1798 http_send(http_t
*http
, /* I - HTTP data */
1799 http_state_t request
, /* I - Request code */
1800 const char *uri
) /* I - URI */
1802 int i
; /* Looping var */
1803 char *ptr
, /* Pointer in buffer */
1804 buf
[1024]; /* Encoded URI buffer */
1805 static const char *codes
[] = /* Request code strings */
1821 static const char *hex
= "0123456789ABCDEF";
1825 if (http
== NULL
|| uri
== NULL
)
1829 * Encode the URI as needed...
1832 for (ptr
= buf
; *uri
!= '\0'; uri
++)
1833 if (*uri
<= ' ' || *uri
>= 127)
1836 *ptr
++ = hex
[(*uri
>> 4) & 15];
1837 *ptr
++ = hex
[*uri
& 15];
1845 * See if we had an error the last time around; if so, reconnect...
1848 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
1849 httpReconnect(http
);
1852 * Send the request header...
1855 http
->state
= request
;
1856 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
1859 http
->status
= HTTP_CONTINUE
;
1862 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
1864 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
1865 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
1867 #endif /* HAVE_LIBSSL */
1869 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
1871 http
->status
= HTTP_ERROR
;
1875 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
1876 if (http
->fields
[i
][0] != '\0')
1878 DEBUG_printf(("%s: %s\n", http_fields
[i
], http
->fields
[i
]));
1880 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], http
->fields
[i
]) < 1)
1882 http
->status
= HTTP_ERROR
;
1887 if (httpPrintf(http
, "\r\n") < 1)
1889 http
->status
= HTTP_ERROR
;
1893 httpClearFields(http
);
1901 * 'http_upgrade()' - Force upgrade to TLS encryption.
1904 static int /* O - Status of connection */
1905 http_upgrade(http_t
*http
) /* I - HTTP data */
1907 SSL_CTX
*context
; /* Context for encryption */
1908 SSL
*conn
; /* Connection for encryption */
1909 char buffer
[1024]; /* Status from server... */
1913 * Send an OPTIONS request to the server, requiring SSL or TLS
1914 * encryption on the link...
1917 if (httpPrintf(http
, "OPTIONS * HTTP/1.1\r\n") < 0)
1919 if (httpPrintf(http
, "Host: %s\r\n", http
->hostname
) < 0)
1921 if (httpPrintf(http
, "Connection: upgrade\r\n") < 0)
1923 if (httpPrintf(http
, "Upgrade: TLS/1.0, SSL/2.0, SSL/3.0\r\n") < 0)
1925 if (httpPrintf(http
, "\r\n") < 0)
1929 * Wait for the response data...
1932 while (httpGets(buffer
, sizeof(buffer
), http
) != NULL
)
1936 context
= SSL_CTX_new(SSLv23_method());
1937 conn
= SSL_new(context
);
1939 SSL_set_fd(conn
, http
->fd
);
1940 if (SSL_connect(conn
) != 1)
1942 SSL_CTX_free(context
);
1945 #if defined(WIN32) || defined(__EMX__)
1946 http
->error
= WSAGetLastError();
1948 http
->error
= errno
;
1949 #endif /* WIN32 || __EMX__ */
1950 http
->status
= HTTP_ERROR
;
1953 closesocket(http
->fd
);
1965 #endif /* HAVE_LIBSSL */
1969 * End of "$Id: http.c,v 1.73 2000/12/20 13:41:13 mike Exp $".