2 * "$Id: http.c 7850 2008-08-20 00:07:25Z mike $"
4 * HTTP routines for CUPS.
6 * Copyright 2007-2010 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 the
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 * _httpCreate() - Create an unconnected HTTP connection.
32 * httpDelete() - Send a DELETE request to the server.
33 * _httpDisconnect() - Disconnect a HTTP connection.
34 * httpEncryption() - Set the required encryption on the link.
35 * httpError() - Get the last error on a connection.
36 * httpFlush() - Flush data from a HTTP connection.
37 * httpFlushWrite() - Flush data in write buffer.
38 * httpGet() - Send a GET request to the server.
39 * httpGetAuthString() - Get the current authorization string.
40 * httpGetBlocking() - Get the blocking/non-block state of a connection.
41 * httpGetCookie() - Get any cookie data from the response.
42 * httpGetFd() - Get the file descriptor associated with a
44 * httpGetField() - Get a field value from a request/response.
45 * httpGetLength() - Get the amount of data remaining from the
46 * content-length or transfer-encoding fields.
47 * httpGetLength2() - Get the amount of data remaining from the
48 * content-length or transfer-encoding fields.
49 * httpGetStatus() - Get the status of the last HTTP request.
50 * httpGetSubField() - Get a sub-field value.
51 * httpGetSubField2() - Get a sub-field value.
52 * httpGets() - Get a line of text from a HTTP connection.
53 * httpHead() - Send a HEAD request to the server.
54 * httpInitialize() - Initialize the HTTP interface library and set the
55 * default HTTP proxy (if any).
56 * httpOptions() - Send an OPTIONS request to the server.
57 * _httpPeek() - Peek at data from a HTTP connection.
58 * httpPost() - Send a POST request to the server.
59 * httpPrintf() - Print a formatted string to a HTTP connection.
60 * httpPut() - Send a PUT request to the server.
61 * httpRead() - Read data from a HTTP connection.
62 * httpRead2() - Read data from a HTTP connection.
63 * _httpReadCDSA() - Read function for the CDSA library.
64 * _httpReadGNUTLS() - Read function for the GNU TLS library.
65 * httpReconnect() - Reconnect to a HTTP server.
66 * httpSetAuthString() - Set the current authorization string.
67 * httpSetCookie() - Set the cookie value(s).
68 * httpSetExpect() - Set the Expect: header in a request.
69 * httpSetField() - Set the value of an HTTP header.
70 * httpSetLength() - Set the content-length and content-encoding.
71 * httpTrace() - Send an TRACE request to the server.
72 * httpUpdate() - Update the current HTTP state for incoming data.
73 * _httpWait() - Wait for data available on a connection (no flush).
74 * httpWait() - Wait for data available on a connection.
75 * httpWrite() - Write data to a HTTP connection.
76 * httpWrite2() - Write data to a HTTP connection.
77 * _httpWriteCDSA() - Write function for the CDSA library.
78 * _httpWriteGNUTLS() - Write function for the GNU TLS library.
79 * http_bio_ctrl() - Control the HTTP connection.
80 * http_bio_free() - Free OpenSSL data.
81 * http_bio_new() - Initialize an OpenSSL BIO structure.
82 * http_bio_puts() - Send a string for OpenSSL.
83 * http_bio_read() - Read data for OpenSSL.
84 * http_bio_write() - Write data for OpenSSL.
85 * http_debug_hex() - Do a hex dump of a buffer.
86 * http_field() - Return the field index for a field name.
87 * http_read_ssl() - Read from a SSL/TLS connection.
88 * http_locking_cb() - Lock/unlock a thread's mutex.
89 * http_send() - Send a request with all fields and the trailing
91 * http_setup_ssl() - Set up SSL/TLS support on a connection.
92 * http_shutdown_ssl() - Shut down SSL/TLS on a connection.
93 * http_threadid_cb() - Return the current thread ID.
94 * http_upgrade() - Force upgrade to TLS encryption.
95 * http_write() - Write a buffer to a HTTP connection.
96 * http_write_chunk() - Write a chunked buffer.
97 * http_write_ssl() - Write to a SSL/TLS connection.
101 * Include necessary headers...
104 #include "cups-private.h"
108 # include <sys/time.h>
109 # include <sys/resource.h>
112 # include <sys/poll.h>
113 #endif /* HAVE_POLL */
117 * Some operating systems have done away with the Fxxxx constants for
118 * the fcntl() call; this works around that "feature"...
122 # define FNONBLK O_NONBLOCK
123 #endif /* !FNONBLK */
131 static void http_debug_hex(const char *prefix
, const char *buffer
,
134 static http_field_t
http_field(const char *name
);
135 static int http_send(http_t
*http
, http_state_t request
,
137 static int http_write(http_t
*http
, const char *buffer
,
139 static int http_write_chunk(http_t
*http
, const char *buffer
,
142 static int http_read_ssl(http_t
*http
, char *buf
, int len
);
143 static int http_setup_ssl(http_t
*http
);
144 static void http_shutdown_ssl(http_t
*http
);
145 static int http_upgrade(http_t
*http
);
146 static int http_write_ssl(http_t
*http
, const char *buf
, int len
);
149 # ifdef HAVE_PTHREAD_H
150 GCRY_THREAD_OPTION_PTHREAD_IMPL
;
151 # endif /* HAVE_PTHREAD_H */
153 # elif defined(HAVE_LIBSSL)
154 static _cups_mutex_t
*http_locks
; /* OpenSSL lock mutexes */
156 static void http_locking_cb(int mode
, int type
, const char *file
,
158 static unsigned long http_threadid_cb(void);
159 # endif /* HAVE_GNUTLS */
160 #endif /* HAVE_SSL */
167 static const char * const http_fields
[] =
184 "If-Unmodified-since",
198 static const char * const http_states
[] =
218 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
220 * BIO methods for OpenSSL...
223 static int http_bio_write(BIO
*h
, const char *buf
, int num
);
224 static int http_bio_read(BIO
*h
, char *buf
, int size
);
225 static int http_bio_puts(BIO
*h
, const char *str
);
226 static long http_bio_ctrl(BIO
*h
, int cmd
, long arg1
, void *arg2
);
227 static int http_bio_new(BIO
*h
);
228 static int http_bio_free(BIO
*data
);
230 static BIO_METHOD http_bio_methods
=
237 NULL
, /* http_bio_gets, */
246 * '_httpBIOMethods()' - Get the OpenSSL BIO methods for HTTP connections.
249 BIO_METHOD
* /* O - BIO methods for OpenSSL */
250 _httpBIOMethods(void)
252 return (&http_bio_methods
);
254 #endif /* HAVE_SSL && HAVE_LIBSSL */
258 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
262 httpBlocking(http_t
*http
, /* I - Connection to server */
263 int b
) /* I - 1 = blocking, 0 = non-blocking */
271 * 'httpCheck()' - Check to see if there is a pending response from the server.
274 int /* O - 0 = no data, 1 = data available */
275 httpCheck(http_t
*http
) /* I - Connection to server */
277 return (httpWait(http
, 0));
282 * 'httpClearCookie()' - Clear the cookie value(s).
284 * @since CUPS 1.1.19/Mac OS X 10.3@
288 httpClearCookie(http_t
*http
) /* I - Connection to server */
302 * 'httpClearFields()' - Clear HTTP request fields.
306 httpClearFields(http_t
*http
) /* I - Connection to server */
310 memset(http
->fields
, 0, sizeof(http
->fields
));
311 if (http
->hostname
[0] == '/')
312 httpSetField(http
, HTTP_FIELD_HOST
, "localhost");
314 httpSetField(http
, HTTP_FIELD_HOST
, http
->hostname
);
316 if (http
->field_authorization
)
318 free(http
->field_authorization
);
319 http
->field_authorization
= NULL
;
322 http
->expect
= (http_status_t
)0;
328 * 'httpClose()' - Close an HTTP connection.
332 httpClose(http_t
*http
) /* I - Connection to server */
335 OM_uint32 minor_status
; /* Minor status code */
336 #endif /* HAVE_GSSAPI */
339 DEBUG_printf(("httpClose(http=%p)", http
));
342 * Range check input...
349 * Close any open connection...
352 _httpDisconnect(http
);
355 * Free memory used...
358 httpAddrFreeList(http
->addrlist
);
364 if (http
->gssctx
!= GSS_C_NO_CONTEXT
)
365 gss_delete_sec_context(&minor_status
, &http
->gssctx
, GSS_C_NO_BUFFER
);
367 if (http
->gssname
!= GSS_C_NO_NAME
)
368 gss_release_name(&minor_status
, &http
->gssname
);
369 #endif /* HAVE_GSSAPI */
371 #ifdef HAVE_AUTHORIZATION_H
373 AuthorizationFree(http
->auth_ref
, kAuthorizationFlagDefaults
);
374 #endif /* HAVE_AUTHORIZATION_H */
376 httpClearFields(http
);
378 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
379 free(http
->authstring
);
386 * 'httpConnect()' - Connect to a HTTP server.
388 * This function is deprecated - use @link httpConnectEncrypt@ instead.
393 http_t
* /* O - New HTTP connection */
394 httpConnect(const char *host
, /* I - Host to connect to */
395 int port
) /* I - Port number */
397 return (httpConnectEncrypt(host
, port
, HTTP_ENCRYPT_IF_REQUESTED
));
402 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
405 http_t
* /* O - New HTTP connection */
407 const char *host
, /* I - Host to connect to */
408 int port
, /* I - Port number */
409 http_encryption_t encryption
) /* I - Type of encryption to use */
411 http_t
*http
; /* New HTTP connection */
414 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)",
415 host
, port
, encryption
));
418 * Create the HTTP structure...
421 if ((http
= _httpCreate(host
, port
, encryption
)) == NULL
)
425 * Connect to the remote system...
428 if (!httpReconnect(http
))
432 * Could not connect to any known address - bail out!
435 httpAddrFreeList(http
->addrlist
);
444 * '_httpCreate()' - Create an unconnected HTTP connection.
447 http_t
* /* O - HTTP connection */
449 const char *host
, /* I - Hostname */
450 int port
, /* I - Port number */
451 http_encryption_t encryption
) /* I - Encryption to use */
453 http_t
*http
; /* New HTTP connection */
454 http_addrlist_t
*addrlist
; /* Host address data */
455 char service
[255]; /* Service name */
458 DEBUG_printf(("4_httpCreate(host=\"%s\", port=%d, encryption=%d)",
459 host
, port
, encryption
));
470 sprintf(service
, "%d", port
);
472 if ((addrlist
= httpAddrGetList(host
, AF_UNSPEC
, service
)) == NULL
)
476 * Allocate memory for the structure...
479 if ((http
= calloc(sizeof(http_t
), 1)) == NULL
)
481 httpAddrFreeList(addrlist
);
486 * Initialize the HTTP data...
489 http
->activity
= time(NULL
);
490 http
->addrlist
= addrlist
;
494 http
->gssctx
= GSS_C_NO_CONTEXT
;
495 http
->gssname
= GSS_C_NO_NAME
;
496 #endif /* HAVE_GSSAPI */
497 http
->version
= HTTP_1_1
;
499 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
501 if (port
== 443) /* Always use encryption for https */
502 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
504 http
->encryption
= encryption
;
507 * Return the new structure...
515 * 'httpDelete()' - Send a DELETE request to the server.
518 int /* O - Status of call (0 = success) */
519 httpDelete(http_t
*http
, /* I - Connection to server */
520 const char *uri
) /* I - URI to delete */
522 return (http_send(http
, HTTP_DELETE
, uri
));
527 * '_httpDisconnect()' - Disconnect a HTTP connection.
531 _httpDisconnect(http_t
*http
) /* I - Connection to server */
535 http_shutdown_ssl(http
);
536 #endif /* HAVE_SSL */
539 closesocket(http
->fd
);
549 * 'httpEncryption()' - Set the required encryption on the link.
552 int /* O - -1 on error, 0 on success */
553 httpEncryption(http_t
*http
, /* I - Connection to server */
554 http_encryption_t e
) /* I - New encryption preference */
556 DEBUG_printf(("httpEncryption(http=%p, e=%d)", http
, e
));
562 http
->encryption
= e
;
564 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
565 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
566 return (httpReconnect(http
));
567 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
568 return (http_upgrade(http
));
572 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
576 #endif /* HAVE_SSL */
581 * 'httpError()' - Get the last error on a connection.
584 int /* O - Error code (errno) value */
585 httpError(http_t
*http
) /* I - Connection to server */
588 return (http
->error
);
595 * 'httpFlush()' - Flush data from a HTTP connection.
599 httpFlush(http_t
*http
) /* I - Connection to server */
601 char buffer
[8192]; /* Junk buffer */
602 int blocking
; /* To block or not to block */
603 http_state_t oldstate
; /* Old state */
606 DEBUG_printf(("httpFlush(http=%p), state=%s", http
,
607 http_states
[http
->state
]));
610 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
613 blocking
= http
->blocking
;
617 * Read any data we can...
620 oldstate
= http
->state
;
621 while (httpRead2(http
, buffer
, sizeof(buffer
)) > 0);
624 * Restore blocking and reset the connection if we didn't get all of
625 * the remaining data...
628 http
->blocking
= blocking
;
630 if (http
->state
== oldstate
&& http
->state
!= HTTP_WAITING
&& http
->fd
>= 0)
633 * Didn't get the data back, so close the current connection.
636 http
->state
= HTTP_WAITING
;
640 http_shutdown_ssl(http
);
641 #endif /* HAVE_SSL */
644 closesocket(http
->fd
);
655 * 'httpFlushWrite()' - Flush data in write buffer.
657 * @since CUPS 1.2/Mac OS X 10.5@
660 int /* O - Bytes written or -1 on error */
661 httpFlushWrite(http_t
*http
) /* I - Connection to server */
663 int bytes
; /* Bytes written */
666 DEBUG_printf(("httpFlushWrite(http=%p)", http
));
668 if (!http
|| !http
->wused
)
670 DEBUG_puts(http
? "1httpFlushWrite: Write buffer is empty." :
671 "1httpFlushWrite: No connection.");
675 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
676 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
678 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
682 DEBUG_printf(("1httpFlushWrite: Returning %d.", bytes
));
689 * 'httpGet()' - Send a GET request to the server.
692 int /* O - Status of call (0 = success) */
693 httpGet(http_t
*http
, /* I - Connection to server */
694 const char *uri
) /* I - URI to get */
696 return (http_send(http
, HTTP_GET
, uri
));
701 * 'httpGetAuthString()' - Get the current authorization string.
703 * The authorization string is set by cupsDoAuthentication() and
704 * httpSetAuthString(). Use httpGetAuthString() to retrieve the
705 * string to use with httpSetField() for the HTTP_FIELD_AUTHORIZATION
708 * @since CUPS 1.3/Mac OS X 10.5@
711 char * /* O - Authorization string */
712 httpGetAuthString(http_t
*http
) /* I - Connection to server */
715 return (http
->authstring
);
722 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
724 * @since CUPS 1.2/Mac OS X 10.5@
727 int /* O - 1 if blocking, 0 if non-blocking */
728 httpGetBlocking(http_t
*http
) /* I - Connection to server */
730 return (http
? http
->blocking
: 0);
735 * 'httpGetCookie()' - Get any cookie data from the response.
737 * @since CUPS 1.1.19/Mac OS X 10.3@
740 const char * /* O - Cookie data or NULL */
741 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
743 return (http
? http
->cookie
: NULL
);
748 * 'httpGetFd()' - Get the file descriptor associated with a connection.
750 * @since CUPS 1.2/Mac OS X 10.5@
753 int /* O - File descriptor or -1 if none */
754 httpGetFd(http_t
*http
) /* I - Connection to server */
756 return (http
? http
->fd
: -1);
761 * 'httpGetField()' - Get a field value from a request/response.
764 const char * /* O - Field value */
765 httpGetField(http_t
*http
, /* I - Connection to server */
766 http_field_t field
) /* I - Field to get */
768 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
770 else if (field
== HTTP_FIELD_AUTHORIZATION
&&
771 http
->field_authorization
)
774 * Special case for WWW-Authenticate: as its contents can be
775 * longer than HTTP_MAX_VALUE...
778 return (http
->field_authorization
);
781 return (http
->fields
[field
]);
786 * 'httpGetLength()' - Get the amount of data remaining from the
787 * content-length or transfer-encoding fields.
789 * This function is deprecated and will not return lengths larger than
790 * 2^31 - 1; use httpGetLength2() instead.
795 int /* O - Content length */
796 httpGetLength(http_t
*http
) /* I - Connection to server */
799 * Get the read content length and return the 32-bit value.
804 httpGetLength2(http
);
806 return (http
->_data_remaining
);
814 * 'httpGetLength2()' - Get the amount of data remaining from the
815 * content-length or transfer-encoding fields.
817 * This function returns the complete content length, even for
818 * content larger than 2^31 - 1.
820 * @since CUPS 1.2/Mac OS X 10.5@
823 off_t
/* O - Content length */
824 httpGetLength2(http_t
*http
) /* I - Connection to server */
826 DEBUG_printf(("2httpGetLength2(http=%p), state=%s", http
,
827 http_states
[http
->state
]));
832 if (!strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
834 DEBUG_puts("4httpGetLength2: chunked request!");
836 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
837 http
->data_remaining
= 0;
841 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
844 * The following is a hack for HTTP servers that don't send a
845 * content-length or transfer-encoding field...
847 * If there is no content-length then the connection must close
848 * after the transfer is complete...
851 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
854 * Default content length is 0 for errors and 2^31-1 for other
855 * successful requests...
858 if (http
->status
>= HTTP_MULTIPLE_CHOICES
)
859 http
->data_remaining
= 0;
861 http
->data_remaining
= 2147483647;
864 http
->data_remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
867 DEBUG_printf(("4httpGetLength2: content_length=" CUPS_LLFMT
,
868 CUPS_LLCAST http
->data_remaining
));
871 if (http
->data_remaining
<= INT_MAX
)
872 http
->_data_remaining
= (int)http
->data_remaining
;
874 http
->_data_remaining
= INT_MAX
;
876 return (http
->data_remaining
);
881 * 'httpGetStatus()' - Get the status of the last HTTP request.
883 * @since CUPS 1.2/Mac OS X 10.5@
886 http_status_t
/* O - HTTP status */
887 httpGetStatus(http_t
*http
) /* I - Connection to server */
889 return (http
? http
->status
: HTTP_ERROR
);
894 * 'httpGetSubField()' - Get a sub-field value.
899 char * /* O - Value or NULL */
900 httpGetSubField(http_t
*http
, /* I - Connection to server */
901 http_field_t field
, /* I - Field index */
902 const char *name
, /* I - Name of sub-field */
903 char *value
) /* O - Value string */
905 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
910 * 'httpGetSubField2()' - Get a sub-field value.
912 * @since CUPS 1.2/Mac OS X 10.5@
915 char * /* O - Value or NULL */
916 httpGetSubField2(http_t
*http
, /* I - Connection to server */
917 http_field_t field
, /* I - Field index */
918 const char *name
, /* I - Name of sub-field */
919 char *value
, /* O - Value string */
920 int valuelen
) /* I - Size of value buffer */
922 const char *fptr
; /* Pointer into field */
923 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
924 *ptr
, /* Pointer into string buffer */
925 *end
; /* End of value buffer */
927 DEBUG_printf(("2httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, "
928 "valuelen=%d)", http
, field
, name
, value
, valuelen
));
930 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
931 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
934 end
= value
+ valuelen
- 1;
936 for (fptr
= http
->fields
[field
]; *fptr
;)
939 * Skip leading whitespace...
942 while (isspace(*fptr
& 255))
952 * Get the sub-field name...
956 *fptr
&& *fptr
!= '=' && !isspace(*fptr
& 255) &&
957 ptr
< (temp
+ sizeof(temp
) - 1);
962 DEBUG_printf(("4httpGetSubField2: name=\"%s\"", temp
));
965 * Skip trailing chars up to the '='...
968 while (isspace(*fptr
& 255))
978 * Skip = and leading whitespace...
983 while (isspace(*fptr
& 255))
989 * Read quoted string...
992 for (ptr
= value
, fptr
++;
993 *fptr
&& *fptr
!= '\"' && ptr
< end
;
998 while (*fptr
&& *fptr
!= '\"')
1007 * Read unquoted string...
1011 *fptr
&& !isspace(*fptr
& 255) && *fptr
!= ',' && ptr
< end
;
1016 while (*fptr
&& !isspace(*fptr
& 255) && *fptr
!= ',')
1020 DEBUG_printf(("4httpGetSubField2: value=\"%s\"", value
));
1023 * See if this is the one...
1026 if (!strcmp(name
, temp
))
1028 DEBUG_printf(("3httpGetSubField2: Returning \"%s\"", value
));
1035 DEBUG_puts("3httpGetSubField2: Returning NULL");
1042 * 'httpGets()' - Get a line of text from a HTTP connection.
1045 char * /* O - Line or NULL */
1046 httpGets(char *line
, /* I - Line to read into */
1047 int length
, /* I - Max length of buffer */
1048 http_t
*http
) /* I - Connection to server */
1050 char *lineptr
, /* Pointer into line */
1051 *lineend
, /* End of line */
1052 *bufptr
, /* Pointer into input buffer */
1053 *bufend
; /* Pointer to end of buffer */
1054 int bytes
, /* Number of bytes read */
1055 eol
; /* End-of-line? */
1058 DEBUG_printf(("2httpGets(line=%p, length=%d, http=%p)", line
, length
, http
));
1060 if (http
== NULL
|| line
== NULL
)
1064 * Read a line from the buffer...
1069 lineend
= line
+ length
- 1;
1072 while (lineptr
< lineend
)
1075 * Pre-load the buffer as needed...
1084 while (http
->used
== 0)
1087 * No newline; see if there is more data to be read...
1090 if (!http
->blocking
&& !_httpWait(http
, 10000, 1))
1092 DEBUG_puts("3httpGets: Timed out!");
1094 http
->error
= WSAETIMEDOUT
;
1096 http
->error
= ETIMEDOUT
;
1103 bytes
= http_read_ssl(http
, http
->buffer
+ http
->used
,
1104 HTTP_MAX_BUFFER
- http
->used
);
1106 #endif /* HAVE_SSL */
1107 bytes
= recv(http
->fd
, http
->buffer
+ http
->used
,
1108 HTTP_MAX_BUFFER
- http
->used
, 0);
1110 DEBUG_printf(("4httpGets: read %d bytes...", bytes
));
1115 * Nope, can't get a line this time...
1119 if (WSAGetLastError() != http
->error
)
1121 http
->error
= WSAGetLastError();
1125 DEBUG_printf(("3httpGets: recv() error %d!", WSAGetLastError()));
1127 DEBUG_printf(("3httpGets: recv() error %d!", errno
));
1129 if (errno
== EINTR
|| errno
== EAGAIN
)
1131 else if (errno
!= http
->error
)
1133 http
->error
= errno
;
1140 else if (bytes
== 0)
1142 http
->error
= EPIPE
;
1148 * Yup, update the amount used...
1151 http
->used
+= bytes
;
1155 * Now copy as much of the current line as possible...
1158 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1159 lineptr
< lineend
&& bufptr
< bufend
;)
1161 if (*bufptr
== 0x0a)
1167 else if (*bufptr
== 0x0d)
1170 *lineptr
++ = *bufptr
++;
1173 http
->used
-= (int)(bufptr
- http
->buffer
);
1175 memmove(http
->buffer
, bufptr
, http
->used
);
1183 http
->activity
= time(NULL
);
1187 DEBUG_printf(("3httpGets: Returning \"%s\"", line
));
1193 DEBUG_puts("3httpGets: No new line available!");
1200 * 'httpHead()' - Send a HEAD request to the server.
1203 int /* O - Status of call (0 = success) */
1204 httpHead(http_t
*http
, /* I - Connection to server */
1205 const char *uri
) /* I - URI for head */
1207 DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", http
, uri
));
1208 return (http_send(http
, HTTP_HEAD
, uri
));
1213 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1214 * default HTTP proxy (if any).
1218 httpInitialize(void)
1220 static int initialized
= 0; /* Have we been called before? */
1222 WSADATA winsockdata
; /* WinSock data */
1225 int i
; /* Looping var */
1226 unsigned char data
[1024]; /* Seed data */
1227 #endif /* HAVE_LIBSSL */
1233 _cupsGlobalUnlock();
1238 WSAStartup(MAKEWORD(1,1), &winsockdata
);
1240 #elif !defined(SO_NOSIGPIPE)
1242 * Ignore SIGPIPE signals...
1246 sigset(SIGPIPE
, SIG_IGN
);
1248 # elif defined(HAVE_SIGACTION)
1249 struct sigaction action
; /* POSIX sigaction data */
1252 memset(&action
, 0, sizeof(action
));
1253 action
.sa_handler
= SIG_IGN
;
1254 sigaction(SIGPIPE
, &action
, NULL
);
1257 signal(SIGPIPE
, SIG_IGN
);
1258 # endif /* !SO_NOSIGPIPE */
1263 * Make sure we handle threading properly...
1266 # ifdef HAVE_PTHREAD_H
1267 gcry_control(GCRYCTL_SET_THREAD_CBS
, &gcry_threads_pthread
);
1268 # endif /* HAVE_PTHREAD_H */
1271 * Initialize GNU TLS...
1274 gnutls_global_init();
1276 #elif defined(HAVE_LIBSSL)
1278 * Initialize OpenSSL...
1281 SSL_load_error_strings();
1285 * Set the threading callbacks...
1288 http_locks
= calloc(CRYPTO_num_locks(), sizeof(_cups_mutex_t
));
1289 # ifdef HAVE_PTHREAD_H
1290 for (i
= 0; i
< CRYPTO_num_locks(); i
++)
1291 pthread_mutex_init(http_locks
+ i
, NULL
);
1292 # endif /* HAVE_PTHREAD_H */
1294 CRYPTO_set_id_callback(http_threadid_cb
);
1295 CRYPTO_set_locking_callback(http_locking_cb
);
1298 * Using the current time is a dubious random seed, but on some systems
1299 * it is the best we can do (on others, this seed isn't even used...)
1302 CUPS_SRAND(time(NULL
));
1304 for (i
= 0; i
< sizeof(data
); i
++)
1305 data
[i
] = CUPS_RAND();
1307 RAND_seed(data
, sizeof(data
));
1308 #endif /* HAVE_GNUTLS */
1311 _cupsGlobalUnlock();
1316 * 'httpOptions()' - Send an OPTIONS request to the server.
1319 int /* O - Status of call (0 = success) */
1320 httpOptions(http_t
*http
, /* I - Connection to server */
1321 const char *uri
) /* I - URI for options */
1323 return (http_send(http
, HTTP_OPTIONS
, uri
));
1328 * '_httpPeek()' - Peek at data from a HTTP connection.
1330 * This function copies available data from the given HTTP connection, reading
1331 * a buffer as needed. The data is still available for reading using
1332 * @link httpRead@ or @link httpRead2@.
1334 * For non-blocking connections the usual timeouts apply.
1337 ssize_t
/* O - Number of bytes copied */
1338 _httpPeek(http_t
*http
, /* I - Connection to server */
1339 char *buffer
, /* I - Buffer for data */
1340 size_t length
) /* I - Maximum number of bytes */
1342 ssize_t bytes
; /* Bytes read */
1343 char len
[32]; /* Length string */
1346 DEBUG_printf(("_httpPeek(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1347 http
, buffer
, CUPS_LLCAST length
));
1349 if (http
== NULL
|| buffer
== NULL
)
1352 http
->activity
= time(NULL
);
1358 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1359 http
->data_remaining
<= 0)
1361 DEBUG_puts("2_httpPeek: Getting chunk length...");
1363 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1365 DEBUG_puts("1_httpPeek: Could not get length!");
1369 http
->data_remaining
= strtoll(len
, NULL
, 16);
1370 if (http
->data_remaining
< 0)
1372 DEBUG_puts("1_httpPeek: Negative chunk length!");
1377 DEBUG_printf(("2_httpPeek: data_remaining=" CUPS_LLFMT
,
1378 CUPS_LLCAST http
->data_remaining
));
1380 if (http
->data_remaining
<= 0)
1383 * A zero-length chunk ends a transfer; unless we are reading POST
1387 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1388 httpGets(len
, sizeof(len
), http
);
1390 if (http
->state
== HTTP_POST_RECV
)
1393 http
->state
= HTTP_WAITING
;
1396 * Prevent future reads for this request...
1399 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1403 else if (length
> (size_t)http
->data_remaining
)
1404 length
= (size_t)http
->data_remaining
;
1406 if (http
->used
== 0)
1409 * Buffer small reads for better performance...
1412 if (!http
->blocking
&& !httpWait(http
, 10000))
1415 if (http
->data_remaining
> sizeof(http
->buffer
))
1416 bytes
= sizeof(http
->buffer
);
1418 bytes
= http
->data_remaining
;
1422 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1424 #endif /* HAVE_SSL */
1426 DEBUG_printf(("2_httpPeek: reading %d bytes from socket into buffer...",
1429 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1431 DEBUG_printf(("2_httpPeek: read %d bytes from socket into buffer...",
1440 http
->error
= WSAGetLastError();
1443 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1445 http
->error
= errno
;
1452 http
->error
= EPIPE
;
1459 if (length
> (size_t)http
->used
)
1460 length
= (size_t)http
->used
;
1462 bytes
= (ssize_t
)length
;
1464 DEBUG_printf(("2_httpPeek: grabbing %d bytes from input buffer...",
1467 memcpy(buffer
, http
->buffer
, length
);
1475 http
->error
= WSAGetLastError();
1477 if (errno
== EINTR
|| errno
== EAGAIN
)
1480 http
->error
= errno
;
1483 else if (bytes
== 0)
1485 http
->error
= EPIPE
;
1490 http_debug_hex("_httpPeek", buffer
, (int)bytes
);
1498 * 'httpPost()' - Send a POST request to the server.
1501 int /* O - Status of call (0 = success) */
1502 httpPost(http_t
*http
, /* I - Connection to server */
1503 const char *uri
) /* I - URI for post */
1505 return (http_send(http
, HTTP_POST
, uri
));
1510 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1515 int /* O - Number of bytes written */
1516 httpPrintf(http_t
*http
, /* I - Connection to server */
1517 const char *format
, /* I - printf-style format string */
1518 ...) /* I - Additional args as needed */
1520 int bytes
; /* Number of bytes to write */
1521 char buf
[16384]; /* Buffer for formatted string */
1522 va_list ap
; /* Variable argument pointer */
1525 DEBUG_printf(("2httpPrintf(http=%p, format=\"%s\", ...)", http
, format
));
1527 va_start(ap
, format
);
1528 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1531 DEBUG_printf(("3httpPrintf: %s", buf
));
1533 if (http
->data_encoding
== HTTP_ENCODE_FIELDS
)
1534 return (httpWrite2(http
, buf
, bytes
));
1539 DEBUG_puts("4httpPrintf: flushing existing data...");
1541 if (httpFlushWrite(http
) < 0)
1545 return (http_write(http
, buf
, bytes
));
1551 * 'httpPut()' - Send a PUT request to the server.
1554 int /* O - Status of call (0 = success) */
1555 httpPut(http_t
*http
, /* I - Connection to server */
1556 const char *uri
) /* I - URI to put */
1558 DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", http
, uri
));
1559 return (http_send(http
, HTTP_PUT
, uri
));
1564 * 'httpRead()' - Read data from a HTTP connection.
1566 * This function is deprecated. Use the httpRead2() function which can
1567 * read more than 2GB of data.
1572 int /* O - Number of bytes read */
1573 httpRead(http_t
*http
, /* I - Connection to server */
1574 char *buffer
, /* I - Buffer for data */
1575 int length
) /* I - Maximum number of bytes */
1577 return ((int)httpRead2(http
, buffer
, length
));
1582 * 'httpRead2()' - Read data from a HTTP connection.
1584 * @since CUPS 1.2/Mac OS X 10.5@
1587 ssize_t
/* O - Number of bytes read */
1588 httpRead2(http_t
*http
, /* I - Connection to server */
1589 char *buffer
, /* I - Buffer for data */
1590 size_t length
) /* I - Maximum number of bytes */
1592 ssize_t bytes
; /* Bytes read */
1593 char len
[32]; /* Length string */
1596 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1597 http
, buffer
, CUPS_LLCAST length
));
1599 if (http
== NULL
|| buffer
== NULL
)
1602 http
->activity
= time(NULL
);
1608 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1609 http
->data_remaining
<= 0)
1611 DEBUG_puts("2httpRead2: Getting chunk length...");
1613 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1615 DEBUG_puts("1httpRead2: Could not get length!");
1619 http
->data_remaining
= strtoll(len
, NULL
, 16);
1620 if (http
->data_remaining
< 0)
1622 DEBUG_puts("1httpRead2: Negative chunk length!");
1627 DEBUG_printf(("2httpRead2: data_remaining=" CUPS_LLFMT
,
1628 CUPS_LLCAST http
->data_remaining
));
1630 if (http
->data_remaining
<= 0)
1633 * A zero-length chunk ends a transfer; unless we are reading POST
1637 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1638 httpGets(len
, sizeof(len
), http
);
1640 if (http
->state
== HTTP_POST_RECV
)
1643 http
->state
= HTTP_WAITING
;
1646 * Prevent future reads for this request...
1649 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1653 else if (length
> (size_t)http
->data_remaining
)
1654 length
= (size_t)http
->data_remaining
;
1656 if (http
->used
== 0 && length
<= 256)
1659 * Buffer small reads for better performance...
1662 if (!http
->blocking
&& !httpWait(http
, 10000))
1665 if (http
->data_remaining
> sizeof(http
->buffer
))
1666 bytes
= sizeof(http
->buffer
);
1668 bytes
= http
->data_remaining
;
1672 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1674 #endif /* HAVE_SSL */
1676 DEBUG_printf(("2httpRead2: reading %d bytes from socket into buffer...",
1679 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1681 DEBUG_printf(("2httpRead2: read %d bytes from socket into buffer...",
1690 http
->error
= WSAGetLastError();
1693 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1695 http
->error
= errno
;
1702 http
->error
= EPIPE
;
1709 if (length
> (size_t)http
->used
)
1710 length
= (size_t)http
->used
;
1712 bytes
= (ssize_t
)length
;
1714 DEBUG_printf(("2httpRead2: grabbing %d bytes from input buffer...",
1717 memcpy(buffer
, http
->buffer
, length
);
1718 http
->used
-= (int)length
;
1721 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
1726 if (!http
->blocking
&& !httpWait(http
, 10000))
1729 bytes
= (ssize_t
)http_read_ssl(http
, buffer
, (int)length
);
1731 #endif /* HAVE_SSL */
1734 if (!http
->blocking
&& !httpWait(http
, 10000))
1737 DEBUG_printf(("2httpRead2: reading " CUPS_LLFMT
" bytes from socket...",
1738 CUPS_LLCAST length
));
1741 bytes
= (ssize_t
)recv(http
->fd
, buffer
, (int)length
, 0);
1743 while ((bytes
= recv(http
->fd
, buffer
, length
, 0)) < 0)
1744 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1748 DEBUG_printf(("2httpRead2: read " CUPS_LLFMT
" bytes from socket...",
1749 CUPS_LLCAST bytes
));
1754 http
->data_remaining
-= bytes
;
1756 if (http
->data_remaining
<= INT_MAX
)
1757 http
->_data_remaining
= (int)http
->data_remaining
;
1759 http
->_data_remaining
= INT_MAX
;
1764 http
->error
= WSAGetLastError();
1766 if (errno
== EINTR
|| errno
== EAGAIN
)
1769 http
->error
= errno
;
1774 http
->error
= EPIPE
;
1778 if (http
->data_remaining
== 0)
1780 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1781 httpGets(len
, sizeof(len
), http
);
1783 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
1785 if (http
->state
== HTTP_POST_RECV
)
1788 http
->state
= HTTP_WAITING
;
1793 http_debug_hex("httpRead2", buffer
, (int)bytes
);
1800 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
1802 * '_httpReadCDSA()' - Read function for the CDSA library.
1805 OSStatus
/* O - -1 on error, 0 on success */
1807 SSLConnectionRef connection
, /* I - SSL/TLS connection */
1808 void *data
, /* I - Data buffer */
1809 size_t *dataLength
) /* IO - Number of bytes */
1811 OSStatus result
; /* Return value */
1812 ssize_t bytes
; /* Number of bytes read */
1813 http_t
*http
; /* HTTP connection */
1816 http
= (http_t
*)connection
;
1818 if (!http
->blocking
)
1821 * Make sure we have data before we read...
1824 if (!_httpWait(http
, 10000, 0))
1826 http
->error
= ETIMEDOUT
;
1833 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
1835 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
1837 if (bytes
== *dataLength
)
1843 *dataLength
= bytes
;
1844 result
= errSSLWouldBlock
;
1851 result
= errSSLClosedGraceful
;
1852 else if (errno
== EAGAIN
)
1853 result
= errSSLWouldBlock
;
1855 result
= errSSLClosedAbort
;
1860 #endif /* HAVE_SSL && HAVE_CDSASSL */
1863 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
1865 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
1868 ssize_t
/* O - Number of bytes read or -1 on error */
1870 gnutls_transport_ptr ptr
, /* I - Connection to server */
1871 void *data
, /* I - Buffer */
1872 size_t length
) /* I - Number of bytes to read */
1874 http_t
*http
; /* HTTP connection */
1877 http
= (http_t
*)ptr
;
1879 if (!http
->blocking
)
1882 * Make sure we have data before we read...
1885 if (!_httpWait(http
, 10000, 0))
1887 http
->error
= ETIMEDOUT
;
1892 return (recv(http
->fd
, data
, length
, 0));
1894 #endif /* HAVE_SSL && HAVE_GNUTLS */
1898 * 'httpReconnect()' - Reconnect to a HTTP server.
1901 int /* O - 0 on success, non-zero on failure */
1902 httpReconnect(http_t
*http
) /* I - Connection to server */
1904 http_addrlist_t
*addr
; /* Connected address */
1906 http_addrlist_t
*current
; /* Current address */
1907 char temp
[256]; /* Temporary address string */
1911 DEBUG_printf(("httpReconnect(http=%p)", http
));
1919 DEBUG_puts("2httpReconnect: Shutting down SSL/TLS...");
1920 http_shutdown_ssl(http
);
1922 #endif /* HAVE_SSL */
1925 * Close any previously open socket...
1930 DEBUG_printf(("2httpReconnect: Closing socket %d...", http
->fd
));
1933 closesocket(http
->fd
);
1942 * Connect to the server...
1946 for (current
= http
->addrlist
; current
; current
= current
->next
)
1947 DEBUG_printf(("2httpReconnect: Address %s:%d",
1948 httpAddrString(&(current
->addr
), temp
, sizeof(temp
)),
1949 _httpAddrPort(&(current
->addr
))));
1952 if ((addr
= httpAddrConnect(http
->addrlist
, &(http
->fd
))) == NULL
)
1955 * Unable to connect...
1959 http
->error
= WSAGetLastError();
1961 http
->error
= errno
;
1963 http
->status
= HTTP_ERROR
;
1965 DEBUG_printf(("1httpReconnect: httpAddrConnect failed: %s",
1966 strerror(http
->error
)));
1971 DEBUG_printf(("2httpReconnect: New socket=%d", http
->fd
));
1973 http
->hostaddr
= &(addr
->addr
);
1975 http
->status
= HTTP_CONTINUE
;
1978 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
1981 * Always do encryption via SSL.
1984 if (http_setup_ssl(http
) != 0)
1987 closesocket(http
->fd
);
1995 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
1996 return (http_upgrade(http
));
1997 #endif /* HAVE_SSL */
1999 DEBUG_printf(("1httpReconnect: Connected to %s:%d...",
2000 httpAddrString(http
->hostaddr
, temp
, sizeof(temp
)),
2001 _httpAddrPort(http
->hostaddr
)));
2008 * 'httpSetAuthString()' - Set the current authorization string.
2010 * This function just stores a copy of the current authorization string in
2011 * the HTTP connection object. You must still call httpSetField() to set
2012 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
2013 * httpHead(), httpOptions(), httpPost, or httpPut().
2015 * @since CUPS 1.3/Mac OS X 10.5@
2019 httpSetAuthString(http_t
*http
, /* I - Connection to server */
2020 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
2021 const char *data
) /* I - Auth data (NULL for none) */
2024 * Range check input...
2030 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
2031 free(http
->authstring
);
2033 http
->authstring
= http
->_authstring
;
2038 * Set the current authorization string...
2041 int len
= (int)strlen(scheme
) + (data
? (int)strlen(data
) + 1 : 0) + 1;
2044 if (len
> (int)sizeof(http
->_authstring
))
2046 if ((temp
= malloc(len
)) == NULL
)
2047 len
= sizeof(http
->_authstring
);
2049 http
->authstring
= temp
;
2053 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
2055 strlcpy(http
->authstring
, scheme
, len
);
2060 * Clear the current authorization string...
2063 http
->_authstring
[0] = '\0';
2069 * 'httpSetCookie()' - Set the cookie value(s).
2071 * @since CUPS 1.1.19/Mac OS X 10.3@
2075 httpSetCookie(http_t
*http
, /* I - Connection */
2076 const char *cookie
) /* I - Cookie string */
2085 http
->cookie
= strdup(cookie
);
2087 http
->cookie
= NULL
;
2092 * 'httpSetExpect()' - Set the Expect: header in a request.
2094 * Currently only HTTP_CONTINUE is supported for the "expect" argument.
2096 * @since CUPS 1.2/Mac OS X 10.5@
2100 httpSetExpect(http_t
*http
, /* I - Connection to server */
2101 http_status_t expect
) /* I - HTTP status to expect (HTTP_CONTINUE) */
2104 http
->expect
= expect
;
2109 * 'httpSetField()' - Set the value of an HTTP header.
2113 httpSetField(http_t
*http
, /* I - Connection to server */
2114 http_field_t field
, /* I - Field index */
2115 const char *value
) /* I - Value */
2118 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
2119 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
2123 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
2125 if (field
== HTTP_FIELD_AUTHORIZATION
)
2128 * Special case for Authorization: as its contents can be
2129 * longer than HTTP_MAX_VALUE
2132 if (http
->field_authorization
)
2133 free(http
->field_authorization
);
2135 http
->field_authorization
= strdup(value
);
2137 else if (field
== HTTP_FIELD_HOST
)
2140 * Special-case for Host: as we don't want a trailing "." on the hostname and
2141 * need to bracket IPv6 numeric addresses.
2144 char *ptr
= strchr(value
, ':');
2146 if (value
[0] != '[' && ptr
&& strchr(ptr
+ 1, ':'))
2149 * Bracket IPv6 numeric addresses...
2151 * This is slightly inefficient (basically copying twice), but is an edge
2152 * case and not worth optimizing...
2155 snprintf(http
->fields
[HTTP_FIELD_HOST
],
2156 sizeof(http
->fields
[HTTP_FIELD_HOST
]), "[%s]", value
);
2161 * Check for a trailing dot on the hostname...
2164 ptr
= http
->fields
[HTTP_FIELD_HOST
];
2168 ptr
+= strlen(ptr
) - 1;
2179 * 'httpSetLength()' - Set the content-length and content-encoding.
2181 * @since CUPS 1.2/Mac OS X 10.5@
2185 httpSetLength(http_t
*http
, /* I - Connection to server */
2186 size_t length
) /* I - Length (0 for chunked) */
2193 strcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked");
2194 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
2198 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
2199 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
2200 CUPS_LLFMT
, CUPS_LLCAST length
);
2206 * 'httpTrace()' - Send an TRACE request to the server.
2209 int /* O - Status of call (0 = success) */
2210 httpTrace(http_t
*http
, /* I - Connection to server */
2211 const char *uri
) /* I - URI for trace */
2213 return (http_send(http
, HTTP_TRACE
, uri
));
2218 * 'httpUpdate()' - Update the current HTTP state for incoming data.
2221 http_status_t
/* O - HTTP status */
2222 httpUpdate(http_t
*http
) /* I - Connection to server */
2224 char line
[32768], /* Line from connection... */
2225 *value
; /* Pointer to value on line */
2226 http_field_t field
; /* Field index */
2227 int major
, minor
, /* HTTP version numbers */
2228 status
; /* Request status */
2231 DEBUG_printf(("httpUpdate(http=%p), state=%s", http
,
2232 http_states
[http
->state
]));
2235 * Flush pending data, if any...
2240 DEBUG_puts("2httpUpdate: flushing buffer...");
2242 if (httpFlushWrite(http
) < 0)
2243 return (HTTP_ERROR
);
2247 * If we haven't issued any commands, then there is nothing to "update"...
2250 if (http
->state
== HTTP_WAITING
)
2251 return (HTTP_CONTINUE
);
2254 * Grab all of the lines we can from the connection...
2257 while (httpGets(line
, sizeof(line
), http
) != NULL
)
2259 DEBUG_printf(("2httpUpdate: Got \"%s\"", line
));
2261 if (line
[0] == '\0')
2264 * Blank line means the start of the data section (if any). Return
2265 * the result code, too...
2267 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
2268 * Instead, we just return HTTP_CONTINUE to the caller and keep on
2272 if (http
->status
== HTTP_CONTINUE
)
2273 return (http
->status
);
2275 if (http
->status
< HTTP_BAD_REQUEST
)
2276 http
->digest_tries
= 0;
2279 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
2281 if (http_setup_ssl(http
) != 0)
2284 closesocket(http
->fd
);
2289 return (HTTP_ERROR
);
2292 return (HTTP_CONTINUE
);
2294 #endif /* HAVE_SSL */
2296 httpGetLength2(http
);
2298 switch (http
->state
)
2302 case HTTP_POST_RECV
:
2305 case HTTP_POST_SEND
:
2310 http
->state
= HTTP_WAITING
;
2314 return (http
->status
);
2316 else if (!strncmp(line
, "HTTP/", 5))
2319 * Got the beginning of a response...
2322 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &status
) != 3)
2323 return (HTTP_ERROR
);
2325 http
->version
= (http_version_t
)(major
* 100 + minor
);
2326 http
->status
= (http_status_t
)status
;
2328 else if ((value
= strchr(line
, ':')) != NULL
)
2335 while (isspace(*value
& 255))
2339 * Be tolerants of servers that send unknown attribute fields...
2342 if (!strcasecmp(line
, "expect"))
2345 * "Expect: 100-continue" or similar...
2348 http
->expect
= (http_status_t
)atoi(value
);
2350 else if (!strcasecmp(line
, "cookie"))
2353 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
2356 httpSetCookie(http
, value
);
2358 else if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
2360 DEBUG_printf(("1httpUpdate: unknown field %s seen!", line
));
2364 httpSetField(http
, field
, value
);
2368 DEBUG_printf(("1httpUpdate: Bad response line \"%s\"!", line
));
2369 http
->status
= HTTP_ERROR
;
2370 return (HTTP_ERROR
);
2375 * See if there was an error...
2378 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
2380 DEBUG_printf(("1httpUpdate: Returning status %d...", http
->status
));
2381 return (http
->status
);
2386 DEBUG_printf(("1httpUpdate: socket error %d - %s", http
->error
,
2387 strerror(http
->error
)));
2388 http
->status
= HTTP_ERROR
;
2389 return (HTTP_ERROR
);
2393 * If we haven't already returned, then there is nothing new...
2396 return (HTTP_CONTINUE
);
2401 * '_httpWait()' - Wait for data available on a connection (no flush).
2404 int /* O - 1 if data is available, 0 otherwise */
2405 _httpWait(http_t
*http
, /* I - Connection to server */
2406 int msec
, /* I - Milliseconds to wait */
2407 int usessl
) /* I - Use SSL context? */
2410 struct pollfd pfd
; /* Polled file descriptor */
2412 fd_set input_set
; /* select() input set */
2413 struct timeval timeout
; /* Timeout */
2414 #endif /* HAVE_POLL */
2415 int nfds
; /* Result from select()/poll() */
2418 DEBUG_printf(("4_httpWait(http=%p, msec=%d, usessl=%d)", http
, msec
, usessl
));
2422 DEBUG_printf(("5_httpWait: Returning 0 since fd=%d", http
->fd
));
2427 * Check the SSL/TLS buffers for data first...
2431 if (http
->tls
&& usessl
)
2434 if (SSL_pending((SSL
*)(http
->tls
)))
2436 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2440 # elif defined(HAVE_GNUTLS)
2441 if (gnutls_record_check_pending(((http_tls_t
*)(http
->tls
))->session
))
2443 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2447 # elif defined(HAVE_CDSASSL)
2448 size_t bytes
; /* Bytes that are available */
2450 if (!SSLGetBufferedReadSize(((http_tls_t
*)(http
->tls
))->session
, &bytes
) &&
2453 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2456 # endif /* HAVE_LIBSSL */
2458 #endif /* HAVE_SSL */
2461 * Then try doing a select() or poll() to poll the socket...
2466 pfd
.events
= POLLIN
;
2468 while ((nfds
= poll(&pfd
, 1, msec
)) < 0 &&
2469 (errno
== EINTR
|| errno
== EAGAIN
));
2474 FD_ZERO(&input_set
);
2475 FD_SET(http
->fd
, &input_set
);
2477 DEBUG_printf(("6_httpWait: msec=%d, http->fd=%d", msec
, http
->fd
));
2481 timeout
.tv_sec
= msec
/ 1000;
2482 timeout
.tv_usec
= (msec
% 1000) * 1000;
2484 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
2487 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
2489 DEBUG_printf(("6_httpWait: select() returned %d...", nfds
));
2492 while (nfds
< 0 && WSAGetLastError() == WSAEINTR
);
2494 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
2496 #endif /* HAVE_POLL */
2498 DEBUG_printf(("5_httpWait: returning with nfds=%d, errno=%d...", nfds
,
2506 * 'httpWait()' - Wait for data available on a connection.
2508 * @since CUPS 1.1.19/Mac OS X 10.3@
2511 int /* O - 1 if data is available, 0 otherwise */
2512 httpWait(http_t
*http
, /* I - Connection to server */
2513 int msec
) /* I - Milliseconds to wait */
2516 * First see if there is data in the buffer...
2526 * Flush pending data, if any...
2531 if (httpFlushWrite(http
) < 0)
2536 * If not, check the SSL/TLS buffers and do a select() on the connection...
2539 return (_httpWait(http
, msec
, 1));
2544 * 'httpWrite()' - Write data to a HTTP connection.
2546 * This function is deprecated. Use the httpWrite2() function which can
2547 * write more than 2GB of data.
2552 int /* O - Number of bytes written */
2553 httpWrite(http_t
*http
, /* I - Connection to server */
2554 const char *buffer
, /* I - Buffer for data */
2555 int length
) /* I - Number of bytes to write */
2557 return ((int)httpWrite2(http
, buffer
, length
));
2562 * 'httpWrite2()' - Write data to a HTTP connection.
2564 * @since CUPS 1.2/Mac OS X 10.5@
2567 ssize_t
/* O - Number of bytes written */
2568 httpWrite2(http_t
*http
, /* I - Connection to server */
2569 const char *buffer
, /* I - Buffer for data */
2570 size_t length
) /* I - Number of bytes to write */
2572 ssize_t bytes
; /* Bytes written */
2575 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
2576 buffer
, CUPS_LLCAST length
));
2579 * Range check input...
2582 if (http
== NULL
|| buffer
== NULL
)
2586 * Mark activity on the connection...
2589 http
->activity
= time(NULL
);
2592 * Buffer small writes for better performance...
2597 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
2599 DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
2600 CUPS_LLFMT
")", http
->wused
, CUPS_LLCAST length
));
2602 httpFlushWrite(http
);
2605 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
) &&
2606 length
< sizeof(http
->wbuffer
))
2609 * Write to buffer...
2612 DEBUG_printf(("2httpWrite2: Copying " CUPS_LLFMT
" bytes to wbuffer...",
2613 CUPS_LLCAST length
));
2615 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
2616 http
->wused
+= (int)length
;
2617 bytes
= (ssize_t
)length
;
2622 * Otherwise write the data directly...
2625 DEBUG_printf(("2httpWrite2: Writing " CUPS_LLFMT
" bytes to socket...",
2626 CUPS_LLCAST length
));
2628 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2629 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
2631 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
2633 DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT
" bytes...",
2634 CUPS_LLCAST bytes
));
2637 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
2638 http
->data_remaining
-= bytes
;
2644 * Handle end-of-request processing...
2647 if ((http
->data_encoding
== HTTP_ENCODE_CHUNKED
&& length
== 0) ||
2648 (http
->data_encoding
== HTTP_ENCODE_LENGTH
&& http
->data_remaining
== 0))
2651 * Finished with the transfer; unless we are sending POST or PUT
2655 DEBUG_puts("2httpWrite: changing states...");
2658 httpFlushWrite(http
);
2660 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2663 * Send a 0-length chunk at the end of the request...
2666 http_write(http
, "0\r\n\r\n", 5);
2669 * Reset the data state...
2672 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
2673 http
->data_remaining
= 0;
2676 if (http
->state
== HTTP_POST_RECV
)
2678 else if (http
->state
== HTTP_PUT_RECV
)
2679 http
->state
= HTTP_STATUS
;
2681 http
->state
= HTTP_WAITING
;
2688 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2690 * '_httpWriteCDSA()' - Write function for the CDSA library.
2693 OSStatus
/* O - -1 on error, 0 on success */
2695 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2696 const void *data
, /* I - Data buffer */
2697 size_t *dataLength
) /* IO - Number of bytes */
2699 OSStatus result
; /* Return value */
2700 ssize_t bytes
; /* Number of bytes read */
2701 http_t
*http
; /* HTTP connection */
2704 http
= (http_t
*)connection
;
2708 bytes
= write(http
->fd
, data
, *dataLength
);
2710 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
2712 if (bytes
== *dataLength
)
2716 else if (bytes
>= 0)
2718 *dataLength
= bytes
;
2719 result
= errSSLWouldBlock
;
2725 if (errno
== EAGAIN
)
2726 result
= errSSLWouldBlock
;
2728 result
= errSSLClosedAbort
;
2733 #endif /* HAVE_SSL && HAVE_CDSASSL */
2736 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2738 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
2741 ssize_t
/* O - Number of bytes written or -1 on error */
2743 gnutls_transport_ptr ptr
, /* I - Connection to server */
2744 const void *data
, /* I - Data buffer */
2745 size_t length
) /* I - Number of bytes to write */
2747 return (send(((http_t
*)ptr
)->fd
, data
, length
, 0));
2749 #endif /* HAVE_SSL && HAVE_GNUTLS */
2752 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
2754 * 'http_bio_ctrl()' - Control the HTTP connection.
2757 static long /* O - Result/data */
2758 http_bio_ctrl(BIO
*h
, /* I - BIO data */
2759 int cmd
, /* I - Control command */
2760 long arg1
, /* I - First argument */
2761 void *arg2
) /* I - Second argument */
2768 case BIO_CTRL_RESET
:
2772 case BIO_C_SET_FILE_PTR
:
2777 case BIO_C_GET_FILE_PTR
:
2780 *((void **)arg2
) = h
->ptr
;
2787 case BIO_CTRL_FLUSH
:
2794 * 'http_bio_free()' - Free OpenSSL data.
2797 static int /* O - 1 on success, 0 on failure */
2798 http_bio_free(BIO
*h
) /* I - BIO data */
2814 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
2817 static int /* O - 1 on success, 0 on failure */
2818 http_bio_new(BIO
*h
) /* I - BIO data */
2833 * 'http_bio_puts()' - Send a string for OpenSSL.
2836 static int /* O - Bytes written */
2837 http_bio_puts(BIO
*h
, /* I - BIO data */
2838 const char *str
) /* I - String to write */
2841 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
2843 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
2849 * 'http_bio_read()' - Read data for OpenSSL.
2852 static int /* O - Bytes read */
2853 http_bio_read(BIO
*h
, /* I - BIO data */
2854 char *buf
, /* I - Buffer */
2855 int size
) /* I - Number of bytes to read */
2857 http_t
*http
; /* HTTP connection */
2860 http
= (http_t
*)h
->ptr
;
2862 if (!http
->blocking
)
2865 * Make sure we have data before we read...
2868 if (!_httpWait(http
, 10000, 0))
2871 http
->error
= WSAETIMEDOUT
;
2873 http
->error
= ETIMEDOUT
;
2880 return (recv(http
->fd
, buf
, size
, 0));
2885 * 'http_bio_write()' - Write data for OpenSSL.
2888 static int /* O - Bytes written */
2889 http_bio_write(BIO
*h
, /* I - BIO data */
2890 const char *buf
, /* I - Buffer to write */
2891 int num
) /* I - Number of bytes to write */
2893 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
2895 #endif /* HAVE_SSL && HAVE_LIBSSL */
2900 * 'http_debug_hex()' - Do a hex dump of a buffer.
2904 http_debug_hex(const char *prefix
, /* I - Prefix for line */
2905 const char *buffer
, /* I - Buffer to dump */
2906 int bytes
) /* I - Bytes to dump */
2908 int i
, j
, /* Looping vars */
2909 ch
; /* Current character */
2910 char line
[255], /* Line buffer */
2911 *start
, /* Start of line after prefix */
2912 *ptr
; /* Pointer into line */
2915 if (_cups_debug_fd
< 0 || _cups_debug_level
< 6)
2918 DEBUG_printf(("6%s: %d bytes:\n", prefix
, bytes
));
2920 snprintf(line
, sizeof(line
), "6%s: ", prefix
);
2921 start
= line
+ strlen(line
);
2923 for (i
= 0; i
< bytes
; i
+= 16)
2925 for (j
= 0, ptr
= start
; j
< 16 && (i
+ j
) < bytes
; j
++, ptr
+= 2)
2926 sprintf(ptr
, "%02X", buffer
[i
+ j
] & 255);
2938 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
2940 ch
= buffer
[i
+ j
] & 255;
2942 if (ch
< ' ' || ch
>= 127)
2956 * 'http_field()' - Return the field index for a field name.
2959 static http_field_t
/* O - Field index */
2960 http_field(const char *name
) /* I - String name */
2962 int i
; /* Looping var */
2965 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2966 if (strcasecmp(name
, http_fields
[i
]) == 0)
2967 return ((http_field_t
)i
);
2969 return (HTTP_FIELD_UNKNOWN
);
2975 * 'http_read_ssl()' - Read from a SSL/TLS connection.
2978 static int /* O - Bytes read */
2979 http_read_ssl(http_t
*http
, /* I - Connection to server */
2980 char *buf
, /* I - Buffer to store data */
2981 int len
) /* I - Length of buffer */
2983 # if defined(HAVE_LIBSSL)
2984 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
2986 # elif defined(HAVE_GNUTLS)
2987 ssize_t result
; /* Return value */
2990 result
= gnutls_record_recv(((http_tls_t
*)(http
->tls
))->session
, buf
, len
);
2992 if (result
< 0 && !errno
)
2995 * Convert GNU TLS error to errno value...
3000 case GNUTLS_E_INTERRUPTED
:
3004 case GNUTLS_E_AGAIN
:
3016 return ((int)result
);
3018 # elif defined(HAVE_CDSASSL)
3019 int result
; /* Return value */
3020 OSStatus error
; /* Error info */
3021 size_t processed
; /* Number of bytes processed */
3024 error
= SSLRead(((http_tls_t
*)http
->tls
)->session
, buf
, len
, &processed
);
3029 result
= (int)processed
;
3031 case errSSLClosedGraceful
:
3034 case errSSLWouldBlock
:
3036 result
= (int)processed
;
3050 # endif /* HAVE_LIBSSL */
3052 #endif /* HAVE_SSL */
3057 * 'http_locking_cb()' - Lock/unlock a thread's mutex.
3061 http_locking_cb(int mode
, /* I - Lock mode */
3062 int type
, /* I - Lock type */
3063 const char *file
, /* I - Source file */
3064 int line
) /* I - Line number */
3066 if (mode
& CRYPTO_LOCK
)
3067 _cupsMutexLock(http_locks
+ type
);
3069 _cupsMutexUnlock(http_locks
+ type
);
3071 #endif /* HAVE_LIBSSL */
3075 * 'http_send()' - Send a request with all fields and the trailing blank line.
3078 static int /* O - 0 on success, non-zero on error */
3079 http_send(http_t
*http
, /* I - Connection to server */
3080 http_state_t request
, /* I - Request code */
3081 const char *uri
) /* I - URI */
3083 int i
; /* Looping var */
3084 char buf
[1024]; /* Encoded URI buffer */
3085 static const char * const codes
[] =
3086 { /* Request code strings */
3103 DEBUG_printf(("7http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
3104 http
, codes
[request
], uri
));
3106 if (http
== NULL
|| uri
== NULL
)
3110 * Set the User-Agent field if it isn't already...
3113 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
3114 httpSetField(http
, HTTP_FIELD_USER_AGENT
, CUPS_MINIMAL
);
3117 * Encode the URI as needed...
3120 _httpEncodeURI(buf
, uri
, sizeof(buf
));
3123 * See if we had an error the last time around; if so, reconnect...
3126 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
3127 if (httpReconnect(http
))
3131 * Flush any written data that is pending...
3136 if (httpFlushWrite(http
) < 0)
3137 if (httpReconnect(http
))
3142 * Send the request header...
3145 http
->state
= request
;
3146 http
->data_encoding
= HTTP_ENCODE_FIELDS
;
3148 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
3151 http
->status
= HTTP_CONTINUE
;
3154 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
3156 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
3157 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
3159 #endif /* HAVE_SSL */
3161 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
3163 http
->status
= HTTP_ERROR
;
3167 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3168 if (http
->fields
[i
][0] != '\0')
3170 DEBUG_printf(("9http_send: %s: %s", http_fields
[i
],
3171 httpGetField(http
, i
)));
3173 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
],
3174 httpGetField(http
, i
)) < 1)
3176 http
->status
= HTTP_ERROR
;
3182 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
3184 http
->status
= HTTP_ERROR
;
3188 if (http
->expect
== HTTP_CONTINUE
&&
3189 (http
->state
== HTTP_POST_RECV
|| http
->state
== HTTP_PUT_RECV
))
3190 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
3192 http
->status
= HTTP_ERROR
;
3196 if (httpPrintf(http
, "\r\n") < 1)
3198 http
->status
= HTTP_ERROR
;
3202 if (httpFlushWrite(http
) < 0)
3205 httpGetLength2(http
);
3206 httpClearFields(http
);
3209 * The Kerberos and AuthRef authentication strings can only be used once...
3212 if (http
->field_authorization
&& http
->authstring
&&
3213 (!strncmp(http
->authstring
, "Negotiate", 9) ||
3214 !strncmp(http
->authstring
, "AuthRef", 7)))
3216 http
->_authstring
[0] = '\0';
3218 if (http
->authstring
!= http
->_authstring
)
3219 free(http
->authstring
);
3221 http
->authstring
= http
->_authstring
;
3230 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
3233 static int /* O - Status of connection */
3234 http_setup_ssl(http_t
*http
) /* I - Connection to server */
3237 SSL_CTX
*context
; /* Context for encryption */
3238 SSL
*conn
; /* Connection for encryption */
3239 BIO
*bio
; /* BIO data */
3240 # elif defined(HAVE_GNUTLS)
3241 http_tls_t
*conn
; /* TLS session object */
3242 gnutls_certificate_client_credentials
*credentials
;
3243 /* TLS credentials */
3244 # elif defined(HAVE_CDSASSL)
3245 OSStatus error
; /* Error code */
3246 http_tls_t
*conn
; /* CDSA connection information */
3247 # endif /* HAVE_LIBSSL */
3250 DEBUG_printf(("7http_setup_ssl(http=%p)", http
));
3253 context
= SSL_CTX_new(SSLv23_client_method());
3255 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
3257 bio
= BIO_new(_httpBIOMethods());
3258 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
3260 conn
= SSL_new(context
);
3261 SSL_set_bio(conn
, bio
, bio
);
3263 if (SSL_connect(conn
) != 1)
3266 unsigned long error
; /* Error code */
3268 while ((error
= ERR_get_error()) != 0)
3269 DEBUG_printf(("8http_setup_ssl: %s", ERR_error_string(error
, NULL
)));
3272 SSL_CTX_free(context
);
3276 http
->error
= WSAGetLastError();
3278 http
->error
= errno
;
3280 http
->status
= HTTP_ERROR
;
3282 return (HTTP_ERROR
);
3285 # elif defined(HAVE_GNUTLS)
3286 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
3288 http
->error
= errno
;
3289 http
->status
= HTTP_ERROR
;
3294 credentials
= (gnutls_certificate_client_credentials
*)
3295 malloc(sizeof(gnutls_certificate_client_credentials
));
3296 if (credentials
== NULL
)
3300 http
->error
= errno
;
3301 http
->status
= HTTP_ERROR
;
3306 gnutls_certificate_allocate_credentials(credentials
);
3308 gnutls_init(&(conn
->session
), GNUTLS_CLIENT
);
3309 gnutls_set_default_priority(conn
->session
);
3310 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
3311 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)http
);
3312 gnutls_transport_set_pull_function(conn
->session
, _httpReadGNUTLS
);
3313 gnutls_transport_set_push_function(conn
->session
, _httpWriteGNUTLS
);
3315 if ((gnutls_handshake(conn
->session
)) != GNUTLS_E_SUCCESS
)
3317 http
->error
= errno
;
3318 http
->status
= HTTP_ERROR
;
3320 gnutls_deinit(conn
->session
);
3321 gnutls_certificate_free_credentials(*credentials
);
3328 conn
->credentials
= credentials
;
3330 # elif defined(HAVE_CDSASSL)
3331 conn
= (http_tls_t
*)calloc(1, sizeof(http_tls_t
));
3336 if ((error
= SSLNewContext(false, &conn
->session
)))
3338 http
->error
= error
;
3339 http
->status
= HTTP_ERROR
;
3346 * Use a union to resolve warnings about int/pointer size mismatches...
3349 error
= SSLSetConnection(conn
->session
, http
);
3352 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
3355 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
3358 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
3361 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
3365 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
3371 http
->error
= error
;
3372 http
->status
= HTTP_ERROR
;
3374 SSLDisposeContext(conn
->session
);
3380 # endif /* HAVE_CDSASSL */
3385 #endif /* HAVE_SSL */
3390 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
3394 http_shutdown_ssl(http_t
*http
) /* I - Connection to server */
3397 SSL_CTX
*context
; /* Context for encryption */
3398 SSL
*conn
; /* Connection for encryption */
3401 conn
= (SSL
*)(http
->tls
);
3402 context
= SSL_get_SSL_CTX(conn
);
3405 SSL_CTX_free(context
);
3408 # elif defined(HAVE_GNUTLS)
3409 http_tls_t
*conn
; /* Encryption session */
3410 gnutls_certificate_client_credentials
*credentials
;
3411 /* TLS credentials */
3414 conn
= (http_tls_t
*)(http
->tls
);
3415 credentials
= (gnutls_certificate_client_credentials
*)(conn
->credentials
);
3417 gnutls_bye(conn
->session
, GNUTLS_SHUT_RDWR
);
3418 gnutls_deinit(conn
->session
);
3419 gnutls_certificate_free_credentials(*credentials
);
3423 # elif defined(HAVE_CDSASSL)
3424 http_tls_t
*conn
; /* CDSA connection information */
3427 conn
= (http_tls_t
*)(http
->tls
);
3429 while (SSLClose(conn
->session
) == errSSLWouldBlock
)
3432 SSLDisposeContext(conn
->session
);
3434 if (conn
->certsArray
)
3435 CFRelease(conn
->certsArray
);
3438 # endif /* HAVE_LIBSSL */
3442 #endif /* HAVE_SSL */
3447 * 'http_threadid_cb()' - Return the current thread ID.
3450 static unsigned long /* O - Thread ID */
3451 http_threadid_cb(void)
3453 # ifdef HAVE_PTHREAD_H
3454 return ((unsigned long)pthread_self());
3457 # endif /* HAVE_PTHREAD_H */
3459 #endif /* HAVE_LIBSSL */
3464 * 'http_upgrade()' - Force upgrade to TLS encryption.
3467 static int /* O - Status of connection */
3468 http_upgrade(http_t
*http
) /* I - Connection to server */
3470 int ret
; /* Return value */
3471 http_t myhttp
; /* Local copy of HTTP data */
3474 DEBUG_printf(("7http_upgrade(%p)", http
));
3477 * Flush the connection to make sure any previous "Upgrade" message
3484 * Copy the HTTP data to a local variable so we can do the OPTIONS
3485 * request without interfering with the existing request data...
3488 memcpy(&myhttp
, http
, sizeof(myhttp
));
3491 * Send an OPTIONS request to the server, requiring SSL or TLS
3492 * encryption on the link...
3495 http
->field_authorization
= NULL
; /* Don't free the auth string */
3497 httpClearFields(http
);
3498 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
3499 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0, SSL/2.0, SSL/3.0");
3501 if ((ret
= httpOptions(http
, "*")) == 0)
3504 * Wait for the secure connection...
3507 while (httpUpdate(http
) == HTTP_CONTINUE
);
3511 * Restore the HTTP request data...
3514 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
3515 http
->data_encoding
= myhttp
.data_encoding
;
3516 http
->data_remaining
= myhttp
.data_remaining
;
3517 http
->_data_remaining
= myhttp
._data_remaining
;
3518 http
->expect
= myhttp
.expect
;
3519 http
->field_authorization
= myhttp
.field_authorization
;
3520 http
->digest_tries
= myhttp
.digest_tries
;
3523 * See if we actually went secure...
3529 * Server does not support HTTP upgrade...
3532 DEBUG_puts("8http_upgrade: Server does not support HTTP upgrade!");
3535 closesocket(http
->fd
);
3547 #endif /* HAVE_SSL */
3551 * 'http_write()' - Write a buffer to a HTTP connection.
3554 static int /* O - Number of bytes written */
3555 http_write(http_t
*http
, /* I - Connection to server */
3556 const char *buffer
, /* I - Buffer for data */
3557 int length
) /* I - Number of bytes to write */
3559 int tbytes
, /* Total bytes sent */
3560 bytes
; /* Bytes sent */
3563 DEBUG_printf(("2http_write(http=%p, buffer=%p, length=%d)", http
, buffer
,
3572 bytes
= http_write_ssl(http
, buffer
, length
);
3574 #endif /* HAVE_SSL */
3575 bytes
= send(http
->fd
, buffer
, length
, 0);
3580 if (WSAGetLastError() != http
->error
)
3582 http
->error
= WSAGetLastError();
3586 if (errno
== EINTR
|| errno
== EAGAIN
)
3588 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
3590 http
->error
= errno
;
3595 DEBUG_printf(("3http_write: error writing data (%s).",
3596 strerror(http
->error
)));
3607 http_debug_hex("http_write", buffer
- tbytes
, tbytes
);
3610 DEBUG_printf(("3http_write: Returning %d.", tbytes
));
3617 * 'http_write_chunk()' - Write a chunked buffer.
3620 static int /* O - Number bytes written */
3621 http_write_chunk(http_t
*http
, /* I - Connection to server */
3622 const char *buffer
, /* I - Buffer to write */
3623 int length
) /* I - Length of buffer */
3625 char header
[255]; /* Chunk header */
3626 int bytes
; /* Bytes written */
3629 DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=%d)",
3630 http
, buffer
, length
));
3633 * Write the chunk header, data, and trailer.
3636 sprintf(header
, "%x\r\n", length
);
3637 if (http_write(http
, header
, (int)strlen(header
)) < 0)
3639 DEBUG_puts("8http_write_chunk: http_write of length failed!");
3643 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
3645 DEBUG_puts("8http_write_chunk: http_write of buffer failed!");
3649 if (http_write(http
, "\r\n", 2) < 0)
3651 DEBUG_puts("8http_write_chunk: http_write of CR LF failed!");
3661 * 'http_write_ssl()' - Write to a SSL/TLS connection.
3664 static int /* O - Bytes written */
3665 http_write_ssl(http_t
*http
, /* I - Connection to server */
3666 const char *buf
, /* I - Buffer holding data */
3667 int len
) /* I - Length of buffer */
3669 ssize_t result
; /* Return value */
3672 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http
, buf
, len
));
3674 # if defined(HAVE_LIBSSL)
3675 result
= SSL_write((SSL
*)(http
->tls
), buf
, len
);
3677 # elif defined(HAVE_GNUTLS)
3678 result
= gnutls_record_send(((http_tls_t
*)(http
->tls
))->session
, buf
, len
);
3680 if (result
< 0 && !errno
)
3683 * Convert GNU TLS error to errno value...
3688 case GNUTLS_E_INTERRUPTED
:
3692 case GNUTLS_E_AGAIN
:
3704 # elif defined(HAVE_CDSASSL)
3705 OSStatus error
; /* Error info */
3706 size_t processed
; /* Number of bytes processed */
3709 error
= SSLWrite(((http_tls_t
*)http
->tls
)->session
, buf
, len
, &processed
);
3714 result
= (int)processed
;
3716 case errSSLClosedGraceful
:
3719 case errSSLWouldBlock
:
3721 result
= (int)processed
;
3733 # endif /* HAVE_LIBSSL */
3735 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result
));
3737 return ((int)result
);
3739 #endif /* HAVE_SSL */
3743 * End of "$Id: http.c 7850 2008-08-20 00:07:25Z mike $".