2 * "$Id: http.c,v 1.71 2000/12/19 15:10:38 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
63 * Include necessary headers...
78 #if !defined(WIN32) && !defined(__EMX__)
80 #endif /* !WIN32 && !__EMX__ */
83 # include <openssl/rand.h>
84 # include <openssl/ssl.h>
85 #endif /* HAVE_LIBSSL */
89 * Some operating systems have done away with the Fxxxx constants for
90 * the fcntl() call; this works around that "feature"...
94 # define FNONBLK O_NONBLOCK
102 static http_field_t
http_field(const char *name
);
103 static int http_send(http_t
*http
, http_state_t request
,
111 static const char *http_fields
[] =
128 "If-Unmodified-since",
141 static const char *days
[7] =
151 static const char *months
[12] =
169 * 'httpInitialize()' - Initialize the HTTP interface library and set the
170 * default HTTP proxy (if any).
177 # if defined(WIN32) || defined(__EMX__)
179 struct timeval curtime
; /* Current time in microseconds */
180 # endif /* WIN32 || __EMX__ */
181 #endif /* HAVE_LIBSSL */
183 #if defined(WIN32) || defined(__EMX__)
184 WSADATA winsockdata
; /* WinSock data */
185 static int initialized
= 0;/* Has WinSock been initialized? */
189 WSAStartup(MAKEWORD(1,1), &winsockdata
);
190 #elif defined(HAVE_SIGSET)
191 sigset(SIGPIPE
, SIG_IGN
);
192 #elif defined(HAVE_SIGACTION)
193 struct sigaction action
; /* POSIX sigaction data */
197 * Ignore SIGPIPE signals...
200 memset(&action
, 0, sizeof(action
));
201 action
.sa_handler
= SIG_IGN
;
202 sigaction(SIGPIPE
, &action
, NULL
);
204 signal(SIGPIPE
, SIG_IGN
);
205 #endif /* WIN32 || __EMX__ */
211 * Using the current time is a dubious random seed, but on some systems
212 * it is the best we can do (on others, this seed isn't even used...)
215 # if defined(WIN32) || defined(__EMX__)
217 gettimeofday(&curtime
, NULL
);
218 RAND_seed(&curtime
, sizeof(curtime
));
219 # endif /* WIN32 || __EMX__ */
220 #endif /* HAVE_LIBSSL */
225 * 'httpCheck()' - Check to see if there is a pending response from the server.
228 int /* O - 0 = no data, 1 = data available */
229 httpCheck(http_t
*http
) /* I - HTTP connection */
231 fd_set input
; /* Input set for select() */
232 struct timeval timeout
; /* Timeout */
236 * First see if there is data in the buffer...
246 * Then try doing a select() to poll the socket...
250 FD_SET(http
->fd
, &input
);
255 return (select(http
->fd
+ 1, &input
, NULL
, NULL
, &timeout
) > 0);
260 * 'httpClose()' - Close an HTTP connection...
264 httpClose(http_t
*http
) /* I - Connection to close */
270 closesocket(http
->fd
);
280 * 'httpConnect()' - Connect to a HTTP server.
283 http_t
* /* O - New HTTP connection */
284 httpConnect(const char *host
, /* I - Host to connect to */
285 int port
) /* I - Port number */
287 http_t
*http
; /* New HTTP connection */
288 struct hostent
*hostaddr
; /* Host address data */
300 if ((hostaddr
= gethostbyname(host
)) == NULL
)
304 * Allocate memory for the structure...
307 http
= calloc(sizeof(http_t
), 1);
311 http
->version
= HTTP_1_1
;
313 http
->activity
= time(NULL
);
316 * Copy the hostname and port and then "reconnect"...
319 strncpy(http
->hostname
, host
, sizeof(http
->hostname
) - 1);
320 memcpy((char *)&(http
->hostaddr
.sin_addr
), hostaddr
->h_addr
, hostaddr
->h_length
);
321 http
->hostaddr
.sin_family
= hostaddr
->h_addrtype
;
323 http
->hostaddr
.sin_port
= htons((u_short
)port
);
325 http
->hostaddr
.sin_port
= htons(port
);
329 * Set the default encryption status...
333 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
336 * Connect to the remote system...
339 if (httpReconnect(http
))
350 * 'httpEncryption()' - Set the required encryption on the link.
353 int /* O - -1 on error, 0 on success */
354 httpEncryption(http_t
*http
, /* I - HTTP data */
355 http_encryption_t e
) /* I - New encryption preference */
360 http
->encryption
= e
;
362 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
363 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
364 return (httpReconnect(http
));
371 * 'httpReconnect()' - Reconnect to a HTTP server...
374 int /* O - 0 on success, non-zero on failure */
375 httpReconnect(http_t
*http
) /* I - HTTP data */
377 int val
; /* Socket option value */
379 SSL_CTX
*context
; /* Context for encryption */
380 SSL
*conn
; /* Connection for encryption */
381 char buffer
[1024]; /* Status from server... */
386 conn
= (SSL
*)(http
->tls
);
387 context
= SSL_get_SSL_CTX(conn
);
390 SSL_CTX_free(context
);
395 #endif /* HAVE_LIBSSL */
398 * Close any previously open socket...
403 closesocket(http
->fd
);
409 * Create the socket and set options to allow reuse.
412 if ((http
->fd
= socket(AF_INET
, SOCK_STREAM
, 0)) < 0)
414 #if defined(WIN32) || defined(__EMX__)
415 http
->error
= WSAGetLastError();
418 #endif /* WIN32 || __EMX__ */
419 http
->status
= HTTP_ERROR
;
424 fcntl(http
->fd
, F_SETFD
, FD_CLOEXEC
); /* Close this socket when starting *
425 * other processes... */
426 #endif /* FD_CLOEXEC */
429 setsockopt(http
->fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *)&val
, sizeof(val
));
433 setsockopt(http
->fd
, SOL_SOCKET
, SO_REUSEPORT
, &val
, sizeof(val
));
434 #endif /* SO_REUSEPORT */
437 * Connect to the server...
440 if (connect(http
->fd
, (struct sockaddr
*)&(http
->hostaddr
),
441 sizeof(http
->hostaddr
)) < 0)
443 #if defined(WIN32) || defined(__EMX__)
444 http
->error
= WSAGetLastError();
447 #endif /* WIN32 || __EMX__ */
448 http
->status
= HTTP_ERROR
;
451 closesocket(http
->fd
);
460 http
->status
= HTTP_CONTINUE
;
463 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
466 * Always do encryption on port 443 (https method); other ports use
467 * the HTTP Upgrade method...
470 if (ntohs(http
->hostaddr
.sin_port
) != 443)
473 * Send an OPTIONS request to the server, requiring SSL or TLS
474 * encryption on the link...
477 httpPrintf(http
, "OPTIONS * HTTP/1.1\r\n");
478 httpPrintf(http
, "Host: %s\r\n", http
->hostname
);
479 httpPrintf(http
, "Connection: upgrade\r\n");
480 httpPrintf(http
, "Upgrade: TLS/1.0, SSL/2.0, SSL/3.0\r\n");
481 httpPrintf(http
, "\r\n");
484 * Wait for the response data...
487 while (httpGets(buffer
, sizeof(buffer
), http
) != NULL
)
492 context
= SSL_CTX_new(TLSv1_method());
493 conn
= SSL_new(context
);
495 SSL_set_fd(conn
, http
->fd
);
496 if (SSL_connect(conn
) != 1)
498 SSL_CTX_free(context
);
501 #if defined(WIN32) || defined(__EMX__)
502 http
->error
= WSAGetLastError();
505 #endif /* WIN32 || __EMX__ */
506 http
->status
= HTTP_ERROR
;
509 closesocket(http
->fd
);
519 #endif /* HAVE_LIBSSL */
526 * 'httpSeparate()' - Separate a Universal Resource Identifier into its
531 httpSeparate(const char *uri
, /* I - Universal Resource Identifier */
532 char *method
, /* O - Method [32] (http, https, etc.) */
533 char *username
, /* O - Username [32] */
534 char *host
, /* O - Hostname [32] */
535 int *port
, /* O - Port number to use */
536 char *resource
) /* O - Resource/filename [1024] */
538 char *ptr
; /* Pointer into string... */
539 const char *atsign
, /* @ sign */
540 *slash
; /* Separator */
543 if (uri
== NULL
|| method
== NULL
|| username
== NULL
|| host
== NULL
||
544 port
== NULL
|| resource
== NULL
)
548 * Grab the method portion of the URI...
551 if (strncmp(uri
, "//", 2) == 0)
554 * Workaround for HP IPP client bug...
557 strcpy(method
, "ipp");
562 * Standard URI with method...
566 while (*uri
!= ':' && *uri
!= '\0')
574 * If the method contains a period or slash, then it's probably
575 * hostname/filename...
578 if (strchr(host
, '.') != NULL
|| strchr(host
, '/') != NULL
|| *uri
== '\0')
580 if ((ptr
= strchr(host
, '/')) != NULL
)
582 strncpy(resource
, ptr
, HTTP_MAX_URI
- 1);
583 resource
[HTTP_MAX_URI
- 1] = '\0';
592 * OK, we have "hostname:port[/resource]"...
595 *port
= strtol(uri
, (char **)&uri
, 10);
599 strncpy(resource
, uri
, HTTP_MAX_URI
- 1);
600 resource
[HTTP_MAX_URI
- 1] = '\0';
606 strcpy(method
, "http");
612 strncpy(method
, host
, 31);
618 * If the method starts with less than 2 slashes then it is a local resource...
621 if (strncmp(uri
, "//", 2) != 0)
623 strncpy(resource
, uri
, 1023);
624 resource
[1023] = '\0';
633 * Grab the usenname, if any...
639 if ((slash
= strchr(uri
, '/')) == NULL
)
640 slash
= uri
+ strlen(uri
);
642 if ((atsign
= strchr(uri
, '@')) != NULL
&& atsign
< slash
)
645 * Got a username:password combo...
649 uri
< atsign
&& ptr
< (username
+ sizeof(username
) - 1);
660 * Grab the hostname...
664 while (*uri
!= ':' && *uri
!= '/' && *uri
!= '\0')
671 if (strcasecmp(method
, "http") == 0)
673 else if (strcasecmp(method
, "https") == 0)
675 else if (strcasecmp(method
, "ipp") == 0)
677 else if (strcasecmp(method
, "socket") == 0) /* Not registered yet... */
685 * Parse port number...
690 while (isdigit(*uri
))
692 *port
= (*port
* 10) + *uri
- '0';
700 * Hostname but no port or path...
709 * The remaining portion is the resource string...
712 strncpy(resource
, uri
, HTTP_MAX_URI
- 1);
713 resource
[HTTP_MAX_URI
- 1] = '\0';
718 * 'httpGetSubField()' - Get a sub-field value.
721 char * /* O - Value or NULL */
722 httpGetSubField(http_t
*http
, /* I - HTTP data */
723 http_field_t field
, /* I - Field index */
724 const char *name
, /* I - Name of sub-field */
725 char *value
) /* O - Value string */
727 const char *fptr
; /* Pointer into field */
728 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
729 *ptr
; /* Pointer into string buffer */
733 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
734 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
735 name
== NULL
|| value
== NULL
)
738 for (fptr
= http
->fields
[field
]; *fptr
;)
741 * Skip leading whitespace...
744 while (isspace(*fptr
));
754 * Get the sub-field name...
758 *fptr
&& *fptr
!= '=' && !isspace(*fptr
) && ptr
< (temp
+ sizeof(temp
) - 1);
764 * Skip trailing chars up to the '='...
767 while (*fptr
&& *fptr
!= '=')
774 * Skip = and leading whitespace...
779 while (isspace(*fptr
));
785 * Read quoted string...
788 for (ptr
= value
, fptr
++;
789 *fptr
&& *fptr
!= '\"' && ptr
< (value
+ HTTP_MAX_VALUE
- 1);
794 while (*fptr
&& *fptr
!= '\"')
803 * Read unquoted string...
807 *fptr
&& !isspace(*fptr
) && *fptr
!= ',' && ptr
< (value
+ HTTP_MAX_VALUE
- 1);
812 while (*fptr
&& !isspace(*fptr
) && *fptr
!= ',')
817 * See if this is the one...
820 if (strcmp(name
, temp
) == 0)
831 * 'httpSetField()' - Set the value of an HTTP header.
835 httpSetField(http_t
*http
, /* I - HTTP data */
836 http_field_t field
, /* I - Field index */
837 const char *value
) /* I - Value */
840 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
841 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
845 strncpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
- 1);
846 http
->fields
[field
][HTTP_MAX_VALUE
- 1] = '\0';
851 * 'httpDelete()' - Send a DELETE request to the server.
854 int /* O - Status of call (0 = success) */
855 httpDelete(http_t
*http
, /* I - HTTP data */
856 const char *uri
) /* I - URI to delete */
858 return (http_send(http
, HTTP_DELETE
, uri
));
863 * 'httpGet()' - Send a GET request to the server.
866 int /* O - Status of call (0 = success) */
867 httpGet(http_t
*http
, /* I - HTTP data */
868 const char *uri
) /* I - URI to get */
870 return (http_send(http
, HTTP_GET
, uri
));
875 * 'httpHead()' - Send a HEAD request to the server.
878 int /* O - Status of call (0 = success) */
879 httpHead(http_t
*http
, /* I - HTTP data */
880 const char *uri
) /* I - URI for head */
882 return (http_send(http
, HTTP_HEAD
, uri
));
887 * 'httpOptions()' - Send an OPTIONS request to the server.
890 int /* O - Status of call (0 = success) */
891 httpOptions(http_t
*http
, /* I - HTTP data */
892 const char *uri
) /* I - URI for options */
894 return (http_send(http
, HTTP_OPTIONS
, uri
));
899 * 'httpPost()' - Send a POST request to the server.
902 int /* O - Status of call (0 = success) */
903 httpPost(http_t
*http
, /* I - HTTP data */
904 const char *uri
) /* I - URI for post */
908 return (http_send(http
, HTTP_POST
, uri
));
913 * 'httpPut()' - Send a PUT request to the server.
916 int /* O - Status of call (0 = success) */
917 httpPut(http_t
*http
, /* I - HTTP data */
918 const char *uri
) /* I - URI to put */
922 return (http_send(http
, HTTP_PUT
, uri
));
927 * 'httpTrace()' - Send an TRACE request to the server.
930 int /* O - Status of call (0 = success) */
931 httpTrace(http_t
*http
, /* I - HTTP data */
932 const char *uri
) /* I - URI for trace */
934 return (http_send(http
, HTTP_TRACE
, uri
));
939 * 'httpFlush()' - Flush data from a HTTP connection.
943 httpFlush(http_t
*http
) /* I - HTTP data */
945 char buffer
[8192]; /* Junk buffer */
948 while (httpRead(http
, buffer
, sizeof(buffer
)) > 0);
953 * 'httpRead()' - Read data from a HTTP connection.
956 int /* O - Number of bytes read */
957 httpRead(http_t
*http
, /* I - HTTP data */
958 char *buffer
, /* I - Buffer for data */
959 int length
) /* I - Maximum number of bytes */
961 int bytes
; /* Bytes read */
962 char len
[32]; /* Length string */
965 DEBUG_printf(("httpRead(%08x, %08x, %d)\n", http
, buffer
, length
));
967 if (http
== NULL
|| buffer
== NULL
)
970 http
->activity
= time(NULL
);
975 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
976 http
->data_remaining
<= 0)
978 DEBUG_puts("httpRead: Getting chunk length...");
980 if (httpGets(len
, sizeof(len
), http
) == NULL
)
982 DEBUG_puts("httpRead: Could not get length!");
986 http
->data_remaining
= strtol(len
, NULL
, 16);
989 DEBUG_printf(("httpRead: data_remaining = %d\n", http
->data_remaining
));
991 if (http
->data_remaining
== 0)
994 * A zero-length chunk ends a transfer; unless we are reading POST
998 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
999 httpGets(len
, sizeof(len
), http
);
1001 if (http
->state
== HTTP_POST_RECV
)
1004 http
->state
= HTTP_WAITING
;
1008 else if (length
> http
->data_remaining
)
1009 length
= http
->data_remaining
;
1013 if (length
> http
->used
)
1014 length
= http
->used
;
1018 DEBUG_printf(("httpRead: grabbing %d bytes from input buffer...\n", bytes
));
1020 memcpy(buffer
, http
->buffer
, length
);
1021 http
->used
-= length
;
1024 memcpy(http
->buffer
, http
->buffer
+ length
, http
->used
);
1028 bytes
= SSL_read((SSL
*)(http
->tls
), buffer
, length
);
1029 #endif /* HAVE_LIBSSL */
1032 DEBUG_printf(("httpRead: reading %d bytes from socket...\n", length
));
1033 bytes
= recv(http
->fd
, buffer
, length
, 0);
1034 DEBUG_printf(("httpRead: read %d bytes from socket...\n", bytes
));
1038 http
->data_remaining
-= bytes
;
1040 #if defined(WIN32) || defined(__EMX__)
1041 http
->error
= WSAGetLastError();
1043 http
->error
= errno
;
1044 #endif /* WIN32 || __EMX__ */
1046 if (http
->data_remaining
== 0)
1048 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1049 httpGets(len
, sizeof(len
), http
);
1051 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
1053 if (http
->state
== HTTP_POST_RECV
)
1056 http
->state
= HTTP_WAITING
;
1065 * 'httpWrite()' - Write data to a HTTP connection.
1068 int /* O - Number of bytes written */
1069 httpWrite(http_t
*http
, /* I - HTTP data */
1070 const char *buffer
, /* I - Buffer for data */
1071 int length
) /* I - Number of bytes to write */
1073 int tbytes
, /* Total bytes sent */
1074 bytes
; /* Bytes sent */
1077 if (http
== NULL
|| buffer
== NULL
)
1080 http
->activity
= time(NULL
);
1082 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1084 if (httpPrintf(http
, "%x\r\n", length
) < 0)
1090 * A zero-length chunk ends a transfer; unless we are sending POST
1094 DEBUG_puts("httpWrite: changing states...");
1096 if (http
->state
== HTTP_POST_RECV
)
1099 http
->state
= HTTP_WAITING
;
1101 if (httpPrintf(http
, "\r\n") < 0)
1114 bytes
= SSL_write((SSL
*)(http
->tls
), buffer
, length
);
1116 #endif /* HAVE_LIBSSL */
1117 bytes
= send(http
->fd
, buffer
, length
, 0);
1121 DEBUG_puts("httpWrite: error writing data...\n");
1129 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1130 http
->data_remaining
-= bytes
;
1133 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1134 if (httpPrintf(http
, "\r\n") < 0)
1137 if (http
->data_remaining
== 0 && http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1140 * Finished with the transfer; unless we are sending POST data, go idle...
1143 DEBUG_puts("httpWrite: changing states...");
1145 if (http
->state
== HTTP_POST_RECV
)
1148 http
->state
= HTTP_WAITING
;
1151 DEBUG_printf(("httpWrite: wrote %d bytes...\n", tbytes
));
1158 * 'httpGets()' - Get a line of text from a HTTP connection.
1161 char * /* O - Line or NULL */
1162 httpGets(char *line
, /* I - Line to read into */
1163 int length
, /* I - Max length of buffer */
1164 http_t
*http
) /* I - HTTP data */
1166 char *lineptr
, /* Pointer into line */
1167 *bufptr
, /* Pointer into input buffer */
1168 *bufend
; /* Pointer to end of buffer */
1169 int bytes
; /* Number of bytes read */
1172 DEBUG_printf(("httpGets(%08x, %d, %08x)\n", line
, length
, http
));
1174 if (http
== NULL
|| line
== NULL
)
1178 * Pre-scan the buffer and see if there is a newline in there...
1181 #if defined(WIN32) || defined(__EMX__)
1185 #endif /* WIN32 || __EMX__ */
1189 bufptr
= http
->buffer
;
1190 bufend
= http
->buffer
+ http
->used
;
1192 while (bufptr
< bufend
)
1193 if (*bufptr
== 0x0a)
1198 if (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
)
1201 * No newline; see if there is more data to be read...
1206 bytes
= SSL_read((SSL
*)(http
->tls
), bufend
,
1207 HTTP_MAX_BUFFER
- http
->used
);
1209 #endif /* HAVE_LIBSSL */
1210 bytes
= recv(http
->fd
, bufend
, HTTP_MAX_BUFFER
- http
->used
, 0);
1215 * Nope, can't get a line this time...
1218 #if defined(WIN32) || defined(__EMX__)
1219 if (WSAGetLastError() != http
->error
)
1221 http
->error
= WSAGetLastError();
1225 DEBUG_printf(("httpGets(): recv() error %d!\n", WSAGetLastError()));
1227 if (errno
!= http
->error
)
1229 http
->error
= errno
;
1233 DEBUG_printf(("httpGets(): recv() error %d!\n", errno
));
1234 #endif /* WIN32 || __EMX__ */
1238 else if (bytes
== 0)
1241 http
->error
= EPIPE
;
1247 * Yup, update the amount used and the end pointer...
1250 http
->used
+= bytes
;
1254 while (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
);
1256 http
->activity
= time(NULL
);
1259 * Read a line from the buffer...
1263 bufptr
= http
->buffer
;
1266 while (bufptr
< bufend
&& bytes
< length
)
1270 if (*bufptr
== 0x0a)
1275 http
->used
-= bytes
;
1277 memcpy(http
->buffer
, bufptr
, http
->used
);
1279 DEBUG_printf(("httpGets(): Returning \"%s\"\n", line
));
1282 else if (*bufptr
== 0x0d)
1285 *lineptr
++ = *bufptr
++;
1288 DEBUG_puts("httpGets(): No new line available!");
1295 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1298 int /* O - Number of bytes written */
1299 httpPrintf(http_t
*http
, /* I - HTTP data */
1300 const char *format
, /* I - printf-style format string */
1301 ...) /* I - Additional args as needed */
1303 int bytes
, /* Number of bytes to write */
1304 nbytes
, /* Number of bytes written */
1305 tbytes
; /* Number of bytes all together */
1306 char buf
[HTTP_MAX_BUFFER
], /* Buffer for formatted string */
1307 *bufptr
; /* Pointer into buffer */
1308 va_list ap
; /* Variable argument pointer */
1311 va_start(ap
, format
);
1312 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1315 DEBUG_printf(("httpPrintf: %s", buf
));
1317 for (tbytes
= 0, bufptr
= buf
; tbytes
< bytes
; tbytes
+= nbytes
, bufptr
+= nbytes
)
1321 nbytes
= SSL_write((SSL
*)(http
->tls
), bufptr
, bytes
- tbytes
);
1323 #endif /* HAVE_LIBSSL */
1324 nbytes
= send(http
->fd
, bufptr
, bytes
- tbytes
, 0);
1335 * 'httpStatus()' - Return a short string describing a HTTP status code.
1338 const char * /* O - String or NULL */
1339 httpStatus(http_status_t status
) /* I - HTTP status code */
1343 case HTTP_CONTINUE
:
1344 return ("Continue");
1345 case HTTP_SWITCHING_PROTOCOLS
:
1346 return ("Switching Protocols");
1351 case HTTP_ACCEPTED
:
1352 return ("Accepted");
1353 case HTTP_NO_CONTENT
:
1354 return ("No Content");
1355 case HTTP_NOT_MODIFIED
:
1356 return ("Not Modified");
1357 case HTTP_BAD_REQUEST
:
1358 return ("Bad Request");
1359 case HTTP_UNAUTHORIZED
:
1360 return ("Unauthorized");
1361 case HTTP_FORBIDDEN
:
1362 return ("Forbidden");
1363 case HTTP_NOT_FOUND
:
1364 return ("Not Found");
1365 case HTTP_REQUEST_TOO_LARGE
:
1366 return ("Request Entity Too Large");
1367 case HTTP_URI_TOO_LONG
:
1368 return ("URI Too Long");
1369 case HTTP_UPGRADE_REQUIRED
:
1370 return ("Upgrade Required");
1371 case HTTP_NOT_IMPLEMENTED
:
1372 return ("Not Implemented");
1373 case HTTP_NOT_SUPPORTED
:
1374 return ("Not Supported");
1382 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
1385 const char * /* O - Date/time string */
1386 httpGetDateString(time_t t
) /* I - UNIX time */
1389 static char datetime
[256];
1393 snprintf(datetime
, sizeof(datetime
), "%s, %02d %s %d %02d:%02d:%02d GMT",
1394 days
[tdate
->tm_wday
], tdate
->tm_mday
, months
[tdate
->tm_mon
],
1395 tdate
->tm_year
+ 1900, tdate
->tm_hour
, tdate
->tm_min
, tdate
->tm_sec
);
1402 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
1405 time_t /* O - UNIX time */
1406 httpGetDateTime(const char *s
) /* I - Date/time string */
1408 int i
; /* Looping var */
1409 struct tm tdate
; /* Time/date structure */
1410 char mon
[16]; /* Abbreviated month name */
1411 int day
, year
; /* Day of month and year */
1412 int hour
, min
, sec
; /* Time */
1415 if (sscanf(s
, "%*s%d%15s%d%d:%d:%d", &day
, mon
, &year
, &hour
, &min
, &sec
) < 6)
1418 for (i
= 0; i
< 12; i
++)
1419 if (strcasecmp(mon
, months
[i
]) == 0)
1426 tdate
.tm_mday
= day
;
1427 tdate
.tm_year
= year
- 1900;
1428 tdate
.tm_hour
= hour
;
1433 return (mktime(&tdate
));
1438 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1441 http_status_t
/* O - HTTP status */
1442 httpUpdate(http_t
*http
) /* I - HTTP data */
1444 char line
[1024], /* Line from connection... */
1445 *value
; /* Pointer to value on line */
1446 http_field_t field
; /* Field index */
1447 int major
, minor
; /* HTTP version numbers */
1448 http_status_t status
; /* Authorization status */
1450 SSL_CTX
*context
; /* Context for encryption */
1451 SSL
*conn
; /* Connection for encryption */
1452 #endif /* HAVE_LIBSSL */
1455 DEBUG_printf(("httpUpdate(%08x)\n", http
));
1458 * If we haven't issued any commands, then there is nothing to "update"...
1461 if (http
->state
== HTTP_WAITING
)
1462 return (HTTP_CONTINUE
);
1465 * Grab all of the lines we can from the connection...
1468 while (httpGets(line
, sizeof(line
), http
) != NULL
)
1472 if (line
[0] == '\0')
1475 * Blank line means the start of the data section (if any). Return
1476 * the result code, too...
1478 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
1479 * Instead, we just return HTTP_CONTINUE to the caller and keep on
1483 if (http
->status
== HTTP_CONTINUE
)
1484 return (http
->status
);
1487 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
1489 context
= SSL_CTX_new(TLSv1_method());
1490 conn
= SSL_new(context
);
1492 SSL_set_fd(conn
, http
->fd
);
1493 if (SSL_connect(conn
) != 1)
1495 SSL_CTX_free(context
);
1498 #if defined(WIN32) || defined(__EMX__)
1499 http
->error
= WSAGetLastError();
1501 http
->error
= errno
;
1502 #endif /* WIN32 || __EMX__ */
1503 http
->status
= HTTP_ERROR
;
1506 closesocket(http
->fd
);
1511 return (HTTP_ERROR
);
1516 return (HTTP_CONTINUE
);
1518 else if (http
->status
== HTTP_UPGRADE_REQUIRED
&&
1519 http
->encryption
!= HTTP_ENCRYPT_NEVER
)
1520 http
->encryption
= HTTP_ENCRYPT_PREFERRED
;
1522 #endif /* HAVE_LIBSSL */
1524 httpGetLength(http
);
1526 switch (http
->state
)
1530 case HTTP_POST_RECV
:
1536 http
->state
= HTTP_WAITING
;
1540 return (http
->status
);
1542 else if (strncmp(line
, "HTTP/", 5) == 0)
1545 * Got the beginning of a response...
1548 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, (int *)&status
) != 3)
1549 return (HTTP_ERROR
);
1551 http
->version
= (http_version_t
)(major
* 100 + minor
);
1552 http
->status
= status
;
1554 else if ((value
= strchr(line
, ':')) != NULL
)
1561 while (isspace(*value
))
1565 * Be tolerants of servers that send unknown attribute fields...
1568 if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
1570 DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line
));
1574 httpSetField(http
, field
, value
);
1578 http
->status
= HTTP_ERROR
;
1579 return (HTTP_ERROR
);
1584 * See if there was an error...
1589 http
->status
= HTTP_ERROR
;
1590 return (HTTP_ERROR
);
1594 * If we haven't already returned, then there is nothing new...
1597 return (HTTP_CONTINUE
);
1602 * 'httpDecode64()' - Base64-decode a string.
1605 char * /* O - Decoded string */
1606 httpDecode64(char *out
, /* I - String to write to */
1607 const char *in
) /* I - String to read from */
1609 int pos
, /* Bit position */
1610 base64
; /* Value of this character */
1611 char *outptr
; /* Output pointer */
1614 for (outptr
= out
, pos
= 0; *in
!= '\0'; in
++)
1617 * Decode this character into a number from 0 to 63...
1620 if (*in
>= 'A' && *in
<= 'Z')
1622 else if (*in
>= 'a' && *in
<= 'z')
1623 base64
= *in
- 'a' + 26;
1624 else if (*in
>= '0' && *in
<= '9')
1625 base64
= *in
- '0' + 52;
1626 else if (*in
== '+')
1628 else if (*in
== '/')
1630 else if (*in
== '=')
1636 * Store the result in the appropriate chars...
1642 *outptr
= base64
<< 2;
1646 *outptr
++ |= (base64
>> 4) & 3;
1647 *outptr
= (base64
<< 4) & 255;
1651 *outptr
++ |= (base64
>> 2) & 15;
1652 *outptr
= (base64
<< 6) & 255;
1656 *outptr
++ |= base64
;
1665 * Return the decoded string...
1673 * 'httpEncode64()' - Base64-encode a string.
1676 char * /* O - Encoded string */
1677 httpEncode64(char *out
, /* I - String to write to */
1678 const char *in
) /* I - String to read from */
1680 char *outptr
; /* Output pointer */
1681 static char base64
[] = /* Base64 characters... */
1683 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1684 "abcdefghijklmnopqrstuvwxyz"
1690 for (outptr
= out
; *in
!= '\0'; in
++)
1693 * Encode the up to 3 characters as 4 Base64 numbers...
1696 *outptr
++ = base64
[in
[0] >> 2];
1697 *outptr
++ = base64
[((in
[0] << 4) | (in
[1] >> 4)) & 63];
1706 *outptr
++ = base64
[((in
[0] << 2) | (in
[1] >> 6)) & 63];
1712 *outptr
++ = base64
[in
[0] & 63];
1719 * Return the encoded string...
1727 * 'httpGetLength()' - Get the amount of data remaining from the
1728 * content-length or transfer-encoding fields.
1731 int /* O - Content length */
1732 httpGetLength(http_t
*http
) /* I - HTTP data */
1734 DEBUG_printf(("httpGetLength(%08x)\n", http
));
1736 if (strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked") == 0)
1738 DEBUG_puts("httpGetLength: chunked request!");
1740 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
1741 http
->data_remaining
= 0;
1745 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1748 * The following is a hack for HTTP servers that don't send a
1749 * content-length or transfer-encoding field...
1751 * If there is no content-length then the connection must close
1752 * after the transfer is complete...
1755 if (http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] == '\0')
1756 http
->data_remaining
= 2147483647;
1758 http
->data_remaining
= atoi(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
]);
1760 DEBUG_printf(("httpGetLength: content_length = %d\n", http
->data_remaining
));
1763 return (http
->data_remaining
);
1768 * 'http_field()' - Return the field index for a field name.
1771 static http_field_t
/* O - Field index */
1772 http_field(const char *name
) /* I - String name */
1774 int i
; /* Looping var */
1777 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
1778 if (strcasecmp(name
, http_fields
[i
]) == 0)
1779 return ((http_field_t
)i
);
1781 return (HTTP_FIELD_UNKNOWN
);
1786 * 'http_send()' - Send a request with all fields and the trailing blank line.
1789 static int /* O - 0 on success, non-zero on error */
1790 http_send(http_t
*http
, /* I - HTTP data */
1791 http_state_t request
, /* I - Request code */
1792 const char *uri
) /* I - URI */
1794 int i
; /* Looping var */
1795 char *ptr
, /* Pointer in buffer */
1796 buf
[1024]; /* Encoded URI buffer */
1797 static const char *codes
[] = /* Request code strings */
1813 static const char *hex
= "0123456789ABCDEF";
1817 if (http
== NULL
|| uri
== NULL
)
1821 * Encode the URI as needed...
1824 for (ptr
= buf
; *uri
!= '\0'; uri
++)
1825 if (*uri
<= ' ' || *uri
>= 127)
1828 *ptr
++ = hex
[(*uri
>> 4) & 15];
1829 *ptr
++ = hex
[*uri
& 15];
1837 * See if we had an error the last time around; if so, reconnect...
1840 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
1841 httpReconnect(http
);
1844 * Send the request header...
1847 http
->state
= request
;
1848 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
1851 http
->status
= HTTP_CONTINUE
;
1854 if (http
->encryption
== HTTP_ENCRYPT_PREFERRED
&& !http
->tls
)
1856 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
1857 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
1859 #endif /* HAVE_LIBSSL */
1861 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
1863 http
->status
= HTTP_ERROR
;
1867 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
1868 if (http
->fields
[i
][0] != '\0')
1870 DEBUG_printf(("%s: %s\n", http_fields
[i
], http
->fields
[i
]));
1872 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], http
->fields
[i
]) < 1)
1874 http
->status
= HTTP_ERROR
;
1879 if (httpPrintf(http
, "\r\n") < 1)
1881 http
->status
= HTTP_ERROR
;
1885 httpClearFields(http
);
1892 * End of "$Id: http.c,v 1.71 2000/12/19 15:10:38 mike Exp $".