2 * "$Id: http.c 7850 2008-08-20 00:07:25Z mike $"
4 * HTTP routines for the Common UNIX Printing System (CUPS).
6 * Copyright 2007-2008 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * This file contains Kerberos support code, copyright 2006 by
12 * These coded instructions, statements, and computer programs are the
13 * property of Apple Inc. and are protected by Federal copyright
14 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
15 * which should have been included with this file. If this file is
16 * file is missing or damaged, see the license at "http://www.cups.org/".
18 * This file is subject to the Apple OS-Developed Software exception.
22 * _httpBIOMethods() - Get the OpenSSL BIO methods for HTTP connections.
23 * httpBlocking() - Set blocking/non-blocking behavior on a connection.
24 * httpCheck() - Check to see if there is a pending response from
26 * httpClearCookie() - Clear the cookie value(s).
27 * httpClearFields() - Clear HTTP request fields.
28 * httpClose() - Close an HTTP connection...
29 * httpConnect() - Connect to a HTTP server.
30 * httpConnectEncrypt() - Connect to a HTTP server using encryption.
31 * httpDelete() - Send a DELETE request to the server.
32 * httpEncryption() - Set the required encryption on the link.
33 * httpError() - Get the last error on a connection.
34 * httpFlush() - Flush data from a HTTP connection.
35 * httpFlushWrite() - Flush data in write buffer.
36 * httpGet() - Send a GET request to the server.
37 * httpGetAuthString() - Get the current authorization string.
38 * httpGetBlocking() - Get the blocking/non-block state of a connection.
39 * httpGetCookie() - Get any cookie data from the response.
40 * httpGetFd() - Get the file descriptor associated with a
42 * httpGetField() - Get a field value from a request/response.
43 * httpGetLength() - Get the amount of data remaining from the
44 * content-length or transfer-encoding fields.
45 * httpGetLength2() - Get the amount of data remaining from the
46 * content-length or transfer-encoding fields.
47 * httpGetStatus() - Get the status of the last HTTP request.
48 * httpGetSubField() - Get a sub-field value.
49 * httpGets() - Get a line of text from a HTTP connection.
50 * httpHead() - Send a HEAD request to the server.
51 * httpInitialize() - Initialize the HTTP interface library and set the
52 * default HTTP proxy (if any).
53 * httpOptions() - Send an OPTIONS request to the server.
54 * httpPost() - Send a POST request to the server.
55 * httpPrintf() - Print a formatted string to a HTTP connection.
56 * httpPut() - Send a PUT request to the server.
57 * httpRead() - Read data from a HTTP connection.
58 * httpRead2() - Read data from a HTTP connection.
59 * _httpReadCDSA() - Read function for the CDSA library.
60 * _httpReadGNUTLS() - Read function for the GNU TLS library.
61 * httpReconnect() - Reconnect to a HTTP server...
62 * httpSetAuthString() - Set the current authorization string.
63 * httpSetCookie() - Set the cookie value(s)...
64 * httpSetExpect() - Set the Expect: header in a request.
65 * httpSetField() - Set the value of an HTTP header.
66 * httpSetLength() - Set the content-length and transfer-encoding.
67 * httpTrace() - Send an TRACE request to the server.
68 * httpUpdate() - Update the current HTTP state for incoming data.
69 * httpWait() - Wait for data available on a connection.
70 * httpWrite() - Write data to a HTTP connection.
71 * httpWrite2() - Write data to a HTTP connection.
72 * _httpWriteCDSA() - Write function for the CDSA library.
73 * _httpWriteGNUTLS() - Write function for the GNU TLS library.
74 * http_bio_ctrl() - Control the HTTP connection.
75 * http_bio_free() - Free OpenSSL data.
76 * http_bio_new() - Initialize an OpenSSL BIO structure.
77 * http_bio_puts() - Send a string for OpenSSL.
78 * http_bio_read() - Read data for OpenSSL.
79 * http_bio_write() - Write data for OpenSSL.
80 * http_debug_hex() - Do a hex dump of a buffer.
81 * http_field() - Return the field index for a field name.
82 * http_read_ssl() - Read from a SSL/TLS connection.
83 * http_send() - Send a request with all fields and the trailing
85 * http_setup_ssl() - Set up SSL/TLS on a connection.
86 * http_shutdown_ssl() - Shut down SSL/TLS on a connection.
87 * http_upgrade() - Force upgrade to TLS encryption.
88 * http_wait() - Wait for data available on a connection.
89 * http_write() - Write data to a connection.
90 * http_write_ssl() - Write to a SSL/TLS connection.
94 * Include necessary headers...
97 #include "http-private.h"
105 # include <sys/time.h>
106 # include <sys/resource.h>
109 # include <sys/poll.h>
110 #endif /* HAVE_POLL */
114 * Some operating systems have done away with the Fxxxx constants for
115 * the fcntl() call; this works around that "feature"...
119 # define FNONBLK O_NONBLOCK
120 #endif /* !FNONBLK */
128 static void http_debug_hex(const char *prefix
, const char *buffer
,
131 static http_field_t
http_field(const char *name
);
132 static int http_send(http_t
*http
, http_state_t request
,
134 static int http_wait(http_t
*http
, int msec
, int usessl
);
135 static int http_write(http_t
*http
, const char *buffer
,
137 static int http_write_chunk(http_t
*http
, const char *buffer
,
140 static int http_read_ssl(http_t
*http
, char *buf
, int len
);
141 static int http_setup_ssl(http_t
*http
);
142 static void http_shutdown_ssl(http_t
*http
);
143 static int http_upgrade(http_t
*http
);
144 static int http_write_ssl(http_t
*http
, const char *buf
, int len
);
145 #endif /* HAVE_SSL */
152 static const char * const http_fields
[] =
169 "If-Unmodified-since",
184 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
186 * BIO methods for OpenSSL...
189 static int http_bio_write(BIO
*h
, const char *buf
, int num
);
190 static int http_bio_read(BIO
*h
, char *buf
, int size
);
191 static int http_bio_puts(BIO
*h
, const char *str
);
192 static long http_bio_ctrl(BIO
*h
, int cmd
, long arg1
, void *arg2
);
193 static int http_bio_new(BIO
*h
);
194 static int http_bio_free(BIO
*data
);
196 static BIO_METHOD http_bio_methods
=
203 NULL
, /* http_bio_gets, */
212 * '_httpBIOMethods()' - Get the OpenSSL BIO methods for HTTP connections.
215 BIO_METHOD
* /* O - BIO methods for OpenSSL */
216 _httpBIOMethods(void)
218 return (&http_bio_methods
);
220 #endif /* HAVE_SSL && HAVE_LIBSSL */
224 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
228 httpBlocking(http_t
*http
, /* I - Connection to server */
229 int b
) /* I - 1 = blocking, 0 = non-blocking */
237 * 'httpCheck()' - Check to see if there is a pending response from the server.
240 int /* O - 0 = no data, 1 = data available */
241 httpCheck(http_t
*http
) /* I - Connection to server */
243 return (httpWait(http
, 0));
248 * 'httpClearCookie()' - Clear the cookie value(s).
250 * @since CUPS 1.1.19@
254 httpClearCookie(http_t
*http
) /* I - Connection to server */
268 * 'httpClearFields()' - Clear HTTP request fields.
272 httpClearFields(http_t
*http
) /* I - Connection to server */
276 memset(http
->fields
, 0, sizeof(http
->fields
));
277 if (http
->hostname
[0] == '/')
278 httpSetField(http
, HTTP_FIELD_HOST
, "localhost");
280 httpSetField(http
, HTTP_FIELD_HOST
, http
->hostname
);
282 if (http
->field_authorization
)
284 free(http
->field_authorization
);
285 http
->field_authorization
= NULL
;
288 http
->expect
= (http_status_t
)0;
294 * 'httpClose()' - Close an HTTP connection...
298 httpClose(http_t
*http
) /* I - Connection to server */
301 OM_uint32 minor_status
; /* Minor status code */
302 #endif /* HAVE_GSSAPI */
305 DEBUG_printf(("httpClose(http=%p)\n", http
));
310 httpAddrFreeList(http
->addrlist
);
317 http_shutdown_ssl(http
);
318 #endif /* HAVE_SSL */
321 closesocket(http
->fd
);
327 if (http
->gssctx
!= GSS_C_NO_CONTEXT
)
328 gss_delete_sec_context(&minor_status
, &http
->gssctx
, GSS_C_NO_BUFFER
);
330 if (http
->gssname
!= GSS_C_NO_NAME
)
331 gss_release_name(&minor_status
, &http
->gssname
);
332 #endif /* HAVE_GSSAPI */
334 #ifdef HAVE_AUTHORIZATION_H
336 AuthorizationFree(http
->auth_ref
, kAuthorizationFlagDefaults
);
337 #endif /* HAVE_AUTHORIZATION_H */
339 httpClearFields(http
);
341 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
342 free(http
->authstring
);
349 * 'httpConnect()' - Connect to a HTTP server.
351 * This function is deprecated - use @link httpConnectEncrypt@ instead.
356 http_t
* /* O - New HTTP connection */
357 httpConnect(const char *host
, /* I - Host to connect to */
358 int port
) /* I - Port number */
360 return (httpConnectEncrypt(host
, port
, HTTP_ENCRYPT_IF_REQUESTED
));
365 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
368 http_t
* /* O - New HTTP connection */
370 const char *host
, /* I - Host to connect to */
371 int port
, /* I - Port number */
372 http_encryption_t encryption
) /* I - Type of encryption to use */
374 http_t
*http
; /* New HTTP connection */
377 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)\n",
378 host
, port
, encryption
));
381 * Create the HTTP structure...
384 if ((http
= _httpCreate(host
, port
, encryption
)) == NULL
)
388 * Connect to the remote system...
391 if (!httpReconnect(http
))
395 * Could not connect to any known address - bail out!
398 httpAddrFreeList(http
->addrlist
);
407 * '_httpCreate()' - Create an unconnected HTTP connection.
410 http_t
* /* O - HTTP connection */
412 const char *host
, /* I - Hostname */
413 int port
, /* I - Port number */
414 http_encryption_t encryption
) /* I - Encryption to use */
416 http_t
*http
; /* New HTTP connection */
417 http_addrlist_t
*addrlist
; /* Host address data */
418 char service
[255]; /* Service name */
421 DEBUG_printf(("_httpCreate(host=\"%s\", port=%d, encryption=%d)\n",
422 host
, port
, encryption
));
433 sprintf(service
, "%d", port
);
435 if ((addrlist
= httpAddrGetList(host
, AF_UNSPEC
, service
)) == NULL
)
439 * Allocate memory for the structure...
442 if ((http
= calloc(sizeof(http_t
), 1)) == NULL
)
444 httpAddrFreeList(addrlist
);
449 * Initialize the HTTP data...
452 http
->activity
= time(NULL
);
453 http
->addrlist
= addrlist
;
457 http
->gssctx
= GSS_C_NO_CONTEXT
;
458 http
->gssname
= GSS_C_NO_NAME
;
459 #endif /* HAVE_GSSAPI */
460 http
->version
= HTTP_1_1
;
462 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
464 if (port
== 443) /* Always use encryption for https */
465 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
467 http
->encryption
= encryption
;
470 * Return the new structure...
478 * 'httpDelete()' - Send a DELETE request to the server.
481 int /* O - Status of call (0 = success) */
482 httpDelete(http_t
*http
, /* I - Connection to server */
483 const char *uri
) /* I - URI to delete */
485 return (http_send(http
, HTTP_DELETE
, uri
));
490 * 'httpEncryption()' - Set the required encryption on the link.
493 int /* O - -1 on error, 0 on success */
494 httpEncryption(http_t
*http
, /* I - Connection to server */
495 http_encryption_t e
) /* I - New encryption preference */
497 DEBUG_printf(("httpEncryption(http=%p, e=%d)\n", http
, e
));
503 http
->encryption
= e
;
505 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
506 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
507 return (httpReconnect(http
));
508 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
509 return (http_upgrade(http
));
513 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
517 #endif /* HAVE_SSL */
522 * 'httpError()' - Get the last error on a connection.
525 int /* O - Error code (errno) value */
526 httpError(http_t
*http
) /* I - Connection to server */
529 return (http
->error
);
536 * 'httpFlush()' - Flush data from a HTTP connection.
540 httpFlush(http_t
*http
) /* I - Connection to server */
542 char buffer
[8192]; /* Junk buffer */
543 int blocking
; /* To block or not to block */
546 DEBUG_printf(("httpFlush(http=%p), state=%d\n", http
, http
->state
));
549 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
552 blocking
= http
->blocking
;
556 * Read any data we can...
559 while (httpRead2(http
, buffer
, sizeof(buffer
)) > 0);
562 * Restore blocking and reset the connection if we didn't get all of
563 * the remaining data...
566 http
->blocking
= blocking
;
568 if (http
->state
!= HTTP_WAITING
&& http
->fd
>= 0)
571 * Didn't get the data back, so close the current connection.
574 http
->state
= HTTP_WAITING
;
578 http_shutdown_ssl(http
);
579 #endif /* HAVE_SSL */
582 closesocket(http
->fd
);
593 * 'httpFlushWrite()' - Flush data in write buffer.
598 int /* O - Bytes written or -1 on error */
599 httpFlushWrite(http_t
*http
) /* I - Connection to server */
601 int bytes
; /* Bytes written */
604 DEBUG_printf(("httpFlushWrite(http=%p)\n", http
));
606 if (!http
|| !http
->wused
)
609 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
610 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
612 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
621 * 'httpGet()' - Send a GET request to the server.
624 int /* O - Status of call (0 = success) */
625 httpGet(http_t
*http
, /* I - Connection to server */
626 const char *uri
) /* I - URI to get */
628 return (http_send(http
, HTTP_GET
, uri
));
633 * 'httpGetAuthString()' - Get the current authorization string.
635 * The authorization string is set by cupsDoAuthentication() and
636 * httpSetAuthString(). Use httpGetAuthString() to retrieve the
637 * string to use with httpSetField() for the HTTP_FIELD_AUTHORIZATION
643 char * /* O - Authorization string */
644 httpGetAuthString(http_t
*http
) /* I - Connection to server */
647 return (http
->authstring
);
654 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
659 int /* O - 1 if blocking, 0 if non-blocking */
660 httpGetBlocking(http_t
*http
) /* I - Connection to server */
662 return (http
? http
->blocking
: 0);
667 * 'httpGetCookie()' - Get any cookie data from the response.
669 * @since CUPS 1.1.19@
672 const char * /* O - Cookie data or NULL */
673 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
675 return (http
? http
->cookie
: NULL
);
680 * 'httpGetFd()' - Get the file descriptor associated with a connection.
685 int /* O - File descriptor or -1 if none */
686 httpGetFd(http_t
*http
) /* I - Connection to server */
688 return (http
? http
->fd
: -1);
693 * 'httpGetField()' - Get a field value from a request/response.
696 const char * /* O - Field value */
697 httpGetField(http_t
*http
, /* I - Connection to server */
698 http_field_t field
) /* I - Field to get */
700 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
702 else if (field
== HTTP_FIELD_AUTHORIZATION
&&
703 http
->field_authorization
)
706 * Special case for WWW-Authenticate: as its contents can be
707 * longer than HTTP_MAX_VALUE...
710 return (http
->field_authorization
);
713 return (http
->fields
[field
]);
718 * 'httpGetLength()' - Get the amount of data remaining from the
719 * content-length or transfer-encoding fields.
721 * This function is deprecated and will not return lengths larger than
722 * 2^31 - 1; use httpGetLength2() instead.
727 int /* O - Content length */
728 httpGetLength(http_t
*http
) /* I - Connection to server */
731 * Get the read content length and return the 32-bit value.
736 httpGetLength2(http
);
738 return (http
->_data_remaining
);
746 * 'httpGetLength2()' - Get the amount of data remaining from the
747 * content-length or transfer-encoding fields.
749 * This function returns the complete content length, even for
750 * content larger than 2^31 - 1.
755 off_t
/* O - Content length */
756 httpGetLength2(http_t
*http
) /* I - Connection to server */
758 DEBUG_printf(("httpGetLength2(http=%p), state=%d\n", http
, http
->state
));
763 if (!strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
765 DEBUG_puts("httpGetLength2: chunked request!");
767 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
768 http
->data_remaining
= 0;
772 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
775 * The following is a hack for HTTP servers that don't send a
776 * content-length or transfer-encoding field...
778 * If there is no content-length then the connection must close
779 * after the transfer is complete...
782 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
785 * Default content length is 0 for errors and 2^31-1 for other
786 * successful requests...
789 if (http
->status
>= HTTP_MULTIPLE_CHOICES
)
790 http
->data_remaining
= 0;
792 http
->data_remaining
= 2147483647;
795 http
->data_remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
798 DEBUG_printf(("httpGetLength2: content_length=" CUPS_LLFMT
"\n",
799 CUPS_LLCAST http
->data_remaining
));
802 if (http
->data_remaining
<= INT_MAX
)
803 http
->_data_remaining
= (int)http
->data_remaining
;
805 http
->_data_remaining
= INT_MAX
;
807 return (http
->data_remaining
);
812 * 'httpGetStatus()' - Get the status of the last HTTP request.
817 http_status_t
/* O - HTTP status */
818 httpGetStatus(http_t
*http
) /* I - Connection to server */
820 return (http
? http
->status
: HTTP_ERROR
);
825 * 'httpGetSubField()' - Get a sub-field value.
830 char * /* O - Value or NULL */
831 httpGetSubField(http_t
*http
, /* I - Connection to server */
832 http_field_t field
, /* I - Field index */
833 const char *name
, /* I - Name of sub-field */
834 char *value
) /* O - Value string */
836 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
841 * 'httpGetSubField2()' - Get a sub-field value.
846 char * /* O - Value or NULL */
847 httpGetSubField2(http_t
*http
, /* I - Connection to server */
848 http_field_t field
, /* I - Field index */
849 const char *name
, /* I - Name of sub-field */
850 char *value
, /* O - Value string */
851 int valuelen
) /* I - Size of value buffer */
853 const char *fptr
; /* Pointer into field */
854 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
855 *ptr
, /* Pointer into string buffer */
856 *end
; /* End of value buffer */
858 DEBUG_printf(("httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, valuelen=%d)\n",
859 http
, field
, name
, value
, valuelen
));
861 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
862 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
865 end
= value
+ valuelen
- 1;
867 for (fptr
= http
->fields
[field
]; *fptr
;)
870 * Skip leading whitespace...
873 while (isspace(*fptr
& 255))
883 * Get the sub-field name...
887 *fptr
&& *fptr
!= '=' && !isspace(*fptr
& 255) &&
888 ptr
< (temp
+ sizeof(temp
) - 1);
893 DEBUG_printf(("httpGetSubField: name=\"%s\"\n", temp
));
896 * Skip trailing chars up to the '='...
899 while (isspace(*fptr
& 255))
909 * Skip = and leading whitespace...
914 while (isspace(*fptr
& 255))
920 * Read quoted string...
923 for (ptr
= value
, fptr
++;
924 *fptr
&& *fptr
!= '\"' && ptr
< end
;
929 while (*fptr
&& *fptr
!= '\"')
938 * Read unquoted string...
942 *fptr
&& !isspace(*fptr
& 255) && *fptr
!= ',' && ptr
< end
;
947 while (*fptr
&& !isspace(*fptr
& 255) && *fptr
!= ',')
951 DEBUG_printf(("httpGetSubField: value=\"%s\"\n", value
));
954 * See if this is the one...
957 if (!strcmp(name
, temp
))
968 * 'httpGets()' - Get a line of text from a HTTP connection.
971 char * /* O - Line or NULL */
972 httpGets(char *line
, /* I - Line to read into */
973 int length
, /* I - Max length of buffer */
974 http_t
*http
) /* I - Connection to server */
976 char *lineptr
, /* Pointer into line */
977 *lineend
, /* End of line */
978 *bufptr
, /* Pointer into input buffer */
979 *bufend
; /* Pointer to end of buffer */
980 int bytes
, /* Number of bytes read */
981 eol
; /* End-of-line? */
984 DEBUG_printf(("httpGets(line=%p, length=%d, http=%p)\n", line
, length
, http
));
986 if (http
== NULL
|| line
== NULL
)
990 * Read a line from the buffer...
994 lineend
= line
+ length
- 1;
997 while (lineptr
< lineend
)
1000 * Pre-load the buffer as needed...
1009 while (http
->used
== 0)
1012 * No newline; see if there is more data to be read...
1015 if (!http
->blocking
&& !http_wait(http
, 10000, 1))
1017 DEBUG_puts("httpGets: Timed out!");
1019 http
->error
= WSAETIMEDOUT
;
1021 http
->error
= ETIMEDOUT
;
1028 bytes
= http_read_ssl(http
, http
->buffer
+ http
->used
,
1029 HTTP_MAX_BUFFER
- http
->used
);
1031 #endif /* HAVE_SSL */
1032 bytes
= recv(http
->fd
, http
->buffer
+ http
->used
,
1033 HTTP_MAX_BUFFER
- http
->used
, 0);
1035 DEBUG_printf(("httpGets: read %d bytes...\n", bytes
));
1040 * Nope, can't get a line this time...
1044 if (WSAGetLastError() != http
->error
)
1046 http
->error
= WSAGetLastError();
1050 DEBUG_printf(("httpGets: recv() error %d!\n", WSAGetLastError()));
1052 DEBUG_printf(("httpGets: recv() error %d!\n", errno
));
1056 else if (errno
!= http
->error
)
1058 http
->error
= errno
;
1065 else if (bytes
== 0)
1067 http
->error
= EPIPE
;
1073 * Yup, update the amount used...
1076 http
->used
+= bytes
;
1080 * Now copy as much of the current line as possible...
1083 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1084 lineptr
< lineend
&& bufptr
< bufend
;)
1086 if (*bufptr
== 0x0a)
1092 else if (*bufptr
== 0x0d)
1095 *lineptr
++ = *bufptr
++;
1098 http
->used
-= (int)(bufptr
- http
->buffer
);
1100 memmove(http
->buffer
, bufptr
, http
->used
);
1108 http
->activity
= time(NULL
);
1112 DEBUG_printf(("httpGets: Returning \"%s\"\n", line
));
1118 DEBUG_puts("httpGets: No new line available!");
1125 * 'httpHead()' - Send a HEAD request to the server.
1128 int /* O - Status of call (0 = success) */
1129 httpHead(http_t
*http
, /* I - Connection to server */
1130 const char *uri
) /* I - URI for head */
1132 return (http_send(http
, HTTP_HEAD
, uri
));
1137 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1138 * default HTTP proxy (if any).
1142 httpInitialize(void)
1146 struct timeval curtime
; /* Current time in microseconds */
1147 # endif /* !WIN32 */
1148 int i
; /* Looping var */
1149 unsigned char data
[1024]; /* Seed data */
1150 #endif /* HAVE_LIBSSL */
1153 WSADATA winsockdata
; /* WinSock data */
1154 static int initialized
= 0; /* Has WinSock been initialized? */
1158 WSAStartup(MAKEWORD(1,1), &winsockdata
);
1159 #elif !defined(SO_NOSIGPIPE)
1161 * Ignore SIGPIPE signals...
1165 sigset(SIGPIPE
, SIG_IGN
);
1166 # elif defined(HAVE_SIGACTION)
1167 struct sigaction action
; /* POSIX sigaction data */
1170 memset(&action
, 0, sizeof(action
));
1171 action
.sa_handler
= SIG_IGN
;
1172 sigaction(SIGPIPE
, &action
, NULL
);
1174 signal(SIGPIPE
, SIG_IGN
);
1175 # endif /* !SO_NOSIGPIPE */
1179 gnutls_global_init();
1180 #endif /* HAVE_GNUTLS */
1183 SSL_load_error_strings();
1187 * Using the current time is a dubious random seed, but on some systems
1188 * it is the best we can do (on others, this seed isn't even used...)
1193 gettimeofday(&curtime
, NULL
);
1194 srand(curtime
.tv_sec
+ curtime
.tv_usec
);
1197 for (i
= 0; i
< sizeof(data
); i
++)
1198 data
[i
] = rand(); /* Yes, this is a poor source of random data... */
1200 RAND_seed(&data
, sizeof(data
));
1201 #endif /* HAVE_LIBSSL */
1206 * 'httpOptions()' - Send an OPTIONS request to the server.
1209 int /* O - Status of call (0 = success) */
1210 httpOptions(http_t
*http
, /* I - Connection to server */
1211 const char *uri
) /* I - URI for options */
1213 return (http_send(http
, HTTP_OPTIONS
, uri
));
1218 * 'httpPost()' - Send a POST request to the server.
1221 int /* O - Status of call (0 = success) */
1222 httpPost(http_t
*http
, /* I - Connection to server */
1223 const char *uri
) /* I - URI for post */
1225 return (http_send(http
, HTTP_POST
, uri
));
1230 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1235 int /* O - Number of bytes written */
1236 httpPrintf(http_t
*http
, /* I - Connection to server */
1237 const char *format
, /* I - printf-style format string */
1238 ...) /* I - Additional args as needed */
1240 int bytes
; /* Number of bytes to write */
1241 char buf
[16384]; /* Buffer for formatted string */
1242 va_list ap
; /* Variable argument pointer */
1245 DEBUG_printf(("httpPrintf(http=%p, format=\"%s\", ...)\n", http
, format
));
1247 va_start(ap
, format
);
1248 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1251 DEBUG_printf(("httpPrintf: %s", buf
));
1253 if (http
->data_encoding
== HTTP_ENCODE_FIELDS
)
1254 return (httpWrite2(http
, buf
, bytes
));
1259 DEBUG_puts(" flushing existing data...");
1261 if (httpFlushWrite(http
) < 0)
1265 return (http_write(http
, buf
, bytes
));
1271 * 'httpPut()' - Send a PUT request to the server.
1274 int /* O - Status of call (0 = success) */
1275 httpPut(http_t
*http
, /* I - Connection to server */
1276 const char *uri
) /* I - URI to put */
1278 return (http_send(http
, HTTP_PUT
, uri
));
1283 * 'httpRead()' - Read data from a HTTP connection.
1285 * This function is deprecated. Use the httpRead2() function which can
1286 * read more than 2GB of data.
1291 int /* O - Number of bytes read */
1292 httpRead(http_t
*http
, /* I - Connection to server */
1293 char *buffer
, /* I - Buffer for data */
1294 int length
) /* I - Maximum number of bytes */
1296 return ((int)httpRead2(http
, buffer
, length
));
1301 * 'httpRead2()' - Read data from a HTTP connection.
1306 ssize_t
/* O - Number of bytes read */
1307 httpRead2(http_t
*http
, /* I - Connection to server */
1308 char *buffer
, /* I - Buffer for data */
1309 size_t length
) /* I - Maximum number of bytes */
1311 ssize_t bytes
; /* Bytes read */
1312 char len
[32]; /* Length string */
1315 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
")\n",
1316 http
, buffer
, CUPS_LLCAST length
));
1318 if (http
== NULL
|| buffer
== NULL
)
1321 http
->activity
= time(NULL
);
1326 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1327 http
->data_remaining
<= 0)
1329 DEBUG_puts("httpRead2: Getting chunk length...");
1331 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1333 DEBUG_puts("httpRead2: Could not get length!");
1337 http
->data_remaining
= strtoll(len
, NULL
, 16);
1338 if (http
->data_remaining
< 0)
1340 DEBUG_puts("httpRead2: Negative chunk length!");
1345 DEBUG_printf(("httpRead2: data_remaining=" CUPS_LLFMT
"\n",
1346 CUPS_LLCAST http
->data_remaining
));
1348 if (http
->data_remaining
<= 0)
1351 * A zero-length chunk ends a transfer; unless we are reading POST
1355 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1356 httpGets(len
, sizeof(len
), http
);
1358 if (http
->state
== HTTP_POST_RECV
)
1361 http
->state
= HTTP_WAITING
;
1364 * Prevent future reads for this request...
1367 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1371 else if (length
> (size_t)http
->data_remaining
)
1372 length
= (size_t)http
->data_remaining
;
1374 if (http
->used
== 0 && length
<= 256)
1377 * Buffer small reads for better performance...
1380 if (!http
->blocking
&& !httpWait(http
, 10000))
1383 if (http
->data_remaining
> sizeof(http
->buffer
))
1384 bytes
= sizeof(http
->buffer
);
1386 bytes
= http
->data_remaining
;
1390 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1392 #endif /* HAVE_SSL */
1394 DEBUG_printf(("httpRead2: reading %d bytes from socket into buffer...\n",
1397 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1399 DEBUG_printf(("httpRead2: read %d bytes from socket into buffer...\n",
1408 http
->error
= WSAGetLastError();
1413 http
->error
= errno
;
1420 http
->error
= EPIPE
;
1427 if (length
> (size_t)http
->used
)
1428 length
= (size_t)http
->used
;
1430 bytes
= (ssize_t
)length
;
1432 DEBUG_printf(("httpRead2: grabbing %d bytes from input buffer...\n",
1435 memcpy(buffer
, http
->buffer
, length
);
1436 http
->used
-= (int)length
;
1439 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
1444 if (!http
->blocking
&& !httpWait(http
, 10000))
1447 bytes
= (ssize_t
)http_read_ssl(http
, buffer
, (int)length
);
1449 #endif /* HAVE_SSL */
1452 if (!http
->blocking
&& !httpWait(http
, 10000))
1455 DEBUG_printf(("httpRead2: reading " CUPS_LLFMT
" bytes from socket...\n",
1456 CUPS_LLCAST length
));
1459 bytes
= (ssize_t
)recv(http
->fd
, buffer
, (int)length
, 0);
1461 while ((bytes
= recv(http
->fd
, buffer
, length
, 0)) < 0)
1466 DEBUG_printf(("httpRead2: read " CUPS_LLFMT
" bytes from socket...\n",
1467 CUPS_LLCAST bytes
));
1472 http
->data_remaining
-= bytes
;
1474 if (http
->data_remaining
<= INT_MAX
)
1475 http
->_data_remaining
= (int)http
->data_remaining
;
1477 http
->_data_remaining
= INT_MAX
;
1482 http
->error
= WSAGetLastError();
1487 http
->error
= errno
;
1492 http
->error
= EPIPE
;
1496 if (http
->data_remaining
== 0)
1498 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1499 httpGets(len
, sizeof(len
), http
);
1501 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
1503 if (http
->state
== HTTP_POST_RECV
)
1506 http
->state
= HTTP_WAITING
;
1511 http_debug_hex("httpRead2", buffer
, (int)bytes
);
1518 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
1520 * '_httpReadCDSA()' - Read function for the CDSA library.
1523 OSStatus
/* O - -1 on error, 0 on success */
1525 SSLConnectionRef connection
, /* I - SSL/TLS connection */
1526 void *data
, /* I - Data buffer */
1527 size_t *dataLength
) /* IO - Number of bytes */
1529 OSStatus result
; /* Return value */
1530 ssize_t bytes
; /* Number of bytes read */
1531 http_t
*http
; /* HTTP connection */
1534 http
= (http_t
*)connection
;
1536 if (!http
->blocking
)
1539 * Make sure we have data before we read...
1542 if (!http_wait(http
, 10000, 0))
1544 http
->error
= ETIMEDOUT
;
1551 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
1553 while (bytes
== -1 && errno
== EINTR
);
1555 if (bytes
== *dataLength
)
1561 *dataLength
= bytes
;
1562 result
= errSSLWouldBlock
;
1569 result
= errSSLClosedGraceful
;
1570 else if (errno
== EAGAIN
)
1571 result
= errSSLWouldBlock
;
1573 result
= errSSLClosedAbort
;
1578 #endif /* HAVE_SSL && HAVE_CDSASSL */
1581 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
1583 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
1586 ssize_t
/* O - Number of bytes read or -1 on error */
1588 gnutls_transport_ptr ptr
, /* I - Connection to server */
1589 void *data
, /* I - Buffer */
1590 size_t length
) /* I - Number of bytes to read */
1592 http_t
*http
; /* HTTP connection */
1595 http
= (http_t
*)ptr
;
1597 if (!http
->blocking
)
1600 * Make sure we have data before we read...
1603 if (!http_wait(http
, 10000, 0))
1605 http
->error
= ETIMEDOUT
;
1610 return (recv(http
->fd
, data
, length
, 0));
1612 #endif /* HAVE_SSL && HAVE_GNUTLS */
1616 * 'httpReconnect()' - Reconnect to a HTTP server.
1619 int /* O - 0 on success, non-zero on failure */
1620 httpReconnect(http_t
*http
) /* I - Connection to server */
1622 http_addrlist_t
*addr
; /* Connected address */
1624 http_addrlist_t
*current
; /* Current address */
1625 char temp
[256]; /* Temporary address string */
1629 DEBUG_printf(("httpReconnect(http=%p)\n", http
));
1637 DEBUG_puts("httpReconnect: Shutting down SSL/TLS...");
1638 http_shutdown_ssl(http
);
1640 #endif /* HAVE_SSL */
1643 * Close any previously open socket...
1648 DEBUG_printf(("httpReconnect: Closing socket %d...\n", http
->fd
));
1651 closesocket(http
->fd
);
1662 * Connect to the server...
1666 for (current
= http
->addrlist
; current
; current
= current
->next
)
1667 DEBUG_printf(("httpReconnect: Address %s:%d\n",
1668 httpAddrString(&(current
->addr
), temp
, sizeof(temp
)),
1669 _httpAddrPort(&(current
->addr
))));
1672 if ((addr
= httpAddrConnect(http
->addrlist
, &(http
->fd
))) == NULL
)
1675 * Unable to connect...
1679 http
->error
= WSAGetLastError();
1681 http
->error
= errno
;
1683 http
->status
= HTTP_ERROR
;
1685 DEBUG_printf(("httpReconnect: httpAddrConnect failed: %s\n",
1686 strerror(http
->error
)));
1691 DEBUG_printf(("httpReconnect: New socket=%d\n", http
->fd
));
1693 http
->hostaddr
= &(addr
->addr
);
1695 http
->status
= HTTP_CONTINUE
;
1698 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
1701 * Always do encryption via SSL.
1704 if (http_setup_ssl(http
) != 0)
1707 closesocket(http
->fd
);
1715 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
1716 return (http_upgrade(http
));
1717 #endif /* HAVE_SSL */
1719 DEBUG_printf(("httpReconnect: Connected to %s:%d...\n",
1720 httpAddrString(http
->hostaddr
, temp
, sizeof(temp
)),
1721 _httpAddrPort(http
->hostaddr
)));
1728 * 'httpSetAuthString()' - Set the current authorization string.
1730 * This function just stores a copy of the current authorization string in
1731 * the HTTP connection object. You must still call httpSetField() to set
1732 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
1733 * httpHead(), httpOptions(), httpPost, or httpPut().
1739 httpSetAuthString(http_t
*http
, /* I - Connection to server */
1740 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
1741 const char *data
) /* I - Auth data (NULL for none) */
1744 * Range check input...
1750 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
1751 free(http
->authstring
);
1753 http
->authstring
= http
->_authstring
;
1758 * Set the current authorization string...
1761 int len
= (int)strlen(scheme
) + (data
? (int)strlen(data
) + 1 : 0) + 1;
1764 if (len
> (int)sizeof(http
->_authstring
))
1766 if ((temp
= malloc(len
)) == NULL
)
1767 len
= sizeof(http
->_authstring
);
1769 http
->authstring
= temp
;
1773 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
1775 strlcpy(http
->authstring
, scheme
, len
);
1780 * Clear the current authorization string...
1783 http
->_authstring
[0] = '\0';
1789 * 'httpSetCookie()' - Set the cookie value(s)...
1791 * @since CUPS 1.1.19@
1795 httpSetCookie(http_t
*http
, /* I - Connection */
1796 const char *cookie
) /* I - Cookie string */
1805 http
->cookie
= strdup(cookie
);
1807 http
->cookie
= NULL
;
1812 * 'httpSetExpect()' - Set the Expect: header in a request.
1814 * Currently only HTTP_CONTINUE is supported for the "expect" argument.
1820 httpSetExpect(http_t
*http
, /* I - Connection to server */
1821 http_status_t expect
) /* I - HTTP status to expect (HTTP_CONTINUE) */
1824 http
->expect
= expect
;
1829 * 'httpSetField()' - Set the value of an HTTP header.
1833 httpSetField(http_t
*http
, /* I - Connection to server */
1834 http_field_t field
, /* I - Field index */
1835 const char *value
) /* I - Value */
1838 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
1839 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
1843 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
1846 * Special case for Authorization: as its contents can be
1847 * longer than HTTP_MAX_VALUE
1850 if (field
== HTTP_FIELD_AUTHORIZATION
)
1852 if (http
->field_authorization
)
1853 free(http
->field_authorization
);
1855 http
->field_authorization
= strdup(value
);
1861 * 'httpSetLength()' - Set the content-length and content-encoding.
1867 httpSetLength(http_t
*http
, /* I - Connection to server */
1868 size_t length
) /* I - Length (0 for chunked) */
1875 strcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked");
1876 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
1880 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
1881 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
1882 CUPS_LLFMT
, CUPS_LLCAST length
);
1888 * 'httpTrace()' - Send an TRACE request to the server.
1891 int /* O - Status of call (0 = success) */
1892 httpTrace(http_t
*http
, /* I - Connection to server */
1893 const char *uri
) /* I - URI for trace */
1895 return (http_send(http
, HTTP_TRACE
, uri
));
1900 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1903 http_status_t
/* O - HTTP status */
1904 httpUpdate(http_t
*http
) /* I - Connection to server */
1906 char line
[32768], /* Line from connection... */
1907 *value
; /* Pointer to value on line */
1908 http_field_t field
; /* Field index */
1909 int major
, minor
, /* HTTP version numbers */
1910 status
; /* Request status */
1913 DEBUG_printf(("httpUpdate(http=%p), state=%d\n", http
, http
->state
));
1916 * Flush pending data, if any...
1921 DEBUG_puts(" flushing buffer...");
1923 if (httpFlushWrite(http
) < 0)
1924 return (HTTP_ERROR
);
1928 * If we haven't issued any commands, then there is nothing to "update"...
1931 if (http
->state
== HTTP_WAITING
)
1932 return (HTTP_CONTINUE
);
1935 * Grab all of the lines we can from the connection...
1938 while (httpGets(line
, sizeof(line
), http
) != NULL
)
1940 DEBUG_printf(("httpUpdate: Got \"%s\"\n", line
));
1942 if (line
[0] == '\0')
1945 * Blank line means the start of the data section (if any). Return
1946 * the result code, too...
1948 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
1949 * Instead, we just return HTTP_CONTINUE to the caller and keep on
1953 if (http
->status
== HTTP_CONTINUE
)
1954 return (http
->status
);
1956 if (http
->status
< HTTP_BAD_REQUEST
)
1957 http
->digest_tries
= 0;
1960 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
1962 if (http_setup_ssl(http
) != 0)
1965 closesocket(http
->fd
);
1970 return (HTTP_ERROR
);
1973 return (HTTP_CONTINUE
);
1975 #endif /* HAVE_SSL */
1977 httpGetLength2(http
);
1979 switch (http
->state
)
1983 case HTTP_POST_RECV
:
1986 case HTTP_POST_SEND
:
1991 http
->state
= HTTP_WAITING
;
1995 return (http
->status
);
1997 else if (strncmp(line
, "HTTP/", 5) == 0)
2000 * Got the beginning of a response...
2003 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &status
) != 3)
2004 return (HTTP_ERROR
);
2006 http
->version
= (http_version_t
)(major
* 100 + minor
);
2007 http
->status
= (http_status_t
)status
;
2009 else if ((value
= strchr(line
, ':')) != NULL
)
2016 while (isspace(*value
& 255))
2020 * Be tolerants of servers that send unknown attribute fields...
2023 if (!strcasecmp(line
, "expect"))
2026 * "Expect: 100-continue" or similar...
2029 http
->expect
= (http_status_t
)atoi(value
);
2031 else if (!strcasecmp(line
, "cookie"))
2034 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
2037 httpSetCookie(http
, value
);
2039 else if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
2041 DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line
));
2045 httpSetField(http
, field
, value
);
2049 http
->status
= HTTP_ERROR
;
2050 return (HTTP_ERROR
);
2055 * See if there was an error...
2058 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
2059 return (http
->status
);
2063 DEBUG_printf(("httpUpdate: socket error %d - %s\n", http
->error
,
2064 strerror(http
->error
)));
2065 http
->status
= HTTP_ERROR
;
2066 return (HTTP_ERROR
);
2070 * If we haven't already returned, then there is nothing new...
2073 return (HTTP_CONTINUE
);
2078 * 'httpWait()' - Wait for data available on a connection.
2080 * @since CUPS 1.1.19@
2083 int /* O - 1 if data is available, 0 otherwise */
2084 httpWait(http_t
*http
, /* I - Connection to server */
2085 int msec
) /* I - Milliseconds to wait */
2088 * First see if there is data in the buffer...
2098 * Flush pending data, if any...
2103 if (httpFlushWrite(http
) < 0)
2108 * If not, check the SSL/TLS buffers and do a select() on the connection...
2111 return (http_wait(http
, msec
, 1));
2116 * 'httpWrite()' - Write data to a HTTP connection.
2118 * This function is deprecated. Use the httpWrite2() function which can
2119 * write more than 2GB of data.
2124 int /* O - Number of bytes written */
2125 httpWrite(http_t
*http
, /* I - Connection to server */
2126 const char *buffer
, /* I - Buffer for data */
2127 int length
) /* I - Number of bytes to write */
2129 return ((int)httpWrite2(http
, buffer
, length
));
2134 * 'httpWrite2()' - Write data to a HTTP connection.
2139 ssize_t
/* O - Number of bytes written */
2140 httpWrite2(http_t
*http
, /* I - Connection to server */
2141 const char *buffer
, /* I - Buffer for data */
2142 size_t length
) /* I - Number of bytes to write */
2144 ssize_t bytes
; /* Bytes written */
2147 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT
")\n", http
,
2148 buffer
, CUPS_LLCAST length
));
2151 * Range check input...
2154 if (http
== NULL
|| buffer
== NULL
)
2158 * Mark activity on the connection...
2161 http
->activity
= time(NULL
);
2164 * Buffer small writes for better performance...
2169 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
2171 DEBUG_printf(("httpWrite2: Flushing buffer (wused=%d, length="
2172 CUPS_LLFMT
")\n", http
->wused
, CUPS_LLCAST length
));
2174 httpFlushWrite(http
);
2177 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
))
2180 * Write to buffer...
2183 DEBUG_printf(("httpWrite2: Copying " CUPS_LLFMT
" bytes to wbuffer...\n",
2184 CUPS_LLCAST length
));
2186 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
2187 http
->wused
+= (int)length
;
2188 bytes
= (ssize_t
)length
;
2193 * Otherwise write the data directly...
2196 DEBUG_printf(("httpWrite2: Writing " CUPS_LLFMT
" bytes to socket...\n",
2197 CUPS_LLCAST length
));
2199 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2200 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
2202 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
2204 DEBUG_printf(("httpWrite2: Wrote " CUPS_LLFMT
" bytes...\n",
2205 CUPS_LLCAST bytes
));
2208 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
2209 http
->data_remaining
-= bytes
;
2215 * Handle end-of-request processing...
2218 if ((http
->data_encoding
== HTTP_ENCODE_CHUNKED
&& length
== 0) ||
2219 (http
->data_encoding
== HTTP_ENCODE_LENGTH
&& http
->data_remaining
== 0))
2222 * Finished with the transfer; unless we are sending POST or PUT
2226 DEBUG_puts("httpWrite: changing states...");
2229 httpFlushWrite(http
);
2231 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2234 * Send a 0-length chunk at the end of the request...
2237 http_write(http
, "0\r\n\r\n", 5);
2240 * Reset the data state...
2243 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
2244 http
->data_remaining
= 0;
2247 if (http
->state
== HTTP_POST_RECV
)
2249 else if (http
->state
== HTTP_PUT_RECV
)
2250 http
->state
= HTTP_STATUS
;
2252 http
->state
= HTTP_WAITING
;
2259 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2261 * '_httpWriteCDSA()' - Write function for the CDSA library.
2264 OSStatus
/* O - -1 on error, 0 on success */
2266 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2267 const void *data
, /* I - Data buffer */
2268 size_t *dataLength
) /* IO - Number of bytes */
2270 OSStatus result
; /* Return value */
2271 ssize_t bytes
; /* Number of bytes read */
2272 http_t
*http
; /* HTTP connection */
2275 http
= (http_t
*)connection
;
2279 bytes
= write(http
->fd
, data
, *dataLength
);
2281 while (bytes
== -1 && errno
== EINTR
);
2283 if (bytes
== *dataLength
)
2287 else if (bytes
>= 0)
2289 *dataLength
= bytes
;
2290 result
= errSSLWouldBlock
;
2296 if (errno
== EAGAIN
)
2297 result
= errSSLWouldBlock
;
2299 result
= errSSLClosedAbort
;
2304 #endif /* HAVE_SSL && HAVE_CDSASSL */
2307 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2309 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
2312 ssize_t
/* O - Number of bytes written or -1 on error */
2314 gnutls_transport_ptr ptr
, /* I - Connection to server */
2315 const void *data
, /* I - Data buffer */
2316 size_t length
) /* I - Number of bytes to write */
2318 return (send(((http_t
*)ptr
)->fd
, data
, length
, 0));
2320 #endif /* HAVE_SSL && HAVE_GNUTLS */
2323 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
2325 * 'http_bio_ctrl()' - Control the HTTP connection.
2328 static long /* O - Result/data */
2329 http_bio_ctrl(BIO
*h
, /* I - BIO data */
2330 int cmd
, /* I - Control command */
2331 long arg1
, /* I - First argument */
2332 void *arg2
) /* I - Second argument */
2339 case BIO_CTRL_RESET
:
2343 case BIO_C_SET_FILE_PTR
:
2348 case BIO_C_GET_FILE_PTR
:
2351 *((void **)arg2
) = h
->ptr
;
2358 case BIO_CTRL_FLUSH
:
2365 * 'http_bio_free()' - Free OpenSSL data.
2368 static int /* O - 1 on success, 0 on failure */
2369 http_bio_free(BIO
*h
) /* I - BIO data */
2385 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
2388 static int /* O - 1 on success, 0 on failure */
2389 http_bio_new(BIO
*h
) /* I - BIO data */
2404 * 'http_bio_puts()' - Send a string for OpenSSL.
2407 static int /* O - Bytes written */
2408 http_bio_puts(BIO
*h
, /* I - BIO data */
2409 const char *str
) /* I - String to write */
2412 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
2414 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
2420 * 'http_bio_read()' - Read data for OpenSSL.
2423 static int /* O - Bytes read */
2424 http_bio_read(BIO
*h
, /* I - BIO data */
2425 char *buf
, /* I - Buffer */
2426 int size
) /* I - Number of bytes to read */
2428 http_t
*http
; /* HTTP connection */
2431 http
= (http_t
*)h
->ptr
;
2433 if (!http
->blocking
)
2436 * Make sure we have data before we read...
2439 if (!http_wait(http
, 10000, 0))
2442 http
->error
= WSAETIMEDOUT
;
2444 http
->error
= ETIMEDOUT
;
2451 return (recv(http
->fd
, buf
, size
, 0));
2456 * 'http_bio_write()' - Write data for OpenSSL.
2459 static int /* O - Bytes written */
2460 http_bio_write(BIO
*h
, /* I - BIO data */
2461 const char *buf
, /* I - Buffer to write */
2462 int num
) /* I - Number of bytes to write */
2464 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
2466 #endif /* HAVE_SSL && HAVE_LIBSSL */
2471 * 'http_debug_hex()' - Do a hex dump of a buffer.
2475 http_debug_hex(const char *prefix
, /* I - Prefix for line */
2476 const char *buffer
, /* I - Buffer to dump */
2477 int bytes
) /* I - Bytes to dump */
2479 int i
, j
, /* Looping vars */
2480 ch
; /* Current character */
2481 char line
[255], /* Line buffer */
2482 *start
, /* Start of line after prefix */
2483 *ptr
; /* Pointer into line */
2486 if (_cups_debug_fd
< 0)
2489 DEBUG_printf(("%s: %d bytes:\n", prefix
, bytes
));
2491 snprintf(line
, sizeof(line
), "%s: ", prefix
);
2492 start
= line
+ strlen(line
);
2494 for (i
= 0; i
< bytes
; i
+= 16)
2496 for (j
= 0, ptr
= start
; j
< 16 && (i
+ j
) < bytes
; j
++, ptr
+= 2)
2497 sprintf(ptr
, "%02X", buffer
[i
+ j
] & 255);
2509 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
2511 ch
= buffer
[i
+ j
] & 255;
2513 if (ch
< ' ' || ch
>= 127)
2527 * 'http_field()' - Return the field index for a field name.
2530 static http_field_t
/* O - Field index */
2531 http_field(const char *name
) /* I - String name */
2533 int i
; /* Looping var */
2536 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2537 if (strcasecmp(name
, http_fields
[i
]) == 0)
2538 return ((http_field_t
)i
);
2540 return (HTTP_FIELD_UNKNOWN
);
2546 * 'http_read_ssl()' - Read from a SSL/TLS connection.
2549 static int /* O - Bytes read */
2550 http_read_ssl(http_t
*http
, /* I - Connection to server */
2551 char *buf
, /* I - Buffer to store data */
2552 int len
) /* I - Length of buffer */
2554 # if defined(HAVE_LIBSSL)
2555 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
2557 # elif defined(HAVE_GNUTLS)
2558 return (gnutls_record_recv(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
2560 # elif defined(HAVE_CDSASSL)
2561 int result
; /* Return value */
2562 OSStatus error
; /* Error info */
2563 size_t processed
; /* Number of bytes processed */
2566 error
= SSLRead(((http_tls_t
*)http
->tls
)->session
, buf
, len
, &processed
);
2571 result
= (int)processed
;
2573 case errSSLClosedGraceful
:
2576 case errSSLWouldBlock
:
2578 result
= (int)processed
;
2592 # endif /* HAVE_LIBSSL */
2594 #endif /* HAVE_SSL */
2598 * 'http_send()' - Send a request with all fields and the trailing blank line.
2601 static int /* O - 0 on success, non-zero on error */
2602 http_send(http_t
*http
, /* I - Connection to server */
2603 http_state_t request
, /* I - Request code */
2604 const char *uri
) /* I - URI */
2606 int i
; /* Looping var */
2607 char buf
[1024]; /* Encoded URI buffer */
2608 static const char * const codes
[] =
2609 { /* Request code strings */
2626 DEBUG_printf(("http_send(http=%p, request=HTTP_%s, uri=\"%s\")\n",
2627 http
, codes
[request
], uri
));
2629 if (http
== NULL
|| uri
== NULL
)
2633 * Set the User-Agent field if it isn't already...
2636 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
2637 httpSetField(http
, HTTP_FIELD_USER_AGENT
, CUPS_MINIMAL
);
2640 * Encode the URI as needed...
2643 _httpEncodeURI(buf
, uri
, sizeof(buf
));
2646 * See if we had an error the last time around; if so, reconnect...
2649 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
2650 if (httpReconnect(http
))
2654 * Flush any written data that is pending...
2658 httpFlushWrite(http
);
2661 * Send the request header...
2664 http
->state
= request
;
2665 http
->data_encoding
= HTTP_ENCODE_FIELDS
;
2667 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
2670 http
->status
= HTTP_CONTINUE
;
2673 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
2675 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
2676 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
2678 #endif /* HAVE_SSL */
2680 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
2682 http
->status
= HTTP_ERROR
;
2686 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2687 if (http
->fields
[i
][0] != '\0')
2689 DEBUG_printf(("http_send: %s: %s\n", http_fields
[i
],
2690 httpGetField(http
, i
)));
2692 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
],
2693 httpGetField(http
, i
)) < 1)
2695 http
->status
= HTTP_ERROR
;
2701 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
2703 http
->status
= HTTP_ERROR
;
2707 if (http
->expect
== HTTP_CONTINUE
&&
2708 (http
->state
== HTTP_POST_RECV
|| http
->state
== HTTP_PUT_RECV
))
2709 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
2711 http
->status
= HTTP_ERROR
;
2715 if (httpPrintf(http
, "\r\n") < 1)
2717 http
->status
= HTTP_ERROR
;
2721 httpFlushWrite(http
);
2722 httpGetLength2(http
);
2723 httpClearFields(http
);
2726 * The Kerberos and AuthRef authentication strings can only be used once...
2729 if (http
->field_authorization
&& http
->authstring
&&
2730 (!strncmp(http
->authstring
, "Negotiate", 9) ||
2731 !strncmp(http
->authstring
, "AuthRef", 7)))
2733 http
->_authstring
[0] = '\0';
2735 if (http
->authstring
!= http
->_authstring
)
2736 free(http
->authstring
);
2738 http
->authstring
= http
->_authstring
;
2747 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
2750 static int /* O - Status of connection */
2751 http_setup_ssl(http_t
*http
) /* I - Connection to server */
2754 SSL_CTX
*context
; /* Context for encryption */
2755 SSL
*conn
; /* Connection for encryption */
2756 BIO
*bio
; /* BIO data */
2757 # elif defined(HAVE_GNUTLS)
2758 http_tls_t
*conn
; /* TLS session object */
2759 gnutls_certificate_client_credentials
*credentials
;
2760 /* TLS credentials */
2761 # elif defined(HAVE_CDSASSL)
2762 OSStatus error
; /* Error code */
2763 http_tls_t
*conn
; /* CDSA connection information */
2764 # endif /* HAVE_LIBSSL */
2767 DEBUG_printf(("http_setup_ssl(http=%p)\n", http
));
2770 context
= SSL_CTX_new(SSLv23_client_method());
2772 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
2774 bio
= BIO_new(_httpBIOMethods());
2775 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
2777 conn
= SSL_new(context
);
2778 SSL_set_bio(conn
, bio
, bio
);
2780 if (SSL_connect(conn
) != 1)
2783 unsigned long error
; /* Error code */
2785 while ((error
= ERR_get_error()) != 0)
2786 printf("http_setup_ssl: %s\n", ERR_error_string(error
, NULL
));
2789 SSL_CTX_free(context
);
2793 http
->error
= WSAGetLastError();
2795 http
->error
= errno
;
2797 http
->status
= HTTP_ERROR
;
2799 return (HTTP_ERROR
);
2802 # elif defined(HAVE_GNUTLS)
2803 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
2805 http
->error
= errno
;
2806 http
->status
= HTTP_ERROR
;
2811 credentials
= (gnutls_certificate_client_credentials
*)
2812 malloc(sizeof(gnutls_certificate_client_credentials
));
2813 if (credentials
== NULL
)
2817 http
->error
= errno
;
2818 http
->status
= HTTP_ERROR
;
2823 gnutls_certificate_allocate_credentials(credentials
);
2825 gnutls_init(&(conn
->session
), GNUTLS_CLIENT
);
2826 gnutls_set_default_priority(conn
->session
);
2827 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
2828 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)http
);
2829 gnutls_transport_set_pull_function(conn
->session
, _httpReadGNUTLS
);
2830 gnutls_transport_set_push_function(conn
->session
, _httpWriteGNUTLS
);
2832 if ((gnutls_handshake(conn
->session
)) != GNUTLS_E_SUCCESS
)
2834 http
->error
= errno
;
2835 http
->status
= HTTP_ERROR
;
2840 conn
->credentials
= credentials
;
2842 # elif defined(HAVE_CDSASSL)
2843 conn
= (http_tls_t
*)calloc(1, sizeof(http_tls_t
));
2848 if ((error
= SSLNewContext(false, &conn
->session
)))
2850 http
->error
= error
;
2851 http
->status
= HTTP_ERROR
;
2858 * Use a union to resolve warnings about int/pointer size mismatches...
2861 error
= SSLSetConnection(conn
->session
, http
);
2864 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
2867 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
2870 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
2873 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
2877 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
2883 http
->error
= error
;
2884 http
->status
= HTTP_ERROR
;
2886 SSLDisposeContext(conn
->session
);
2892 # endif /* HAVE_CDSASSL */
2897 #endif /* HAVE_SSL */
2902 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
2906 http_shutdown_ssl(http_t
*http
) /* I - Connection to server */
2909 SSL_CTX
*context
; /* Context for encryption */
2910 SSL
*conn
; /* Connection for encryption */
2913 conn
= (SSL
*)(http
->tls
);
2914 context
= SSL_get_SSL_CTX(conn
);
2917 SSL_CTX_free(context
);
2920 # elif defined(HAVE_GNUTLS)
2921 http_tls_t
*conn
; /* Encryption session */
2922 gnutls_certificate_client_credentials
*credentials
;
2923 /* TLS credentials */
2926 conn
= (http_tls_t
*)(http
->tls
);
2927 credentials
= (gnutls_certificate_client_credentials
*)(conn
->credentials
);
2929 gnutls_bye(conn
->session
, GNUTLS_SHUT_RDWR
);
2930 gnutls_deinit(conn
->session
);
2931 gnutls_certificate_free_credentials(*credentials
);
2935 # elif defined(HAVE_CDSASSL)
2936 http_tls_t
*conn
; /* CDSA connection information */
2939 conn
= (http_tls_t
*)(http
->tls
);
2941 while (SSLClose(conn
->session
) == errSSLWouldBlock
)
2944 SSLDisposeContext(conn
->session
);
2946 if (conn
->certsArray
)
2947 CFRelease(conn
->certsArray
);
2950 # endif /* HAVE_LIBSSL */
2954 #endif /* HAVE_SSL */
2959 * 'http_upgrade()' - Force upgrade to TLS encryption.
2962 static int /* O - Status of connection */
2963 http_upgrade(http_t
*http
) /* I - Connection to server */
2965 int ret
; /* Return value */
2966 http_t myhttp
; /* Local copy of HTTP data */
2969 DEBUG_printf(("http_upgrade(%p)\n", http
));
2972 * Copy the HTTP data to a local variable so we can do the OPTIONS
2973 * request without interfering with the existing request data...
2976 memcpy(&myhttp
, http
, sizeof(myhttp
));
2979 * Send an OPTIONS request to the server, requiring SSL or TLS
2980 * encryption on the link...
2983 http
->field_authorization
= NULL
; /* Don't free the auth string */
2985 httpClearFields(http
);
2986 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
2987 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0, SSL/2.0, SSL/3.0");
2989 if ((ret
= httpOptions(http
, "*")) == 0)
2992 * Wait for the secure connection...
2995 while (httpUpdate(http
) == HTTP_CONTINUE
);
3001 * Restore the HTTP request data...
3004 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
3005 http
->data_encoding
= myhttp
.data_encoding
;
3006 http
->data_remaining
= myhttp
.data_remaining
;
3007 http
->_data_remaining
= myhttp
._data_remaining
;
3008 http
->expect
= myhttp
.expect
;
3009 http
->field_authorization
= myhttp
.field_authorization
;
3010 http
->digest_tries
= myhttp
.digest_tries
;
3013 * See if we actually went secure...
3019 * Server does not support HTTP upgrade...
3022 DEBUG_puts("Server does not support HTTP upgrade!");
3025 closesocket(http
->fd
);
3037 #endif /* HAVE_SSL */
3041 * 'http_wait()' - Wait for data available on a connection.
3044 static int /* O - 1 if data is available, 0 otherwise */
3045 http_wait(http_t
*http
, /* I - Connection to server */
3046 int msec
, /* I - Milliseconds to wait */
3047 int usessl
) /* I - Use SSL context? */
3050 struct pollfd pfd
; /* Polled file descriptor */
3052 fd_set input_set
; /* select() input set */
3053 struct timeval timeout
; /* Timeout */
3054 #endif /* HAVE_POLL */
3055 int nfds
; /* Result from select()/poll() */
3058 DEBUG_printf(("http_wait(http=%p, msec=%d)\n", http
, msec
));
3064 * Check the SSL/TLS buffers for data first...
3068 if (http
->tls
&& usessl
)
3071 if (SSL_pending((SSL
*)(http
->tls
)))
3073 # elif defined(HAVE_GNUTLS)
3074 if (gnutls_record_check_pending(((http_tls_t
*)(http
->tls
))->session
))
3076 # elif defined(HAVE_CDSASSL)
3077 size_t bytes
; /* Bytes that are available */
3079 if (!SSLGetBufferedReadSize(((http_tls_t
*)(http
->tls
))->session
, &bytes
) &&
3082 # endif /* HAVE_LIBSSL */
3084 #endif /* HAVE_SSL */
3087 * Then try doing a select() or poll() to poll the socket...
3092 pfd
.events
= POLLIN
;
3094 while ((nfds
= poll(&pfd
, 1, msec
)) < 0 && errno
== EINTR
);
3099 FD_ZERO(&input_set
);
3100 FD_SET(http
->fd
, &input_set
);
3102 DEBUG_printf(("http_wait: msec=%d, http->fd=%d\n", msec
, http
->fd
));
3106 timeout
.tv_sec
= msec
/ 1000;
3107 timeout
.tv_usec
= (msec
% 1000) * 1000;
3109 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
3112 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
3114 DEBUG_printf(("http_wait: select() returned %d...\n", nfds
));
3117 while (nfds
< 0 && WSAGetLastError() == WSAEINTR
);
3119 while (nfds
< 0 && errno
== EINTR
);
3121 #endif /* HAVE_POLL */
3123 DEBUG_printf(("http_wait: returning with nfds=%d...\n", nfds
));
3130 * 'http_write()' - Write a buffer to a HTTP connection.
3133 static int /* O - Number of bytes written */
3134 http_write(http_t
*http
, /* I - Connection to server */
3135 const char *buffer
, /* I - Buffer for data */
3136 int length
) /* I - Number of bytes to write */
3138 int tbytes
, /* Total bytes sent */
3139 bytes
; /* Bytes sent */
3148 bytes
= http_write_ssl(http
, buffer
, length
);
3150 #endif /* HAVE_SSL */
3151 bytes
= send(http
->fd
, buffer
, length
, 0);
3156 if (WSAGetLastError() != http
->error
)
3158 http
->error
= WSAGetLastError();
3164 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
3166 http
->error
= errno
;
3171 DEBUG_puts("http_write: error writing data...\n");
3182 http_debug_hex("http_write", buffer
- tbytes
, tbytes
);
3190 * 'http_write_chunk()' - Write a chunked buffer.
3193 static int /* O - Number bytes written */
3194 http_write_chunk(http_t
*http
, /* I - Connection to server */
3195 const char *buffer
, /* I - Buffer to write */
3196 int length
) /* I - Length of buffer */
3198 char header
[255]; /* Chunk header */
3199 int bytes
; /* Bytes written */
3201 DEBUG_printf(("http_write_chunk(http=%p, buffer=%p, length=%d)\n",
3202 http
, buffer
, length
));
3205 * Write the chunk header, data, and trailer.
3208 sprintf(header
, "%x\r\n", length
);
3209 if (http_write(http
, header
, (int)strlen(header
)) < 0)
3211 DEBUG_puts(" http_write of length failed!");
3215 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
3217 DEBUG_puts(" http_write of buffer failed!");
3221 if (http_write(http
, "\r\n", 2) < 0)
3223 DEBUG_puts(" http_write of CR LF failed!");
3233 * 'http_write_ssl()' - Write to a SSL/TLS connection.
3236 static int /* O - Bytes written */
3237 http_write_ssl(http_t
*http
, /* I - Connection to server */
3238 const char *buf
, /* I - Buffer holding data */
3239 int len
) /* I - Length of buffer */
3241 # if defined(HAVE_LIBSSL)
3242 return (SSL_write((SSL
*)(http
->tls
), buf
, len
));
3244 # elif defined(HAVE_GNUTLS)
3245 return (gnutls_record_send(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
3246 # elif defined(HAVE_CDSASSL)
3247 int result
; /* Return value */
3248 OSStatus error
; /* Error info */
3249 size_t processed
; /* Number of bytes processed */
3252 error
= SSLWrite(((http_tls_t
*)http
->tls
)->session
, buf
, len
, &processed
);
3257 result
= (int)processed
;
3259 case errSSLClosedGraceful
:
3262 case errSSLWouldBlock
:
3264 result
= (int)processed
;
3278 # endif /* HAVE_LIBSSL */
3280 #endif /* HAVE_SSL */
3284 * End of "$Id: http.c 7850 2008-08-20 00:07:25Z mike $".