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"
110 # include <sys/time.h>
111 # include <sys/resource.h>
114 # include <sys/poll.h>
115 #endif /* HAVE_POLL */
119 * Some operating systems have done away with the Fxxxx constants for
120 * the fcntl() call; this works around that "feature"...
124 # define FNONBLK O_NONBLOCK
125 #endif /* !FNONBLK */
133 static void http_debug_hex(const char *prefix
, const char *buffer
,
136 static http_field_t
http_field(const char *name
);
137 static int http_send(http_t
*http
, http_state_t request
,
139 static int http_write(http_t
*http
, const char *buffer
,
141 static int http_write_chunk(http_t
*http
, const char *buffer
,
144 static int http_read_ssl(http_t
*http
, char *buf
, int len
);
145 static int http_setup_ssl(http_t
*http
);
146 static void http_shutdown_ssl(http_t
*http
);
147 static int http_upgrade(http_t
*http
);
148 static int http_write_ssl(http_t
*http
, const char *buf
, int len
);
151 # ifdef HAVE_PTHREAD_H
152 GCRY_THREAD_OPTION_PTHREAD_IMPL
;
153 # endif /* HAVE_PTHREAD_H */
155 # elif defined(HAVE_LIBSSL)
156 static _cups_mutex_t
*http_locks
; /* OpenSSL lock mutexes */
158 static void http_locking_cb(int mode
, int type
, const char *file
,
160 static unsigned long http_threadid_cb(void);
161 # endif /* HAVE_GNUTLS */
162 #endif /* HAVE_SSL */
169 static const char * const http_fields
[] =
186 "If-Unmodified-since",
200 static const char * const http_states
[] =
220 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
222 * BIO methods for OpenSSL...
225 static int http_bio_write(BIO
*h
, const char *buf
, int num
);
226 static int http_bio_read(BIO
*h
, char *buf
, int size
);
227 static int http_bio_puts(BIO
*h
, const char *str
);
228 static long http_bio_ctrl(BIO
*h
, int cmd
, long arg1
, void *arg2
);
229 static int http_bio_new(BIO
*h
);
230 static int http_bio_free(BIO
*data
);
232 static BIO_METHOD http_bio_methods
=
239 NULL
, /* http_bio_gets, */
248 * '_httpBIOMethods()' - Get the OpenSSL BIO methods for HTTP connections.
251 BIO_METHOD
* /* O - BIO methods for OpenSSL */
252 _httpBIOMethods(void)
254 return (&http_bio_methods
);
256 #endif /* HAVE_SSL && HAVE_LIBSSL */
260 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
264 httpBlocking(http_t
*http
, /* I - Connection to server */
265 int b
) /* I - 1 = blocking, 0 = non-blocking */
273 * 'httpCheck()' - Check to see if there is a pending response from the server.
276 int /* O - 0 = no data, 1 = data available */
277 httpCheck(http_t
*http
) /* I - Connection to server */
279 return (httpWait(http
, 0));
284 * 'httpClearCookie()' - Clear the cookie value(s).
286 * @since CUPS 1.1.19/Mac OS X 10.3@
290 httpClearCookie(http_t
*http
) /* I - Connection to server */
304 * 'httpClearFields()' - Clear HTTP request fields.
308 httpClearFields(http_t
*http
) /* I - Connection to server */
312 memset(http
->fields
, 0, sizeof(http
->fields
));
313 if (http
->hostname
[0] == '/')
314 httpSetField(http
, HTTP_FIELD_HOST
, "localhost");
316 httpSetField(http
, HTTP_FIELD_HOST
, http
->hostname
);
318 if (http
->field_authorization
)
320 free(http
->field_authorization
);
321 http
->field_authorization
= NULL
;
324 http
->expect
= (http_status_t
)0;
330 * 'httpClose()' - Close an HTTP connection.
334 httpClose(http_t
*http
) /* I - Connection to server */
337 OM_uint32 minor_status
; /* Minor status code */
338 #endif /* HAVE_GSSAPI */
341 DEBUG_printf(("httpClose(http=%p)", http
));
344 * Range check input...
351 * Close any open connection...
354 _httpDisconnect(http
);
357 * Free memory used...
360 httpAddrFreeList(http
->addrlist
);
366 if (http
->gssctx
!= GSS_C_NO_CONTEXT
)
367 gss_delete_sec_context(&minor_status
, &http
->gssctx
, GSS_C_NO_BUFFER
);
369 if (http
->gssname
!= GSS_C_NO_NAME
)
370 gss_release_name(&minor_status
, &http
->gssname
);
371 #endif /* HAVE_GSSAPI */
373 #ifdef HAVE_AUTHORIZATION_H
375 AuthorizationFree(http
->auth_ref
, kAuthorizationFlagDefaults
);
376 #endif /* HAVE_AUTHORIZATION_H */
378 httpClearFields(http
);
380 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
381 free(http
->authstring
);
388 * 'httpConnect()' - Connect to a HTTP server.
390 * This function is deprecated - use @link httpConnectEncrypt@ instead.
395 http_t
* /* O - New HTTP connection */
396 httpConnect(const char *host
, /* I - Host to connect to */
397 int port
) /* I - Port number */
399 return (httpConnectEncrypt(host
, port
, HTTP_ENCRYPT_IF_REQUESTED
));
404 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
407 http_t
* /* O - New HTTP connection */
409 const char *host
, /* I - Host to connect to */
410 int port
, /* I - Port number */
411 http_encryption_t encryption
) /* I - Type of encryption to use */
413 http_t
*http
; /* New HTTP connection */
416 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)",
417 host
, port
, encryption
));
420 * Create the HTTP structure...
423 if ((http
= _httpCreate(host
, port
, encryption
)) == NULL
)
427 * Connect to the remote system...
430 if (!httpReconnect(http
))
434 * Could not connect to any known address - bail out!
437 httpAddrFreeList(http
->addrlist
);
446 * '_httpCreate()' - Create an unconnected HTTP connection.
449 http_t
* /* O - HTTP connection */
451 const char *host
, /* I - Hostname */
452 int port
, /* I - Port number */
453 http_encryption_t encryption
) /* I - Encryption to use */
455 http_t
*http
; /* New HTTP connection */
456 http_addrlist_t
*addrlist
; /* Host address data */
457 char service
[255]; /* Service name */
460 DEBUG_printf(("4_httpCreate(host=\"%s\", port=%d, encryption=%d)",
461 host
, port
, encryption
));
472 sprintf(service
, "%d", port
);
474 if ((addrlist
= httpAddrGetList(host
, AF_UNSPEC
, service
)) == NULL
)
478 * Allocate memory for the structure...
481 if ((http
= calloc(sizeof(http_t
), 1)) == NULL
)
483 httpAddrFreeList(addrlist
);
488 * Initialize the HTTP data...
491 http
->activity
= time(NULL
);
492 http
->addrlist
= addrlist
;
496 http
->gssctx
= GSS_C_NO_CONTEXT
;
497 http
->gssname
= GSS_C_NO_NAME
;
498 #endif /* HAVE_GSSAPI */
499 http
->version
= HTTP_1_1
;
501 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
503 if (port
== 443) /* Always use encryption for https */
504 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
506 http
->encryption
= encryption
;
509 * Return the new structure...
517 * 'httpDelete()' - Send a DELETE request to the server.
520 int /* O - Status of call (0 = success) */
521 httpDelete(http_t
*http
, /* I - Connection to server */
522 const char *uri
) /* I - URI to delete */
524 return (http_send(http
, HTTP_DELETE
, uri
));
529 * '_httpDisconnect()' - Disconnect a HTTP connection.
533 _httpDisconnect(http_t
*http
) /* I - Connection to server */
537 http_shutdown_ssl(http
);
538 #endif /* HAVE_SSL */
541 closesocket(http
->fd
);
551 * 'httpEncryption()' - Set the required encryption on the link.
554 int /* O - -1 on error, 0 on success */
555 httpEncryption(http_t
*http
, /* I - Connection to server */
556 http_encryption_t e
) /* I - New encryption preference */
558 DEBUG_printf(("httpEncryption(http=%p, e=%d)", http
, e
));
564 http
->encryption
= e
;
566 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
567 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
568 return (httpReconnect(http
));
569 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
570 return (http_upgrade(http
));
574 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
578 #endif /* HAVE_SSL */
583 * 'httpError()' - Get the last error on a connection.
586 int /* O - Error code (errno) value */
587 httpError(http_t
*http
) /* I - Connection to server */
590 return (http
->error
);
597 * 'httpFlush()' - Flush data from a HTTP connection.
601 httpFlush(http_t
*http
) /* I - Connection to server */
603 char buffer
[8192]; /* Junk buffer */
604 int blocking
; /* To block or not to block */
605 http_state_t oldstate
; /* Old state */
608 DEBUG_printf(("httpFlush(http=%p), state=%s", http
,
609 http_states
[http
->state
]));
612 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
615 blocking
= http
->blocking
;
619 * Read any data we can...
622 oldstate
= http
->state
;
623 while (httpRead2(http
, buffer
, sizeof(buffer
)) > 0);
626 * Restore blocking and reset the connection if we didn't get all of
627 * the remaining data...
630 http
->blocking
= blocking
;
632 if (http
->state
== oldstate
&& http
->state
!= HTTP_WAITING
&& http
->fd
>= 0)
635 * Didn't get the data back, so close the current connection.
638 http
->state
= HTTP_WAITING
;
642 http_shutdown_ssl(http
);
643 #endif /* HAVE_SSL */
646 closesocket(http
->fd
);
657 * 'httpFlushWrite()' - Flush data in write buffer.
659 * @since CUPS 1.2/Mac OS X 10.5@
662 int /* O - Bytes written or -1 on error */
663 httpFlushWrite(http_t
*http
) /* I - Connection to server */
665 int bytes
; /* Bytes written */
668 DEBUG_printf(("httpFlushWrite(http=%p)", http
));
670 if (!http
|| !http
->wused
)
672 DEBUG_puts(http
? "1httpFlushWrite: Write buffer is empty." :
673 "1httpFlushWrite: No connection.");
677 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
678 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
680 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
684 DEBUG_printf(("1httpFlushWrite: Returning %d.", bytes
));
691 * 'httpGet()' - Send a GET request to the server.
694 int /* O - Status of call (0 = success) */
695 httpGet(http_t
*http
, /* I - Connection to server */
696 const char *uri
) /* I - URI to get */
698 return (http_send(http
, HTTP_GET
, uri
));
703 * 'httpGetAuthString()' - Get the current authorization string.
705 * The authorization string is set by cupsDoAuthentication() and
706 * httpSetAuthString(). Use httpGetAuthString() to retrieve the
707 * string to use with httpSetField() for the HTTP_FIELD_AUTHORIZATION
710 * @since CUPS 1.3/Mac OS X 10.5@
713 char * /* O - Authorization string */
714 httpGetAuthString(http_t
*http
) /* I - Connection to server */
717 return (http
->authstring
);
724 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
726 * @since CUPS 1.2/Mac OS X 10.5@
729 int /* O - 1 if blocking, 0 if non-blocking */
730 httpGetBlocking(http_t
*http
) /* I - Connection to server */
732 return (http
? http
->blocking
: 0);
737 * 'httpGetCookie()' - Get any cookie data from the response.
739 * @since CUPS 1.1.19/Mac OS X 10.3@
742 const char * /* O - Cookie data or NULL */
743 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
745 return (http
? http
->cookie
: NULL
);
750 * 'httpGetFd()' - Get the file descriptor associated with a connection.
752 * @since CUPS 1.2/Mac OS X 10.5@
755 int /* O - File descriptor or -1 if none */
756 httpGetFd(http_t
*http
) /* I - Connection to server */
758 return (http
? http
->fd
: -1);
763 * 'httpGetField()' - Get a field value from a request/response.
766 const char * /* O - Field value */
767 httpGetField(http_t
*http
, /* I - Connection to server */
768 http_field_t field
) /* I - Field to get */
770 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
772 else if (field
== HTTP_FIELD_AUTHORIZATION
&&
773 http
->field_authorization
)
776 * Special case for WWW-Authenticate: as its contents can be
777 * longer than HTTP_MAX_VALUE...
780 return (http
->field_authorization
);
783 return (http
->fields
[field
]);
788 * 'httpGetLength()' - Get the amount of data remaining from the
789 * content-length or transfer-encoding fields.
791 * This function is deprecated and will not return lengths larger than
792 * 2^31 - 1; use httpGetLength2() instead.
797 int /* O - Content length */
798 httpGetLength(http_t
*http
) /* I - Connection to server */
801 * Get the read content length and return the 32-bit value.
806 httpGetLength2(http
);
808 return (http
->_data_remaining
);
816 * 'httpGetLength2()' - Get the amount of data remaining from the
817 * content-length or transfer-encoding fields.
819 * This function returns the complete content length, even for
820 * content larger than 2^31 - 1.
822 * @since CUPS 1.2/Mac OS X 10.5@
825 off_t
/* O - Content length */
826 httpGetLength2(http_t
*http
) /* I - Connection to server */
828 DEBUG_printf(("2httpGetLength2(http=%p), state=%s", http
,
829 http_states
[http
->state
]));
834 if (!strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
836 DEBUG_puts("4httpGetLength2: chunked request!");
838 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
839 http
->data_remaining
= 0;
843 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
846 * The following is a hack for HTTP servers that don't send a
847 * content-length or transfer-encoding field...
849 * If there is no content-length then the connection must close
850 * after the transfer is complete...
853 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
856 * Default content length is 0 for errors and 2^31-1 for other
857 * successful requests...
860 if (http
->status
>= HTTP_MULTIPLE_CHOICES
)
861 http
->data_remaining
= 0;
863 http
->data_remaining
= 2147483647;
866 http
->data_remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
869 DEBUG_printf(("4httpGetLength2: content_length=" CUPS_LLFMT
,
870 CUPS_LLCAST http
->data_remaining
));
873 if (http
->data_remaining
<= INT_MAX
)
874 http
->_data_remaining
= (int)http
->data_remaining
;
876 http
->_data_remaining
= INT_MAX
;
878 return (http
->data_remaining
);
883 * 'httpGetStatus()' - Get the status of the last HTTP request.
885 * @since CUPS 1.2/Mac OS X 10.5@
888 http_status_t
/* O - HTTP status */
889 httpGetStatus(http_t
*http
) /* I - Connection to server */
891 return (http
? http
->status
: HTTP_ERROR
);
896 * 'httpGetSubField()' - Get a sub-field value.
901 char * /* O - Value or NULL */
902 httpGetSubField(http_t
*http
, /* I - Connection to server */
903 http_field_t field
, /* I - Field index */
904 const char *name
, /* I - Name of sub-field */
905 char *value
) /* O - Value string */
907 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
912 * 'httpGetSubField2()' - Get a sub-field value.
914 * @since CUPS 1.2/Mac OS X 10.5@
917 char * /* O - Value or NULL */
918 httpGetSubField2(http_t
*http
, /* I - Connection to server */
919 http_field_t field
, /* I - Field index */
920 const char *name
, /* I - Name of sub-field */
921 char *value
, /* O - Value string */
922 int valuelen
) /* I - Size of value buffer */
924 const char *fptr
; /* Pointer into field */
925 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
926 *ptr
, /* Pointer into string buffer */
927 *end
; /* End of value buffer */
929 DEBUG_printf(("2httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, "
930 "valuelen=%d)", http
, field
, name
, value
, valuelen
));
932 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
933 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
936 end
= value
+ valuelen
- 1;
938 for (fptr
= http
->fields
[field
]; *fptr
;)
941 * Skip leading whitespace...
944 while (isspace(*fptr
& 255))
954 * Get the sub-field name...
958 *fptr
&& *fptr
!= '=' && !isspace(*fptr
& 255) &&
959 ptr
< (temp
+ sizeof(temp
) - 1);
964 DEBUG_printf(("4httpGetSubField2: name=\"%s\"", temp
));
967 * Skip trailing chars up to the '='...
970 while (isspace(*fptr
& 255))
980 * Skip = and leading whitespace...
985 while (isspace(*fptr
& 255))
991 * Read quoted string...
994 for (ptr
= value
, fptr
++;
995 *fptr
&& *fptr
!= '\"' && ptr
< end
;
1000 while (*fptr
&& *fptr
!= '\"')
1009 * Read unquoted string...
1013 *fptr
&& !isspace(*fptr
& 255) && *fptr
!= ',' && ptr
< end
;
1018 while (*fptr
&& !isspace(*fptr
& 255) && *fptr
!= ',')
1022 DEBUG_printf(("4httpGetSubField2: value=\"%s\"", value
));
1025 * See if this is the one...
1028 if (!strcmp(name
, temp
))
1030 DEBUG_printf(("3httpGetSubField2: Returning \"%s\"", value
));
1037 DEBUG_puts("3httpGetSubField2: Returning NULL");
1044 * 'httpGets()' - Get a line of text from a HTTP connection.
1047 char * /* O - Line or NULL */
1048 httpGets(char *line
, /* I - Line to read into */
1049 int length
, /* I - Max length of buffer */
1050 http_t
*http
) /* I - Connection to server */
1052 char *lineptr
, /* Pointer into line */
1053 *lineend
, /* End of line */
1054 *bufptr
, /* Pointer into input buffer */
1055 *bufend
; /* Pointer to end of buffer */
1056 int bytes
, /* Number of bytes read */
1057 eol
; /* End-of-line? */
1060 DEBUG_printf(("2httpGets(line=%p, length=%d, http=%p)", line
, length
, http
));
1062 if (http
== NULL
|| line
== NULL
)
1066 * Read a line from the buffer...
1071 lineend
= line
+ length
- 1;
1074 while (lineptr
< lineend
)
1077 * Pre-load the buffer as needed...
1086 while (http
->used
== 0)
1089 * No newline; see if there is more data to be read...
1092 if (!http
->blocking
&& !_httpWait(http
, 10000, 1))
1094 DEBUG_puts("3httpGets: Timed out!");
1096 http
->error
= WSAETIMEDOUT
;
1098 http
->error
= ETIMEDOUT
;
1105 bytes
= http_read_ssl(http
, http
->buffer
+ http
->used
,
1106 HTTP_MAX_BUFFER
- http
->used
);
1108 #endif /* HAVE_SSL */
1109 bytes
= recv(http
->fd
, http
->buffer
+ http
->used
,
1110 HTTP_MAX_BUFFER
- http
->used
, 0);
1112 DEBUG_printf(("4httpGets: read %d bytes...", bytes
));
1117 * Nope, can't get a line this time...
1121 DEBUG_printf(("3httpGets: recv() error %d!", WSAGetLastError()));
1123 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
1125 else if (WSAGetLastError() != http
->error
)
1127 http
->error
= WSAGetLastError();
1132 DEBUG_printf(("3httpGets: recv() error %d!", errno
));
1134 if (errno
== EINTR
|| errno
== EAGAIN
)
1136 else if (errno
!= http
->error
)
1138 http
->error
= errno
;
1145 else if (bytes
== 0)
1147 http
->error
= EPIPE
;
1153 * Yup, update the amount used...
1156 http
->used
+= bytes
;
1160 * Now copy as much of the current line as possible...
1163 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1164 lineptr
< lineend
&& bufptr
< bufend
;)
1166 if (*bufptr
== 0x0a)
1172 else if (*bufptr
== 0x0d)
1175 *lineptr
++ = *bufptr
++;
1178 http
->used
-= (int)(bufptr
- http
->buffer
);
1180 memmove(http
->buffer
, bufptr
, http
->used
);
1188 http
->activity
= time(NULL
);
1192 DEBUG_printf(("3httpGets: Returning \"%s\"", line
));
1198 DEBUG_puts("3httpGets: No new line available!");
1205 * 'httpHead()' - Send a HEAD request to the server.
1208 int /* O - Status of call (0 = success) */
1209 httpHead(http_t
*http
, /* I - Connection to server */
1210 const char *uri
) /* I - URI for head */
1212 DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", http
, uri
));
1213 return (http_send(http
, HTTP_HEAD
, uri
));
1218 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1219 * default HTTP proxy (if any).
1223 httpInitialize(void)
1225 static int initialized
= 0; /* Have we been called before? */
1227 WSADATA winsockdata
; /* WinSock data */
1230 int i
; /* Looping var */
1231 unsigned char data
[1024]; /* Seed data */
1232 #endif /* HAVE_LIBSSL */
1238 _cupsGlobalUnlock();
1243 WSAStartup(MAKEWORD(1,1), &winsockdata
);
1245 #elif !defined(SO_NOSIGPIPE)
1247 * Ignore SIGPIPE signals...
1251 sigset(SIGPIPE
, SIG_IGN
);
1253 # elif defined(HAVE_SIGACTION)
1254 struct sigaction action
; /* POSIX sigaction data */
1257 memset(&action
, 0, sizeof(action
));
1258 action
.sa_handler
= SIG_IGN
;
1259 sigaction(SIGPIPE
, &action
, NULL
);
1262 signal(SIGPIPE
, SIG_IGN
);
1263 # endif /* !SO_NOSIGPIPE */
1268 * Make sure we handle threading properly...
1271 # ifdef HAVE_PTHREAD_H
1272 gcry_control(GCRYCTL_SET_THREAD_CBS
, &gcry_threads_pthread
);
1273 # endif /* HAVE_PTHREAD_H */
1276 * Initialize GNU TLS...
1279 gnutls_global_init();
1281 #elif defined(HAVE_LIBSSL)
1283 * Initialize OpenSSL...
1286 SSL_load_error_strings();
1290 * Set the threading callbacks...
1293 http_locks
= calloc(CRYPTO_num_locks(), sizeof(_cups_mutex_t
));
1294 # ifdef HAVE_PTHREAD_H
1295 for (i
= 0; i
< CRYPTO_num_locks(); i
++)
1296 pthread_mutex_init(http_locks
+ i
, NULL
);
1297 # endif /* HAVE_PTHREAD_H */
1299 CRYPTO_set_id_callback(http_threadid_cb
);
1300 CRYPTO_set_locking_callback(http_locking_cb
);
1303 * Using the current time is a dubious random seed, but on some systems
1304 * it is the best we can do (on others, this seed isn't even used...)
1307 CUPS_SRAND(time(NULL
));
1309 for (i
= 0; i
< sizeof(data
); i
++)
1310 data
[i
] = CUPS_RAND();
1312 RAND_seed(data
, sizeof(data
));
1313 #endif /* HAVE_GNUTLS */
1316 _cupsGlobalUnlock();
1321 * 'httpOptions()' - Send an OPTIONS request to the server.
1324 int /* O - Status of call (0 = success) */
1325 httpOptions(http_t
*http
, /* I - Connection to server */
1326 const char *uri
) /* I - URI for options */
1328 return (http_send(http
, HTTP_OPTIONS
, uri
));
1333 * '_httpPeek()' - Peek at data from a HTTP connection.
1335 * This function copies available data from the given HTTP connection, reading
1336 * a buffer as needed. The data is still available for reading using
1337 * @link httpRead@ or @link httpRead2@.
1339 * For non-blocking connections the usual timeouts apply.
1342 ssize_t
/* O - Number of bytes copied */
1343 _httpPeek(http_t
*http
, /* I - Connection to server */
1344 char *buffer
, /* I - Buffer for data */
1345 size_t length
) /* I - Maximum number of bytes */
1347 ssize_t bytes
; /* Bytes read */
1348 char len
[32]; /* Length string */
1351 DEBUG_printf(("_httpPeek(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1352 http
, buffer
, CUPS_LLCAST length
));
1354 if (http
== NULL
|| buffer
== NULL
)
1357 http
->activity
= time(NULL
);
1363 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1364 http
->data_remaining
<= 0)
1366 DEBUG_puts("2_httpPeek: Getting chunk length...");
1368 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1370 DEBUG_puts("1_httpPeek: Could not get length!");
1374 http
->data_remaining
= strtoll(len
, NULL
, 16);
1375 if (http
->data_remaining
< 0)
1377 DEBUG_puts("1_httpPeek: Negative chunk length!");
1382 DEBUG_printf(("2_httpPeek: data_remaining=" CUPS_LLFMT
,
1383 CUPS_LLCAST http
->data_remaining
));
1385 if (http
->data_remaining
<= 0)
1388 * A zero-length chunk ends a transfer; unless we are reading POST
1392 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1393 httpGets(len
, sizeof(len
), http
);
1395 if (http
->state
== HTTP_POST_RECV
)
1398 http
->state
= HTTP_WAITING
;
1401 * Prevent future reads for this request...
1404 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1408 else if (length
> (size_t)http
->data_remaining
)
1409 length
= (size_t)http
->data_remaining
;
1411 if (http
->used
== 0)
1414 * Buffer small reads for better performance...
1417 if (!http
->blocking
&& !httpWait(http
, 10000))
1420 if (http
->data_remaining
> sizeof(http
->buffer
))
1421 bytes
= sizeof(http
->buffer
);
1423 bytes
= http
->data_remaining
;
1427 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1429 #endif /* HAVE_SSL */
1431 DEBUG_printf(("2_httpPeek: reading %d bytes from socket into buffer...",
1434 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1436 DEBUG_printf(("2_httpPeek: read %d bytes from socket into buffer...",
1445 if (WSAGetLastError() != WSAEINTR
&& WSAGetLastError() != WSAEWOULDBLOCK
)
1447 http
->error
= WSAGetLastError();
1451 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1453 http
->error
= errno
;
1460 http
->error
= EPIPE
;
1467 if (length
> (size_t)http
->used
)
1468 length
= (size_t)http
->used
;
1470 bytes
= (ssize_t
)length
;
1472 DEBUG_printf(("2_httpPeek: grabbing %d bytes from input buffer...",
1475 memcpy(buffer
, http
->buffer
, length
);
1483 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
1486 http
->error
= WSAGetLastError();
1488 if (errno
== EINTR
|| errno
== EAGAIN
)
1491 http
->error
= errno
;
1494 else if (bytes
== 0)
1496 http
->error
= EPIPE
;
1501 http_debug_hex("_httpPeek", buffer
, (int)bytes
);
1509 * 'httpPost()' - Send a POST request to the server.
1512 int /* O - Status of call (0 = success) */
1513 httpPost(http_t
*http
, /* I - Connection to server */
1514 const char *uri
) /* I - URI for post */
1516 return (http_send(http
, HTTP_POST
, uri
));
1521 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1526 int /* O - Number of bytes written */
1527 httpPrintf(http_t
*http
, /* I - Connection to server */
1528 const char *format
, /* I - printf-style format string */
1529 ...) /* I - Additional args as needed */
1531 int bytes
; /* Number of bytes to write */
1532 char buf
[16384]; /* Buffer for formatted string */
1533 va_list ap
; /* Variable argument pointer */
1536 DEBUG_printf(("2httpPrintf(http=%p, format=\"%s\", ...)", http
, format
));
1538 va_start(ap
, format
);
1539 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1542 DEBUG_printf(("3httpPrintf: %s", buf
));
1544 if (http
->data_encoding
== HTTP_ENCODE_FIELDS
)
1545 return (httpWrite2(http
, buf
, bytes
));
1550 DEBUG_puts("4httpPrintf: flushing existing data...");
1552 if (httpFlushWrite(http
) < 0)
1556 return (http_write(http
, buf
, bytes
));
1562 * 'httpPut()' - Send a PUT request to the server.
1565 int /* O - Status of call (0 = success) */
1566 httpPut(http_t
*http
, /* I - Connection to server */
1567 const char *uri
) /* I - URI to put */
1569 DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", http
, uri
));
1570 return (http_send(http
, HTTP_PUT
, uri
));
1575 * 'httpRead()' - Read data from a HTTP connection.
1577 * This function is deprecated. Use the httpRead2() function which can
1578 * read more than 2GB of data.
1583 int /* O - Number of bytes read */
1584 httpRead(http_t
*http
, /* I - Connection to server */
1585 char *buffer
, /* I - Buffer for data */
1586 int length
) /* I - Maximum number of bytes */
1588 return ((int)httpRead2(http
, buffer
, length
));
1593 * 'httpRead2()' - Read data from a HTTP connection.
1595 * @since CUPS 1.2/Mac OS X 10.5@
1598 ssize_t
/* O - Number of bytes read */
1599 httpRead2(http_t
*http
, /* I - Connection to server */
1600 char *buffer
, /* I - Buffer for data */
1601 size_t length
) /* I - Maximum number of bytes */
1603 ssize_t bytes
; /* Bytes read */
1604 char len
[32]; /* Length string */
1607 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1608 http
, buffer
, CUPS_LLCAST length
));
1610 if (http
== NULL
|| buffer
== NULL
)
1613 http
->activity
= time(NULL
);
1619 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1620 http
->data_remaining
<= 0)
1622 DEBUG_puts("2httpRead2: Getting chunk length...");
1624 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1626 DEBUG_puts("1httpRead2: Could not get length!");
1630 http
->data_remaining
= strtoll(len
, NULL
, 16);
1631 if (http
->data_remaining
< 0)
1633 DEBUG_puts("1httpRead2: Negative chunk length!");
1638 DEBUG_printf(("2httpRead2: data_remaining=" CUPS_LLFMT
,
1639 CUPS_LLCAST http
->data_remaining
));
1641 if (http
->data_remaining
<= 0)
1644 * A zero-length chunk ends a transfer; unless we are reading POST
1648 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1649 httpGets(len
, sizeof(len
), http
);
1651 if (http
->state
== HTTP_POST_RECV
)
1654 http
->state
= HTTP_WAITING
;
1657 * Prevent future reads for this request...
1660 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1664 else if (length
> (size_t)http
->data_remaining
)
1665 length
= (size_t)http
->data_remaining
;
1667 if (http
->used
== 0 && length
<= 256)
1670 * Buffer small reads for better performance...
1673 if (!http
->blocking
&& !httpWait(http
, 10000))
1676 if (http
->data_remaining
> sizeof(http
->buffer
))
1677 bytes
= sizeof(http
->buffer
);
1679 bytes
= http
->data_remaining
;
1683 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1685 #endif /* HAVE_SSL */
1687 DEBUG_printf(("2httpRead2: reading %d bytes from socket into buffer...",
1690 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1692 DEBUG_printf(("2httpRead2: read %d bytes from socket into buffer...",
1701 if (WSAGetLastError() != WSAEINTR
&& WSAGetLastError() != WSAEWOULDBLOCK
)
1703 http
->error
= WSAGetLastError();
1707 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1709 http
->error
= errno
;
1716 http
->error
= EPIPE
;
1723 if (length
> (size_t)http
->used
)
1724 length
= (size_t)http
->used
;
1726 bytes
= (ssize_t
)length
;
1728 DEBUG_printf(("2httpRead2: grabbing %d bytes from input buffer...",
1731 memcpy(buffer
, http
->buffer
, length
);
1732 http
->used
-= (int)length
;
1735 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
1740 if (!http
->blocking
&& !httpWait(http
, 10000))
1743 bytes
= (ssize_t
)http_read_ssl(http
, buffer
, (int)length
);
1745 #endif /* HAVE_SSL */
1748 if (!http
->blocking
&& !httpWait(http
, 10000))
1751 DEBUG_printf(("2httpRead2: reading " CUPS_LLFMT
" bytes from socket...",
1752 CUPS_LLCAST length
));
1755 while ((bytes
= (ssize_t
) recv(http
->fd
, buffer
, (int)length
, 0)) < 0)
1756 if (WSAGetLastError() != WSAEINTR
&& WSAGetLastError() != WSAEWOULDBLOCK
)
1759 while ((bytes
= recv(http
->fd
, buffer
, length
, 0)) < 0)
1760 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1764 DEBUG_printf(("2httpRead2: read " CUPS_LLFMT
" bytes from socket...",
1765 CUPS_LLCAST bytes
));
1770 http
->data_remaining
-= bytes
;
1772 if (http
->data_remaining
<= INT_MAX
)
1773 http
->_data_remaining
= (int)http
->data_remaining
;
1775 http
->_data_remaining
= INT_MAX
;
1780 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
1783 http
->error
= WSAGetLastError();
1785 if (errno
== EINTR
|| errno
== EAGAIN
)
1788 http
->error
= errno
;
1793 http
->error
= EPIPE
;
1797 if (http
->data_remaining
== 0)
1799 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1800 httpGets(len
, sizeof(len
), http
);
1802 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
1804 if (http
->state
== HTTP_POST_RECV
)
1807 http
->state
= HTTP_WAITING
;
1812 http_debug_hex("httpRead2", buffer
, (int)bytes
);
1819 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
1821 * '_httpReadCDSA()' - Read function for the CDSA library.
1824 OSStatus
/* O - -1 on error, 0 on success */
1826 SSLConnectionRef connection
, /* I - SSL/TLS connection */
1827 void *data
, /* I - Data buffer */
1828 size_t *dataLength
) /* IO - Number of bytes */
1830 OSStatus result
; /* Return value */
1831 ssize_t bytes
; /* Number of bytes read */
1832 http_t
*http
; /* HTTP connection */
1835 http
= (http_t
*)connection
;
1837 if (!http
->blocking
)
1840 * Make sure we have data before we read...
1843 if (!_httpWait(http
, 10000, 0))
1845 http
->error
= ETIMEDOUT
;
1852 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
1854 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
1856 if (bytes
== *dataLength
)
1862 *dataLength
= bytes
;
1863 result
= errSSLWouldBlock
;
1870 result
= errSSLClosedGraceful
;
1871 else if (errno
== EAGAIN
)
1872 result
= errSSLWouldBlock
;
1874 result
= errSSLClosedAbort
;
1879 #endif /* HAVE_SSL && HAVE_CDSASSL */
1882 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
1884 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
1887 ssize_t
/* O - Number of bytes read or -1 on error */
1889 gnutls_transport_ptr ptr
, /* I - Connection to server */
1890 void *data
, /* I - Buffer */
1891 size_t length
) /* I - Number of bytes to read */
1893 http_t
*http
; /* HTTP connection */
1896 http
= (http_t
*)ptr
;
1898 if (!http
->blocking
)
1901 * Make sure we have data before we read...
1904 if (!_httpWait(http
, 10000, 0))
1906 http
->error
= ETIMEDOUT
;
1911 return (recv(http
->fd
, data
, length
, 0));
1913 #endif /* HAVE_SSL && HAVE_GNUTLS */
1917 * 'httpReconnect()' - Reconnect to a HTTP server.
1920 int /* O - 0 on success, non-zero on failure */
1921 httpReconnect(http_t
*http
) /* I - Connection to server */
1923 http_addrlist_t
*addr
; /* Connected address */
1925 http_addrlist_t
*current
; /* Current address */
1926 char temp
[256]; /* Temporary address string */
1930 DEBUG_printf(("httpReconnect(http=%p)", http
));
1938 DEBUG_puts("2httpReconnect: Shutting down SSL/TLS...");
1939 http_shutdown_ssl(http
);
1941 #endif /* HAVE_SSL */
1944 * Close any previously open socket...
1949 DEBUG_printf(("2httpReconnect: Closing socket %d...", http
->fd
));
1952 closesocket(http
->fd
);
1961 * Connect to the server...
1965 for (current
= http
->addrlist
; current
; current
= current
->next
)
1966 DEBUG_printf(("2httpReconnect: Address %s:%d",
1967 httpAddrString(&(current
->addr
), temp
, sizeof(temp
)),
1968 _httpAddrPort(&(current
->addr
))));
1971 if ((addr
= httpAddrConnect(http
->addrlist
, &(http
->fd
))) == NULL
)
1974 * Unable to connect...
1978 http
->error
= WSAGetLastError();
1980 http
->error
= errno
;
1982 http
->status
= HTTP_ERROR
;
1984 DEBUG_printf(("1httpReconnect: httpAddrConnect failed: %s",
1985 strerror(http
->error
)));
1990 DEBUG_printf(("2httpReconnect: New socket=%d", http
->fd
));
1992 http
->hostaddr
= &(addr
->addr
);
1994 http
->status
= HTTP_CONTINUE
;
1997 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
2000 * Always do encryption via SSL.
2003 if (http_setup_ssl(http
) != 0)
2006 closesocket(http
->fd
);
2014 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
2015 return (http_upgrade(http
));
2016 #endif /* HAVE_SSL */
2018 DEBUG_printf(("1httpReconnect: Connected to %s:%d...",
2019 httpAddrString(http
->hostaddr
, temp
, sizeof(temp
)),
2020 _httpAddrPort(http
->hostaddr
)));
2027 * 'httpSetAuthString()' - Set the current authorization string.
2029 * This function just stores a copy of the current authorization string in
2030 * the HTTP connection object. You must still call httpSetField() to set
2031 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
2032 * httpHead(), httpOptions(), httpPost, or httpPut().
2034 * @since CUPS 1.3/Mac OS X 10.5@
2038 httpSetAuthString(http_t
*http
, /* I - Connection to server */
2039 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
2040 const char *data
) /* I - Auth data (NULL for none) */
2043 * Range check input...
2049 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
2050 free(http
->authstring
);
2052 http
->authstring
= http
->_authstring
;
2057 * Set the current authorization string...
2060 int len
= (int)strlen(scheme
) + (data
? (int)strlen(data
) + 1 : 0) + 1;
2063 if (len
> (int)sizeof(http
->_authstring
))
2065 if ((temp
= malloc(len
)) == NULL
)
2066 len
= sizeof(http
->_authstring
);
2068 http
->authstring
= temp
;
2072 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
2074 strlcpy(http
->authstring
, scheme
, len
);
2079 * Clear the current authorization string...
2082 http
->_authstring
[0] = '\0';
2088 * 'httpSetCookie()' - Set the cookie value(s).
2090 * @since CUPS 1.1.19/Mac OS X 10.3@
2094 httpSetCookie(http_t
*http
, /* I - Connection */
2095 const char *cookie
) /* I - Cookie string */
2104 http
->cookie
= strdup(cookie
);
2106 http
->cookie
= NULL
;
2111 * 'httpSetExpect()' - Set the Expect: header in a request.
2113 * Currently only HTTP_CONTINUE is supported for the "expect" argument.
2115 * @since CUPS 1.2/Mac OS X 10.5@
2119 httpSetExpect(http_t
*http
, /* I - Connection to server */
2120 http_status_t expect
) /* I - HTTP status to expect (HTTP_CONTINUE) */
2123 http
->expect
= expect
;
2128 * 'httpSetField()' - Set the value of an HTTP header.
2132 httpSetField(http_t
*http
, /* I - Connection to server */
2133 http_field_t field
, /* I - Field index */
2134 const char *value
) /* I - Value */
2137 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
2138 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
2142 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
2144 if (field
== HTTP_FIELD_AUTHORIZATION
)
2147 * Special case for Authorization: as its contents can be
2148 * longer than HTTP_MAX_VALUE
2151 if (http
->field_authorization
)
2152 free(http
->field_authorization
);
2154 http
->field_authorization
= strdup(value
);
2156 else if (field
== HTTP_FIELD_HOST
)
2159 * Special-case for Host: as we don't want a trailing "." on the hostname and
2160 * need to bracket IPv6 numeric addresses.
2163 char *ptr
= strchr(value
, ':');
2165 if (value
[0] != '[' && ptr
&& strchr(ptr
+ 1, ':'))
2168 * Bracket IPv6 numeric addresses...
2170 * This is slightly inefficient (basically copying twice), but is an edge
2171 * case and not worth optimizing...
2174 snprintf(http
->fields
[HTTP_FIELD_HOST
],
2175 sizeof(http
->fields
[HTTP_FIELD_HOST
]), "[%s]", value
);
2180 * Check for a trailing dot on the hostname...
2183 ptr
= http
->fields
[HTTP_FIELD_HOST
];
2187 ptr
+= strlen(ptr
) - 1;
2198 * 'httpSetLength()' - Set the content-length and content-encoding.
2200 * @since CUPS 1.2/Mac OS X 10.5@
2204 httpSetLength(http_t
*http
, /* I - Connection to server */
2205 size_t length
) /* I - Length (0 for chunked) */
2212 strcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked");
2213 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
2217 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
2218 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
2219 CUPS_LLFMT
, CUPS_LLCAST length
);
2225 * 'httpTrace()' - Send an TRACE request to the server.
2228 int /* O - Status of call (0 = success) */
2229 httpTrace(http_t
*http
, /* I - Connection to server */
2230 const char *uri
) /* I - URI for trace */
2232 return (http_send(http
, HTTP_TRACE
, uri
));
2237 * 'httpUpdate()' - Update the current HTTP state for incoming data.
2240 http_status_t
/* O - HTTP status */
2241 httpUpdate(http_t
*http
) /* I - Connection to server */
2243 char line
[32768], /* Line from connection... */
2244 *value
; /* Pointer to value on line */
2245 http_field_t field
; /* Field index */
2246 int major
, minor
, /* HTTP version numbers */
2247 status
; /* Request status */
2250 DEBUG_printf(("httpUpdate(http=%p), state=%s", http
,
2251 http_states
[http
->state
]));
2254 * Flush pending data, if any...
2259 DEBUG_puts("2httpUpdate: flushing buffer...");
2261 if (httpFlushWrite(http
) < 0)
2262 return (HTTP_ERROR
);
2266 * If we haven't issued any commands, then there is nothing to "update"...
2269 if (http
->state
== HTTP_WAITING
)
2270 return (HTTP_CONTINUE
);
2273 * Grab all of the lines we can from the connection...
2276 while (httpGets(line
, sizeof(line
), http
) != NULL
)
2278 DEBUG_printf(("2httpUpdate: Got \"%s\"", line
));
2280 if (line
[0] == '\0')
2283 * Blank line means the start of the data section (if any). Return
2284 * the result code, too...
2286 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
2287 * Instead, we just return HTTP_CONTINUE to the caller and keep on
2291 if (http
->status
== HTTP_CONTINUE
)
2292 return (http
->status
);
2294 if (http
->status
< HTTP_BAD_REQUEST
)
2295 http
->digest_tries
= 0;
2298 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
2300 if (http_setup_ssl(http
) != 0)
2303 closesocket(http
->fd
);
2308 return (HTTP_ERROR
);
2311 return (HTTP_CONTINUE
);
2313 #endif /* HAVE_SSL */
2315 httpGetLength2(http
);
2317 switch (http
->state
)
2321 case HTTP_POST_RECV
:
2324 case HTTP_POST_SEND
:
2329 http
->state
= HTTP_WAITING
;
2333 return (http
->status
);
2335 else if (!strncmp(line
, "HTTP/", 5))
2338 * Got the beginning of a response...
2341 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &status
) != 3)
2342 return (HTTP_ERROR
);
2344 http
->version
= (http_version_t
)(major
* 100 + minor
);
2345 http
->status
= (http_status_t
)status
;
2347 else if ((value
= strchr(line
, ':')) != NULL
)
2354 while (isspace(*value
& 255))
2358 * Be tolerants of servers that send unknown attribute fields...
2361 if (!strcasecmp(line
, "expect"))
2364 * "Expect: 100-continue" or similar...
2367 http
->expect
= (http_status_t
)atoi(value
);
2369 else if (!strcasecmp(line
, "cookie"))
2372 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
2375 httpSetCookie(http
, value
);
2377 else if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
2379 DEBUG_printf(("1httpUpdate: unknown field %s seen!", line
));
2383 httpSetField(http
, field
, value
);
2387 DEBUG_printf(("1httpUpdate: Bad response line \"%s\"!", line
));
2388 http
->status
= HTTP_ERROR
;
2389 return (HTTP_ERROR
);
2394 * See if there was an error...
2397 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
2399 DEBUG_printf(("1httpUpdate: Returning status %d...", http
->status
));
2400 return (http
->status
);
2405 DEBUG_printf(("1httpUpdate: socket error %d - %s", http
->error
,
2406 strerror(http
->error
)));
2407 http
->status
= HTTP_ERROR
;
2408 return (HTTP_ERROR
);
2412 * If we haven't already returned, then there is nothing new...
2415 return (HTTP_CONTINUE
);
2420 * '_httpWait()' - Wait for data available on a connection (no flush).
2423 int /* O - 1 if data is available, 0 otherwise */
2424 _httpWait(http_t
*http
, /* I - Connection to server */
2425 int msec
, /* I - Milliseconds to wait */
2426 int usessl
) /* I - Use SSL context? */
2429 struct pollfd pfd
; /* Polled file descriptor */
2431 fd_set input_set
; /* select() input set */
2432 struct timeval timeout
; /* Timeout */
2433 #endif /* HAVE_POLL */
2434 int nfds
; /* Result from select()/poll() */
2437 DEBUG_printf(("4_httpWait(http=%p, msec=%d, usessl=%d)", http
, msec
, usessl
));
2441 DEBUG_printf(("5_httpWait: Returning 0 since fd=%d", http
->fd
));
2446 * Check the SSL/TLS buffers for data first...
2450 if (http
->tls
&& usessl
)
2453 if (SSL_pending((SSL
*)(http
->tls
)))
2455 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2459 # elif defined(HAVE_GNUTLS)
2460 if (gnutls_record_check_pending(((http_tls_t
*)(http
->tls
))->session
))
2462 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2466 # elif defined(HAVE_CDSASSL)
2467 size_t bytes
; /* Bytes that are available */
2469 if (!SSLGetBufferedReadSize(((http_tls_t
*)(http
->tls
))->session
, &bytes
) &&
2472 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2475 # endif /* HAVE_LIBSSL */
2477 #endif /* HAVE_SSL */
2480 * Then try doing a select() or poll() to poll the socket...
2485 pfd
.events
= POLLIN
;
2487 while ((nfds
= poll(&pfd
, 1, msec
)) < 0 &&
2488 (errno
== EINTR
|| errno
== EAGAIN
));
2493 FD_ZERO(&input_set
);
2494 FD_SET(http
->fd
, &input_set
);
2496 DEBUG_printf(("6_httpWait: msec=%d, http->fd=%d", msec
, http
->fd
));
2500 timeout
.tv_sec
= msec
/ 1000;
2501 timeout
.tv_usec
= (msec
% 1000) * 1000;
2503 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
2506 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
2508 DEBUG_printf(("6_httpWait: select() returned %d...", nfds
));
2511 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
2512 WSAGetLastError() == WSAEWOULDBLOCK
));
2514 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
2516 #endif /* HAVE_POLL */
2518 DEBUG_printf(("5_httpWait: returning with nfds=%d, errno=%d...", nfds
,
2526 * 'httpWait()' - Wait for data available on a connection.
2528 * @since CUPS 1.1.19/Mac OS X 10.3@
2531 int /* O - 1 if data is available, 0 otherwise */
2532 httpWait(http_t
*http
, /* I - Connection to server */
2533 int msec
) /* I - Milliseconds to wait */
2536 * First see if there is data in the buffer...
2546 * Flush pending data, if any...
2551 if (httpFlushWrite(http
) < 0)
2556 * If not, check the SSL/TLS buffers and do a select() on the connection...
2559 return (_httpWait(http
, msec
, 1));
2564 * 'httpWrite()' - Write data to a HTTP connection.
2566 * This function is deprecated. Use the httpWrite2() function which can
2567 * write more than 2GB of data.
2572 int /* O - Number of bytes written */
2573 httpWrite(http_t
*http
, /* I - Connection to server */
2574 const char *buffer
, /* I - Buffer for data */
2575 int length
) /* I - Number of bytes to write */
2577 return ((int)httpWrite2(http
, buffer
, length
));
2582 * 'httpWrite2()' - Write data to a HTTP connection.
2584 * @since CUPS 1.2/Mac OS X 10.5@
2587 ssize_t
/* O - Number of bytes written */
2588 httpWrite2(http_t
*http
, /* I - Connection to server */
2589 const char *buffer
, /* I - Buffer for data */
2590 size_t length
) /* I - Number of bytes to write */
2592 ssize_t bytes
; /* Bytes written */
2595 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
2596 buffer
, CUPS_LLCAST length
));
2599 * Range check input...
2602 if (http
== NULL
|| buffer
== NULL
)
2606 * Mark activity on the connection...
2609 http
->activity
= time(NULL
);
2612 * Buffer small writes for better performance...
2617 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
2619 DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
2620 CUPS_LLFMT
")", http
->wused
, CUPS_LLCAST length
));
2622 httpFlushWrite(http
);
2625 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
) &&
2626 length
< sizeof(http
->wbuffer
))
2629 * Write to buffer...
2632 DEBUG_printf(("2httpWrite2: Copying " CUPS_LLFMT
" bytes to wbuffer...",
2633 CUPS_LLCAST length
));
2635 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
2636 http
->wused
+= (int)length
;
2637 bytes
= (ssize_t
)length
;
2642 * Otherwise write the data directly...
2645 DEBUG_printf(("2httpWrite2: Writing " CUPS_LLFMT
" bytes to socket...",
2646 CUPS_LLCAST length
));
2648 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2649 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
2651 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
2653 DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT
" bytes...",
2654 CUPS_LLCAST bytes
));
2657 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
2658 http
->data_remaining
-= bytes
;
2664 * Handle end-of-request processing...
2667 if ((http
->data_encoding
== HTTP_ENCODE_CHUNKED
&& length
== 0) ||
2668 (http
->data_encoding
== HTTP_ENCODE_LENGTH
&& http
->data_remaining
== 0))
2671 * Finished with the transfer; unless we are sending POST or PUT
2675 DEBUG_puts("2httpWrite: changing states...");
2678 httpFlushWrite(http
);
2680 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2683 * Send a 0-length chunk at the end of the request...
2686 http_write(http
, "0\r\n\r\n", 5);
2689 * Reset the data state...
2692 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
2693 http
->data_remaining
= 0;
2696 if (http
->state
== HTTP_POST_RECV
)
2698 else if (http
->state
== HTTP_PUT_RECV
)
2699 http
->state
= HTTP_STATUS
;
2701 http
->state
= HTTP_WAITING
;
2708 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2710 * '_httpWriteCDSA()' - Write function for the CDSA library.
2713 OSStatus
/* O - -1 on error, 0 on success */
2715 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2716 const void *data
, /* I - Data buffer */
2717 size_t *dataLength
) /* IO - Number of bytes */
2719 OSStatus result
; /* Return value */
2720 ssize_t bytes
; /* Number of bytes read */
2721 http_t
*http
; /* HTTP connection */
2724 http
= (http_t
*)connection
;
2728 bytes
= write(http
->fd
, data
, *dataLength
);
2730 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
2732 if (bytes
== *dataLength
)
2736 else if (bytes
>= 0)
2738 *dataLength
= bytes
;
2739 result
= errSSLWouldBlock
;
2745 if (errno
== EAGAIN
)
2746 result
= errSSLWouldBlock
;
2748 result
= errSSLClosedAbort
;
2753 #endif /* HAVE_SSL && HAVE_CDSASSL */
2756 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2758 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
2761 ssize_t
/* O - Number of bytes written or -1 on error */
2763 gnutls_transport_ptr ptr
, /* I - Connection to server */
2764 const void *data
, /* I - Data buffer */
2765 size_t length
) /* I - Number of bytes to write */
2767 return (send(((http_t
*)ptr
)->fd
, data
, length
, 0));
2769 #endif /* HAVE_SSL && HAVE_GNUTLS */
2772 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
2774 * 'http_bio_ctrl()' - Control the HTTP connection.
2777 static long /* O - Result/data */
2778 http_bio_ctrl(BIO
*h
, /* I - BIO data */
2779 int cmd
, /* I - Control command */
2780 long arg1
, /* I - First argument */
2781 void *arg2
) /* I - Second argument */
2788 case BIO_CTRL_RESET
:
2792 case BIO_C_SET_FILE_PTR
:
2797 case BIO_C_GET_FILE_PTR
:
2800 *((void **)arg2
) = h
->ptr
;
2807 case BIO_CTRL_FLUSH
:
2814 * 'http_bio_free()' - Free OpenSSL data.
2817 static int /* O - 1 on success, 0 on failure */
2818 http_bio_free(BIO
*h
) /* I - BIO data */
2834 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
2837 static int /* O - 1 on success, 0 on failure */
2838 http_bio_new(BIO
*h
) /* I - BIO data */
2853 * 'http_bio_puts()' - Send a string for OpenSSL.
2856 static int /* O - Bytes written */
2857 http_bio_puts(BIO
*h
, /* I - BIO data */
2858 const char *str
) /* I - String to write */
2861 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
2863 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
2869 * 'http_bio_read()' - Read data for OpenSSL.
2872 static int /* O - Bytes read */
2873 http_bio_read(BIO
*h
, /* I - BIO data */
2874 char *buf
, /* I - Buffer */
2875 int size
) /* I - Number of bytes to read */
2877 http_t
*http
; /* HTTP connection */
2880 http
= (http_t
*)h
->ptr
;
2882 if (!http
->blocking
)
2885 * Make sure we have data before we read...
2888 if (!_httpWait(http
, 10000, 0))
2891 http
->error
= WSAETIMEDOUT
;
2893 http
->error
= ETIMEDOUT
;
2900 return (recv(http
->fd
, buf
, size
, 0));
2905 * 'http_bio_write()' - Write data for OpenSSL.
2908 static int /* O - Bytes written */
2909 http_bio_write(BIO
*h
, /* I - BIO data */
2910 const char *buf
, /* I - Buffer to write */
2911 int num
) /* I - Number of bytes to write */
2913 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
2915 #endif /* HAVE_SSL && HAVE_LIBSSL */
2920 * 'http_debug_hex()' - Do a hex dump of a buffer.
2924 http_debug_hex(const char *prefix
, /* I - Prefix for line */
2925 const char *buffer
, /* I - Buffer to dump */
2926 int bytes
) /* I - Bytes to dump */
2928 int i
, j
, /* Looping vars */
2929 ch
; /* Current character */
2930 char line
[255], /* Line buffer */
2931 *start
, /* Start of line after prefix */
2932 *ptr
; /* Pointer into line */
2935 if (_cups_debug_fd
< 0 || _cups_debug_level
< 6)
2938 DEBUG_printf(("6%s: %d bytes:\n", prefix
, bytes
));
2940 snprintf(line
, sizeof(line
), "6%s: ", prefix
);
2941 start
= line
+ strlen(line
);
2943 for (i
= 0; i
< bytes
; i
+= 16)
2945 for (j
= 0, ptr
= start
; j
< 16 && (i
+ j
) < bytes
; j
++, ptr
+= 2)
2946 sprintf(ptr
, "%02X", buffer
[i
+ j
] & 255);
2958 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
2960 ch
= buffer
[i
+ j
] & 255;
2962 if (ch
< ' ' || ch
>= 127)
2976 * 'http_field()' - Return the field index for a field name.
2979 static http_field_t
/* O - Field index */
2980 http_field(const char *name
) /* I - String name */
2982 int i
; /* Looping var */
2985 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2986 if (strcasecmp(name
, http_fields
[i
]) == 0)
2987 return ((http_field_t
)i
);
2989 return (HTTP_FIELD_UNKNOWN
);
2995 * 'http_read_ssl()' - Read from a SSL/TLS connection.
2998 static int /* O - Bytes read */
2999 http_read_ssl(http_t
*http
, /* I - Connection to server */
3000 char *buf
, /* I - Buffer to store data */
3001 int len
) /* I - Length of buffer */
3003 # if defined(HAVE_LIBSSL)
3004 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
3006 # elif defined(HAVE_GNUTLS)
3007 ssize_t result
; /* Return value */
3010 result
= gnutls_record_recv(((http_tls_t
*)(http
->tls
))->session
, buf
, len
);
3012 if (result
< 0 && !errno
)
3015 * Convert GNU TLS error to errno value...
3020 case GNUTLS_E_INTERRUPTED
:
3024 case GNUTLS_E_AGAIN
:
3036 return ((int)result
);
3038 # elif defined(HAVE_CDSASSL)
3039 int result
; /* Return value */
3040 OSStatus error
; /* Error info */
3041 size_t processed
; /* Number of bytes processed */
3044 error
= SSLRead(((http_tls_t
*)http
->tls
)->session
, buf
, len
, &processed
);
3049 result
= (int)processed
;
3051 case errSSLClosedGraceful
:
3054 case errSSLWouldBlock
:
3056 result
= (int)processed
;
3070 # elif defined(HAVE_SSPISSL)
3071 return _sspiRead((_sspi_struct_t
*) http
->tls
, buf
, len
);
3072 # endif /* HAVE_LIBSSL */
3074 #endif /* HAVE_SSL */
3079 * 'http_locking_cb()' - Lock/unlock a thread's mutex.
3083 http_locking_cb(int mode
, /* I - Lock mode */
3084 int type
, /* I - Lock type */
3085 const char *file
, /* I - Source file */
3086 int line
) /* I - Line number */
3088 if (mode
& CRYPTO_LOCK
)
3089 _cupsMutexLock(http_locks
+ type
);
3091 _cupsMutexUnlock(http_locks
+ type
);
3093 #endif /* HAVE_LIBSSL */
3097 * 'http_send()' - Send a request with all fields and the trailing blank line.
3100 static int /* O - 0 on success, non-zero on error */
3101 http_send(http_t
*http
, /* I - Connection to server */
3102 http_state_t request
, /* I - Request code */
3103 const char *uri
) /* I - URI */
3105 int i
; /* Looping var */
3106 char buf
[1024]; /* Encoded URI buffer */
3107 static const char * const codes
[] =
3108 { /* Request code strings */
3125 DEBUG_printf(("7http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
3126 http
, codes
[request
], uri
));
3128 if (http
== NULL
|| uri
== NULL
)
3132 * Set the User-Agent field if it isn't already...
3135 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
3136 httpSetField(http
, HTTP_FIELD_USER_AGENT
, CUPS_MINIMAL
);
3139 * Encode the URI as needed...
3142 _httpEncodeURI(buf
, uri
, sizeof(buf
));
3145 * See if we had an error the last time around; if so, reconnect...
3148 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
3149 if (httpReconnect(http
))
3153 * Flush any written data that is pending...
3158 if (httpFlushWrite(http
) < 0)
3159 if (httpReconnect(http
))
3164 * Send the request header...
3167 http
->state
= request
;
3168 http
->data_encoding
= HTTP_ENCODE_FIELDS
;
3170 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
3173 http
->status
= HTTP_CONTINUE
;
3176 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
3178 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
3179 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
3181 #endif /* HAVE_SSL */
3183 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
3185 http
->status
= HTTP_ERROR
;
3189 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3190 if (http
->fields
[i
][0] != '\0')
3192 DEBUG_printf(("9http_send: %s: %s", http_fields
[i
],
3193 httpGetField(http
, i
)));
3195 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
],
3196 httpGetField(http
, i
)) < 1)
3198 http
->status
= HTTP_ERROR
;
3204 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
3206 http
->status
= HTTP_ERROR
;
3210 if (http
->expect
== HTTP_CONTINUE
&&
3211 (http
->state
== HTTP_POST_RECV
|| http
->state
== HTTP_PUT_RECV
))
3212 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
3214 http
->status
= HTTP_ERROR
;
3218 if (httpPrintf(http
, "\r\n") < 1)
3220 http
->status
= HTTP_ERROR
;
3224 if (httpFlushWrite(http
) < 0)
3227 httpGetLength2(http
);
3228 httpClearFields(http
);
3231 * The Kerberos and AuthRef authentication strings can only be used once...
3234 if (http
->field_authorization
&& http
->authstring
&&
3235 (!strncmp(http
->authstring
, "Negotiate", 9) ||
3236 !strncmp(http
->authstring
, "AuthRef", 7)))
3238 http
->_authstring
[0] = '\0';
3240 if (http
->authstring
!= http
->_authstring
)
3241 free(http
->authstring
);
3243 http
->authstring
= http
->_authstring
;
3252 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
3255 static int /* O - Status of connection */
3256 http_setup_ssl(http_t
*http
) /* I - Connection to server */
3259 SSL_CTX
*context
; /* Context for encryption */
3260 SSL
*conn
; /* Connection for encryption */
3261 BIO
*bio
; /* BIO data */
3262 # elif defined(HAVE_GNUTLS)
3263 http_tls_t
*conn
; /* TLS session object */
3264 gnutls_certificate_client_credentials
*credentials
;
3265 /* TLS credentials */
3266 # elif defined(HAVE_CDSASSL)
3267 OSStatus error
; /* Error code */
3268 http_tls_t
*conn
; /* CDSA connection information */
3269 # elif defined(HAVE_SSPISSL)
3270 TCHAR username
[256]; /* Username returned from GetUserName() */
3271 TCHAR commonName
[256]; /* Common name for certificate */
3272 DWORD dwSize
; /* 32 bit size */
3273 _sspi_struct_t
*conn
; /* SSPI connection information */
3274 # endif /* HAVE_LIBSSL */
3277 DEBUG_printf(("7http_setup_ssl(http=%p)", http
));
3280 context
= SSL_CTX_new(SSLv23_client_method());
3282 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
3284 bio
= BIO_new(_httpBIOMethods());
3285 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
3287 conn
= SSL_new(context
);
3288 SSL_set_bio(conn
, bio
, bio
);
3290 if (SSL_connect(conn
) != 1)
3293 unsigned long error
; /* Error code */
3295 while ((error
= ERR_get_error()) != 0)
3296 DEBUG_printf(("8http_setup_ssl: %s", ERR_error_string(error
, NULL
)));
3299 SSL_CTX_free(context
);
3303 http
->error
= WSAGetLastError();
3305 http
->error
= errno
;
3307 http
->status
= HTTP_ERROR
;
3309 return (HTTP_ERROR
);
3312 # elif defined(HAVE_GNUTLS)
3313 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
3315 http
->error
= errno
;
3316 http
->status
= HTTP_ERROR
;
3321 credentials
= (gnutls_certificate_client_credentials
*)
3322 malloc(sizeof(gnutls_certificate_client_credentials
));
3323 if (credentials
== NULL
)
3327 http
->error
= errno
;
3328 http
->status
= HTTP_ERROR
;
3333 gnutls_certificate_allocate_credentials(credentials
);
3335 gnutls_init(&(conn
->session
), GNUTLS_CLIENT
);
3336 gnutls_set_default_priority(conn
->session
);
3337 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
3338 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)http
);
3339 gnutls_transport_set_pull_function(conn
->session
, _httpReadGNUTLS
);
3340 gnutls_transport_set_push_function(conn
->session
, _httpWriteGNUTLS
);
3342 if ((gnutls_handshake(conn
->session
)) != GNUTLS_E_SUCCESS
)
3344 http
->error
= errno
;
3345 http
->status
= HTTP_ERROR
;
3347 gnutls_deinit(conn
->session
);
3348 gnutls_certificate_free_credentials(*credentials
);
3355 conn
->credentials
= credentials
;
3357 # elif defined(HAVE_CDSASSL)
3358 conn
= (http_tls_t
*)calloc(1, sizeof(http_tls_t
));
3363 if ((error
= SSLNewContext(false, &conn
->session
)))
3365 http
->error
= error
;
3366 http
->status
= HTTP_ERROR
;
3373 * Use a union to resolve warnings about int/pointer size mismatches...
3376 error
= SSLSetConnection(conn
->session
, http
);
3379 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
3382 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
3385 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
3388 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
3392 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
3398 http
->error
= error
;
3399 http
->status
= HTTP_ERROR
;
3401 SSLDisposeContext(conn
->session
);
3407 # elif defined(HAVE_SSPISSL)
3408 conn
= _sspiAlloc();
3413 conn
->sock
= http
->fd
;
3414 dwSize
= sizeof(username
) / sizeof(TCHAR
);
3415 GetUserName(username
, &dwSize
);
3416 _sntprintf_s(commonName
, sizeof(commonName
) / sizeof(TCHAR
),
3417 sizeof(commonName
) / sizeof(TCHAR
), TEXT("CN=%s"), username
);
3419 if (!_sspiGetCredentials(conn
, L
"ClientContainer", commonName
, FALSE
))
3425 _sspiSetAllowsAnyRoot(conn
, TRUE
);
3426 _sspiSetAllowsExpiredCerts(conn
, TRUE
);
3428 if (!_sspiConnect(conn
, http
->hostname
))
3433 # endif /* HAVE_CDSASSL */
3438 #endif /* HAVE_SSL */
3443 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
3447 http_shutdown_ssl(http_t
*http
) /* I - Connection to server */
3450 SSL_CTX
*context
; /* Context for encryption */
3451 SSL
*conn
; /* Connection for encryption */
3454 conn
= (SSL
*)(http
->tls
);
3455 context
= SSL_get_SSL_CTX(conn
);
3458 SSL_CTX_free(context
);
3461 # elif defined(HAVE_GNUTLS)
3462 http_tls_t
*conn
; /* Encryption session */
3463 gnutls_certificate_client_credentials
*credentials
;
3464 /* TLS credentials */
3467 conn
= (http_tls_t
*)(http
->tls
);
3468 credentials
= (gnutls_certificate_client_credentials
*)(conn
->credentials
);
3470 gnutls_bye(conn
->session
, GNUTLS_SHUT_RDWR
);
3471 gnutls_deinit(conn
->session
);
3472 gnutls_certificate_free_credentials(*credentials
);
3476 # elif defined(HAVE_CDSASSL)
3477 http_tls_t
*conn
; /* CDSA connection information */
3480 conn
= (http_tls_t
*)(http
->tls
);
3482 while (SSLClose(conn
->session
) == errSSLWouldBlock
)
3485 SSLDisposeContext(conn
->session
);
3487 if (conn
->certsArray
)
3488 CFRelease(conn
->certsArray
);
3491 # elif defined(HAVE_SSPISSL)
3492 _sspi_struct_t
*conn
; /* SSPI connection information */
3494 conn
= (_sspi_struct_t
*)(http
->tls
);
3496 # endif /* HAVE_LIBSSL */
3500 #endif /* HAVE_SSL */
3505 * 'http_threadid_cb()' - Return the current thread ID.
3508 static unsigned long /* O - Thread ID */
3509 http_threadid_cb(void)
3511 # ifdef HAVE_PTHREAD_H
3512 return ((unsigned long)pthread_self());
3515 # endif /* HAVE_PTHREAD_H */
3517 #endif /* HAVE_LIBSSL */
3522 * 'http_upgrade()' - Force upgrade to TLS encryption.
3525 static int /* O - Status of connection */
3526 http_upgrade(http_t
*http
) /* I - Connection to server */
3528 int ret
; /* Return value */
3529 http_t myhttp
; /* Local copy of HTTP data */
3532 DEBUG_printf(("7http_upgrade(%p)", http
));
3535 * Flush the connection to make sure any previous "Upgrade" message
3542 * Copy the HTTP data to a local variable so we can do the OPTIONS
3543 * request without interfering with the existing request data...
3546 memcpy(&myhttp
, http
, sizeof(myhttp
));
3549 * Send an OPTIONS request to the server, requiring SSL or TLS
3550 * encryption on the link...
3553 http
->field_authorization
= NULL
; /* Don't free the auth string */
3555 httpClearFields(http
);
3556 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
3557 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0, SSL/2.0, SSL/3.0");
3559 if ((ret
= httpOptions(http
, "*")) == 0)
3562 * Wait for the secure connection...
3565 while (httpUpdate(http
) == HTTP_CONTINUE
);
3569 * Restore the HTTP request data...
3572 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
3573 http
->data_encoding
= myhttp
.data_encoding
;
3574 http
->data_remaining
= myhttp
.data_remaining
;
3575 http
->_data_remaining
= myhttp
._data_remaining
;
3576 http
->expect
= myhttp
.expect
;
3577 http
->field_authorization
= myhttp
.field_authorization
;
3578 http
->digest_tries
= myhttp
.digest_tries
;
3581 * See if we actually went secure...
3587 * Server does not support HTTP upgrade...
3590 DEBUG_puts("8http_upgrade: Server does not support HTTP upgrade!");
3593 closesocket(http
->fd
);
3605 #endif /* HAVE_SSL */
3609 * 'http_write()' - Write a buffer to a HTTP connection.
3612 static int /* O - Number of bytes written */
3613 http_write(http_t
*http
, /* I - Connection to server */
3614 const char *buffer
, /* I - Buffer for data */
3615 int length
) /* I - Number of bytes to write */
3617 int tbytes
, /* Total bytes sent */
3618 bytes
; /* Bytes sent */
3621 DEBUG_printf(("2http_write(http=%p, buffer=%p, length=%d)", http
, buffer
,
3630 bytes
= http_write_ssl(http
, buffer
, length
);
3632 #endif /* HAVE_SSL */
3633 bytes
= send(http
->fd
, buffer
, length
, 0);
3638 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
3640 else if (WSAGetLastError() != http
->error
&& WSAGetLastError() != WSAECONNRESET
)
3642 http
->error
= WSAGetLastError();
3646 if (errno
== EINTR
|| errno
== EAGAIN
)
3648 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
3650 http
->error
= errno
;
3655 DEBUG_printf(("3http_write: error writing data (%s).",
3656 strerror(http
->error
)));
3667 http_debug_hex("http_write", buffer
- tbytes
, tbytes
);
3670 DEBUG_printf(("3http_write: Returning %d.", tbytes
));
3677 * 'http_write_chunk()' - Write a chunked buffer.
3680 static int /* O - Number bytes written */
3681 http_write_chunk(http_t
*http
, /* I - Connection to server */
3682 const char *buffer
, /* I - Buffer to write */
3683 int length
) /* I - Length of buffer */
3685 char header
[255]; /* Chunk header */
3686 int bytes
; /* Bytes written */
3689 DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=%d)",
3690 http
, buffer
, length
));
3693 * Write the chunk header, data, and trailer.
3696 sprintf(header
, "%x\r\n", length
);
3697 if (http_write(http
, header
, (int)strlen(header
)) < 0)
3699 DEBUG_puts("8http_write_chunk: http_write of length failed!");
3703 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
3705 DEBUG_puts("8http_write_chunk: http_write of buffer failed!");
3709 if (http_write(http
, "\r\n", 2) < 0)
3711 DEBUG_puts("8http_write_chunk: http_write of CR LF failed!");
3721 * 'http_write_ssl()' - Write to a SSL/TLS connection.
3724 static int /* O - Bytes written */
3725 http_write_ssl(http_t
*http
, /* I - Connection to server */
3726 const char *buf
, /* I - Buffer holding data */
3727 int len
) /* I - Length of buffer */
3729 ssize_t result
; /* Return value */
3732 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http
, buf
, len
));
3734 # if defined(HAVE_LIBSSL)
3735 result
= SSL_write((SSL
*)(http
->tls
), buf
, len
);
3737 # elif defined(HAVE_GNUTLS)
3738 result
= gnutls_record_send(((http_tls_t
*)(http
->tls
))->session
, buf
, len
);
3740 if (result
< 0 && !errno
)
3743 * Convert GNU TLS error to errno value...
3748 case GNUTLS_E_INTERRUPTED
:
3752 case GNUTLS_E_AGAIN
:
3764 # elif defined(HAVE_CDSASSL)
3765 OSStatus error
; /* Error info */
3766 size_t processed
; /* Number of bytes processed */
3769 error
= SSLWrite(((http_tls_t
*)http
->tls
)->session
, buf
, len
, &processed
);
3774 result
= (int)processed
;
3776 case errSSLClosedGraceful
:
3779 case errSSLWouldBlock
:
3781 result
= (int)processed
;
3793 # elif defined(HAVE_SSPISSL)
3794 return _sspiWrite((_sspi_struct_t
*) http
->tls
, (void*) buf
, len
);
3795 # endif /* HAVE_LIBSSL */
3797 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result
));
3799 return ((int)result
);
3801 #endif /* HAVE_SSL */
3805 * End of "$Id: http.c 7850 2008-08-20 00:07:25Z mike $".