2 * "$Id: http.c,v 1.82.2.24 2003/01/24 19:19:42 mike Exp $"
4 * HTTP routines for the Common UNIX Printing System (CUPS).
6 * Copyright 1997-2003 by Easy Software Products, all rights reserved.
8 * These coded instructions, statements, and computer programs are the
9 * property of Easy Software Products and are protected by Federal
10 * copyright law. Distribution and use rights are outlined in the file
11 * "LICENSE.txt" which should have been included with this file. If this
12 * file is missing or damaged please contact Easy Software Products
15 * Attn: CUPS Licensing Information
16 * Easy Software Products
17 * 44141 Airport View Drive, Suite 204
18 * Hollywood, Maryland 20636-3111 USA
20 * Voice: (301) 373-9603
21 * EMail: cups-info@cups.org
22 * WWW: http://www.cups.org
24 * This file is subject to the Apple OS-Developed Software exception.
28 * httpInitialize() - Initialize the HTTP interface library and set the
29 * default HTTP proxy (if any).
30 * httpCheck() - Check to see if there is a pending response from
32 * httpClose() - Close an HTTP connection...
33 * httpConnect() - Connect to a HTTP server.
34 * httpConnectEncrypt() - Connect to a HTTP server using encryption.
35 * httpEncryption() - Set the required encryption on the link.
36 * httpReconnect() - Reconnect to a HTTP server...
37 * httpSetField() - Set the value of an HTTP header.
38 * httpDelete() - Send a DELETE request to the server.
39 * httpGet() - Send a GET request to the server.
40 * httpHead() - Send a HEAD request to the server.
41 * httpOptions() - Send an OPTIONS request to the server.
42 * httpPost() - Send a POST request to the server.
43 * httpPut() - Send a PUT request to the server.
44 * httpTrace() - Send an TRACE request to the server.
45 * httpFlush() - Flush data from a HTTP connection.
46 * httpRead() - Read data from a HTTP connection.
47 * httpWrite() - Write data to a HTTP connection.
48 * httpGets() - Get a line of text from a HTTP connection.
49 * httpPrintf() - Print a formatted string to a HTTP connection.
50 * httpStatus() - Return a short string describing a HTTP status code.
51 * httpGetDateString() - Get a formatted date/time string from a time value.
52 * httpGetDateTime() - Get a time value from a formatted date/time string.
53 * httpUpdate() - Update the current HTTP state for incoming data.
54 * httpDecode64() - Base64-decode a string.
55 * httpEncode64() - Base64-encode a string.
56 * httpGetLength() - Get the amount of data remaining from the
57 * content-length or transfer-encoding fields.
58 * http_field() - Return the field index for a field name.
59 * http_send() - Send a request with all fields and the trailing
61 * http_upgrade() - Force upgrade to TLS encryption.
62 * http_setup_ssl() - Set up SSL/TLS on a connection.
63 * http_shutdown_ssl() - Shut down SSL/TLS on a connection.
64 * http_read_ssl() - Read from a SSL/TLS connection.
65 * http_write_ssl() - Write to a SSL/TLS connection.
66 * CDSAReadFunc() - Read function for CDSA decryption code.
67 * CDSAWriteFunc() - Write function for CDSA encryption code.
71 * Include necessary headers...
82 #include "http-private.h"
92 * Some operating systems have done away with the Fxxxx constants for
93 * the fcntl() call; this works around that "feature"...
97 # define FNONBLK O_NONBLOCK
105 static http_field_t
http_field(const char *name
);
106 static int http_send(http_t
*http
, http_state_t request
,
109 static int http_upgrade(http_t
*http
);
110 static int http_setup_ssl(http_t
*http
);
111 static void http_shutdown_ssl(http_t
*http
);
112 static int http_read_ssl(http_t
*http
, char *buf
, int len
);
113 static int http_write_ssl(http_t
*http
, const char *buf
, int len
);
115 static OSStatus
CDSAReadFunc(SSLConnectionRef connection
, void *data
, size_t *dataLength
);
116 static OSStatus
CDSAWriteFunc(SSLConnectionRef connection
, const void *data
, size_t *dataLength
);
117 # endif /* HAVE_CDSASSL */
118 #endif /* HAVE_SSL */
125 static const char *http_fields
[] =
142 "If-Unmodified-since",
155 static const char *days
[7] =
165 static const char *months
[12] =
183 * 'httpInitialize()' - Initialize the HTTP interface library and set the
184 * default HTTP proxy (if any).
191 struct timeval curtime
; /* Current time in microseconds */
192 int i
; /* Looping var */
193 unsigned char data
[1024]; /* Seed data */
194 #endif /* HAVE_LIBSSL */
197 WSADATA winsockdata
; /* WinSock data */
198 static int initialized
= 0;/* Has WinSock been initialized? */
202 WSAStartup(MAKEWORD(1,1), &winsockdata
);
203 #elif defined(HAVE_SIGSET)
204 sigset(SIGPIPE
, SIG_IGN
);
205 #elif defined(HAVE_SIGACTION)
206 struct sigaction action
; /* POSIX sigaction data */
210 * Ignore SIGPIPE signals...
213 memset(&action
, 0, sizeof(action
));
214 action
.sa_handler
= SIG_IGN
;
215 sigaction(SIGPIPE
, &action
, NULL
);
217 signal(SIGPIPE
, SIG_IGN
);
221 gnutls_global_init();
222 #endif /* HAVE_GNUTLS */
225 SSL_load_error_strings();
229 * Using the current time is a dubious random seed, but on some systems
230 * it is the best we can do (on others, this seed isn't even used...)
233 gettimeofday(&curtime
, NULL
);
234 srand(curtime
.tv_sec
+ curtime
.tv_usec
);
236 for (i
= 0; i
< sizeof(data
); i
++)
237 data
[i
] = rand(); /* Yes, this is a poor source of random data... */
239 RAND_seed(&data
, sizeof(data
));
240 #endif /* HAVE_LIBSSL */
245 * 'httpCheck()' - Check to see if there is a pending response from the server.
248 int /* O - 0 = no data, 1 = data available */
249 httpCheck(http_t
*http
) /* I - HTTP connection */
251 fd_set input
; /* Input set for select() */
252 struct timeval timeout
; /* Timeout */
256 * First see if there is data in the buffer...
266 * Then try doing a select() to poll the socket...
270 FD_SET(http
->fd
, &input
);
275 return (select(http
->fd
+ 1, &input
, NULL
, NULL
, &timeout
) > 0);
280 * 'httpClose()' - Close an HTTP connection...
284 httpClose(http_t
*http
) /* I - Connection to close */
291 http_shutdown_ssl(http
);
292 #endif /* HAVE_SSL */
295 closesocket(http
->fd
);
305 * 'httpConnect()' - Connect to a HTTP server.
308 http_t
* /* O - New HTTP connection */
309 httpConnect(const char *host
, /* I - Host to connect to */
310 int port
) /* I - Port number */
312 http_encryption_t encrypt
;/* Type of encryption to use */
316 * Set the default encryption status...
320 encrypt
= HTTP_ENCRYPT_ALWAYS
;
322 encrypt
= HTTP_ENCRYPT_IF_REQUESTED
;
324 return (httpConnectEncrypt(host
, port
, encrypt
));
329 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
332 http_t
* /* O - New HTTP connection */
333 httpConnectEncrypt(const char *host
, /* I - Host to connect to */
334 int port
, /* I - Port number */
335 http_encryption_t encrypt
)
336 /* I - Type of encryption to use */
338 int i
; /* Looping var */
339 http_t
*http
; /* New HTTP connection */
340 struct hostent
*hostaddr
; /* Host address data */
352 if ((hostaddr
= httpGetHostByName(host
)) == NULL
)
355 * This hack to make users that don't have a localhost entry in
356 * their hosts file or DNS happy...
359 if (strcasecmp(host
, "localhost") != 0)
361 else if ((hostaddr
= httpGetHostByName("127.0.0.1")) == NULL
)
366 * Verify that it is an IPv4 address (IPv6 support will come in CUPS 1.2...)
370 if ((hostaddr
->h_addrtype
!= AF_INET
|| hostaddr
->h_length
!= 4) &&
371 (hostaddr
->h_addrtype
!= AF_INET6
|| hostaddr
->h_length
!= 16))
374 if (hostaddr
->h_addrtype
!= AF_INET
|| hostaddr
->h_length
!= 4)
376 #endif /* AF_INET6 */
379 * Allocate memory for the structure...
382 http
= calloc(sizeof(http_t
), 1);
386 http
->version
= HTTP_1_1
;
388 http
->activity
= time(NULL
);
392 * Set the encryption status...
395 if (port
== 443) /* Always use encryption for https */
396 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
398 http
->encryption
= encrypt
;
401 * Loop through the addresses we have until one of them connects...
404 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
406 for (i
= 0; hostaddr
->h_addr_list
[i
]; i
++)
409 * Load the address...
412 httpAddrLoad(hostaddr
, port
, i
, &(http
->hostaddr
));
415 * Connect to the remote system...
418 if (!httpReconnect(http
))
423 * Return the new structure if we could connect; otherwise, bail out...
426 if (hostaddr
->h_addr_list
[i
])
437 * 'httpEncryption()' - Set the required encryption on the link.
440 int /* O - -1 on error, 0 on success */
441 httpEncryption(http_t
*http
, /* I - HTTP data */
442 http_encryption_t e
) /* I - New encryption preference */
448 http
->encryption
= e
;
450 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
451 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
452 return (httpReconnect(http
));
453 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
454 return (http_upgrade(http
));
458 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
462 #endif /* HAVE_SSL */
467 * 'httpReconnect()' - Reconnect to a HTTP server...
470 int /* O - 0 on success, non-zero on failure */
471 httpReconnect(http_t
*http
) /* I - HTTP data */
473 int val
; /* Socket option value */
477 http_shutdown_ssl(http
);
478 #endif /* HAVE_SSL */
481 * Close any previously open socket...
486 closesocket(http
->fd
);
492 * Create the socket and set options to allow reuse.
495 if ((http
->fd
= socket(http
->hostaddr
.addr
.sa_family
, SOCK_STREAM
, 0)) < 0)
498 http
->error
= WSAGetLastError();
502 http
->status
= HTTP_ERROR
;
507 fcntl(http
->fd
, F_SETFD
, FD_CLOEXEC
); /* Close this socket when starting *
508 * other processes... */
509 #endif /* FD_CLOEXEC */
512 setsockopt(http
->fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *)&val
, sizeof(val
));
516 setsockopt(http
->fd
, SOL_SOCKET
, SO_REUSEPORT
, &val
, sizeof(val
));
517 #endif /* SO_REUSEPORT */
520 * Using TCP_NODELAY improves responsiveness, especially on systems
521 * with a slow loopback interface... Since we write large buffers
522 * when sending print files and requests, there shouldn't be any
523 * performance penalty for this...
527 setsockopt(http
->fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
530 * Connect to the server...
533 if (connect(http
->fd
, (struct sockaddr
*)&(http
->hostaddr
),
534 sizeof(http
->hostaddr
)) < 0)
537 http
->error
= WSAGetLastError();
541 http
->status
= HTTP_ERROR
;
544 closesocket(http
->fd
);
555 http
->status
= HTTP_CONTINUE
;
558 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
561 * Always do encryption via SSL.
564 if (http_setup_ssl(http
) != 0)
567 closesocket(http
->fd
);
575 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
576 return (http_upgrade(http
));
577 #endif /* HAVE_SSL */
584 * 'httpGetSubField()' - Get a sub-field value.
587 char * /* O - Value or NULL */
588 httpGetSubField(http_t
*http
, /* I - HTTP data */
589 http_field_t field
, /* I - Field index */
590 const char *name
, /* I - Name of sub-field */
591 char *value
) /* O - Value string */
593 const char *fptr
; /* Pointer into field */
594 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
595 *ptr
; /* Pointer into string buffer */
599 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
600 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
601 name
== NULL
|| value
== NULL
)
604 for (fptr
= http
->fields
[field
]; *fptr
;)
607 * Skip leading whitespace...
610 while (isspace(*fptr
))
620 * Get the sub-field name...
624 *fptr
&& *fptr
!= '=' && !isspace(*fptr
) && ptr
< (temp
+ sizeof(temp
) - 1);
630 * Skip trailing chars up to the '='...
633 while (*fptr
&& *fptr
!= '=')
640 * Skip = and leading whitespace...
645 while (isspace(*fptr
))
651 * Read quoted string...
654 for (ptr
= value
, fptr
++;
655 *fptr
&& *fptr
!= '\"' && ptr
< (value
+ HTTP_MAX_VALUE
- 1);
660 while (*fptr
&& *fptr
!= '\"')
669 * Read unquoted string...
673 *fptr
&& !isspace(*fptr
) && *fptr
!= ',' && ptr
< (value
+ HTTP_MAX_VALUE
- 1);
678 while (*fptr
&& !isspace(*fptr
) && *fptr
!= ',')
683 * See if this is the one...
686 if (strcmp(name
, temp
) == 0)
697 * 'httpSetField()' - Set the value of an HTTP header.
701 httpSetField(http_t
*http
, /* I - HTTP data */
702 http_field_t field
, /* I - Field index */
703 const char *value
) /* I - Value */
706 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
707 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
711 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
716 * 'httpDelete()' - Send a DELETE request to the server.
719 int /* O - Status of call (0 = success) */
720 httpDelete(http_t
*http
, /* I - HTTP data */
721 const char *uri
) /* I - URI to delete */
723 return (http_send(http
, HTTP_DELETE
, uri
));
728 * 'httpGet()' - Send a GET request to the server.
731 int /* O - Status of call (0 = success) */
732 httpGet(http_t
*http
, /* I - HTTP data */
733 const char *uri
) /* I - URI to get */
735 return (http_send(http
, HTTP_GET
, uri
));
740 * 'httpHead()' - Send a HEAD request to the server.
743 int /* O - Status of call (0 = success) */
744 httpHead(http_t
*http
, /* I - HTTP data */
745 const char *uri
) /* I - URI for head */
747 return (http_send(http
, HTTP_HEAD
, uri
));
752 * 'httpOptions()' - Send an OPTIONS request to the server.
755 int /* O - Status of call (0 = success) */
756 httpOptions(http_t
*http
, /* I - HTTP data */
757 const char *uri
) /* I - URI for options */
759 return (http_send(http
, HTTP_OPTIONS
, uri
));
764 * 'httpPost()' - Send a POST request to the server.
767 int /* O - Status of call (0 = success) */
768 httpPost(http_t
*http
, /* I - HTTP data */
769 const char *uri
) /* I - URI for post */
773 return (http_send(http
, HTTP_POST
, uri
));
778 * 'httpPut()' - Send a PUT request to the server.
781 int /* O - Status of call (0 = success) */
782 httpPut(http_t
*http
, /* I - HTTP data */
783 const char *uri
) /* I - URI to put */
787 return (http_send(http
, HTTP_PUT
, uri
));
792 * 'httpTrace()' - Send an TRACE request to the server.
795 int /* O - Status of call (0 = success) */
796 httpTrace(http_t
*http
, /* I - HTTP data */
797 const char *uri
) /* I - URI for trace */
799 return (http_send(http
, HTTP_TRACE
, uri
));
804 * 'httpFlush()' - Flush data from a HTTP connection.
808 httpFlush(http_t
*http
) /* I - HTTP data */
810 char buffer
[8192]; /* Junk buffer */
813 while (httpRead(http
, buffer
, sizeof(buffer
)) > 0);
818 * 'httpRead()' - Read data from a HTTP connection.
821 int /* O - Number of bytes read */
822 httpRead(http_t
*http
, /* I - HTTP data */
823 char *buffer
, /* I - Buffer for data */
824 int length
) /* I - Maximum number of bytes */
826 int bytes
; /* Bytes read */
827 char len
[32]; /* Length string */
830 DEBUG_printf(("httpRead(%p, %p, %d)\n", http
, buffer
, length
));
832 if (http
== NULL
|| buffer
== NULL
)
835 http
->activity
= time(NULL
);
840 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
841 http
->data_remaining
<= 0)
843 DEBUG_puts("httpRead: Getting chunk length...");
845 if (httpGets(len
, sizeof(len
), http
) == NULL
)
847 DEBUG_puts("httpRead: Could not get length!");
851 http
->data_remaining
= strtol(len
, NULL
, 16);
852 if (http
->data_remaining
< 0)
854 DEBUG_puts("httpRead: Negative chunk length!");
859 DEBUG_printf(("httpRead: data_remaining = %d\n", http
->data_remaining
));
861 if (http
->data_remaining
<= 0)
864 * A zero-length chunk ends a transfer; unless we are reading POST
868 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
869 httpGets(len
, sizeof(len
), http
);
871 if (http
->state
== HTTP_POST_RECV
)
874 http
->state
= HTTP_WAITING
;
878 else if (length
> http
->data_remaining
)
879 length
= http
->data_remaining
;
881 if (http
->used
== 0 && length
<= 256)
884 * Buffer small reads for better performance...
887 if (http
->data_remaining
> sizeof(http
->buffer
))
888 bytes
= sizeof(http
->buffer
);
890 bytes
= http
->data_remaining
;
894 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
896 #endif /* HAVE_SSL */
898 DEBUG_printf(("httpRead: reading %d bytes from socket into buffer...\n",
901 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
903 DEBUG_printf(("httpRead: read %d bytes from socket into buffer...\n",
912 http
->error
= WSAGetLastError();
928 if (length
> http
->used
)
933 DEBUG_printf(("httpRead: grabbing %d bytes from input buffer...\n", bytes
));
935 memcpy(buffer
, http
->buffer
, length
);
936 http
->used
-= length
;
939 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
943 bytes
= http_read_ssl(http
, buffer
, length
);
944 #endif /* HAVE_SSL */
947 DEBUG_printf(("httpRead: reading %d bytes from socket...\n", length
));
948 bytes
= recv(http
->fd
, buffer
, length
, 0);
949 DEBUG_printf(("httpRead: read %d bytes from socket...\n", bytes
));
953 http
->data_remaining
-= bytes
;
957 http
->error
= WSAGetLastError();
966 if (http
->data_remaining
== 0)
968 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
969 httpGets(len
, sizeof(len
), http
);
971 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
973 if (http
->state
== HTTP_POST_RECV
)
976 http
->state
= HTTP_WAITING
;
983 printf("httpRead: Read %d bytes:\n", bytes
);
984 for (i
= 0; i
< bytes
; i
+= 16)
988 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
989 printf(" %02X", buffer
[i
+ j
] & 255);
998 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1000 ch
= buffer
[i
+ j
] & 255;
1002 if (ch
< ' ' || ch
== 127)
1017 * 'httpWrite()' - Write data to a HTTP connection.
1020 int /* O - Number of bytes written */
1021 httpWrite(http_t
*http
, /* I - HTTP data */
1022 const char *buffer
, /* I - Buffer for data */
1023 int length
) /* I - Number of bytes to write */
1025 int tbytes
, /* Total bytes sent */
1026 bytes
; /* Bytes sent */
1029 if (http
== NULL
|| buffer
== NULL
)
1032 http
->activity
= time(NULL
);
1034 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1036 if (httpPrintf(http
, "%x\r\n", length
) < 0)
1042 * A zero-length chunk ends a transfer; unless we are sending POST
1046 DEBUG_puts("httpWrite: changing states...");
1048 if (http
->state
== HTTP_POST_RECV
)
1050 else if (http
->state
== HTTP_PUT_RECV
)
1051 http
->state
= HTTP_STATUS
;
1053 http
->state
= HTTP_WAITING
;
1055 if (httpPrintf(http
, "\r\n") < 0)
1068 bytes
= http_write_ssl(http
, buffer
, length
);
1070 #endif /* HAVE_SSL */
1071 bytes
= send(http
->fd
, buffer
, length
, 0);
1076 if (WSAGetLastError() != http
->error
)
1078 http
->error
= WSAGetLastError();
1084 else if (errno
!= http
->error
)
1086 http
->error
= errno
;
1091 DEBUG_puts("httpWrite: error writing data...\n");
1099 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1100 http
->data_remaining
-= bytes
;
1103 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1104 if (httpPrintf(http
, "\r\n") < 0)
1107 if (http
->data_remaining
== 0 && http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1110 * Finished with the transfer; unless we are sending POST data, go idle...
1113 DEBUG_puts("httpWrite: changing states...");
1115 if (http
->state
== HTTP_POST_RECV
)
1118 http
->state
= HTTP_WAITING
;
1124 printf("httpWrite: wrote %d bytes: \n", tbytes
);
1125 for (i
= 0, buffer
-= tbytes
; i
< tbytes
; i
+= 16)
1129 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
1130 printf(" %02X", buffer
[i
+ j
] & 255);
1139 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
1141 ch
= buffer
[i
+ j
] & 255;
1143 if (ch
< ' ' || ch
== 127)
1157 * 'httpGets()' - Get a line of text from a HTTP connection.
1160 char * /* O - Line or NULL */
1161 httpGets(char *line
, /* I - Line to read into */
1162 int length
, /* I - Max length of buffer */
1163 http_t
*http
) /* I - HTTP data */
1165 char *lineptr
, /* Pointer into line */
1166 *bufptr
, /* Pointer into input buffer */
1167 *bufend
; /* Pointer to end of buffer */
1168 int bytes
; /* Number of bytes read */
1171 DEBUG_printf(("httpGets(%p, %d, %p)\n", line
, length
, http
));
1173 if (http
== NULL
|| line
== NULL
)
1177 * Pre-scan the buffer and see if there is a newline in there...
1188 bufptr
= http
->buffer
;
1189 bufend
= http
->buffer
+ http
->used
;
1191 while (bufptr
< bufend
)
1192 if (*bufptr
== 0x0a)
1197 if (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
)
1200 * No newline; see if there is more data to be read...
1205 bytes
= http_read_ssl(http
, bufend
, HTTP_MAX_BUFFER
- http
->used
);
1207 #endif /* HAVE_SSL */
1208 bytes
= recv(http
->fd
, bufend
, HTTP_MAX_BUFFER
- http
->used
, 0);
1213 * Nope, can't get a line this time...
1217 if (WSAGetLastError() != http
->error
)
1219 http
->error
= WSAGetLastError();
1223 DEBUG_printf(("httpGets(): recv() error %d!\n", WSAGetLastError()));
1227 else if (errno
!= http
->error
)
1229 http
->error
= errno
;
1233 DEBUG_printf(("httpGets(): recv() error %d!\n", errno
));
1238 else if (bytes
== 0)
1241 http
->error
= EPIPE
;
1247 * Yup, update the amount used and the end pointer...
1250 http
->used
+= bytes
;
1255 while (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
);
1257 http
->activity
= time(NULL
);
1260 * Read a line from the buffer...
1264 bufptr
= http
->buffer
;
1268 while (bufptr
< bufend
&& bytes
< length
)
1272 if (*bufptr
== 0x0a)
1277 else if (*bufptr
== 0x0d)
1280 *lineptr
++ = *bufptr
++;
1287 http
->used
-= bytes
;
1289 memmove(http
->buffer
, bufptr
, http
->used
);
1291 DEBUG_printf(("httpGets(): Returning \"%s\"\n", line
));
1295 DEBUG_puts("httpGets(): No new line available!");
1302 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1305 int /* O - Number of bytes written */
1306 httpPrintf(http_t
*http
, /* I - HTTP data */
1307 const char *format
, /* I - printf-style format string */
1308 ...) /* I - Additional args as needed */
1310 int bytes
, /* Number of bytes to write */
1311 nbytes
, /* Number of bytes written */
1312 tbytes
; /* Number of bytes all together */
1313 char buf
[HTTP_MAX_BUFFER
], /* Buffer for formatted string */
1314 *bufptr
; /* Pointer into buffer */
1315 va_list ap
; /* Variable argument pointer */
1318 va_start(ap
, format
);
1319 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1322 DEBUG_printf(("httpPrintf: %s", buf
));
1324 for (tbytes
= 0, bufptr
= buf
; tbytes
< bytes
; tbytes
+= nbytes
, bufptr
+= nbytes
)
1328 nbytes
= http_write_ssl(http
, bufptr
, bytes
- tbytes
);
1330 #endif /* HAVE_SSL */
1331 nbytes
= send(http
->fd
, bufptr
, bytes
- tbytes
, 0);
1338 if (WSAGetLastError() != http
->error
)
1340 http
->error
= WSAGetLastError();
1346 else if (errno
!= http
->error
)
1348 http
->error
= errno
;
1362 * 'httpStatus()' - Return a short string describing a HTTP status code.
1365 const char * /* O - String or NULL */
1366 httpStatus(http_status_t status
) /* I - HTTP status code */
1370 case HTTP_CONTINUE
:
1371 return ("Continue");
1372 case HTTP_SWITCHING_PROTOCOLS
:
1373 return ("Switching Protocols");
1378 case HTTP_ACCEPTED
:
1379 return ("Accepted");
1380 case HTTP_NO_CONTENT
:
1381 return ("No Content");
1382 case HTTP_NOT_MODIFIED
:
1383 return ("Not Modified");
1384 case HTTP_BAD_REQUEST
:
1385 return ("Bad Request");
1386 case HTTP_UNAUTHORIZED
:
1387 return ("Unauthorized");
1388 case HTTP_FORBIDDEN
:
1389 return ("Forbidden");
1390 case HTTP_NOT_FOUND
:
1391 return ("Not Found");
1392 case HTTP_REQUEST_TOO_LARGE
:
1393 return ("Request Entity Too Large");
1394 case HTTP_URI_TOO_LONG
:
1395 return ("URI Too Long");
1396 case HTTP_UPGRADE_REQUIRED
:
1397 return ("Upgrade Required");
1398 case HTTP_NOT_IMPLEMENTED
:
1399 return ("Not Implemented");
1400 case HTTP_NOT_SUPPORTED
:
1401 return ("Not Supported");
1409 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
1412 const char * /* O - Date/time string */
1413 httpGetDateString(time_t t
) /* I - UNIX time */
1416 static char datetime
[256];
1420 snprintf(datetime
, sizeof(datetime
), "%s, %02d %s %d %02d:%02d:%02d GMT",
1421 days
[tdate
->tm_wday
], tdate
->tm_mday
, months
[tdate
->tm_mon
],
1422 tdate
->tm_year
+ 1900, tdate
->tm_hour
, tdate
->tm_min
, tdate
->tm_sec
);
1429 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
1432 time_t /* O - UNIX time */
1433 httpGetDateTime(const char *s
) /* I - Date/time string */
1435 int i
; /* Looping var */
1436 struct tm tdate
; /* Time/date structure */
1437 char mon
[16]; /* Abbreviated month name */
1438 int day
, year
; /* Day of month and year */
1439 int hour
, min
, sec
; /* Time */
1442 if (sscanf(s
, "%*s%d%15s%d%d:%d:%d", &day
, mon
, &year
, &hour
, &min
, &sec
) < 6)
1445 for (i
= 0; i
< 12; i
++)
1446 if (strcasecmp(mon
, months
[i
]) == 0)
1453 tdate
.tm_mday
= day
;
1454 tdate
.tm_year
= year
- 1900;
1455 tdate
.tm_hour
= hour
;
1460 return (mktime(&tdate
));
1465 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1468 http_status_t
/* O - HTTP status */
1469 httpUpdate(http_t
*http
) /* I - HTTP data */
1471 char line
[1024], /* Line from connection... */
1472 *value
; /* Pointer to value on line */
1473 http_field_t field
; /* Field index */
1474 int major
, minor
; /* HTTP version numbers */
1475 http_status_t status
; /* Authorization status */
1478 DEBUG_printf(("httpUpdate(%p)\n", http
));
1481 * If we haven't issued any commands, then there is nothing to "update"...
1484 if (http
->state
== HTTP_WAITING
)
1485 return (HTTP_CONTINUE
);
1488 * Grab all of the lines we can from the connection...
1491 while (httpGets(line
, sizeof(line
), http
) != NULL
)
1495 if (line
[0] == '\0')
1498 * Blank line means the start of the data section (if any). Return
1499 * the result code, too...
1501 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
1502 * Instead, we just return HTTP_CONTINUE to the caller and keep on
1506 if (http
->status
== HTTP_CONTINUE
)
1507 return (http
->status
);
1510 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
1512 if (http_setup_ssl(http
) != 0)
1515 closesocket(http
->fd
);
1520 return (HTTP_ERROR
);
1523 return (HTTP_CONTINUE
);
1525 else if (http
->status
== HTTP_UPGRADE_REQUIRED
&&
1526 http
->encryption
!= HTTP_ENCRYPT_NEVER
)
1527 http
->encryption
= HTTP_ENCRYPT_REQUIRED
;
1528 #endif /* HAVE_SSL */
1530 httpGetLength(http
);
1532 switch (http
->state
)
1536 case HTTP_POST_RECV
:
1542 http
->state
= HTTP_WAITING
;
1546 return (http
->status
);
1548 else if (strncmp(line
, "HTTP/", 5) == 0)
1551 * Got the beginning of a response...
1554 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, (int *)&status
) != 3)
1555 return (HTTP_ERROR
);
1557 http
->version
= (http_version_t
)(major
* 100 + minor
);
1558 http
->status
= status
;
1560 else if ((value
= strchr(line
, ':')) != NULL
)
1567 while (isspace(*value
))
1571 * Be tolerants of servers that send unknown attribute fields...
1574 if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
1576 DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line
));
1580 httpSetField(http
, field
, value
);
1584 http
->status
= HTTP_ERROR
;
1585 return (HTTP_ERROR
);
1590 * See if there was an error...
1595 http
->status
= HTTP_ERROR
;
1596 return (HTTP_ERROR
);
1600 * If we haven't already returned, then there is nothing new...
1603 return (HTTP_CONTINUE
);
1608 * 'httpDecode64()' - Base64-decode a string.
1611 char * /* O - Decoded string */
1612 httpDecode64(char *out
, /* I - String to write to */
1613 const char *in
) /* I - String to read from */
1615 int pos
, /* Bit position */
1616 base64
; /* Value of this character */
1617 char *outptr
; /* Output pointer */
1620 for (outptr
= out
, pos
= 0; *in
!= '\0'; in
++)
1623 * Decode this character into a number from 0 to 63...
1626 if (*in
>= 'A' && *in
<= 'Z')
1628 else if (*in
>= 'a' && *in
<= 'z')
1629 base64
= *in
- 'a' + 26;
1630 else if (*in
>= '0' && *in
<= '9')
1631 base64
= *in
- '0' + 52;
1632 else if (*in
== '+')
1634 else if (*in
== '/')
1636 else if (*in
== '=')
1642 * Store the result in the appropriate chars...
1648 *outptr
= base64
<< 2;
1652 *outptr
++ |= (base64
>> 4) & 3;
1653 *outptr
= (base64
<< 4) & 255;
1657 *outptr
++ |= (base64
>> 2) & 15;
1658 *outptr
= (base64
<< 6) & 255;
1662 *outptr
++ |= base64
;
1671 * Return the decoded string...
1679 * 'httpEncode64()' - Base64-encode a string.
1682 char * /* O - Encoded string */
1683 httpEncode64(char *out
, /* I - String to write to */
1684 const char *in
) /* I - String to read from */
1686 char *outptr
; /* Output pointer */
1687 static char base64
[] = /* Base64 characters... */
1689 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1690 "abcdefghijklmnopqrstuvwxyz"
1696 for (outptr
= out
; *in
!= '\0'; in
++)
1699 * Encode the up to 3 characters as 4 Base64 numbers...
1702 *outptr
++ = base64
[in
[0] >> 2];
1703 *outptr
++ = base64
[((in
[0] << 4) | (in
[1] >> 4)) & 63];
1712 *outptr
++ = base64
[((in
[0] << 2) | (in
[1] >> 6)) & 63];
1718 *outptr
++ = base64
[in
[0] & 63];
1725 * Return the encoded string...
1733 * 'httpGetLength()' - Get the amount of data remaining from the
1734 * content-length or transfer-encoding fields.
1737 int /* O - Content length */
1738 httpGetLength(http_t
*http
) /* I - HTTP data */
1740 DEBUG_printf(("httpGetLength(%p)\n", http
));
1742 if (strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked") == 0)
1744 DEBUG_puts("httpGetLength: chunked request!");
1746 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
1747 http
->data_remaining
= 0;
1751 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1754 * The following is a hack for HTTP servers that don't send a
1755 * content-length or transfer-encoding field...
1757 * If there is no content-length then the connection must close
1758 * after the transfer is complete...
1761 if (http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] == '\0')
1762 http
->data_remaining
= 2147483647;
1764 http
->data_remaining
= atoi(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
]);
1766 DEBUG_printf(("httpGetLength: content_length = %d\n", http
->data_remaining
));
1769 return (http
->data_remaining
);
1774 * 'http_field()' - Return the field index for a field name.
1777 static http_field_t
/* O - Field index */
1778 http_field(const char *name
) /* I - String name */
1780 int i
; /* Looping var */
1783 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
1784 if (strcasecmp(name
, http_fields
[i
]) == 0)
1785 return ((http_field_t
)i
);
1787 return (HTTP_FIELD_UNKNOWN
);
1792 * 'http_send()' - Send a request with all fields and the trailing blank line.
1795 static int /* O - 0 on success, non-zero on error */
1796 http_send(http_t
*http
, /* I - HTTP data */
1797 http_state_t request
, /* I - Request code */
1798 const char *uri
) /* I - URI */
1800 int i
; /* Looping var */
1801 char *ptr
, /* Pointer in buffer */
1802 buf
[1024]; /* Encoded URI buffer */
1803 static const char *codes
[] = /* Request code strings */
1819 static const char *hex
= "0123456789ABCDEF";
1823 if (http
== NULL
|| uri
== NULL
)
1827 * Encode the URI as needed...
1830 for (ptr
= buf
; *uri
!= '\0' && ptr
< (buf
+ sizeof(buf
) - 1); uri
++)
1831 if (*uri
<= ' ' || *uri
>= 127)
1833 if (ptr
< (buf
+ sizeof(buf
) - 1))
1835 if (ptr
< (buf
+ sizeof(buf
) - 1))
1836 *ptr
++ = hex
[(*uri
>> 4) & 15];
1837 if (ptr
< (buf
+ sizeof(buf
) - 1))
1838 *ptr
++ = hex
[*uri
& 15];
1846 * See if we had an error the last time around; if so, reconnect...
1849 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
1850 httpReconnect(http
);
1853 * Send the request header...
1856 http
->state
= request
;
1857 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
1860 http
->status
= HTTP_CONTINUE
;
1863 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
1865 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
1866 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
1868 #endif /* HAVE_SSL */
1870 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
1872 http
->status
= HTTP_ERROR
;
1876 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
1877 if (http
->fields
[i
][0] != '\0')
1879 DEBUG_printf(("%s: %s\n", http_fields
[i
], http
->fields
[i
]));
1881 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], http
->fields
[i
]) < 1)
1883 http
->status
= HTTP_ERROR
;
1888 if (httpPrintf(http
, "\r\n") < 1)
1890 http
->status
= HTTP_ERROR
;
1894 httpClearFields(http
);
1902 * 'http_upgrade()' - Force upgrade to TLS encryption.
1905 static int /* O - Status of connection */
1906 http_upgrade(http_t
*http
) /* I - HTTP data */
1908 int ret
; /* Return value */
1909 http_t myhttp
; /* Local copy of HTTP data */
1912 DEBUG_printf(("http_upgrade(%p)\n", http
));
1915 * Copy the HTTP data to a local variable so we can do the OPTIONS
1916 * request without interfering with the existing request data...
1919 memcpy(&myhttp
, http
, sizeof(myhttp
));
1922 * Send an OPTIONS request to the server, requiring SSL or TLS
1923 * encryption on the link...
1926 httpClearFields(&myhttp
);
1927 httpSetField(&myhttp
, HTTP_FIELD_CONNECTION
, "upgrade");
1928 httpSetField(&myhttp
, HTTP_FIELD_UPGRADE
, "TLS/1.0, SSL/2.0, SSL/3.0");
1930 if ((ret
= httpOptions(&myhttp
, "*")) == 0)
1933 * Wait for the secure connection...
1936 while (httpUpdate(&myhttp
) == HTTP_CONTINUE
);
1942 * Copy the HTTP data back over, if any...
1945 http
->fd
= myhttp
.fd
;
1946 http
->error
= myhttp
.error
;
1947 http
->activity
= myhttp
.activity
;
1948 http
->status
= myhttp
.status
;
1949 http
->version
= myhttp
.version
;
1950 http
->keep_alive
= myhttp
.keep_alive
;
1951 http
->used
= myhttp
.used
;
1954 memcpy(http
->buffer
, myhttp
.buffer
, http
->used
);
1956 http
->auth_type
= myhttp
.auth_type
;
1957 http
->nonce_count
= myhttp
.nonce_count
;
1959 memcpy(http
->nonce
, myhttp
.nonce
, sizeof(http
->nonce
));
1961 http
->tls
= myhttp
.tls
;
1962 http
->encryption
= myhttp
.encryption
;
1965 * See if we actually went secure...
1971 * Server does not support HTTP upgrade...
1974 DEBUG_puts("Server does not support HTTP upgrade!");
1977 closesocket(http
->fd
);
1992 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
1995 static int /* O - Status of connection */
1996 http_setup_ssl(http_t
*http
) /* I - HTTP data */
1999 SSL_CTX
*context
; /* Context for encryption */
2000 SSL
*conn
; /* Connection for encryption */
2001 # elif defined(HAVE_GNUTLS)
2002 http_tls_t
*conn
; /* TLS session object */
2003 gnutls_certificate_client_credentials
*credentials
;
2004 /* TLS credentials */
2005 # elif defined(HAVE_CDSASSL)
2006 SSLContextRef conn
; /* Context for encryption */
2007 OSStatus error
; /* Error info */
2008 # endif /* HAVE_LIBSSL */
2012 context
= SSL_CTX_new(SSLv23_client_method());
2013 conn
= SSL_new(context
);
2015 SSL_set_fd(conn
, http
->fd
);
2016 if (SSL_connect(conn
) != 1)
2018 SSL_CTX_free(context
);
2022 http
->error
= WSAGetLastError();
2024 http
->error
= errno
;
2026 http
->status
= HTTP_ERROR
;
2028 return (HTTP_ERROR
);
2031 # elif defined(HAVE_GNUTLS)
2032 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
2036 http
->error
= errno
;
2037 http
->status
= HTTP_ERROR
;
2042 credentials
= (gnutls_certificate_client_credentials
*)
2043 malloc(sizeof(gnutls_certificate_client_credentials
));
2044 if (credentials
== NULL
)
2048 http
->error
= errno
;
2049 http
->status
= HTTP_ERROR
;
2054 gnutls_certificate_allocate_credentials(credentials
);
2056 gnutls_init(&(conn
->session
), GNUTLS_CLIENT
);
2057 gnutls_set_default_priority(conn
->session
);
2058 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
2059 gnutls_transport_set_ptr(conn
->session
, http
->fd
);
2061 if ((gnutls_handshake(conn
->session
)) != GNUTLS_E_SUCCESS
)
2063 http
->error
= errno
;
2064 http
->status
= HTTP_ERROR
;
2069 conn
->credentials
= credentials
;
2071 # elif defined(HAVE_CDSASSL)
2072 error
= SSLNewContext(false, &conn
);
2075 error
= SSLSetIOFuncs(conn
, CDSAReadFunc
, CDSAWriteFunc
);
2078 error
= SSLSetConnection(conn
, (SSLConnectionRef
)http
->fd
);
2081 error
= SSLSetAllowsExpiredCerts(conn
, true);
2084 error
= SSLSetAllowsAnyRoot(conn
, true);
2087 error
= SSLHandshake(conn
);
2091 http
->error
= error
;
2092 http
->status
= HTTP_ERROR
;
2094 SSLDisposeContext(conn
);
2100 # endif /* HAVE_CDSASSL */
2108 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
2112 http_shutdown_ssl(http_t
*http
) /* I - HTTP data */
2115 SSL_CTX
*context
; /* Context for encryption */
2116 SSL
*conn
; /* Connection for encryption */
2119 conn
= (SSL
*)(http
->tls
);
2120 context
= SSL_get_SSL_CTX(conn
);
2123 SSL_CTX_free(context
);
2126 # elif defined(HAVE_GNUTLS)
2127 http_tls_t
*conn
; /* Encryption session */
2128 gnutls_certificate_client_credentials
*credentials
;
2129 /* TLS credentials */
2132 conn
= (http_tls_t
*)(http
->tls
);
2133 credentials
= (gnutls_certificate_client_credentials
*)(conn
->credentials
);
2135 gnutls_bye(conn
->session
, GNUTLS_SHUT_RDWR
);
2136 gnutls_deinit(conn
->session
);
2137 gnutls_certificate_free_credentials(*credentials
);
2141 # elif defined(HAVE_CDSASSL)
2142 SSLClose((SSLContextRef
)http
->tls
);
2143 SSLDisposeContext((SSLContextRef
)http
->tls
);
2144 # endif /* HAVE_LIBSSL */
2151 * 'http_read_ssl()' - Read from a SSL/TLS connection.
2154 static int /* O - Bytes read */
2155 http_read_ssl(http_t
*http
, /* I - HTTP data */
2156 char *buf
, /* I - Buffer to store data */
2157 int len
) /* I - Length of buffer */
2159 # if defined(HAVE_LIBSSL)
2160 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
2162 # elif defined(HAVE_GNUTLS)
2163 return (gnutls_record_recv(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
2165 # elif defined(HAVE_CDSASSL)
2166 OSStatus error
; /* Error info */
2167 size_t processed
; /* Number of bytes processed */
2170 error
= SSLRead((SSLContextRef
)http
->tls
, buf
, len
, &processed
);
2176 http
->error
= error
;
2180 # endif /* HAVE_LIBSSL */
2185 * 'http_write_ssl()' - Write to a SSL/TLS connection.
2188 static int /* O - Bytes written */
2189 http_write_ssl(http_t
*http
, /* I - HTTP data */
2190 const char *buf
, /* I - Buffer holding data */
2191 int len
) /* I - Length of buffer */
2193 # if defined(HAVE_LIBSSL)
2194 return (SSL_write((SSL
*)(http
->tls
), buf
, len
));
2196 # elif defined(HAVE_GNUTLS)
2197 return (gnutls_record_send(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
2198 # elif defined(HAVE_CDSASSL)
2199 OSStatus error
; /* Error info */
2200 size_t processed
; /* Number of bytes processed */
2203 error
= SSLWrite((SSLContextRef
)http
->tls
, buf
, len
, &processed
);
2209 http
->error
= error
;
2212 # endif /* HAVE_LIBSSL */
2216 # if defined(HAVE_CDSASSL)
2218 * 'CDSAReadFunc()' - Read function for CDSA decryption code.
2221 static OSStatus
/* O - -1 on error, 0 on success */
2222 CDSAReadFunc(SSLConnectionRef connection
, /* I - SSL/TLS connection */
2223 void *data
, /* I - Data buffer */
2224 size_t *dataLength
) /* IO - Number of bytes */
2226 ssize_t bytes
; /* Number of bytes read */
2229 bytes
= recv((int)connection
, data
, *dataLength
, 0);
2232 *dataLength
= bytes
;
2241 * 'CDSAWriteFunc()' - Write function for CDSA encryption code.
2244 static OSStatus
/* O - -1 on error, 0 on success */
2245 CDSAWriteFunc(SSLConnectionRef connection
, /* I - SSL/TLS connection */
2246 const void *data
, /* I - Data buffer */
2247 size_t *dataLength
) /* IO - Number of bytes */
2252 bytes
= write((int)connection
, data
, *dataLength
);
2255 *dataLength
= bytes
;
2261 # endif /* HAVE_CDSASSL */
2262 #endif /* HAVE_SSL */
2266 * End of "$Id: http.c,v 1.82.2.24 2003/01/24 19:19:42 mike Exp $".