2 * "$Id: http.c,v 1.77 2001/02/07 01:25:39 mike Exp $"
4 * HTTP routines for the Common UNIX Printing System (CUPS) scheduler.
6 * Copyright 1997-2001 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/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 */
187 #if defined(WIN32) || defined(__EMX__)
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
);
209 #endif /* WIN32 || __EMX__ */
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_t
*http
; /* New HTTP connection */
315 struct hostent
*hostaddr
; /* Host address data */
327 if ((hostaddr
= gethostbyname(host
)) == NULL
)
331 * Allocate memory for the structure...
334 http
= calloc(sizeof(http_t
), 1);
338 http
->version
= HTTP_1_1
;
340 http
->activity
= time(NULL
);
343 * Copy the hostname and port and then "reconnect"...
346 strncpy(http
->hostname
, host
, sizeof(http
->hostname
) - 1);
347 memcpy((char *)&(http
->hostaddr
.sin_addr
), hostaddr
->h_addr
, hostaddr
->h_length
);
348 http
->hostaddr
.sin_family
= hostaddr
->h_addrtype
;
350 http
->hostaddr
.sin_port
= htons((u_short
)port
);
352 http
->hostaddr
.sin_port
= htons(port
);
356 * Set the default encryption status...
360 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
363 * Connect to the remote system...
366 if (httpReconnect(http
))
377 * 'httpEncryption()' - Set the required encryption on the link.
380 int /* O - -1 on error, 0 on success */
381 httpEncryption(http_t
*http
, /* I - HTTP data */
382 http_encryption_t e
) /* I - New encryption preference */
388 http
->encryption
= e
;
390 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
391 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
392 return (httpReconnect(http
));
393 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
394 return (http_upgrade(http
));
398 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
402 #endif /* HAVE_LIBSSL */
407 * 'httpReconnect()' - Reconnect to a HTTP server...
410 int /* O - 0 on success, non-zero on failure */
411 httpReconnect(http_t
*http
) /* I - HTTP data */
413 int val
; /* Socket option value */
415 SSL_CTX
*context
; /* Context for encryption */
416 SSL
*conn
; /* Connection for encryption */
421 conn
= (SSL
*)(http
->tls
);
422 context
= SSL_get_SSL_CTX(conn
);
425 SSL_CTX_free(context
);
430 #endif /* HAVE_LIBSSL */
433 * Close any previously open socket...
438 closesocket(http
->fd
);
444 * Create the socket and set options to allow reuse.
447 if ((http
->fd
= socket(AF_INET
, SOCK_STREAM
, 0)) < 0)
449 #if defined(WIN32) || defined(__EMX__)
450 http
->error
= WSAGetLastError();
453 #endif /* WIN32 || __EMX__ */
454 http
->status
= HTTP_ERROR
;
459 fcntl(http
->fd
, F_SETFD
, FD_CLOEXEC
); /* Close this socket when starting *
460 * other processes... */
461 #endif /* FD_CLOEXEC */
464 setsockopt(http
->fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *)&val
, sizeof(val
));
468 setsockopt(http
->fd
, SOL_SOCKET
, SO_REUSEPORT
, &val
, sizeof(val
));
469 #endif /* SO_REUSEPORT */
472 * Connect to the server...
475 if (connect(http
->fd
, (struct sockaddr
*)&(http
->hostaddr
),
476 sizeof(http
->hostaddr
)) < 0)
478 #if defined(WIN32) || defined(__EMX__)
479 http
->error
= WSAGetLastError();
482 #endif /* WIN32 || __EMX__ */
483 http
->status
= HTTP_ERROR
;
486 closesocket(http
->fd
);
495 http
->status
= HTTP_CONTINUE
;
498 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
501 * Always do encryption via SSL.
504 context
= SSL_CTX_new(SSLv23_method());
505 conn
= SSL_new(context
);
507 SSL_set_fd(conn
, http
->fd
);
508 if (SSL_connect(conn
) != 1)
510 SSL_CTX_free(context
);
513 #if defined(WIN32) || defined(__EMX__)
514 http
->error
= WSAGetLastError();
517 #endif /* WIN32 || __EMX__ */
518 http
->status
= HTTP_ERROR
;
521 closesocket(http
->fd
);
531 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
532 return (http_upgrade(http
));
533 #endif /* HAVE_LIBSSL */
540 * 'httpSeparate()' - Separate a Universal Resource Identifier into its
545 httpSeparate(const char *uri
, /* I - Universal Resource Identifier */
546 char *method
, /* O - Method [32] (http, https, etc.) */
547 char *username
, /* O - Username [32] */
548 char *host
, /* O - Hostname [32] */
549 int *port
, /* O - Port number to use */
550 char *resource
) /* O - Resource/filename [1024] */
552 char *ptr
; /* Pointer into string... */
553 const char *atsign
, /* @ sign */
554 *slash
; /* Separator */
557 if (uri
== NULL
|| method
== NULL
|| username
== NULL
|| host
== NULL
||
558 port
== NULL
|| resource
== NULL
)
562 * Grab the method portion of the URI...
565 if (strncmp(uri
, "//", 2) == 0)
568 * Workaround for HP IPP client bug...
571 strcpy(method
, "ipp");
576 * Standard URI with method...
580 while (*uri
!= ':' && *uri
!= '\0')
588 * If the method contains a period or slash, then it's probably
589 * hostname/filename...
592 if (strchr(host
, '.') != NULL
|| strchr(host
, '/') != NULL
|| *uri
== '\0')
594 if ((ptr
= strchr(host
, '/')) != NULL
)
596 strncpy(resource
, ptr
, HTTP_MAX_URI
- 1);
597 resource
[HTTP_MAX_URI
- 1] = '\0';
606 * OK, we have "hostname:port[/resource]"...
609 *port
= strtol(uri
, (char **)&uri
, 10);
613 strncpy(resource
, uri
, HTTP_MAX_URI
- 1);
614 resource
[HTTP_MAX_URI
- 1] = '\0';
620 strcpy(method
, "http");
626 strncpy(method
, host
, 31);
632 * If the method starts with less than 2 slashes then it is a local resource...
635 if (strncmp(uri
, "//", 2) != 0)
637 strncpy(resource
, uri
, 1023);
638 resource
[1023] = '\0';
647 * Grab the usenname, if any...
653 if ((slash
= strchr(uri
, '/')) == NULL
)
654 slash
= uri
+ strlen(uri
);
656 if ((atsign
= strchr(uri
, '@')) != NULL
&& atsign
< slash
)
659 * Got a username:password combo...
663 uri
< atsign
&& ptr
< (username
+ sizeof(username
) - 1);
674 * Grab the hostname...
678 while (*uri
!= ':' && *uri
!= '/' && *uri
!= '\0')
685 if (strcasecmp(method
, "http") == 0)
687 else if (strcasecmp(method
, "https") == 0)
689 else if (strcasecmp(method
, "ipp") == 0)
691 else if (strcasecmp(method
, "socket") == 0) /* Not registered yet... */
699 * Parse port number...
704 while (isdigit(*uri
))
706 *port
= (*port
* 10) + *uri
- '0';
714 * Hostname but no port or path...
723 * The remaining portion is the resource string...
726 strncpy(resource
, uri
, HTTP_MAX_URI
- 1);
727 resource
[HTTP_MAX_URI
- 1] = '\0';
732 * 'httpGetSubField()' - Get a sub-field value.
735 char * /* O - Value or NULL */
736 httpGetSubField(http_t
*http
, /* I - HTTP data */
737 http_field_t field
, /* I - Field index */
738 const char *name
, /* I - Name of sub-field */
739 char *value
) /* O - Value string */
741 const char *fptr
; /* Pointer into field */
742 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
743 *ptr
; /* Pointer into string buffer */
747 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
748 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
749 name
== NULL
|| value
== NULL
)
752 for (fptr
= http
->fields
[field
]; *fptr
;)
755 * Skip leading whitespace...
758 while (isspace(*fptr
));
768 * Get the sub-field name...
772 *fptr
&& *fptr
!= '=' && !isspace(*fptr
) && ptr
< (temp
+ sizeof(temp
) - 1);
778 * Skip trailing chars up to the '='...
781 while (*fptr
&& *fptr
!= '=')
788 * Skip = and leading whitespace...
793 while (isspace(*fptr
));
799 * Read quoted string...
802 for (ptr
= value
, fptr
++;
803 *fptr
&& *fptr
!= '\"' && ptr
< (value
+ HTTP_MAX_VALUE
- 1);
808 while (*fptr
&& *fptr
!= '\"')
817 * Read unquoted string...
821 *fptr
&& !isspace(*fptr
) && *fptr
!= ',' && ptr
< (value
+ HTTP_MAX_VALUE
- 1);
826 while (*fptr
&& !isspace(*fptr
) && *fptr
!= ',')
831 * See if this is the one...
834 if (strcmp(name
, temp
) == 0)
845 * 'httpSetField()' - Set the value of an HTTP header.
849 httpSetField(http_t
*http
, /* I - HTTP data */
850 http_field_t field
, /* I - Field index */
851 const char *value
) /* I - Value */
854 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
855 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
859 strncpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
- 1);
860 http
->fields
[field
][HTTP_MAX_VALUE
- 1] = '\0';
865 * 'httpDelete()' - Send a DELETE request to the server.
868 int /* O - Status of call (0 = success) */
869 httpDelete(http_t
*http
, /* I - HTTP data */
870 const char *uri
) /* I - URI to delete */
872 return (http_send(http
, HTTP_DELETE
, uri
));
877 * 'httpGet()' - Send a GET request to the server.
880 int /* O - Status of call (0 = success) */
881 httpGet(http_t
*http
, /* I - HTTP data */
882 const char *uri
) /* I - URI to get */
884 return (http_send(http
, HTTP_GET
, uri
));
889 * 'httpHead()' - Send a HEAD request to the server.
892 int /* O - Status of call (0 = success) */
893 httpHead(http_t
*http
, /* I - HTTP data */
894 const char *uri
) /* I - URI for head */
896 return (http_send(http
, HTTP_HEAD
, uri
));
901 * 'httpOptions()' - Send an OPTIONS request to the server.
904 int /* O - Status of call (0 = success) */
905 httpOptions(http_t
*http
, /* I - HTTP data */
906 const char *uri
) /* I - URI for options */
908 return (http_send(http
, HTTP_OPTIONS
, uri
));
913 * 'httpPost()' - Send a POST request to the server.
916 int /* O - Status of call (0 = success) */
917 httpPost(http_t
*http
, /* I - HTTP data */
918 const char *uri
) /* I - URI for post */
922 return (http_send(http
, HTTP_POST
, uri
));
927 * 'httpPut()' - Send a PUT request to the server.
930 int /* O - Status of call (0 = success) */
931 httpPut(http_t
*http
, /* I - HTTP data */
932 const char *uri
) /* I - URI to put */
936 return (http_send(http
, HTTP_PUT
, uri
));
941 * 'httpTrace()' - Send an TRACE request to the server.
944 int /* O - Status of call (0 = success) */
945 httpTrace(http_t
*http
, /* I - HTTP data */
946 const char *uri
) /* I - URI for trace */
948 return (http_send(http
, HTTP_TRACE
, uri
));
953 * 'httpFlush()' - Flush data from a HTTP connection.
957 httpFlush(http_t
*http
) /* I - HTTP data */
959 char buffer
[8192]; /* Junk buffer */
962 while (httpRead(http
, buffer
, sizeof(buffer
)) > 0);
967 * 'httpRead()' - Read data from a HTTP connection.
970 int /* O - Number of bytes read */
971 httpRead(http_t
*http
, /* I - HTTP data */
972 char *buffer
, /* I - Buffer for data */
973 int length
) /* I - Maximum number of bytes */
975 int bytes
; /* Bytes read */
976 char len
[32]; /* Length string */
979 DEBUG_printf(("httpRead(%08x, %08x, %d)\n", http
, buffer
, length
));
981 if (http
== NULL
|| buffer
== NULL
)
984 http
->activity
= time(NULL
);
989 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
990 http
->data_remaining
<= 0)
992 DEBUG_puts("httpRead: Getting chunk length...");
994 if (httpGets(len
, sizeof(len
), http
) == NULL
)
996 DEBUG_puts("httpRead: Could not get length!");
1000 http
->data_remaining
= strtol(len
, NULL
, 16);
1003 DEBUG_printf(("httpRead: data_remaining = %d\n", http
->data_remaining
));
1005 if (http
->data_remaining
== 0)
1008 * A zero-length chunk ends a transfer; unless we are reading POST
1012 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1013 httpGets(len
, sizeof(len
), http
);
1015 if (http
->state
== HTTP_POST_RECV
)
1018 http
->state
= HTTP_WAITING
;
1022 else if (length
> http
->data_remaining
)
1023 length
= http
->data_remaining
;
1027 if (length
> http
->used
)
1028 length
= http
->used
;
1032 DEBUG_printf(("httpRead: grabbing %d bytes from input buffer...\n", bytes
));
1034 memcpy(buffer
, http
->buffer
, length
);
1035 http
->used
-= length
;
1038 memcpy(http
->buffer
, http
->buffer
+ length
, http
->used
);
1042 bytes
= SSL_read((SSL
*)(http
->tls
), buffer
, length
);
1043 #endif /* HAVE_LIBSSL */
1046 DEBUG_printf(("httpRead: reading %d bytes from socket...\n", length
));
1047 bytes
= recv(http
->fd
, buffer
, length
, 0);
1048 DEBUG_printf(("httpRead: read %d bytes from socket...\n", bytes
));
1052 http
->data_remaining
-= bytes
;
1054 #if defined(WIN32) || defined(__EMX__)
1055 http
->error
= WSAGetLastError();
1057 http
->error
= errno
;
1058 #endif /* WIN32 || __EMX__ */
1060 if (http
->data_remaining
== 0)
1062 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1063 httpGets(len
, sizeof(len
), http
);
1065 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
1067 if (http
->state
== HTTP_POST_RECV
)
1070 http
->state
= HTTP_WAITING
;
1079 * 'httpWrite()' - Write data to a HTTP connection.
1082 int /* O - Number of bytes written */
1083 httpWrite(http_t
*http
, /* I - HTTP data */
1084 const char *buffer
, /* I - Buffer for data */
1085 int length
) /* I - Number of bytes to write */
1087 int tbytes
, /* Total bytes sent */
1088 bytes
; /* Bytes sent */
1091 if (http
== NULL
|| buffer
== NULL
)
1094 http
->activity
= time(NULL
);
1096 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1098 if (httpPrintf(http
, "%x\r\n", length
) < 0)
1104 * A zero-length chunk ends a transfer; unless we are sending POST
1108 DEBUG_puts("httpWrite: changing states...");
1110 if (http
->state
== HTTP_POST_RECV
)
1113 http
->state
= HTTP_WAITING
;
1115 if (httpPrintf(http
, "\r\n") < 0)
1128 bytes
= SSL_write((SSL
*)(http
->tls
), buffer
, length
);
1130 #endif /* HAVE_LIBSSL */
1131 bytes
= send(http
->fd
, buffer
, length
, 0);
1135 DEBUG_puts("httpWrite: error writing data...\n");
1143 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1144 http
->data_remaining
-= bytes
;
1147 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1148 if (httpPrintf(http
, "\r\n") < 0)
1151 if (http
->data_remaining
== 0 && http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1154 * Finished with the transfer; unless we are sending POST data, go idle...
1157 DEBUG_puts("httpWrite: changing states...");
1159 if (http
->state
== HTTP_POST_RECV
)
1162 http
->state
= HTTP_WAITING
;
1165 DEBUG_printf(("httpWrite: wrote %d bytes...\n", tbytes
));
1172 * 'httpGets()' - Get a line of text from a HTTP connection.
1175 char * /* O - Line or NULL */
1176 httpGets(char *line
, /* I - Line to read into */
1177 int length
, /* I - Max length of buffer */
1178 http_t
*http
) /* I - HTTP data */
1180 char *lineptr
, /* Pointer into line */
1181 *bufptr
, /* Pointer into input buffer */
1182 *bufend
; /* Pointer to end of buffer */
1183 int bytes
; /* Number of bytes read */
1186 DEBUG_printf(("httpGets(%08x, %d, %08x)\n", line
, length
, http
));
1188 if (http
== NULL
|| line
== NULL
)
1192 * Pre-scan the buffer and see if there is a newline in there...
1195 #if defined(WIN32) || defined(__EMX__)
1199 #endif /* WIN32 || __EMX__ */
1203 bufptr
= http
->buffer
;
1204 bufend
= http
->buffer
+ http
->used
;
1206 while (bufptr
< bufend
)
1207 if (*bufptr
== 0x0a)
1212 if (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
)
1215 * No newline; see if there is more data to be read...
1220 bytes
= SSL_read((SSL
*)(http
->tls
), bufend
,
1221 HTTP_MAX_BUFFER
- http
->used
);
1223 #endif /* HAVE_LIBSSL */
1224 bytes
= recv(http
->fd
, bufend
, HTTP_MAX_BUFFER
- http
->used
, 0);
1229 * Nope, can't get a line this time...
1232 #if defined(WIN32) || defined(__EMX__)
1233 if (WSAGetLastError() != http
->error
)
1235 http
->error
= WSAGetLastError();
1239 DEBUG_printf(("httpGets(): recv() error %d!\n", WSAGetLastError()));
1241 if (errno
!= http
->error
)
1243 http
->error
= errno
;
1247 DEBUG_printf(("httpGets(): recv() error %d!\n", errno
));
1248 #endif /* WIN32 || __EMX__ */
1252 else if (bytes
== 0)
1255 http
->error
= EPIPE
;
1261 * Yup, update the amount used and the end pointer...
1264 http
->used
+= bytes
;
1268 while (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
);
1270 http
->activity
= time(NULL
);
1273 * Read a line from the buffer...
1277 bufptr
= http
->buffer
;
1281 while (bufptr
< bufend
&& bytes
< length
)
1285 if (*bufptr
== 0x0a)
1290 else if (*bufptr
== 0x0d)
1293 *lineptr
++ = *bufptr
++;
1300 http
->used
-= bytes
;
1302 memcpy(http
->buffer
, bufptr
, http
->used
);
1304 DEBUG_printf(("httpGets(): Returning \"%s\"\n", line
));
1308 DEBUG_puts("httpGets(): No new line available!");
1315 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1318 int /* O - Number of bytes written */
1319 httpPrintf(http_t
*http
, /* I - HTTP data */
1320 const char *format
, /* I - printf-style format string */
1321 ...) /* I - Additional args as needed */
1323 int bytes
, /* Number of bytes to write */
1324 nbytes
, /* Number of bytes written */
1325 tbytes
; /* Number of bytes all together */
1326 char buf
[HTTP_MAX_BUFFER
], /* Buffer for formatted string */
1327 *bufptr
; /* Pointer into buffer */
1328 va_list ap
; /* Variable argument pointer */
1331 va_start(ap
, format
);
1332 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1335 DEBUG_printf(("httpPrintf: %s", buf
));
1337 for (tbytes
= 0, bufptr
= buf
; tbytes
< bytes
; tbytes
+= nbytes
, bufptr
+= nbytes
)
1341 nbytes
= SSL_write((SSL
*)(http
->tls
), bufptr
, bytes
- tbytes
);
1343 #endif /* HAVE_LIBSSL */
1344 nbytes
= send(http
->fd
, bufptr
, bytes
- tbytes
, 0);
1355 * 'httpStatus()' - Return a short string describing a HTTP status code.
1358 const char * /* O - String or NULL */
1359 httpStatus(http_status_t status
) /* I - HTTP status code */
1363 case HTTP_CONTINUE
:
1364 return ("Continue");
1365 case HTTP_SWITCHING_PROTOCOLS
:
1366 return ("Switching Protocols");
1371 case HTTP_ACCEPTED
:
1372 return ("Accepted");
1373 case HTTP_NO_CONTENT
:
1374 return ("No Content");
1375 case HTTP_NOT_MODIFIED
:
1376 return ("Not Modified");
1377 case HTTP_BAD_REQUEST
:
1378 return ("Bad Request");
1379 case HTTP_UNAUTHORIZED
:
1380 return ("Unauthorized");
1381 case HTTP_FORBIDDEN
:
1382 return ("Forbidden");
1383 case HTTP_NOT_FOUND
:
1384 return ("Not Found");
1385 case HTTP_REQUEST_TOO_LARGE
:
1386 return ("Request Entity Too Large");
1387 case HTTP_URI_TOO_LONG
:
1388 return ("URI Too Long");
1389 case HTTP_UPGRADE_REQUIRED
:
1390 return ("Upgrade Required");
1391 case HTTP_NOT_IMPLEMENTED
:
1392 return ("Not Implemented");
1393 case HTTP_NOT_SUPPORTED
:
1394 return ("Not Supported");
1402 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
1405 const char * /* O - Date/time string */
1406 httpGetDateString(time_t t
) /* I - UNIX time */
1409 static char datetime
[256];
1413 snprintf(datetime
, sizeof(datetime
), "%s, %02d %s %d %02d:%02d:%02d GMT",
1414 days
[tdate
->tm_wday
], tdate
->tm_mday
, months
[tdate
->tm_mon
],
1415 tdate
->tm_year
+ 1900, tdate
->tm_hour
, tdate
->tm_min
, tdate
->tm_sec
);
1422 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
1425 time_t /* O - UNIX time */
1426 httpGetDateTime(const char *s
) /* I - Date/time string */
1428 int i
; /* Looping var */
1429 struct tm tdate
; /* Time/date structure */
1430 char mon
[16]; /* Abbreviated month name */
1431 int day
, year
; /* Day of month and year */
1432 int hour
, min
, sec
; /* Time */
1435 if (sscanf(s
, "%*s%d%15s%d%d:%d:%d", &day
, mon
, &year
, &hour
, &min
, &sec
) < 6)
1438 for (i
= 0; i
< 12; i
++)
1439 if (strcasecmp(mon
, months
[i
]) == 0)
1446 tdate
.tm_mday
= day
;
1447 tdate
.tm_year
= year
- 1900;
1448 tdate
.tm_hour
= hour
;
1453 return (mktime(&tdate
));
1458 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1461 http_status_t
/* O - HTTP status */
1462 httpUpdate(http_t
*http
) /* I - HTTP data */
1464 char line
[1024], /* Line from connection... */
1465 *value
; /* Pointer to value on line */
1466 http_field_t field
; /* Field index */
1467 int major
, minor
; /* HTTP version numbers */
1468 http_status_t status
; /* Authorization status */
1470 SSL_CTX
*context
; /* Context for encryption */
1471 SSL
*conn
; /* Connection for encryption */
1472 #endif /* HAVE_LIBSSL */
1475 DEBUG_printf(("httpUpdate(%08x)\n", http
));
1478 * If we haven't issued any commands, then there is nothing to "update"...
1481 if (http
->state
== HTTP_WAITING
)
1482 return (HTTP_CONTINUE
);
1485 * Grab all of the lines we can from the connection...
1488 while (httpGets(line
, sizeof(line
), http
) != NULL
)
1492 if (line
[0] == '\0')
1495 * Blank line means the start of the data section (if any). Return
1496 * the result code, too...
1498 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
1499 * Instead, we just return HTTP_CONTINUE to the caller and keep on
1503 if (http
->status
== HTTP_CONTINUE
)
1504 return (http
->status
);
1507 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
1509 context
= SSL_CTX_new(SSLv23_method());
1510 conn
= SSL_new(context
);
1512 SSL_set_fd(conn
, http
->fd
);
1513 if (SSL_connect(conn
) != 1)
1515 SSL_CTX_free(context
);
1518 #if defined(WIN32) || defined(__EMX__)
1519 http
->error
= WSAGetLastError();
1521 http
->error
= errno
;
1522 #endif /* WIN32 || __EMX__ */
1523 http
->status
= HTTP_ERROR
;
1526 closesocket(http
->fd
);
1531 return (HTTP_ERROR
);
1536 return (HTTP_CONTINUE
);
1538 else if (http
->status
== HTTP_UPGRADE_REQUIRED
&&
1539 http
->encryption
!= HTTP_ENCRYPT_NEVER
)
1540 http
->encryption
= HTTP_ENCRYPT_REQUIRED
;
1541 #endif /* HAVE_LIBSSL */
1543 httpGetLength(http
);
1545 switch (http
->state
)
1549 case HTTP_POST_RECV
:
1555 http
->state
= HTTP_WAITING
;
1559 return (http
->status
);
1561 else if (strncmp(line
, "HTTP/", 5) == 0)
1564 * Got the beginning of a response...
1567 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, (int *)&status
) != 3)
1568 return (HTTP_ERROR
);
1570 http
->version
= (http_version_t
)(major
* 100 + minor
);
1571 http
->status
= status
;
1573 else if ((value
= strchr(line
, ':')) != NULL
)
1580 while (isspace(*value
))
1584 * Be tolerants of servers that send unknown attribute fields...
1587 if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
1589 DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line
));
1593 httpSetField(http
, field
, value
);
1597 http
->status
= HTTP_ERROR
;
1598 return (HTTP_ERROR
);
1603 * See if there was an error...
1608 http
->status
= HTTP_ERROR
;
1609 return (HTTP_ERROR
);
1613 * If we haven't already returned, then there is nothing new...
1616 return (HTTP_CONTINUE
);
1621 * 'httpDecode64()' - Base64-decode a string.
1624 char * /* O - Decoded string */
1625 httpDecode64(char *out
, /* I - String to write to */
1626 const char *in
) /* I - String to read from */
1628 int pos
, /* Bit position */
1629 base64
; /* Value of this character */
1630 char *outptr
; /* Output pointer */
1633 for (outptr
= out
, pos
= 0; *in
!= '\0'; in
++)
1636 * Decode this character into a number from 0 to 63...
1639 if (*in
>= 'A' && *in
<= 'Z')
1641 else if (*in
>= 'a' && *in
<= 'z')
1642 base64
= *in
- 'a' + 26;
1643 else if (*in
>= '0' && *in
<= '9')
1644 base64
= *in
- '0' + 52;
1645 else if (*in
== '+')
1647 else if (*in
== '/')
1649 else if (*in
== '=')
1655 * Store the result in the appropriate chars...
1661 *outptr
= base64
<< 2;
1665 *outptr
++ |= (base64
>> 4) & 3;
1666 *outptr
= (base64
<< 4) & 255;
1670 *outptr
++ |= (base64
>> 2) & 15;
1671 *outptr
= (base64
<< 6) & 255;
1675 *outptr
++ |= base64
;
1684 * Return the decoded string...
1692 * 'httpEncode64()' - Base64-encode a string.
1695 char * /* O - Encoded string */
1696 httpEncode64(char *out
, /* I - String to write to */
1697 const char *in
) /* I - String to read from */
1699 char *outptr
; /* Output pointer */
1700 static char base64
[] = /* Base64 characters... */
1702 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1703 "abcdefghijklmnopqrstuvwxyz"
1709 for (outptr
= out
; *in
!= '\0'; in
++)
1712 * Encode the up to 3 characters as 4 Base64 numbers...
1715 *outptr
++ = base64
[in
[0] >> 2];
1716 *outptr
++ = base64
[((in
[0] << 4) | (in
[1] >> 4)) & 63];
1725 *outptr
++ = base64
[((in
[0] << 2) | (in
[1] >> 6)) & 63];
1731 *outptr
++ = base64
[in
[0] & 63];
1738 * Return the encoded string...
1746 * 'httpGetLength()' - Get the amount of data remaining from the
1747 * content-length or transfer-encoding fields.
1750 int /* O - Content length */
1751 httpGetLength(http_t
*http
) /* I - HTTP data */
1753 DEBUG_printf(("httpGetLength(%08x)\n", http
));
1755 if (strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked") == 0)
1757 DEBUG_puts("httpGetLength: chunked request!");
1759 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
1760 http
->data_remaining
= 0;
1764 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1767 * The following is a hack for HTTP servers that don't send a
1768 * content-length or transfer-encoding field...
1770 * If there is no content-length then the connection must close
1771 * after the transfer is complete...
1774 if (http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] == '\0')
1775 http
->data_remaining
= 2147483647;
1777 http
->data_remaining
= atoi(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
]);
1779 DEBUG_printf(("httpGetLength: content_length = %d\n", http
->data_remaining
));
1782 return (http
->data_remaining
);
1787 * 'http_field()' - Return the field index for a field name.
1790 static http_field_t
/* O - Field index */
1791 http_field(const char *name
) /* I - String name */
1793 int i
; /* Looping var */
1796 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
1797 if (strcasecmp(name
, http_fields
[i
]) == 0)
1798 return ((http_field_t
)i
);
1800 return (HTTP_FIELD_UNKNOWN
);
1805 * 'http_send()' - Send a request with all fields and the trailing blank line.
1808 static int /* O - 0 on success, non-zero on error */
1809 http_send(http_t
*http
, /* I - HTTP data */
1810 http_state_t request
, /* I - Request code */
1811 const char *uri
) /* I - URI */
1813 int i
; /* Looping var */
1814 char *ptr
, /* Pointer in buffer */
1815 buf
[1024]; /* Encoded URI buffer */
1816 static const char *codes
[] = /* Request code strings */
1832 static const char *hex
= "0123456789ABCDEF";
1836 if (http
== NULL
|| uri
== NULL
)
1840 * Encode the URI as needed...
1843 for (ptr
= buf
; *uri
!= '\0'; uri
++)
1844 if (*uri
<= ' ' || *uri
>= 127)
1847 *ptr
++ = hex
[(*uri
>> 4) & 15];
1848 *ptr
++ = hex
[*uri
& 15];
1856 * See if we had an error the last time around; if so, reconnect...
1859 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
1860 httpReconnect(http
);
1863 * Send the request header...
1866 http
->state
= request
;
1867 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
1870 http
->status
= HTTP_CONTINUE
;
1873 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
1875 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
1876 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
1878 #endif /* HAVE_LIBSSL */
1880 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
1882 http
->status
= HTTP_ERROR
;
1886 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
1887 if (http
->fields
[i
][0] != '\0')
1889 DEBUG_printf(("%s: %s\n", http_fields
[i
], http
->fields
[i
]));
1891 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], http
->fields
[i
]) < 1)
1893 http
->status
= HTTP_ERROR
;
1898 if (httpPrintf(http
, "\r\n") < 1)
1900 http
->status
= HTTP_ERROR
;
1904 httpClearFields(http
);
1912 * 'http_upgrade()' - Force upgrade to TLS encryption.
1915 static int /* O - Status of connection */
1916 http_upgrade(http_t
*http
) /* I - HTTP data */
1918 int ret
; /* Return value */
1919 http_t myhttp
; /* Local copy of HTTP data */
1922 DEBUG_printf(("http_upgrade(%p)\n", http
));
1925 * Copy the HTTP data to a local variable so we can do the OPTIONS
1926 * request without interfering with the existing request data...
1929 memcpy(&myhttp
, http
, sizeof(myhttp
));
1932 * Send an OPTIONS request to the server, requiring SSL or TLS
1933 * encryption on the link...
1936 httpClearFields(&myhttp
);
1937 httpSetField(&myhttp
, HTTP_FIELD_CONNECTION
, "upgrade");
1938 httpSetField(&myhttp
, HTTP_FIELD_UPGRADE
, "TLS/1.0, SSL/2.0, SSL/3.0");
1940 if ((ret
= httpOptions(&myhttp
, "*")) == 0)
1943 * Wait for the secure connection...
1946 while (httpUpdate(&myhttp
) == HTTP_CONTINUE
);
1952 * Copy the HTTP data back over, if any...
1955 http
->fd
= myhttp
.fd
;
1956 http
->error
= myhttp
.error
;
1957 http
->activity
= myhttp
.activity
;
1958 http
->status
= myhttp
.status
;
1959 http
->version
= myhttp
.version
;
1960 http
->keep_alive
= myhttp
.keep_alive
;
1961 http
->used
= myhttp
.used
;
1964 memcpy(http
->buffer
, myhttp
.buffer
, http
->used
);
1966 http
->auth_type
= myhttp
.auth_type
;
1967 http
->nonce_count
= myhttp
.nonce_count
;
1969 memcpy(http
->nonce
, myhttp
.nonce
, sizeof(http
->nonce
));
1971 http
->tls
= myhttp
.tls
;
1972 http
->encryption
= myhttp
.encryption
;
1975 * See if we actually went secure...
1981 * Server does not support HTTP upgrade...
1984 DEBUG_puts("Server does not support HTTP upgrade!");
1987 closesocket(http
->fd
);
1999 #endif /* HAVE_LIBSSL */
2003 * End of "$Id: http.c,v 1.77 2001/02/07 01:25:39 mike Exp $".