2 * "$Id: http.c 7661 2008-06-16 21:46:51Z mike $"
4 * HTTP routines for the Common UNIX Printing System (CUPS).
6 * Copyright 2007-2008 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * This file contains Kerberos support code, copyright 2006 by
12 * These coded instructions, statements, and computer programs are the
13 * property of Apple Inc. and are protected by Federal copyright
14 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
15 * which should have been included with this file. If this file is
16 * file is missing or damaged, see the license at "http://www.cups.org/".
18 * This file is subject to the Apple OS-Developed Software exception.
22 * _httpBIOMethods() - Get the OpenSSL BIO methods for HTTP connections.
23 * httpBlocking() - Set blocking/non-blocking behavior on a connection.
24 * httpCheck() - Check to see if there is a pending response from
26 * httpClearCookie() - Clear the cookie value(s).
27 * httpClearFields() - Clear HTTP request fields.
28 * httpClose() - Close an HTTP connection...
29 * httpConnect() - Connect to a HTTP server.
30 * httpConnectEncrypt() - Connect to a HTTP server using encryption.
31 * httpDelete() - Send a DELETE request to the server.
32 * httpEncryption() - Set the required encryption on the link.
33 * httpError() - Get the last error on a connection.
34 * httpFlush() - Flush data from a HTTP connection.
35 * httpFlushWrite() - Flush data in write buffer.
36 * httpGet() - Send a GET request to the server.
37 * httpGetAuthString() - Get the current authorization string.
38 * httpGetBlocking() - Get the blocking/non-block state of a connection.
39 * httpGetCookie() - Get any cookie data from the response.
40 * httpGetFd() - Get the file descriptor associated with a
42 * httpGetField() - Get a field value from a request/response.
43 * httpGetLength() - Get the amount of data remaining from the
44 * content-length or transfer-encoding fields.
45 * httpGetLength2() - Get the amount of data remaining from the
46 * content-length or transfer-encoding fields.
47 * httpGetStatus() - Get the status of the last HTTP request.
48 * httpGetSubField() - Get a sub-field value.
49 * httpGets() - Get a line of text from a HTTP connection.
50 * httpHead() - Send a HEAD request to the server.
51 * httpInitialize() - Initialize the HTTP interface library and set the
52 * default HTTP proxy (if any).
53 * httpOptions() - Send an OPTIONS request to the server.
54 * httpPost() - Send a POST request to the server.
55 * httpPrintf() - Print a formatted string to a HTTP connection.
56 * httpPut() - Send a PUT request to the server.
57 * httpRead() - Read data from a HTTP connection.
58 * httpRead2() - Read data from a HTTP connection.
59 * _httpReadCDSA() - Read function for the CDSA library.
60 * _httpReadGNUTLS() - Read function for the GNU TLS library.
61 * httpReconnect() - Reconnect to a HTTP server...
62 * httpSetAuthString() - Set the current authorization string.
63 * httpSetCookie() - Set the cookie value(s)...
64 * httpSetExpect() - Set the Expect: header in a request.
65 * httpSetField() - Set the value of an HTTP header.
66 * httpSetLength() - Set the content-length and transfer-encoding.
67 * httpTrace() - Send an TRACE request to the server.
68 * httpUpdate() - Update the current HTTP state for incoming data.
69 * httpWait() - Wait for data available on a connection.
70 * httpWrite() - Write data to a HTTP connection.
71 * httpWrite2() - Write data to a HTTP connection.
72 * _httpWriteCDSA() - Write function for the CDSA library.
73 * _httpWriteGNUTLS() - Write function for the GNU TLS library.
74 * http_bio_ctrl() - Control the HTTP connection.
75 * http_bio_free() - Free OpenSSL data.
76 * http_bio_new() - Initialize an OpenSSL BIO structure.
77 * http_bio_puts() - Send a string for OpenSSL.
78 * http_bio_read() - Read data for OpenSSL.
79 * http_bio_write() - Write data for OpenSSL.
80 * http_debug_hex() - Do a hex dump of a buffer.
81 * http_field() - Return the field index for a field name.
82 * http_read_ssl() - Read from a SSL/TLS connection.
83 * http_send() - Send a request with all fields and the trailing
85 * http_setup_ssl() - Set up SSL/TLS on a connection.
86 * http_shutdown_ssl() - Shut down SSL/TLS on a connection.
87 * http_upgrade() - Force upgrade to TLS encryption.
88 * http_wait() - Wait for data available on a connection.
89 * http_write() - Write data to a connection.
90 * http_write_ssl() - Write to a SSL/TLS connection.
94 * Include necessary headers...
97 #include "http-private.h"
105 # include <sys/time.h>
106 # include <sys/resource.h>
109 # include <sys/poll.h>
110 #endif /* HAVE_POLL */
114 * Some operating systems have done away with the Fxxxx constants for
115 * the fcntl() call; this works around that "feature"...
119 # define FNONBLK O_NONBLOCK
120 #endif /* !FNONBLK */
128 static void http_debug_hex(const char *prefix
, const char *buffer
,
131 static http_field_t
http_field(const char *name
);
132 static int http_send(http_t
*http
, http_state_t request
,
134 static int http_wait(http_t
*http
, int msec
, int usessl
);
135 static int http_write(http_t
*http
, const char *buffer
,
137 static int http_write_chunk(http_t
*http
, const char *buffer
,
140 static int http_read_ssl(http_t
*http
, char *buf
, int len
);
141 static int http_setup_ssl(http_t
*http
);
142 static void http_shutdown_ssl(http_t
*http
);
143 static int http_upgrade(http_t
*http
);
144 static int http_write_ssl(http_t
*http
, const char *buf
, int len
);
145 #endif /* HAVE_SSL */
152 static const char * const http_fields
[] =
169 "If-Unmodified-since",
184 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
186 * BIO methods for OpenSSL...
189 static int http_bio_write(BIO
*h
, const char *buf
, int num
);
190 static int http_bio_read(BIO
*h
, char *buf
, int size
);
191 static int http_bio_puts(BIO
*h
, const char *str
);
192 static long http_bio_ctrl(BIO
*h
, int cmd
, long arg1
, void *arg2
);
193 static int http_bio_new(BIO
*h
);
194 static int http_bio_free(BIO
*data
);
196 static BIO_METHOD http_bio_methods
=
203 NULL
, /* http_bio_gets, */
212 * '_httpBIOMethods()' - Get the OpenSSL BIO methods for HTTP connections.
215 BIO_METHOD
* /* O - BIO methods for OpenSSL */
216 _httpBIOMethods(void)
218 return (&http_bio_methods
);
220 #endif /* HAVE_SSL && HAVE_LIBSSL */
224 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
228 httpBlocking(http_t
*http
, /* I - Connection to server */
229 int b
) /* I - 1 = blocking, 0 = non-blocking */
237 * 'httpCheck()' - Check to see if there is a pending response from the server.
240 int /* O - 0 = no data, 1 = data available */
241 httpCheck(http_t
*http
) /* I - Connection to server */
243 return (httpWait(http
, 0));
248 * 'httpClearCookie()' - Clear the cookie value(s).
250 * @since CUPS 1.1.19@
254 httpClearCookie(http_t
*http
) /* I - Connection to server */
268 * 'httpClearFields()' - Clear HTTP request fields.
272 httpClearFields(http_t
*http
) /* I - Connection to server */
276 memset(http
->fields
, 0, sizeof(http
->fields
));
277 if (http
->hostname
[0] == '/')
278 httpSetField(http
, HTTP_FIELD_HOST
, "localhost");
280 httpSetField(http
, HTTP_FIELD_HOST
, http
->hostname
);
282 if (http
->field_authorization
)
284 free(http
->field_authorization
);
285 http
->field_authorization
= NULL
;
288 http
->expect
= (http_status_t
)0;
294 * 'httpClose()' - Close an HTTP connection...
298 httpClose(http_t
*http
) /* I - Connection to server */
301 OM_uint32 minor_status
; /* Minor status code */
302 #endif /* HAVE_GSSAPI */
305 DEBUG_printf(("httpClose(http=%p)\n", http
));
310 httpAddrFreeList(http
->addrlist
);
317 http_shutdown_ssl(http
);
318 #endif /* HAVE_SSL */
321 closesocket(http
->fd
);
327 if (http
->gssctx
!= GSS_C_NO_CONTEXT
)
328 gss_delete_sec_context(&minor_status
, &http
->gssctx
, GSS_C_NO_BUFFER
);
330 if (http
->gssname
!= GSS_C_NO_NAME
)
331 gss_release_name(&minor_status
, &http
->gssname
);
332 #endif /* HAVE_GSSAPI */
334 #ifdef HAVE_AUTHORIZATION_H
336 AuthorizationFree(http
->auth_ref
, kAuthorizationFlagDefaults
);
337 #endif /* HAVE_AUTHORIZATION_H */
339 httpClearFields(http
);
341 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
342 free(http
->authstring
);
349 * 'httpConnect()' - Connect to a HTTP server.
352 http_t
* /* O - New HTTP connection */
353 httpConnect(const char *host
, /* I - Host to connect to */
354 int port
) /* I - Port number */
356 http_encryption_t encryption
; /* Type of encryption to use */
360 * Set the default encryption status...
364 encryption
= HTTP_ENCRYPT_ALWAYS
;
366 encryption
= HTTP_ENCRYPT_IF_REQUESTED
;
368 return (httpConnectEncrypt(host
, port
, encryption
));
373 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
376 http_t
* /* O - New HTTP connection */
378 const char *host
, /* I - Host to connect to */
379 int port
, /* I - Port number */
380 http_encryption_t encryption
) /* I - Type of encryption to use */
382 http_t
*http
; /* New HTTP connection */
383 http_addrlist_t
*addrlist
; /* Host address data */
384 char service
[255]; /* Service name */
387 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)\n",
388 host
? host
: "(null)", port
, encryption
));
399 sprintf(service
, "%d", port
);
401 if ((addrlist
= httpAddrGetList(host
, AF_UNSPEC
, service
)) == NULL
)
405 * Allocate memory for the structure...
408 if ((http
= calloc(sizeof(http_t
), 1)) == NULL
)
410 httpAddrFreeList(addrlist
);
414 http
->version
= HTTP_1_1
;
416 http
->activity
= time(NULL
);
420 http
->gssctx
= GSS_C_NO_CONTEXT
;
421 http
->gssname
= GSS_C_NO_NAME
;
422 #endif /* HAVE_GSSAPI */
425 * Set the encryption status...
428 if (port
== 443) /* Always use encryption for https */
429 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
431 http
->encryption
= encryption
;
434 * Loop through the addresses we have until one of them connects...
437 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
440 * Connect to the remote system...
443 http
->addrlist
= addrlist
;
445 if (!httpReconnect(http
))
449 * Could not connect to any known address - bail out!
452 httpAddrFreeList(addrlist
);
461 * 'httpDelete()' - Send a DELETE request to the server.
464 int /* O - Status of call (0 = success) */
465 httpDelete(http_t
*http
, /* I - Connection to server */
466 const char *uri
) /* I - URI to delete */
468 return (http_send(http
, HTTP_DELETE
, uri
));
473 * 'httpEncryption()' - Set the required encryption on the link.
476 int /* O - -1 on error, 0 on success */
477 httpEncryption(http_t
*http
, /* I - Connection to server */
478 http_encryption_t e
) /* I - New encryption preference */
480 DEBUG_printf(("httpEncryption(http=%p, e=%d)\n", http
, e
));
486 http
->encryption
= e
;
488 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
489 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
490 return (httpReconnect(http
));
491 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
492 return (http_upgrade(http
));
496 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
500 #endif /* HAVE_SSL */
505 * 'httpError()' - Get the last error on a connection.
508 int /* O - Error code (errno) value */
509 httpError(http_t
*http
) /* I - Connection to server */
512 return (http
->error
);
519 * 'httpFlush()' - Flush data from a HTTP connection.
523 httpFlush(http_t
*http
) /* I - Connection to server */
525 char buffer
[8192]; /* Junk buffer */
526 int blocking
; /* To block or not to block */
529 DEBUG_printf(("httpFlush(http=%p), state=%d\n", http
, http
->state
));
532 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
535 blocking
= http
->blocking
;
539 * Read any data we can...
542 while (httpRead2(http
, buffer
, sizeof(buffer
)) > 0);
545 * Restore blocking and reset the connection if we didn't get all of
546 * the remaining data...
549 http
->blocking
= blocking
;
551 if (http
->state
!= HTTP_WAITING
&& http
->fd
>= 0)
554 * Didn't get the data back, so close the current connection.
557 http
->state
= HTTP_WAITING
;
561 http_shutdown_ssl(http
);
562 #endif /* HAVE_SSL */
565 closesocket(http
->fd
);
576 * 'httpFlushWrite()' - Flush data in write buffer.
581 int /* O - Bytes written or -1 on error */
582 httpFlushWrite(http_t
*http
) /* I - Connection to server */
584 int bytes
; /* Bytes written */
587 DEBUG_printf(("httpFlushWrite(http=%p)\n", http
));
589 if (!http
|| !http
->wused
)
592 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
593 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
595 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
604 * 'httpGet()' - Send a GET request to the server.
607 int /* O - Status of call (0 = success) */
608 httpGet(http_t
*http
, /* I - Connection to server */
609 const char *uri
) /* I - URI to get */
611 return (http_send(http
, HTTP_GET
, uri
));
616 * 'httpGetAuthString()' - Get the current authorization string.
618 * The authorization string is set by cupsDoAuthentication() and
619 * httpSetAuthString(). Use httpGetAuthString() to retrieve the
620 * string to use with httpSetField() for the HTTP_FIELD_AUTHORIZATION
626 char * /* O - Authorization string */
627 httpGetAuthString(http_t
*http
) /* I - Connection to server */
630 return (http
->authstring
);
637 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
642 int /* O - 1 if blocking, 0 if non-blocking */
643 httpGetBlocking(http_t
*http
) /* I - Connection to server */
645 return (http
? http
->blocking
: 0);
650 * 'httpGetCookie()' - Get any cookie data from the response.
652 * @since CUPS 1.1.19@
655 const char * /* O - Cookie data or NULL */
656 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
658 return (http
? http
->cookie
: NULL
);
663 * 'httpGetFd()' - Get the file descriptor associated with a connection.
668 int /* O - File descriptor or -1 if none */
669 httpGetFd(http_t
*http
) /* I - Connection to server */
671 return (http
? http
->fd
: -1);
676 * 'httpGetField()' - Get a field value from a request/response.
679 const char * /* O - Field value */
680 httpGetField(http_t
*http
, /* I - Connection to server */
681 http_field_t field
) /* I - Field to get */
683 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
685 else if (field
== HTTP_FIELD_AUTHORIZATION
&&
686 http
->field_authorization
)
689 * Special case for WWW-Authenticate: as its contents can be
690 * longer than HTTP_MAX_VALUE...
693 return (http
->field_authorization
);
696 return (http
->fields
[field
]);
701 * 'httpGetLength()' - Get the amount of data remaining from the
702 * content-length or transfer-encoding fields.
704 * This function is deprecated and will not return lengths larger than
705 * 2^31 - 1; use httpGetLength2() instead.
710 int /* O - Content length */
711 httpGetLength(http_t
*http
) /* I - Connection to server */
714 * Get the read content length and return the 32-bit value.
719 httpGetLength2(http
);
721 return (http
->_data_remaining
);
729 * 'httpGetLength2()' - Get the amount of data remaining from the
730 * content-length or transfer-encoding fields.
732 * This function returns the complete content length, even for
733 * content larger than 2^31 - 1.
738 off_t
/* O - Content length */
739 httpGetLength2(http_t
*http
) /* I - Connection to server */
741 DEBUG_printf(("httpGetLength2(http=%p), state=%d\n", http
, http
->state
));
746 if (!strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
748 DEBUG_puts("httpGetLength2: chunked request!");
750 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
751 http
->data_remaining
= 0;
755 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
758 * The following is a hack for HTTP servers that don't send a
759 * content-length or transfer-encoding field...
761 * If there is no content-length then the connection must close
762 * after the transfer is complete...
765 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
768 * Default content length is 0 for errors and 2^31-1 for other
769 * successful requests...
772 if (http
->status
>= HTTP_MULTIPLE_CHOICES
)
773 http
->data_remaining
= 0;
775 http
->data_remaining
= 2147483647;
778 http
->data_remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
781 DEBUG_printf(("httpGetLength2: content_length=" CUPS_LLFMT
"\n",
782 CUPS_LLCAST http
->data_remaining
));
785 if (http
->data_remaining
<= INT_MAX
)
786 http
->_data_remaining
= (int)http
->data_remaining
;
788 http
->_data_remaining
= INT_MAX
;
790 return (http
->data_remaining
);
795 * 'httpGetStatus()' - Get the status of the last HTTP request.
800 http_status_t
/* O - HTTP status */
801 httpGetStatus(http_t
*http
) /* I - Connection to server */
803 return (http
? http
->status
: HTTP_ERROR
);
808 * 'httpGetSubField()' - Get a sub-field value.
813 char * /* O - Value or NULL */
814 httpGetSubField(http_t
*http
, /* I - Connection to server */
815 http_field_t field
, /* I - Field index */
816 const char *name
, /* I - Name of sub-field */
817 char *value
) /* O - Value string */
819 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
824 * 'httpGetSubField2()' - Get a sub-field value.
829 char * /* O - Value or NULL */
830 httpGetSubField2(http_t
*http
, /* I - Connection to server */
831 http_field_t field
, /* I - Field index */
832 const char *name
, /* I - Name of sub-field */
833 char *value
, /* O - Value string */
834 int valuelen
) /* I - Size of value buffer */
836 const char *fptr
; /* Pointer into field */
837 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
838 *ptr
, /* Pointer into string buffer */
839 *end
; /* End of value buffer */
841 DEBUG_printf(("httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, valuelen=%d)\n",
842 http
, field
, name
, value
, valuelen
));
844 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
845 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
848 end
= value
+ valuelen
- 1;
850 for (fptr
= http
->fields
[field
]; *fptr
;)
853 * Skip leading whitespace...
856 while (isspace(*fptr
& 255))
866 * Get the sub-field name...
870 *fptr
&& *fptr
!= '=' && !isspace(*fptr
& 255) &&
871 ptr
< (temp
+ sizeof(temp
) - 1);
876 DEBUG_printf(("httpGetSubField: name=\"%s\"\n", temp
));
879 * Skip trailing chars up to the '='...
882 while (isspace(*fptr
& 255))
892 * Skip = and leading whitespace...
897 while (isspace(*fptr
& 255))
903 * Read quoted string...
906 for (ptr
= value
, fptr
++;
907 *fptr
&& *fptr
!= '\"' && ptr
< end
;
912 while (*fptr
&& *fptr
!= '\"')
921 * Read unquoted string...
925 *fptr
&& !isspace(*fptr
& 255) && *fptr
!= ',' && ptr
< end
;
930 while (*fptr
&& !isspace(*fptr
& 255) && *fptr
!= ',')
934 DEBUG_printf(("httpGetSubField: value=\"%s\"\n", value
));
937 * See if this is the one...
940 if (!strcmp(name
, temp
))
951 * 'httpGets()' - Get a line of text from a HTTP connection.
954 char * /* O - Line or NULL */
955 httpGets(char *line
, /* I - Line to read into */
956 int length
, /* I - Max length of buffer */
957 http_t
*http
) /* I - Connection to server */
959 char *lineptr
, /* Pointer into line */
960 *lineend
, /* End of line */
961 *bufptr
, /* Pointer into input buffer */
962 *bufend
; /* Pointer to end of buffer */
963 int bytes
, /* Number of bytes read */
964 eol
; /* End-of-line? */
967 DEBUG_printf(("httpGets(line=%p, length=%d, http=%p)\n", line
, length
, http
));
969 if (http
== NULL
|| line
== NULL
)
973 * Read a line from the buffer...
977 lineend
= line
+ length
- 1;
980 while (lineptr
< lineend
)
983 * Pre-load the buffer as needed...
992 while (http
->used
== 0)
995 * No newline; see if there is more data to be read...
998 if (!http
->blocking
&& !http_wait(http
, 10000, 1))
1000 DEBUG_puts("httpGets: Timed out!");
1002 http
->error
= WSAETIMEDOUT
;
1004 http
->error
= ETIMEDOUT
;
1011 bytes
= http_read_ssl(http
, http
->buffer
+ http
->used
,
1012 HTTP_MAX_BUFFER
- http
->used
);
1014 #endif /* HAVE_SSL */
1015 bytes
= recv(http
->fd
, http
->buffer
+ http
->used
,
1016 HTTP_MAX_BUFFER
- http
->used
, 0);
1018 DEBUG_printf(("httpGets: read %d bytes...\n", bytes
));
1023 * Nope, can't get a line this time...
1027 if (WSAGetLastError() != http
->error
)
1029 http
->error
= WSAGetLastError();
1033 DEBUG_printf(("httpGets: recv() error %d!\n", WSAGetLastError()));
1035 DEBUG_printf(("httpGets: recv() error %d!\n", errno
));
1039 else if (errno
!= http
->error
)
1041 http
->error
= errno
;
1048 else if (bytes
== 0)
1050 http
->error
= EPIPE
;
1056 * Yup, update the amount used...
1059 http
->used
+= bytes
;
1063 * Now copy as much of the current line as possible...
1066 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1067 lineptr
< lineend
&& bufptr
< bufend
;)
1069 if (*bufptr
== 0x0a)
1075 else if (*bufptr
== 0x0d)
1078 *lineptr
++ = *bufptr
++;
1081 http
->used
-= (int)(bufptr
- http
->buffer
);
1083 memmove(http
->buffer
, bufptr
, http
->used
);
1091 http
->activity
= time(NULL
);
1095 DEBUG_printf(("httpGets: Returning \"%s\"\n", line
));
1101 DEBUG_puts("httpGets: No new line available!");
1108 * 'httpHead()' - Send a HEAD request to the server.
1111 int /* O - Status of call (0 = success) */
1112 httpHead(http_t
*http
, /* I - Connection to server */
1113 const char *uri
) /* I - URI for head */
1115 return (http_send(http
, HTTP_HEAD
, uri
));
1120 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1121 * default HTTP proxy (if any).
1125 httpInitialize(void)
1129 struct timeval curtime
; /* Current time in microseconds */
1130 # endif /* !WIN32 */
1131 int i
; /* Looping var */
1132 unsigned char data
[1024]; /* Seed data */
1133 #endif /* HAVE_LIBSSL */
1136 WSADATA winsockdata
; /* WinSock data */
1137 static int initialized
= 0; /* Has WinSock been initialized? */
1141 WSAStartup(MAKEWORD(1,1), &winsockdata
);
1142 #elif !defined(SO_NOSIGPIPE)
1144 * Ignore SIGPIPE signals...
1148 sigset(SIGPIPE
, SIG_IGN
);
1149 # elif defined(HAVE_SIGACTION)
1150 struct sigaction action
; /* POSIX sigaction data */
1153 memset(&action
, 0, sizeof(action
));
1154 action
.sa_handler
= SIG_IGN
;
1155 sigaction(SIGPIPE
, &action
, NULL
);
1157 signal(SIGPIPE
, SIG_IGN
);
1158 # endif /* !SO_NOSIGPIPE */
1162 gnutls_global_init();
1163 #endif /* HAVE_GNUTLS */
1166 SSL_load_error_strings();
1170 * Using the current time is a dubious random seed, but on some systems
1171 * it is the best we can do (on others, this seed isn't even used...)
1176 gettimeofday(&curtime
, NULL
);
1177 srand(curtime
.tv_sec
+ curtime
.tv_usec
);
1180 for (i
= 0; i
< sizeof(data
); i
++)
1181 data
[i
] = rand(); /* Yes, this is a poor source of random data... */
1183 RAND_seed(&data
, sizeof(data
));
1184 #endif /* HAVE_LIBSSL */
1189 * 'httpOptions()' - Send an OPTIONS request to the server.
1192 int /* O - Status of call (0 = success) */
1193 httpOptions(http_t
*http
, /* I - Connection to server */
1194 const char *uri
) /* I - URI for options */
1196 return (http_send(http
, HTTP_OPTIONS
, uri
));
1201 * 'httpPost()' - Send a POST request to the server.
1204 int /* O - Status of call (0 = success) */
1205 httpPost(http_t
*http
, /* I - Connection to server */
1206 const char *uri
) /* I - URI for post */
1208 return (http_send(http
, HTTP_POST
, uri
));
1213 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1218 int /* O - Number of bytes written */
1219 httpPrintf(http_t
*http
, /* I - Connection to server */
1220 const char *format
, /* I - printf-style format string */
1221 ...) /* I - Additional args as needed */
1223 int bytes
; /* Number of bytes to write */
1224 char buf
[16384]; /* Buffer for formatted string */
1225 va_list ap
; /* Variable argument pointer */
1228 DEBUG_printf(("httpPrintf(http=%p, format=\"%s\", ...)\n", http
, format
));
1230 va_start(ap
, format
);
1231 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1234 DEBUG_printf(("httpPrintf: %s", buf
));
1236 if (http
->data_encoding
== HTTP_ENCODE_FIELDS
)
1237 return (httpWrite2(http
, buf
, bytes
));
1242 DEBUG_puts(" flushing existing data...");
1244 if (httpFlushWrite(http
) < 0)
1248 return (http_write(http
, buf
, bytes
));
1254 * 'httpPut()' - Send a PUT request to the server.
1257 int /* O - Status of call (0 = success) */
1258 httpPut(http_t
*http
, /* I - Connection to server */
1259 const char *uri
) /* I - URI to put */
1261 return (http_send(http
, HTTP_PUT
, uri
));
1266 * 'httpRead()' - Read data from a HTTP connection.
1268 * This function is deprecated. Use the httpRead2() function which can
1269 * read more than 2GB of data.
1274 int /* O - Number of bytes read */
1275 httpRead(http_t
*http
, /* I - Connection to server */
1276 char *buffer
, /* I - Buffer for data */
1277 int length
) /* I - Maximum number of bytes */
1279 return ((int)httpRead2(http
, buffer
, length
));
1284 * 'httpRead2()' - Read data from a HTTP connection.
1289 ssize_t
/* O - Number of bytes read */
1290 httpRead2(http_t
*http
, /* I - Connection to server */
1291 char *buffer
, /* I - Buffer for data */
1292 size_t length
) /* I - Maximum number of bytes */
1294 ssize_t bytes
; /* Bytes read */
1295 char len
[32]; /* Length string */
1298 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
")\n",
1299 http
, buffer
, CUPS_LLCAST length
));
1301 if (http
== NULL
|| buffer
== NULL
)
1304 http
->activity
= time(NULL
);
1309 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1310 http
->data_remaining
<= 0)
1312 DEBUG_puts("httpRead2: Getting chunk length...");
1314 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1316 DEBUG_puts("httpRead2: Could not get length!");
1320 http
->data_remaining
= strtoll(len
, NULL
, 16);
1321 if (http
->data_remaining
< 0)
1323 DEBUG_puts("httpRead2: Negative chunk length!");
1328 DEBUG_printf(("httpRead2: data_remaining=" CUPS_LLFMT
"\n",
1329 CUPS_LLCAST http
->data_remaining
));
1331 if (http
->data_remaining
<= 0)
1334 * A zero-length chunk ends a transfer; unless we are reading POST
1338 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1339 httpGets(len
, sizeof(len
), http
);
1341 if (http
->state
== HTTP_POST_RECV
)
1344 http
->state
= HTTP_WAITING
;
1347 * Prevent future reads for this request...
1350 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1354 else if (length
> (size_t)http
->data_remaining
)
1355 length
= (size_t)http
->data_remaining
;
1357 if (http
->used
== 0 && length
<= 256)
1360 * Buffer small reads for better performance...
1363 if (!http
->blocking
&& !httpWait(http
, 10000))
1366 if (http
->data_remaining
> sizeof(http
->buffer
))
1367 bytes
= sizeof(http
->buffer
);
1369 bytes
= http
->data_remaining
;
1373 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1375 #endif /* HAVE_SSL */
1377 DEBUG_printf(("httpRead2: reading %d bytes from socket into buffer...\n",
1380 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1382 DEBUG_printf(("httpRead2: read %d bytes from socket into buffer...\n",
1391 http
->error
= WSAGetLastError();
1396 http
->error
= errno
;
1403 http
->error
= EPIPE
;
1410 if (length
> (size_t)http
->used
)
1411 length
= (size_t)http
->used
;
1413 bytes
= (ssize_t
)length
;
1415 DEBUG_printf(("httpRead2: grabbing %d bytes from input buffer...\n",
1418 memcpy(buffer
, http
->buffer
, length
);
1419 http
->used
-= (int)length
;
1422 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
1427 if (!http
->blocking
&& !httpWait(http
, 10000))
1430 bytes
= (ssize_t
)http_read_ssl(http
, buffer
, (int)length
);
1432 #endif /* HAVE_SSL */
1435 if (!http
->blocking
&& !httpWait(http
, 10000))
1438 DEBUG_printf(("httpRead2: reading " CUPS_LLFMT
" bytes from socket...\n",
1439 CUPS_LLCAST length
));
1442 bytes
= (ssize_t
)recv(http
->fd
, buffer
, (int)length
, 0);
1444 while ((bytes
= recv(http
->fd
, buffer
, length
, 0)) < 0)
1449 DEBUG_printf(("httpRead2: read " CUPS_LLFMT
" bytes from socket...\n",
1450 CUPS_LLCAST bytes
));
1455 http
->data_remaining
-= bytes
;
1457 if (http
->data_remaining
<= INT_MAX
)
1458 http
->_data_remaining
= (int)http
->data_remaining
;
1460 http
->_data_remaining
= INT_MAX
;
1465 http
->error
= WSAGetLastError();
1470 http
->error
= errno
;
1475 http
->error
= EPIPE
;
1479 if (http
->data_remaining
== 0)
1481 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1482 httpGets(len
, sizeof(len
), http
);
1484 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
1486 if (http
->state
== HTTP_POST_RECV
)
1489 http
->state
= HTTP_WAITING
;
1494 http_debug_hex("httpRead2", buffer
, (int)bytes
);
1501 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
1503 * '_httpReadCDSA()' - Read function for the CDSA library.
1506 OSStatus
/* O - -1 on error, 0 on success */
1508 SSLConnectionRef connection
, /* I - SSL/TLS connection */
1509 void *data
, /* I - Data buffer */
1510 size_t *dataLength
) /* IO - Number of bytes */
1512 OSStatus result
; /* Return value */
1513 ssize_t bytes
; /* Number of bytes read */
1514 http_t
*http
; /* HTTP connection */
1517 http
= (http_t
*)connection
;
1519 if (!http
->blocking
)
1522 * Make sure we have data before we read...
1525 if (!http_wait(http
, 10000, 0))
1527 http
->error
= ETIMEDOUT
;
1534 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
1536 while (bytes
== -1 && errno
== EINTR
);
1538 if (bytes
== *dataLength
)
1544 *dataLength
= bytes
;
1545 result
= errSSLWouldBlock
;
1552 result
= errSSLClosedGraceful
;
1553 else if (errno
== EAGAIN
)
1554 result
= errSSLWouldBlock
;
1556 result
= errSSLClosedAbort
;
1561 #endif /* HAVE_SSL && HAVE_CDSASSL */
1564 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
1566 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
1569 ssize_t
/* O - Number of bytes read or -1 on error */
1571 gnutls_transport_ptr ptr
, /* I - Connection to server */
1572 void *data
, /* I - Buffer */
1573 size_t length
) /* I - Number of bytes to read */
1575 http_t
*http
; /* HTTP connection */
1578 http
= (http_t
*)ptr
;
1580 if (!http
->blocking
)
1583 * Make sure we have data before we read...
1586 if (!http_wait(http
, 10000, 0))
1588 http
->error
= ETIMEDOUT
;
1593 return (recv(http
->fd
, data
, length
, 0));
1595 #endif /* HAVE_SSL && HAVE_GNUTLS */
1599 * 'httpReconnect()' - Reconnect to a HTTP server.
1602 int /* O - 0 on success, non-zero on failure */
1603 httpReconnect(http_t
*http
) /* I - Connection to server */
1605 http_addrlist_t
*addr
; /* Connected address */
1608 DEBUG_printf(("httpReconnect(http=%p)\n", http
));
1615 http_shutdown_ssl(http
);
1616 #endif /* HAVE_SSL */
1619 * Close any previously open socket...
1625 closesocket(http
->fd
);
1634 * Connect to the server...
1637 if ((addr
= httpAddrConnect(http
->addrlist
, &(http
->fd
))) == NULL
)
1640 * Unable to connect...
1644 http
->error
= WSAGetLastError();
1646 http
->error
= errno
;
1648 http
->status
= HTTP_ERROR
;
1653 http
->hostaddr
= &(addr
->addr
);
1655 http
->status
= HTTP_CONTINUE
;
1658 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
1661 * Always do encryption via SSL.
1664 if (http_setup_ssl(http
) != 0)
1667 closesocket(http
->fd
);
1675 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
1676 return (http_upgrade(http
));
1677 #endif /* HAVE_SSL */
1684 * 'httpSetAuthString()' - Set the current authorization string.
1686 * This function just stores a copy of the current authorization string in
1687 * the HTTP connection object. You must still call httpSetField() to set
1688 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
1689 * httpHead(), httpOptions(), httpPost, or httpPut().
1695 httpSetAuthString(http_t
*http
, /* I - Connection to server */
1696 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
1697 const char *data
) /* I - Auth data (NULL for none) */
1700 * Range check input...
1706 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
1707 free(http
->authstring
);
1709 http
->authstring
= http
->_authstring
;
1714 * Set the current authorization string...
1717 int len
= (int)strlen(scheme
) + (data
? (int)strlen(data
) + 1 : 0) + 1;
1720 if (len
> (int)sizeof(http
->_authstring
))
1722 if ((temp
= malloc(len
)) == NULL
)
1723 len
= sizeof(http
->_authstring
);
1725 http
->authstring
= temp
;
1729 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
1731 strlcpy(http
->authstring
, scheme
, len
);
1736 * Clear the current authorization string...
1739 http
->_authstring
[0] = '\0';
1745 * 'httpSetCookie()' - Set the cookie value(s)...
1747 * @since CUPS 1.1.19@
1751 httpSetCookie(http_t
*http
, /* I - Connection */
1752 const char *cookie
) /* I - Cookie string */
1761 http
->cookie
= strdup(cookie
);
1763 http
->cookie
= NULL
;
1768 * 'httpSetExpect()' - Set the Expect: header in a request.
1770 * Currently only HTTP_CONTINUE is supported for the "expect" argument.
1776 httpSetExpect(http_t
*http
, /* I - Connection to server */
1777 http_status_t expect
) /* I - HTTP status to expect (HTTP_CONTINUE) */
1780 http
->expect
= expect
;
1785 * 'httpSetField()' - Set the value of an HTTP header.
1789 httpSetField(http_t
*http
, /* I - Connection to server */
1790 http_field_t field
, /* I - Field index */
1791 const char *value
) /* I - Value */
1794 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
1795 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
1799 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
1802 * Special case for Authorization: as its contents can be
1803 * longer than HTTP_MAX_VALUE
1806 if (field
== HTTP_FIELD_AUTHORIZATION
)
1808 if (http
->field_authorization
)
1809 free(http
->field_authorization
);
1811 http
->field_authorization
= strdup(value
);
1817 * 'httpSetLength()' - Set the content-length and content-encoding.
1823 httpSetLength(http_t
*http
, /* I - Connection to server */
1824 size_t length
) /* I - Length (0 for chunked) */
1831 strcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked");
1832 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
1836 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
1837 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
1838 CUPS_LLFMT
, CUPS_LLCAST length
);
1844 * 'httpTrace()' - Send an TRACE request to the server.
1847 int /* O - Status of call (0 = success) */
1848 httpTrace(http_t
*http
, /* I - Connection to server */
1849 const char *uri
) /* I - URI for trace */
1851 return (http_send(http
, HTTP_TRACE
, uri
));
1856 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1859 http_status_t
/* O - HTTP status */
1860 httpUpdate(http_t
*http
) /* I - Connection to server */
1862 char line
[32768], /* Line from connection... */
1863 *value
; /* Pointer to value on line */
1864 http_field_t field
; /* Field index */
1865 int major
, minor
, /* HTTP version numbers */
1866 status
; /* Request status */
1869 DEBUG_printf(("httpUpdate(http=%p), state=%d\n", http
, http
->state
));
1872 * Flush pending data, if any...
1877 DEBUG_puts(" flushing buffer...");
1879 if (httpFlushWrite(http
) < 0)
1880 return (HTTP_ERROR
);
1884 * If we haven't issued any commands, then there is nothing to "update"...
1887 if (http
->state
== HTTP_WAITING
)
1888 return (HTTP_CONTINUE
);
1891 * Grab all of the lines we can from the connection...
1894 while (httpGets(line
, sizeof(line
), http
) != NULL
)
1896 DEBUG_printf(("httpUpdate: Got \"%s\"\n", line
));
1898 if (line
[0] == '\0')
1901 * Blank line means the start of the data section (if any). Return
1902 * the result code, too...
1904 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
1905 * Instead, we just return HTTP_CONTINUE to the caller and keep on
1909 if (http
->status
== HTTP_CONTINUE
)
1910 return (http
->status
);
1912 if (http
->status
< HTTP_BAD_REQUEST
)
1913 http
->digest_tries
= 0;
1916 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
1918 if (http_setup_ssl(http
) != 0)
1921 closesocket(http
->fd
);
1926 return (HTTP_ERROR
);
1929 return (HTTP_CONTINUE
);
1931 #endif /* HAVE_SSL */
1933 httpGetLength2(http
);
1935 switch (http
->state
)
1939 case HTTP_POST_RECV
:
1942 case HTTP_POST_SEND
:
1947 http
->state
= HTTP_WAITING
;
1951 return (http
->status
);
1953 else if (strncmp(line
, "HTTP/", 5) == 0)
1956 * Got the beginning of a response...
1959 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &status
) != 3)
1960 return (HTTP_ERROR
);
1962 http
->version
= (http_version_t
)(major
* 100 + minor
);
1963 http
->status
= (http_status_t
)status
;
1965 else if ((value
= strchr(line
, ':')) != NULL
)
1972 while (isspace(*value
& 255))
1976 * Be tolerants of servers that send unknown attribute fields...
1979 if (!strcasecmp(line
, "expect"))
1982 * "Expect: 100-continue" or similar...
1985 http
->expect
= (http_status_t
)atoi(value
);
1987 else if (!strcasecmp(line
, "cookie"))
1990 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
1993 httpSetCookie(http
, value
);
1995 else if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
1997 DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line
));
2001 httpSetField(http
, field
, value
);
2005 http
->status
= HTTP_ERROR
;
2006 return (HTTP_ERROR
);
2011 * See if there was an error...
2014 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
2015 return (http
->status
);
2019 DEBUG_printf(("httpUpdate: socket error %d - %s\n", http
->error
,
2020 strerror(http
->error
)));
2021 http
->status
= HTTP_ERROR
;
2022 return (HTTP_ERROR
);
2026 * If we haven't already returned, then there is nothing new...
2029 return (HTTP_CONTINUE
);
2034 * 'httpWait()' - Wait for data available on a connection.
2036 * @since CUPS 1.1.19@
2039 int /* O - 1 if data is available, 0 otherwise */
2040 httpWait(http_t
*http
, /* I - Connection to server */
2041 int msec
) /* I - Milliseconds to wait */
2044 * First see if there is data in the buffer...
2054 * Flush pending data, if any...
2059 if (httpFlushWrite(http
) < 0)
2064 * If not, check the SSL/TLS buffers and do a select() on the connection...
2067 return (http_wait(http
, msec
, 1));
2072 * 'httpWrite()' - Write data to a HTTP connection.
2074 * This function is deprecated. Use the httpWrite2() function which can
2075 * write more than 2GB of data.
2080 int /* O - Number of bytes written */
2081 httpWrite(http_t
*http
, /* I - Connection to server */
2082 const char *buffer
, /* I - Buffer for data */
2083 int length
) /* I - Number of bytes to write */
2085 return ((int)httpWrite2(http
, buffer
, length
));
2090 * 'httpWrite2()' - Write data to a HTTP connection.
2095 ssize_t
/* O - Number of bytes written */
2096 httpWrite2(http_t
*http
, /* I - Connection to server */
2097 const char *buffer
, /* I - Buffer for data */
2098 size_t length
) /* I - Number of bytes to write */
2100 ssize_t bytes
; /* Bytes written */
2103 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT
")\n", http
,
2104 buffer
, CUPS_LLCAST length
));
2107 * Range check input...
2110 if (http
== NULL
|| buffer
== NULL
)
2114 * Mark activity on the connection...
2117 http
->activity
= time(NULL
);
2120 * Buffer small writes for better performance...
2125 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
2127 DEBUG_printf(("httpWrite2: Flushing buffer (wused=%d, length="
2128 CUPS_LLFMT
")\n", http
->wused
, CUPS_LLCAST length
));
2130 httpFlushWrite(http
);
2133 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
))
2136 * Write to buffer...
2139 DEBUG_printf(("httpWrite2: Copying " CUPS_LLFMT
" bytes to wbuffer...\n",
2140 CUPS_LLCAST length
));
2142 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
2143 http
->wused
+= (int)length
;
2144 bytes
= (ssize_t
)length
;
2149 * Otherwise write the data directly...
2152 DEBUG_printf(("httpWrite2: Writing " CUPS_LLFMT
" bytes to socket...\n",
2153 CUPS_LLCAST length
));
2155 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2156 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
2158 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
2160 DEBUG_printf(("httpWrite2: Wrote " CUPS_LLFMT
" bytes...\n",
2161 CUPS_LLCAST bytes
));
2164 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
2165 http
->data_remaining
-= bytes
;
2171 * Handle end-of-request processing...
2174 if ((http
->data_encoding
== HTTP_ENCODE_CHUNKED
&& length
== 0) ||
2175 (http
->data_encoding
== HTTP_ENCODE_LENGTH
&& http
->data_remaining
== 0))
2178 * Finished with the transfer; unless we are sending POST or PUT
2182 DEBUG_puts("httpWrite: changing states...");
2185 httpFlushWrite(http
);
2187 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2190 * Send a 0-length chunk at the end of the request...
2193 http_write(http
, "0\r\n\r\n", 5);
2196 * Reset the data state...
2199 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
2200 http
->data_remaining
= 0;
2203 if (http
->state
== HTTP_POST_RECV
)
2205 else if (http
->state
== HTTP_PUT_RECV
)
2206 http
->state
= HTTP_STATUS
;
2208 http
->state
= HTTP_WAITING
;
2215 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2217 * '_httpWriteCDSA()' - Write function for the CDSA library.
2220 OSStatus
/* O - -1 on error, 0 on success */
2222 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2223 const void *data
, /* I - Data buffer */
2224 size_t *dataLength
) /* IO - Number of bytes */
2226 OSStatus result
; /* Return value */
2227 ssize_t bytes
; /* Number of bytes read */
2228 http_t
*http
; /* HTTP connection */
2231 http
= (http_t
*)connection
;
2235 bytes
= write(http
->fd
, data
, *dataLength
);
2237 while (bytes
== -1 && errno
== EINTR
);
2239 if (bytes
== *dataLength
)
2243 else if (bytes
>= 0)
2245 *dataLength
= bytes
;
2246 result
= errSSLWouldBlock
;
2252 if (errno
== EAGAIN
)
2253 result
= errSSLWouldBlock
;
2255 result
= errSSLClosedAbort
;
2260 #endif /* HAVE_SSL && HAVE_CDSASSL */
2263 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2265 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
2268 ssize_t
/* O - Number of bytes written or -1 on error */
2270 gnutls_transport_ptr ptr
, /* I - Connection to server */
2271 const void *data
, /* I - Data buffer */
2272 size_t length
) /* I - Number of bytes to write */
2274 return (send(((http_t
*)ptr
)->fd
, data
, length
, 0));
2276 #endif /* HAVE_SSL && HAVE_GNUTLS */
2279 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
2281 * 'http_bio_ctrl()' - Control the HTTP connection.
2284 static long /* O - Result/data */
2285 http_bio_ctrl(BIO
*h
, /* I - BIO data */
2286 int cmd
, /* I - Control command */
2287 long arg1
, /* I - First argument */
2288 void *arg2
) /* I - Second argument */
2295 case BIO_CTRL_RESET
:
2299 case BIO_C_SET_FILE_PTR
:
2304 case BIO_C_GET_FILE_PTR
:
2307 *((void **)arg2
) = h
->ptr
;
2314 case BIO_CTRL_FLUSH
:
2321 * 'http_bio_free()' - Free OpenSSL data.
2324 static int /* O - 1 on success, 0 on failure */
2325 http_bio_free(BIO
*h
) /* I - BIO data */
2341 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
2344 static int /* O - 1 on success, 0 on failure */
2345 http_bio_new(BIO
*h
) /* I - BIO data */
2360 * 'http_bio_puts()' - Send a string for OpenSSL.
2363 static int /* O - Bytes written */
2364 http_bio_puts(BIO
*h
, /* I - BIO data */
2365 const char *str
) /* I - String to write */
2368 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
2370 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
2376 * 'http_bio_read()' - Read data for OpenSSL.
2379 static int /* O - Bytes read */
2380 http_bio_read(BIO
*h
, /* I - BIO data */
2381 char *buf
, /* I - Buffer */
2382 int size
) /* I - Number of bytes to read */
2384 http_t
*http
; /* HTTP connection */
2387 http
= (http_t
*)h
->ptr
;
2389 if (!http
->blocking
)
2392 * Make sure we have data before we read...
2395 if (!http_wait(http
, 10000, 0))
2398 http
->error
= WSAETIMEDOUT
;
2400 http
->error
= ETIMEDOUT
;
2407 return (recv(http
->fd
, buf
, size
, 0));
2412 * 'http_bio_write()' - Write data for OpenSSL.
2415 static int /* O - Bytes written */
2416 http_bio_write(BIO
*h
, /* I - BIO data */
2417 const char *buf
, /* I - Buffer to write */
2418 int num
) /* I - Number of bytes to write */
2420 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
2422 #endif /* HAVE_SSL && HAVE_LIBSSL */
2427 * 'http_debug_hex()' - Do a hex dump of a buffer.
2431 http_debug_hex(const char *prefix
, /* I - Prefix for line */
2432 const char *buffer
, /* I - Buffer to dump */
2433 int bytes
) /* I - Bytes to dump */
2435 int i
, j
, /* Looping vars */
2436 ch
; /* Current character */
2437 char line
[255], /* Line buffer */
2438 *start
, /* Start of line after prefix */
2439 *ptr
; /* Pointer into line */
2442 if (_cups_debug_fd
< 0)
2445 DEBUG_printf(("%s: %d bytes:\n", prefix
, bytes
));
2447 snprintf(line
, sizeof(line
), "%s: ", prefix
);
2448 start
= line
+ strlen(line
);
2450 for (i
= 0; i
< bytes
; i
+= 16)
2452 for (j
= 0, ptr
= start
; j
< 16 && (i
+ j
) < bytes
; j
++, ptr
+= 2)
2453 sprintf(ptr
, "%02X", buffer
[i
+ j
] & 255);
2465 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
2467 ch
= buffer
[i
+ j
] & 255;
2469 if (ch
< ' ' || ch
>= 127)
2483 * 'http_field()' - Return the field index for a field name.
2486 static http_field_t
/* O - Field index */
2487 http_field(const char *name
) /* I - String name */
2489 int i
; /* Looping var */
2492 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2493 if (strcasecmp(name
, http_fields
[i
]) == 0)
2494 return ((http_field_t
)i
);
2496 return (HTTP_FIELD_UNKNOWN
);
2502 * 'http_read_ssl()' - Read from a SSL/TLS connection.
2505 static int /* O - Bytes read */
2506 http_read_ssl(http_t
*http
, /* I - Connection to server */
2507 char *buf
, /* I - Buffer to store data */
2508 int len
) /* I - Length of buffer */
2510 # if defined(HAVE_LIBSSL)
2511 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
2513 # elif defined(HAVE_GNUTLS)
2514 return (gnutls_record_recv(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
2516 # elif defined(HAVE_CDSASSL)
2517 int result
; /* Return value */
2518 OSStatus error
; /* Error info */
2519 size_t processed
; /* Number of bytes processed */
2522 error
= SSLRead(((http_tls_t
*)http
->tls
)->session
, buf
, len
, &processed
);
2527 result
= (int)processed
;
2529 case errSSLClosedGraceful
:
2532 case errSSLWouldBlock
:
2534 result
= (int)processed
;
2548 # endif /* HAVE_LIBSSL */
2550 #endif /* HAVE_SSL */
2554 * 'http_send()' - Send a request with all fields and the trailing blank line.
2557 static int /* O - 0 on success, non-zero on error */
2558 http_send(http_t
*http
, /* I - Connection to server */
2559 http_state_t request
, /* I - Request code */
2560 const char *uri
) /* I - URI */
2562 int i
; /* Looping var */
2563 char buf
[1024]; /* Encoded URI buffer */
2564 static const char * const codes
[] =
2565 { /* Request code strings */
2582 DEBUG_printf(("http_send(http=%p, request=HTTP_%s, uri=\"%s\")\n",
2583 http
, codes
[request
], uri
));
2585 if (http
== NULL
|| uri
== NULL
)
2589 * Set the User-Agent field if it isn't already...
2592 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
2593 httpSetField(http
, HTTP_FIELD_USER_AGENT
, CUPS_MINIMAL
);
2596 * Encode the URI as needed...
2599 _httpEncodeURI(buf
, uri
, sizeof(buf
));
2602 * See if we had an error the last time around; if so, reconnect...
2605 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
2606 if (httpReconnect(http
))
2610 * Flush any written data that is pending...
2614 httpFlushWrite(http
);
2617 * Send the request header...
2620 http
->state
= request
;
2621 http
->data_encoding
= HTTP_ENCODE_FIELDS
;
2623 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
2626 http
->status
= HTTP_CONTINUE
;
2629 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
2631 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
2632 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
2634 #endif /* HAVE_SSL */
2636 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
2638 http
->status
= HTTP_ERROR
;
2642 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2643 if (http
->fields
[i
][0] != '\0')
2645 DEBUG_printf(("http_send: %s: %s\n", http_fields
[i
],
2646 httpGetField(http
, i
)));
2648 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
],
2649 httpGetField(http
, i
)) < 1)
2651 http
->status
= HTTP_ERROR
;
2657 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
2659 http
->status
= HTTP_ERROR
;
2663 if (http
->expect
== HTTP_CONTINUE
&&
2664 (http
->state
== HTTP_POST_RECV
|| http
->state
== HTTP_PUT_RECV
))
2665 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
2667 http
->status
= HTTP_ERROR
;
2671 if (httpPrintf(http
, "\r\n") < 1)
2673 http
->status
= HTTP_ERROR
;
2677 httpFlushWrite(http
);
2678 httpGetLength2(http
);
2679 httpClearFields(http
);
2682 * The Kerberos and AuthRef authentication strings can only be used once...
2685 if (http
->field_authorization
&& http
->authstring
&&
2686 (!strncmp(http
->authstring
, "Negotiate", 9) ||
2687 !strncmp(http
->authstring
, "AuthRef", 7)))
2689 http
->_authstring
[0] = '\0';
2691 if (http
->authstring
!= http
->_authstring
)
2692 free(http
->authstring
);
2694 http
->authstring
= http
->_authstring
;
2703 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
2706 static int /* O - Status of connection */
2707 http_setup_ssl(http_t
*http
) /* I - Connection to server */
2710 SSL_CTX
*context
; /* Context for encryption */
2711 SSL
*conn
; /* Connection for encryption */
2712 BIO
*bio
; /* BIO data */
2713 # elif defined(HAVE_GNUTLS)
2714 http_tls_t
*conn
; /* TLS session object */
2715 gnutls_certificate_client_credentials
*credentials
;
2716 /* TLS credentials */
2717 # elif defined(HAVE_CDSASSL)
2718 OSStatus error
; /* Error code */
2719 http_tls_t
*conn
; /* CDSA connection information */
2720 # endif /* HAVE_LIBSSL */
2723 DEBUG_printf(("http_setup_ssl(http=%p)\n", http
));
2726 context
= SSL_CTX_new(SSLv23_client_method());
2728 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
2730 bio
= BIO_new(_httpBIOMethods());
2731 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
2733 conn
= SSL_new(context
);
2734 SSL_set_bio(conn
, bio
, bio
);
2736 if (SSL_connect(conn
) != 1)
2739 unsigned long error
; /* Error code */
2741 while ((error
= ERR_get_error()) != 0)
2742 printf("http_setup_ssl: %s\n", ERR_error_string(error
, NULL
));
2745 SSL_CTX_free(context
);
2749 http
->error
= WSAGetLastError();
2751 http
->error
= errno
;
2753 http
->status
= HTTP_ERROR
;
2755 return (HTTP_ERROR
);
2758 # elif defined(HAVE_GNUTLS)
2759 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
2761 http
->error
= errno
;
2762 http
->status
= HTTP_ERROR
;
2767 credentials
= (gnutls_certificate_client_credentials
*)
2768 malloc(sizeof(gnutls_certificate_client_credentials
));
2769 if (credentials
== NULL
)
2773 http
->error
= errno
;
2774 http
->status
= HTTP_ERROR
;
2779 gnutls_certificate_allocate_credentials(credentials
);
2781 gnutls_init(&(conn
->session
), GNUTLS_CLIENT
);
2782 gnutls_set_default_priority(conn
->session
);
2783 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
2784 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)http
);
2785 gnutls_transport_set_pull_function(conn
->session
, _httpReadGNUTLS
);
2786 gnutls_transport_set_push_function(conn
->session
, _httpWriteGNUTLS
);
2788 if ((gnutls_handshake(conn
->session
)) != GNUTLS_E_SUCCESS
)
2790 http
->error
= errno
;
2791 http
->status
= HTTP_ERROR
;
2796 conn
->credentials
= credentials
;
2798 # elif defined(HAVE_CDSASSL)
2799 conn
= (http_tls_t
*)calloc(1, sizeof(http_tls_t
));
2804 if ((error
= SSLNewContext(false, &conn
->session
)))
2806 http
->error
= error
;
2807 http
->status
= HTTP_ERROR
;
2814 * Use a union to resolve warnings about int/pointer size mismatches...
2817 error
= SSLSetConnection(conn
->session
, http
);
2820 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
2823 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
2826 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
2829 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
2833 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
2839 http
->error
= error
;
2840 http
->status
= HTTP_ERROR
;
2842 SSLDisposeContext(conn
->session
);
2848 # endif /* HAVE_CDSASSL */
2853 #endif /* HAVE_SSL */
2858 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
2862 http_shutdown_ssl(http_t
*http
) /* I - Connection to server */
2865 SSL_CTX
*context
; /* Context for encryption */
2866 SSL
*conn
; /* Connection for encryption */
2869 conn
= (SSL
*)(http
->tls
);
2870 context
= SSL_get_SSL_CTX(conn
);
2873 SSL_CTX_free(context
);
2876 # elif defined(HAVE_GNUTLS)
2877 http_tls_t
*conn
; /* Encryption session */
2878 gnutls_certificate_client_credentials
*credentials
;
2879 /* TLS credentials */
2882 conn
= (http_tls_t
*)(http
->tls
);
2883 credentials
= (gnutls_certificate_client_credentials
*)(conn
->credentials
);
2885 gnutls_bye(conn
->session
, GNUTLS_SHUT_RDWR
);
2886 gnutls_deinit(conn
->session
);
2887 gnutls_certificate_free_credentials(*credentials
);
2891 # elif defined(HAVE_CDSASSL)
2892 http_tls_t
*conn
; /* CDSA connection information */
2895 conn
= (http_tls_t
*)(http
->tls
);
2897 while (SSLClose(conn
->session
) == errSSLWouldBlock
)
2900 SSLDisposeContext(conn
->session
);
2902 if (conn
->certsArray
)
2903 CFRelease(conn
->certsArray
);
2906 # endif /* HAVE_LIBSSL */
2910 #endif /* HAVE_SSL */
2915 * 'http_upgrade()' - Force upgrade to TLS encryption.
2918 static int /* O - Status of connection */
2919 http_upgrade(http_t
*http
) /* I - Connection to server */
2921 int ret
; /* Return value */
2922 http_t myhttp
; /* Local copy of HTTP data */
2925 DEBUG_printf(("http_upgrade(%p)\n", http
));
2928 * Copy the HTTP data to a local variable so we can do the OPTIONS
2929 * request without interfering with the existing request data...
2932 memcpy(&myhttp
, http
, sizeof(myhttp
));
2935 * Send an OPTIONS request to the server, requiring SSL or TLS
2936 * encryption on the link...
2939 http
->field_authorization
= NULL
; /* Don't free the auth string */
2941 httpClearFields(http
);
2942 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
2943 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0, SSL/2.0, SSL/3.0");
2945 if ((ret
= httpOptions(http
, "*")) == 0)
2948 * Wait for the secure connection...
2951 while (httpUpdate(http
) == HTTP_CONTINUE
);
2957 * Restore the HTTP request data...
2960 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
2961 http
->data_encoding
= myhttp
.data_encoding
;
2962 http
->data_remaining
= myhttp
.data_remaining
;
2963 http
->_data_remaining
= myhttp
._data_remaining
;
2964 http
->expect
= myhttp
.expect
;
2965 http
->field_authorization
= myhttp
.field_authorization
;
2966 http
->digest_tries
= myhttp
.digest_tries
;
2969 * See if we actually went secure...
2975 * Server does not support HTTP upgrade...
2978 DEBUG_puts("Server does not support HTTP upgrade!");
2981 closesocket(http
->fd
);
2993 #endif /* HAVE_SSL */
2997 * 'http_wait()' - Wait for data available on a connection.
3000 static int /* O - 1 if data is available, 0 otherwise */
3001 http_wait(http_t
*http
, /* I - Connection to server */
3002 int msec
, /* I - Milliseconds to wait */
3003 int usessl
) /* I - Use SSL context? */
3006 struct pollfd pfd
; /* Polled file descriptor */
3008 fd_set input_set
; /* select() input set */
3009 struct timeval timeout
; /* Timeout */
3010 #endif /* HAVE_POLL */
3011 int nfds
; /* Result from select()/poll() */
3014 DEBUG_printf(("http_wait(http=%p, msec=%d)\n", http
, msec
));
3020 * Check the SSL/TLS buffers for data first...
3024 if (http
->tls
&& usessl
)
3027 if (SSL_pending((SSL
*)(http
->tls
)))
3029 # elif defined(HAVE_GNUTLS)
3030 if (gnutls_record_check_pending(((http_tls_t
*)(http
->tls
))->session
))
3032 # elif defined(HAVE_CDSASSL)
3033 size_t bytes
; /* Bytes that are available */
3035 if (!SSLGetBufferedReadSize(((http_tls_t
*)http
->tls
)->session
, &bytes
) && bytes
> 0)
3037 # endif /* HAVE_LIBSSL */
3039 #endif /* HAVE_SSL */
3042 * Then try doing a select() or poll() to poll the socket...
3047 pfd
.events
= POLLIN
;
3049 while ((nfds
= poll(&pfd
, 1, msec
)) < 0 && errno
== EINTR
);
3054 FD_ZERO(&input_set
);
3055 FD_SET(http
->fd
, &input_set
);
3057 DEBUG_printf(("http_wait: msec=%d, http->fd=%d\n", msec
, http
->fd
));
3061 timeout
.tv_sec
= msec
/ 1000;
3062 timeout
.tv_usec
= (msec
% 1000) * 1000;
3064 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
3067 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
3069 DEBUG_printf(("http_wait: select() returned %d...\n", nfds
));
3072 while (nfds
< 0 && WSAGetLastError() == WSAEINTR
);
3074 while (nfds
< 0 && errno
== EINTR
);
3076 #endif /* HAVE_POLL */
3078 DEBUG_printf(("http_wait: returning with nfds=%d...\n", nfds
));
3085 * 'http_write()' - Write a buffer to a HTTP connection.
3088 static int /* O - Number of bytes written */
3089 http_write(http_t
*http
, /* I - Connection to server */
3090 const char *buffer
, /* I - Buffer for data */
3091 int length
) /* I - Number of bytes to write */
3093 int tbytes
, /* Total bytes sent */
3094 bytes
; /* Bytes sent */
3103 bytes
= http_write_ssl(http
, buffer
, length
);
3105 #endif /* HAVE_SSL */
3106 bytes
= send(http
->fd
, buffer
, length
, 0);
3111 if (WSAGetLastError() != http
->error
)
3113 http
->error
= WSAGetLastError();
3119 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
3121 http
->error
= errno
;
3126 DEBUG_puts("http_write: error writing data...\n");
3137 http_debug_hex("http_write", buffer
- tbytes
, tbytes
);
3145 * 'http_write_chunk()' - Write a chunked buffer.
3148 static int /* O - Number bytes written */
3149 http_write_chunk(http_t
*http
, /* I - Connection to server */
3150 const char *buffer
, /* I - Buffer to write */
3151 int length
) /* I - Length of buffer */
3153 char header
[255]; /* Chunk header */
3154 int bytes
; /* Bytes written */
3156 DEBUG_printf(("http_write_chunk(http=%p, buffer=%p, length=%d)\n",
3157 http
, buffer
, length
));
3160 * Write the chunk header, data, and trailer.
3163 sprintf(header
, "%x\r\n", length
);
3164 if (http_write(http
, header
, (int)strlen(header
)) < 0)
3166 DEBUG_puts(" http_write of length failed!");
3170 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
3172 DEBUG_puts(" http_write of buffer failed!");
3176 if (http_write(http
, "\r\n", 2) < 0)
3178 DEBUG_puts(" http_write of CR LF failed!");
3188 * 'http_write_ssl()' - Write to a SSL/TLS connection.
3191 static int /* O - Bytes written */
3192 http_write_ssl(http_t
*http
, /* I - Connection to server */
3193 const char *buf
, /* I - Buffer holding data */
3194 int len
) /* I - Length of buffer */
3196 # if defined(HAVE_LIBSSL)
3197 return (SSL_write((SSL
*)(http
->tls
), buf
, len
));
3199 # elif defined(HAVE_GNUTLS)
3200 return (gnutls_record_send(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
3201 # elif defined(HAVE_CDSASSL)
3202 int result
; /* Return value */
3203 OSStatus error
; /* Error info */
3204 size_t processed
; /* Number of bytes processed */
3207 error
= SSLWrite(((http_tls_t
*)http
->tls
)->session
, buf
, len
, &processed
);
3212 result
= (int)processed
;
3214 case errSSLClosedGraceful
:
3217 case errSSLWouldBlock
:
3219 result
= (int)processed
;
3233 # endif /* HAVE_LIBSSL */
3235 #endif /* HAVE_SSL */
3239 * End of "$Id: http.c 7661 2008-06-16 21:46:51Z mike $".