2 * "$Id: http.c 6724 2007-07-25 20:39:33Z 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_field() - Return the field index for a field name.
81 * http_read_ssl() - Read from a SSL/TLS connection.
82 * http_send() - Send a request with all fields and the trailing
84 * http_setup_ssl() - Set up SSL/TLS on a connection.
85 * http_shutdown_ssl() - Shut down SSL/TLS on a connection.
86 * http_upgrade() - Force upgrade to TLS encryption.
87 * http_wait() - Wait for data available on a connection.
88 * http_write() - Write data to a connection.
89 * http_write_ssl() - Write to a SSL/TLS connection.
93 * Include necessary headers...
96 #include "http-private.h"
104 # include <sys/time.h>
105 # include <sys/resource.h>
108 # include <sys/poll.h>
109 #endif /* HAVE_POLL */
113 * Some operating systems have done away with the Fxxxx constants for
114 * the fcntl() call; this works around that "feature"...
118 # define FNONBLK O_NONBLOCK
119 #endif /* !FNONBLK */
126 static http_field_t
http_field(const char *name
);
127 static int http_send(http_t
*http
, http_state_t request
,
129 static int http_wait(http_t
*http
, int msec
, int usessl
);
130 static int http_write(http_t
*http
, const char *buffer
,
132 static int http_write_chunk(http_t
*http
, const char *buffer
,
135 static int http_read_ssl(http_t
*http
, char *buf
, int len
);
136 static int http_setup_ssl(http_t
*http
);
137 static void http_shutdown_ssl(http_t
*http
);
138 static int http_upgrade(http_t
*http
);
139 static int http_write_ssl(http_t
*http
, const char *buf
, int len
);
140 #endif /* HAVE_SSL */
147 static const char * const http_fields
[] =
164 "If-Unmodified-since",
179 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
181 * BIO methods for OpenSSL...
184 static int http_bio_write(BIO
*h
, const char *buf
, int num
);
185 static int http_bio_read(BIO
*h
, char *buf
, int size
);
186 static int http_bio_puts(BIO
*h
, const char *str
);
187 static long http_bio_ctrl(BIO
*h
, int cmd
, long arg1
, void *arg2
);
188 static int http_bio_new(BIO
*h
);
189 static int http_bio_free(BIO
*data
);
191 static BIO_METHOD http_bio_methods
=
198 NULL
, /* http_bio_gets, */
207 * '_httpBIOMethods()' - Get the OpenSSL BIO methods for HTTP connections.
210 BIO_METHOD
* /* O - BIO methods for OpenSSL */
211 _httpBIOMethods(void)
213 return (&http_bio_methods
);
215 #endif /* HAVE_SSL && HAVE_LIBSSL */
219 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
223 httpBlocking(http_t
*http
, /* I - Connection to server */
224 int b
) /* I - 1 = blocking, 0 = non-blocking */
232 * 'httpCheck()' - Check to see if there is a pending response from the server.
235 int /* O - 0 = no data, 1 = data available */
236 httpCheck(http_t
*http
) /* I - Connection to server */
238 return (httpWait(http
, 0));
243 * 'httpClearCookie()' - Clear the cookie value(s).
245 * @since CUPS 1.1.19@
249 httpClearCookie(http_t
*http
) /* I - Connection to server */
263 * 'httpClearFields()' - Clear HTTP request fields.
267 httpClearFields(http_t
*http
) /* I - Connection to server */
271 memset(http
->fields
, 0, sizeof(http
->fields
));
272 if (http
->hostname
[0] == '/')
273 httpSetField(http
, HTTP_FIELD_HOST
, "localhost");
275 httpSetField(http
, HTTP_FIELD_HOST
, http
->hostname
);
277 if (http
->field_authorization
)
279 free(http
->field_authorization
);
280 http
->field_authorization
= NULL
;
283 http
->expect
= (http_status_t
)0;
289 * 'httpClose()' - Close an HTTP connection...
293 httpClose(http_t
*http
) /* I - Connection to server */
296 OM_uint32 minor_status
, /* Minor status code */
297 major_status
; /* Major status code */
298 #endif /* HAVE_GSSAPI */
301 DEBUG_printf(("httpClose(http=%p)\n", http
));
306 httpAddrFreeList(http
->addrlist
);
313 http_shutdown_ssl(http
);
314 #endif /* HAVE_SSL */
317 closesocket(http
->fd
);
323 if (http
->gssctx
!= GSS_C_NO_CONTEXT
)
324 major_status
= gss_delete_sec_context(&minor_status
, &http
->gssctx
,
327 if (http
->gssname
!= GSS_C_NO_NAME
)
328 major_status
= gss_release_name(&minor_status
, &http
->gssname
);
329 #endif /* HAVE_GSSAPI */
331 #ifdef HAVE_AUTHORIZATION_H
333 AuthorizationFree(http
->auth_ref
, kAuthorizationFlagDefaults
);
334 #endif /* HAVE_AUTHORIZATION_H */
336 httpClearFields(http
);
338 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
339 free(http
->authstring
);
346 * 'httpConnect()' - Connect to a HTTP server.
349 http_t
* /* O - New HTTP connection */
350 httpConnect(const char *host
, /* I - Host to connect to */
351 int port
) /* I - Port number */
353 http_encryption_t encryption
; /* Type of encryption to use */
357 * Set the default encryption status...
361 encryption
= HTTP_ENCRYPT_ALWAYS
;
363 encryption
= HTTP_ENCRYPT_IF_REQUESTED
;
365 return (httpConnectEncrypt(host
, port
, encryption
));
370 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
373 http_t
* /* O - New HTTP connection */
375 const char *host
, /* I - Host to connect to */
376 int port
, /* I - Port number */
377 http_encryption_t encryption
) /* I - Type of encryption to use */
379 http_t
*http
; /* New HTTP connection */
380 http_addrlist_t
*addrlist
; /* Host address data */
381 char service
[255]; /* Service name */
384 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)\n",
385 host
? host
: "(null)", port
, encryption
));
396 sprintf(service
, "%d", port
);
398 if ((addrlist
= httpAddrGetList(host
, AF_UNSPEC
, service
)) == NULL
)
402 * Allocate memory for the structure...
405 if ((http
= calloc(sizeof(http_t
), 1)) == NULL
)
407 httpAddrFreeList(addrlist
);
411 http
->version
= HTTP_1_1
;
413 http
->activity
= time(NULL
);
417 http
->gssctx
= GSS_C_NO_CONTEXT
;
418 http
->gssname
= GSS_C_NO_NAME
;
419 #endif /* HAVE_GSSAPI */
422 * Set the encryption status...
425 if (port
== 443) /* Always use encryption for https */
426 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
428 http
->encryption
= encryption
;
431 * Loop through the addresses we have until one of them connects...
434 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
437 * Connect to the remote system...
440 http
->addrlist
= addrlist
;
442 if (!httpReconnect(http
))
446 * Could not connect to any known address - bail out!
449 httpAddrFreeList(addrlist
);
458 * 'httpDelete()' - Send a DELETE request to the server.
461 int /* O - Status of call (0 = success) */
462 httpDelete(http_t
*http
, /* I - Connection to server */
463 const char *uri
) /* I - URI to delete */
465 return (http_send(http
, HTTP_DELETE
, uri
));
470 * 'httpEncryption()' - Set the required encryption on the link.
473 int /* O - -1 on error, 0 on success */
474 httpEncryption(http_t
*http
, /* I - Connection to server */
475 http_encryption_t e
) /* I - New encryption preference */
477 DEBUG_printf(("httpEncryption(http=%p, e=%d)\n", http
, e
));
483 http
->encryption
= e
;
485 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
486 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
487 return (httpReconnect(http
));
488 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
489 return (http_upgrade(http
));
493 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
497 #endif /* HAVE_SSL */
502 * 'httpError()' - Get the last error on a connection.
505 int /* O - Error code (errno) value */
506 httpError(http_t
*http
) /* I - Connection to server */
509 return (http
->error
);
516 * 'httpFlush()' - Flush data from a HTTP connection.
520 httpFlush(http_t
*http
) /* I - Connection to server */
522 char buffer
[8192]; /* Junk buffer */
523 int blocking
; /* To block or not to block */
526 DEBUG_printf(("httpFlush(http=%p), state=%d\n", http
, http
->state
));
529 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
532 blocking
= http
->blocking
;
536 * Read any data we can...
539 while (httpRead2(http
, buffer
, sizeof(buffer
)) > 0);
542 * Restore blocking and reset the connection if we didn't get all of
543 * the remaining data...
546 http
->blocking
= blocking
;
548 if (http
->state
!= HTTP_WAITING
&& http
->fd
>= 0)
551 * Didn't get the data back, so close the current connection.
554 http
->state
= HTTP_WAITING
;
558 http_shutdown_ssl(http
);
559 #endif /* HAVE_SSL */
562 closesocket(http
->fd
);
573 * 'httpFlushWrite()' - Flush data in write buffer.
578 int /* O - Bytes written or -1 on error */
579 httpFlushWrite(http_t
*http
) /* I - Connection to server */
581 int bytes
; /* Bytes written */
584 DEBUG_printf(("httpFlushWrite(http=%p)\n", http
));
586 if (!http
|| !http
->wused
)
589 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
590 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
592 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
601 * 'httpGet()' - Send a GET request to the server.
604 int /* O - Status of call (0 = success) */
605 httpGet(http_t
*http
, /* I - Connection to server */
606 const char *uri
) /* I - URI to get */
608 return (http_send(http
, HTTP_GET
, uri
));
613 * 'httpGetAuthString()' - Get the current authorization string.
615 * The authorization string is set by cupsDoAuthentication() and
616 * httpSetAuthString(). Use httpGetAuthString() to retrieve the
617 * string to use with httpSetField() for the HTTP_FIELD_AUTHORIZATION
623 char * /* O - Authorization string */
624 httpGetAuthString(http_t
*http
) /* I - Connection to server */
627 return (http
->authstring
);
634 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
639 int /* O - 1 if blocking, 0 if non-blocking */
640 httpGetBlocking(http_t
*http
) /* I - Connection to server */
642 return (http
? http
->blocking
: 0);
647 * 'httpGetCookie()' - Get any cookie data from the response.
649 * @since CUPS 1.1.19@
652 const char * /* O - Cookie data or NULL */
653 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
655 return (http
? http
->cookie
: NULL
);
660 * 'httpGetFd()' - Get the file descriptor associated with a connection.
665 int /* O - File descriptor or -1 if none */
666 httpGetFd(http_t
*http
) /* I - Connection to server */
668 return (http
? http
->fd
: -1);
673 * 'httpGetField()' - Get a field value from a request/response.
676 const char * /* O - Field value */
677 httpGetField(http_t
*http
, /* I - Connection to server */
678 http_field_t field
) /* I - Field to get */
680 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
682 else if (field
== HTTP_FIELD_AUTHORIZATION
&&
683 http
->field_authorization
)
686 * Special case for WWW-Authenticate: as its contents can be
687 * longer than HTTP_MAX_VALUE...
690 return (http
->field_authorization
);
693 return (http
->fields
[field
]);
698 * 'httpGetLength()' - Get the amount of data remaining from the
699 * content-length or transfer-encoding fields.
701 * This function is deprecated and will not return lengths larger than
702 * 2^31 - 1; use httpGetLength2() instead.
707 int /* O - Content length */
708 httpGetLength(http_t
*http
) /* I - Connection to server */
711 * Get the read content length and return the 32-bit value.
716 httpGetLength2(http
);
718 return (http
->_data_remaining
);
726 * 'httpGetLength2()' - Get the amount of data remaining from the
727 * content-length or transfer-encoding fields.
729 * This function returns the complete content length, even for
730 * content larger than 2^31 - 1.
735 off_t
/* O - Content length */
736 httpGetLength2(http_t
*http
) /* I - Connection to server */
738 DEBUG_printf(("httpGetLength2(http=%p), state=%d\n", http
, http
->state
));
743 if (!strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
745 DEBUG_puts("httpGetLength2: chunked request!");
747 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
748 http
->data_remaining
= 0;
752 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
755 * The following is a hack for HTTP servers that don't send a
756 * content-length or transfer-encoding field...
758 * If there is no content-length then the connection must close
759 * after the transfer is complete...
762 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
765 * Default content length is 0 for errors and 2^31-1 for other
766 * successful requests...
769 if (http
->status
>= HTTP_MULTIPLE_CHOICES
)
770 http
->data_remaining
= 0;
772 http
->data_remaining
= 2147483647;
775 http
->data_remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
778 DEBUG_printf(("httpGetLength2: content_length=" CUPS_LLFMT
"\n",
779 CUPS_LLCAST http
->data_remaining
));
782 if (http
->data_remaining
<= INT_MAX
)
783 http
->_data_remaining
= (int)http
->data_remaining
;
785 http
->_data_remaining
= INT_MAX
;
787 return (http
->data_remaining
);
792 * 'httpGetStatus()' - Get the status of the last HTTP request.
797 http_status_t
/* O - HTTP status */
798 httpGetStatus(http_t
*http
) /* I - Connection to server */
800 return (http
? http
->status
: HTTP_ERROR
);
805 * 'httpGetSubField()' - Get a sub-field value.
810 char * /* O - Value or NULL */
811 httpGetSubField(http_t
*http
, /* I - Connection to server */
812 http_field_t field
, /* I - Field index */
813 const char *name
, /* I - Name of sub-field */
814 char *value
) /* O - Value string */
816 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
821 * 'httpGetSubField2()' - Get a sub-field value.
826 char * /* O - Value or NULL */
827 httpGetSubField2(http_t
*http
, /* I - Connection to server */
828 http_field_t field
, /* I - Field index */
829 const char *name
, /* I - Name of sub-field */
830 char *value
, /* O - Value string */
831 int valuelen
) /* I - Size of value buffer */
833 const char *fptr
; /* Pointer into field */
834 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
835 *ptr
, /* Pointer into string buffer */
836 *end
; /* End of value buffer */
838 DEBUG_printf(("httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, valuelen=%d)\n",
839 http
, field
, name
, value
, valuelen
));
841 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
842 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
845 end
= value
+ valuelen
- 1;
847 for (fptr
= http
->fields
[field
]; *fptr
;)
850 * Skip leading whitespace...
853 while (isspace(*fptr
& 255))
863 * Get the sub-field name...
867 *fptr
&& *fptr
!= '=' && !isspace(*fptr
& 255) &&
868 ptr
< (temp
+ sizeof(temp
) - 1);
873 DEBUG_printf(("httpGetSubField: name=\"%s\"\n", temp
));
876 * Skip trailing chars up to the '='...
879 while (isspace(*fptr
& 255))
889 * Skip = and leading whitespace...
894 while (isspace(*fptr
& 255))
900 * Read quoted string...
903 for (ptr
= value
, fptr
++;
904 *fptr
&& *fptr
!= '\"' && ptr
< end
;
909 while (*fptr
&& *fptr
!= '\"')
918 * Read unquoted string...
922 *fptr
&& !isspace(*fptr
& 255) && *fptr
!= ',' && ptr
< end
;
927 while (*fptr
&& !isspace(*fptr
& 255) && *fptr
!= ',')
931 DEBUG_printf(("httpGetSubField: value=\"%s\"\n", value
));
934 * See if this is the one...
937 if (!strcmp(name
, temp
))
948 * 'httpGets()' - Get a line of text from a HTTP connection.
951 char * /* O - Line or NULL */
952 httpGets(char *line
, /* I - Line to read into */
953 int length
, /* I - Max length of buffer */
954 http_t
*http
) /* I - Connection to server */
956 char *lineptr
, /* Pointer into line */
957 *lineend
, /* End of line */
958 *bufptr
, /* Pointer into input buffer */
959 *bufend
; /* Pointer to end of buffer */
960 int bytes
, /* Number of bytes read */
961 eol
; /* End-of-line? */
964 DEBUG_printf(("httpGets(line=%p, length=%d, http=%p)\n", line
, length
, http
));
966 if (http
== NULL
|| line
== NULL
)
970 * Read a line from the buffer...
974 lineend
= line
+ length
- 1;
977 while (lineptr
< lineend
)
980 * Pre-load the buffer as needed...
989 while (http
->used
== 0)
992 * No newline; see if there is more data to be read...
995 if (!http
->blocking
&& !http_wait(http
, 10000, 1))
997 DEBUG_puts("httpGets: Timed out!");
999 http
->error
= WSAETIMEDOUT
;
1001 http
->error
= ETIMEDOUT
;
1008 bytes
= http_read_ssl(http
, http
->buffer
+ http
->used
,
1009 HTTP_MAX_BUFFER
- http
->used
);
1011 #endif /* HAVE_SSL */
1012 bytes
= recv(http
->fd
, http
->buffer
+ http
->used
,
1013 HTTP_MAX_BUFFER
- http
->used
, 0);
1015 DEBUG_printf(("httpGets: read %d bytes...\n", bytes
));
1020 * Nope, can't get a line this time...
1024 if (WSAGetLastError() != http
->error
)
1026 http
->error
= WSAGetLastError();
1030 DEBUG_printf(("httpGets: recv() error %d!\n", WSAGetLastError()));
1032 DEBUG_printf(("httpGets: recv() error %d!\n", errno
));
1036 else if (errno
!= http
->error
)
1038 http
->error
= errno
;
1045 else if (bytes
== 0)
1047 http
->error
= EPIPE
;
1053 * Yup, update the amount used...
1056 http
->used
+= bytes
;
1060 * Now copy as much of the current line as possible...
1063 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1064 lineptr
< lineend
&& bufptr
< bufend
;)
1066 if (*bufptr
== 0x0a)
1072 else if (*bufptr
== 0x0d)
1075 *lineptr
++ = *bufptr
++;
1078 http
->used
-= (int)(bufptr
- http
->buffer
);
1080 memmove(http
->buffer
, bufptr
, http
->used
);
1088 http
->activity
= time(NULL
);
1092 DEBUG_printf(("httpGets: Returning \"%s\"\n", line
));
1098 DEBUG_puts("httpGets: No new line available!");
1105 * 'httpHead()' - Send a HEAD request to the server.
1108 int /* O - Status of call (0 = success) */
1109 httpHead(http_t
*http
, /* I - Connection to server */
1110 const char *uri
) /* I - URI for head */
1112 return (http_send(http
, HTTP_HEAD
, uri
));
1117 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1118 * default HTTP proxy (if any).
1122 httpInitialize(void)
1126 struct timeval curtime
; /* Current time in microseconds */
1127 # endif /* !WIN32 */
1128 int i
; /* Looping var */
1129 unsigned char data
[1024]; /* Seed data */
1130 #endif /* HAVE_LIBSSL */
1133 WSADATA winsockdata
; /* WinSock data */
1134 static int initialized
= 0; /* Has WinSock been initialized? */
1138 WSAStartup(MAKEWORD(1,1), &winsockdata
);
1139 #elif !defined(SO_NOSIGPIPE)
1141 * Ignore SIGPIPE signals...
1145 sigset(SIGPIPE
, SIG_IGN
);
1146 # elif defined(HAVE_SIGACTION)
1147 struct sigaction action
; /* POSIX sigaction data */
1150 memset(&action
, 0, sizeof(action
));
1151 action
.sa_handler
= SIG_IGN
;
1152 sigaction(SIGPIPE
, &action
, NULL
);
1154 signal(SIGPIPE
, SIG_IGN
);
1155 # endif /* !SO_NOSIGPIPE */
1159 gnutls_global_init();
1160 #endif /* HAVE_GNUTLS */
1163 SSL_load_error_strings();
1167 * Using the current time is a dubious random seed, but on some systems
1168 * it is the best we can do (on others, this seed isn't even used...)
1173 gettimeofday(&curtime
, NULL
);
1174 srand(curtime
.tv_sec
+ curtime
.tv_usec
);
1177 for (i
= 0; i
< sizeof(data
); i
++)
1178 data
[i
] = rand(); /* Yes, this is a poor source of random data... */
1180 RAND_seed(&data
, sizeof(data
));
1181 #endif /* HAVE_LIBSSL */
1186 * 'httpOptions()' - Send an OPTIONS request to the server.
1189 int /* O - Status of call (0 = success) */
1190 httpOptions(http_t
*http
, /* I - Connection to server */
1191 const char *uri
) /* I - URI for options */
1193 return (http_send(http
, HTTP_OPTIONS
, uri
));
1198 * 'httpPost()' - Send a POST request to the server.
1201 int /* O - Status of call (0 = success) */
1202 httpPost(http_t
*http
, /* I - Connection to server */
1203 const char *uri
) /* I - URI for post */
1205 return (http_send(http
, HTTP_POST
, uri
));
1210 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1215 int /* O - Number of bytes written */
1216 httpPrintf(http_t
*http
, /* I - Connection to server */
1217 const char *format
, /* I - printf-style format string */
1218 ...) /* I - Additional args as needed */
1220 int bytes
; /* Number of bytes to write */
1221 char buf
[16384]; /* Buffer for formatted string */
1222 va_list ap
; /* Variable argument pointer */
1225 DEBUG_printf(("httpPrintf(http=%p, format=\"%s\", ...)\n", http
, format
));
1227 va_start(ap
, format
);
1228 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1231 DEBUG_printf(("httpPrintf: %s", buf
));
1233 if (http
->data_encoding
== HTTP_ENCODE_FIELDS
)
1234 return (httpWrite2(http
, buf
, bytes
));
1239 DEBUG_puts(" flushing existing data...");
1241 if (httpFlushWrite(http
) < 0)
1245 return (http_write(http
, buf
, bytes
));
1251 * 'httpPut()' - Send a PUT request to the server.
1254 int /* O - Status of call (0 = success) */
1255 httpPut(http_t
*http
, /* I - Connection to server */
1256 const char *uri
) /* I - URI to put */
1258 return (http_send(http
, HTTP_PUT
, uri
));
1263 * 'httpRead()' - Read data from a HTTP connection.
1265 * This function is deprecated. Use the httpRead2() function which can
1266 * read more than 2GB of data.
1271 int /* O - Number of bytes read */
1272 httpRead(http_t
*http
, /* I - Connection to server */
1273 char *buffer
, /* I - Buffer for data */
1274 int length
) /* I - Maximum number of bytes */
1276 return ((int)httpRead2(http
, buffer
, length
));
1281 * 'httpRead2()' - Read data from a HTTP connection.
1286 ssize_t
/* O - Number of bytes read */
1287 httpRead2(http_t
*http
, /* I - Connection to server */
1288 char *buffer
, /* I - Buffer for data */
1289 size_t length
) /* I - Maximum number of bytes */
1291 ssize_t bytes
; /* Bytes read */
1292 char len
[32]; /* Length string */
1295 DEBUG_printf(("httpRead(http=%p, buffer=%p, length=" CUPS_LLFMT
")\n",
1296 http
, buffer
, CUPS_LLCAST length
));
1298 if (http
== NULL
|| buffer
== NULL
)
1301 http
->activity
= time(NULL
);
1306 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1307 http
->data_remaining
<= 0)
1309 DEBUG_puts("httpRead2: Getting chunk length...");
1311 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1313 DEBUG_puts("httpRead2: Could not get length!");
1317 http
->data_remaining
= strtoll(len
, NULL
, 16);
1318 if (http
->data_remaining
< 0)
1320 DEBUG_puts("httpRead2: Negative chunk length!");
1325 DEBUG_printf(("httpRead2: data_remaining=" CUPS_LLFMT
"\n",
1326 CUPS_LLCAST http
->data_remaining
));
1328 if (http
->data_remaining
<= 0)
1331 * A zero-length chunk ends a transfer; unless we are reading POST
1335 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1336 httpGets(len
, sizeof(len
), http
);
1338 if (http
->state
== HTTP_POST_RECV
)
1341 http
->state
= HTTP_WAITING
;
1344 * Prevent future reads for this request...
1347 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1351 else if (length
> (size_t)http
->data_remaining
)
1352 length
= (size_t)http
->data_remaining
;
1354 if (http
->used
== 0 && length
<= 256)
1357 * Buffer small reads for better performance...
1360 if (!http
->blocking
&& !httpWait(http
, 10000))
1363 if (http
->data_remaining
> sizeof(http
->buffer
))
1364 bytes
= sizeof(http
->buffer
);
1366 bytes
= http
->data_remaining
;
1370 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1372 #endif /* HAVE_SSL */
1374 DEBUG_printf(("httpRead2: reading %d bytes from socket into buffer...\n",
1377 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1379 DEBUG_printf(("httpRead2: read %d bytes from socket into buffer...\n",
1388 http
->error
= WSAGetLastError();
1393 http
->error
= errno
;
1400 http
->error
= EPIPE
;
1407 if (length
> (size_t)http
->used
)
1408 length
= (size_t)http
->used
;
1410 bytes
= (ssize_t
)length
;
1412 DEBUG_printf(("httpRead2: grabbing %d bytes from input buffer...\n",
1415 memcpy(buffer
, http
->buffer
, length
);
1416 http
->used
-= (int)length
;
1419 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
1424 if (!http
->blocking
&& !httpWait(http
, 10000))
1427 bytes
= (ssize_t
)http_read_ssl(http
, buffer
, (int)length
);
1429 #endif /* HAVE_SSL */
1432 if (!http
->blocking
&& !httpWait(http
, 10000))
1435 DEBUG_printf(("httpRead2: reading " CUPS_LLFMT
" bytes from socket...\n",
1436 CUPS_LLCAST length
));
1439 bytes
= (ssize_t
)recv(http
->fd
, buffer
, (int)length
, 0);
1441 while ((bytes
= recv(http
->fd
, buffer
, length
, 0)) < 0)
1446 DEBUG_printf(("httpRead2: read " CUPS_LLFMT
" bytes from socket...\n",
1447 CUPS_LLCAST bytes
));
1452 http
->data_remaining
-= bytes
;
1454 if (http
->data_remaining
<= INT_MAX
)
1455 http
->_data_remaining
= (int)http
->data_remaining
;
1457 http
->_data_remaining
= INT_MAX
;
1462 http
->error
= WSAGetLastError();
1467 http
->error
= errno
;
1472 http
->error
= EPIPE
;
1476 if (http
->data_remaining
== 0)
1478 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1479 httpGets(len
, sizeof(len
), http
);
1481 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
1483 if (http
->state
== HTTP_POST_RECV
)
1486 http
->state
= HTTP_WAITING
;
1493 printf("httpRead2: Read " CUPS_LLFMT
" bytes:\n", CUPS_LLCAST bytes
);
1494 for (i
= 0; i
< bytes
; i
+= 16)
1498 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1499 printf(" %02X", buffer
[i
+ j
] & 255);
1508 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1510 ch
= buffer
[i
+ j
] & 255;
1512 if (ch
< ' ' || ch
>= 127)
1526 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
1528 * '_httpReadCDSA()' - Read function for the CDSA library.
1531 OSStatus
/* O - -1 on error, 0 on success */
1533 SSLConnectionRef connection
, /* I - SSL/TLS connection */
1534 void *data
, /* I - Data buffer */
1535 size_t *dataLength
) /* IO - Number of bytes */
1537 OSStatus result
; /* Return value */
1538 ssize_t bytes
; /* Number of bytes read */
1539 http_t
*http
; /* HTTP connection */
1542 http
= (http_t
*)connection
;
1544 if (!http
->blocking
)
1547 * Make sure we have data before we read...
1550 if (!http_wait(http
, 10000, 0))
1552 http
->error
= ETIMEDOUT
;
1559 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
1561 while (bytes
== -1 && errno
== EINTR
);
1563 if (bytes
== *dataLength
)
1569 *dataLength
= bytes
;
1570 result
= errSSLWouldBlock
;
1577 result
= errSSLClosedGraceful
;
1578 else if (errno
== EAGAIN
)
1579 result
= errSSLWouldBlock
;
1581 result
= errSSLClosedAbort
;
1586 #endif /* HAVE_SSL && HAVE_CDSASSL */
1589 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
1591 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
1594 ssize_t
/* O - Number of bytes read or -1 on error */
1596 gnutls_transport_ptr ptr
, /* I - Connection to server */
1597 void *data
, /* I - Buffer */
1598 size_t length
) /* I - Number of bytes to read */
1600 http_t
*http
; /* HTTP connection */
1603 http
= (http_t
*)ptr
;
1605 if (!http
->blocking
)
1608 * Make sure we have data before we read...
1611 if (!http_wait(http
, 10000, 0))
1613 http
->error
= ETIMEDOUT
;
1618 return (recv(http
->fd
, data
, length
, 0));
1620 #endif /* HAVE_SSL && HAVE_GNUTLS */
1624 * 'httpReconnect()' - Reconnect to a HTTP server.
1627 int /* O - 0 on success, non-zero on failure */
1628 httpReconnect(http_t
*http
) /* I - Connection to server */
1630 http_addrlist_t
*addr
; /* Connected address */
1633 DEBUG_printf(("httpReconnect(http=%p)\n", http
));
1640 http_shutdown_ssl(http
);
1641 #endif /* HAVE_SSL */
1644 * Close any previously open socket...
1650 closesocket(http
->fd
);
1659 * Connect to the server...
1662 if ((addr
= httpAddrConnect(http
->addrlist
, &(http
->fd
))) == NULL
)
1665 * Unable to connect...
1669 http
->error
= WSAGetLastError();
1671 http
->error
= errno
;
1673 http
->status
= HTTP_ERROR
;
1678 http
->hostaddr
= &(addr
->addr
);
1680 http
->status
= HTTP_CONTINUE
;
1683 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
1686 * Always do encryption via SSL.
1689 if (http_setup_ssl(http
) != 0)
1692 closesocket(http
->fd
);
1700 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
1701 return (http_upgrade(http
));
1702 #endif /* HAVE_SSL */
1709 * 'httpSetAuthString()' - Set the current authorization string.
1711 * This function just stores a copy of the current authorization string in
1712 * the HTTP connection object. You must still call httpSetField() to set
1713 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
1714 * httpHead(), httpOptions(), httpPost, or httpPut().
1720 httpSetAuthString(http_t
*http
, /* I - Connection to server */
1721 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
1722 const char *data
) /* I - Auth data (NULL for none) */
1725 * Range check input...
1731 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
1732 free(http
->authstring
);
1734 http
->authstring
= http
->_authstring
;
1739 * Set the current authorization string...
1742 int len
= (int)strlen(scheme
) + (data
? (int)strlen(data
) + 1 : 0) + 1;
1745 if (len
> (int)sizeof(http
->_authstring
))
1747 if ((temp
= malloc(len
)) == NULL
)
1748 len
= sizeof(http
->_authstring
);
1750 http
->authstring
= temp
;
1754 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
1756 strlcpy(http
->authstring
, scheme
, len
);
1761 * Clear the current authorization string...
1764 http
->_authstring
[0] = '\0';
1770 * 'httpSetCookie()' - Set the cookie value(s)...
1772 * @since CUPS 1.1.19@
1776 httpSetCookie(http_t
*http
, /* I - Connection */
1777 const char *cookie
) /* I - Cookie string */
1786 http
->cookie
= strdup(cookie
);
1788 http
->cookie
= NULL
;
1793 * 'httpSetExpect()' - Set the Expect: header in a request.
1795 * Currently only HTTP_CONTINUE is supported for the "expect" argument.
1801 httpSetExpect(http_t
*http
, /* I - Connection to server */
1802 http_status_t expect
) /* I - HTTP status to expect (HTTP_CONTINUE) */
1805 http
->expect
= expect
;
1810 * 'httpSetField()' - Set the value of an HTTP header.
1814 httpSetField(http_t
*http
, /* I - Connection to server */
1815 http_field_t field
, /* I - Field index */
1816 const char *value
) /* I - Value */
1819 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
1820 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
1824 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
1827 * Special case for Authorization: as its contents can be
1828 * longer than HTTP_MAX_VALUE
1831 if (field
== HTTP_FIELD_AUTHORIZATION
)
1833 if (http
->field_authorization
)
1834 free(http
->field_authorization
);
1836 http
->field_authorization
= strdup(value
);
1842 * 'httpSetLength()' - Set the content-length and content-encoding.
1848 httpSetLength(http_t
*http
, /* I - Connection to server */
1849 size_t length
) /* I - Length (0 for chunked) */
1856 strcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked");
1857 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
1861 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
1862 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
1863 CUPS_LLFMT
, CUPS_LLCAST length
);
1869 * 'httpTrace()' - Send an TRACE request to the server.
1872 int /* O - Status of call (0 = success) */
1873 httpTrace(http_t
*http
, /* I - Connection to server */
1874 const char *uri
) /* I - URI for trace */
1876 return (http_send(http
, HTTP_TRACE
, uri
));
1881 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1884 http_status_t
/* O - HTTP status */
1885 httpUpdate(http_t
*http
) /* I - Connection to server */
1887 char line
[32768], /* Line from connection... */
1888 *value
; /* Pointer to value on line */
1889 http_field_t field
; /* Field index */
1890 int major
, minor
, /* HTTP version numbers */
1891 status
; /* Request status */
1894 DEBUG_printf(("httpUpdate(http=%p), state=%d\n", http
, http
->state
));
1897 * Flush pending data, if any...
1902 DEBUG_puts(" flushing buffer...");
1904 if (httpFlushWrite(http
) < 0)
1905 return (HTTP_ERROR
);
1909 * If we haven't issued any commands, then there is nothing to "update"...
1912 if (http
->state
== HTTP_WAITING
)
1913 return (HTTP_CONTINUE
);
1916 * Grab all of the lines we can from the connection...
1919 while (httpGets(line
, sizeof(line
), http
) != NULL
)
1921 DEBUG_printf(("httpUpdate: Got \"%s\"\n", line
));
1923 if (line
[0] == '\0')
1926 * Blank line means the start of the data section (if any). Return
1927 * the result code, too...
1929 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
1930 * Instead, we just return HTTP_CONTINUE to the caller and keep on
1934 if (http
->status
== HTTP_CONTINUE
)
1935 return (http
->status
);
1937 if (http
->status
< HTTP_BAD_REQUEST
)
1938 http
->digest_tries
= 0;
1941 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
1943 if (http_setup_ssl(http
) != 0)
1946 closesocket(http
->fd
);
1951 return (HTTP_ERROR
);
1954 return (HTTP_CONTINUE
);
1956 #endif /* HAVE_SSL */
1958 httpGetLength2(http
);
1960 switch (http
->state
)
1964 case HTTP_POST_RECV
:
1967 case HTTP_POST_SEND
:
1972 http
->state
= HTTP_WAITING
;
1976 return (http
->status
);
1978 else if (strncmp(line
, "HTTP/", 5) == 0)
1981 * Got the beginning of a response...
1984 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &status
) != 3)
1985 return (HTTP_ERROR
);
1987 http
->version
= (http_version_t
)(major
* 100 + minor
);
1988 http
->status
= (http_status_t
)status
;
1990 else if ((value
= strchr(line
, ':')) != NULL
)
1997 while (isspace(*value
& 255))
2001 * Be tolerants of servers that send unknown attribute fields...
2004 if (!strcasecmp(line
, "expect"))
2007 * "Expect: 100-continue" or similar...
2010 http
->expect
= (http_status_t
)atoi(value
);
2012 else if (!strcasecmp(line
, "cookie"))
2015 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
2018 httpSetCookie(http
, value
);
2020 else if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
2022 DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line
));
2026 httpSetField(http
, field
, value
);
2030 http
->status
= HTTP_ERROR
;
2031 return (HTTP_ERROR
);
2036 * See if there was an error...
2039 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
2040 return (http
->status
);
2044 DEBUG_printf(("httpUpdate: socket error %d - %s\n", http
->error
,
2045 strerror(http
->error
)));
2046 http
->status
= HTTP_ERROR
;
2047 return (HTTP_ERROR
);
2051 * If we haven't already returned, then there is nothing new...
2054 return (HTTP_CONTINUE
);
2059 * 'httpWait()' - Wait for data available on a connection.
2061 * @since CUPS 1.1.19@
2064 int /* O - 1 if data is available, 0 otherwise */
2065 httpWait(http_t
*http
, /* I - Connection to server */
2066 int msec
) /* I - Milliseconds to wait */
2069 * First see if there is data in the buffer...
2079 * Flush pending data, if any...
2084 if (httpFlushWrite(http
) < 0)
2089 * If not, check the SSL/TLS buffers and do a select() on the connection...
2092 return (http_wait(http
, msec
, 1));
2097 * 'httpWrite()' - Write data to a HTTP connection.
2099 * This function is deprecated. Use the httpWrite2() function which can
2100 * write more than 2GB of data.
2105 int /* O - Number of bytes written */
2106 httpWrite(http_t
*http
, /* I - Connection to server */
2107 const char *buffer
, /* I - Buffer for data */
2108 int length
) /* I - Number of bytes to write */
2110 return ((int)httpWrite2(http
, buffer
, length
));
2115 * 'httpWrite2()' - Write data to a HTTP connection.
2120 ssize_t
/* O - Number of bytes written */
2121 httpWrite2(http_t
*http
, /* I - Connection to server */
2122 const char *buffer
, /* I - Buffer for data */
2123 size_t length
) /* I - Number of bytes to write */
2125 ssize_t bytes
; /* Bytes written */
2128 DEBUG_printf(("httpWrite(http=%p, buffer=%p, length=" CUPS_LLFMT
")\n", http
,
2129 buffer
, CUPS_LLCAST length
));
2132 * Range check input...
2135 if (http
== NULL
|| buffer
== NULL
)
2139 * Mark activity on the connection...
2142 http
->activity
= time(NULL
);
2145 * Buffer small writes for better performance...
2150 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
2152 DEBUG_printf((" flushing buffer (wused=%d, length=" CUPS_LLFMT
")\n",
2153 http
->wused
, CUPS_LLCAST length
));
2155 httpFlushWrite(http
);
2158 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
))
2161 * Write to buffer...
2164 DEBUG_printf((" copying " CUPS_LLFMT
" bytes to wbuffer...\n",
2165 CUPS_LLCAST length
));
2167 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
2168 http
->wused
+= (int)length
;
2169 bytes
= (ssize_t
)length
;
2174 * Otherwise write the data directly...
2177 DEBUG_printf((" writing " CUPS_LLFMT
" bytes to socket...\n",
2178 CUPS_LLCAST length
));
2180 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2181 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
2183 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
2185 DEBUG_printf((" wrote " CUPS_LLFMT
" bytes...\n", CUPS_LLCAST bytes
));
2188 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
2189 http
->data_remaining
-= bytes
;
2195 * Handle end-of-request processing...
2198 if ((http
->data_encoding
== HTTP_ENCODE_CHUNKED
&& length
== 0) ||
2199 (http
->data_encoding
== HTTP_ENCODE_LENGTH
&& http
->data_remaining
== 0))
2202 * Finished with the transfer; unless we are sending POST or PUT
2206 DEBUG_puts("httpWrite: changing states...");
2209 httpFlushWrite(http
);
2211 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2214 * Send a 0-length chunk at the end of the request...
2217 http_write(http
, "0\r\n\r\n", 5);
2220 * Reset the data state...
2223 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
2224 http
->data_remaining
= 0;
2227 if (http
->state
== HTTP_POST_RECV
)
2229 else if (http
->state
== HTTP_PUT_RECV
)
2230 http
->state
= HTTP_STATUS
;
2232 http
->state
= HTTP_WAITING
;
2239 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2241 * '_httpWriteCDSA()' - Write function for the CDSA library.
2244 OSStatus
/* O - -1 on error, 0 on success */
2246 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2247 const void *data
, /* I - Data buffer */
2248 size_t *dataLength
) /* IO - Number of bytes */
2250 OSStatus result
; /* Return value */
2251 ssize_t bytes
; /* Number of bytes read */
2252 http_t
*http
; /* HTTP connection */
2255 http
= (http_t
*)connection
;
2259 bytes
= write(http
->fd
, data
, *dataLength
);
2261 while (bytes
== -1 && errno
== EINTR
);
2263 if (bytes
== *dataLength
)
2267 else if (bytes
>= 0)
2269 *dataLength
= bytes
;
2270 result
= errSSLWouldBlock
;
2276 if (errno
== EAGAIN
)
2277 result
= errSSLWouldBlock
;
2279 result
= errSSLClosedAbort
;
2284 #endif /* HAVE_SSL && HAVE_CDSASSL */
2287 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2289 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
2292 ssize_t
/* O - Number of bytes written or -1 on error */
2294 gnutls_transport_ptr ptr
, /* I - Connection to server */
2295 const void *data
, /* I - Data buffer */
2296 size_t length
) /* I - Number of bytes to write */
2298 return (send(((http_t
*)ptr
)->fd
, data
, length
, 0));
2300 #endif /* HAVE_SSL && HAVE_GNUTLS */
2303 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
2305 * 'http_bio_ctrl()' - Control the HTTP connection.
2308 static long /* O - Result/data */
2309 http_bio_ctrl(BIO
*h
, /* I - BIO data */
2310 int cmd
, /* I - Control command */
2311 long arg1
, /* I - First argument */
2312 void *arg2
) /* I - Second argument */
2319 case BIO_CTRL_RESET
:
2323 case BIO_C_SET_FILE_PTR
:
2328 case BIO_C_GET_FILE_PTR
:
2331 *((void **)arg2
) = h
->ptr
;
2338 case BIO_CTRL_FLUSH
:
2345 * 'http_bio_free()' - Free OpenSSL data.
2348 static int /* O - 1 on success, 0 on failure */
2349 http_bio_free(BIO
*h
) /* I - BIO data */
2365 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
2368 static int /* O - 1 on success, 0 on failure */
2369 http_bio_new(BIO
*h
) /* I - BIO data */
2384 * 'http_bio_puts()' - Send a string for OpenSSL.
2387 static int /* O - Bytes written */
2388 http_bio_puts(BIO
*h
, /* I - BIO data */
2389 const char *str
) /* I - String to write */
2392 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
2394 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
2400 * 'http_bio_read()' - Read data for OpenSSL.
2403 static int /* O - Bytes read */
2404 http_bio_read(BIO
*h
, /* I - BIO data */
2405 char *buf
, /* I - Buffer */
2406 int size
) /* I - Number of bytes to read */
2408 http_t
*http
; /* HTTP connection */
2411 http
= (http_t
*)h
->ptr
;
2413 if (!http
->blocking
)
2416 * Make sure we have data before we read...
2419 if (!http_wait(http
, 10000, 0))
2422 http
->error
= WSAETIMEDOUT
;
2424 http
->error
= ETIMEDOUT
;
2431 return (recv(http
->fd
, buf
, size
, 0));
2436 * 'http_bio_write()' - Write data for OpenSSL.
2439 static int /* O - Bytes written */
2440 http_bio_write(BIO
*h
, /* I - BIO data */
2441 const char *buf
, /* I - Buffer to write */
2442 int num
) /* I - Number of bytes to write */
2444 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
2446 #endif /* HAVE_SSL && HAVE_LIBSSL */
2450 * 'http_field()' - Return the field index for a field name.
2453 static http_field_t
/* O - Field index */
2454 http_field(const char *name
) /* I - String name */
2456 int i
; /* Looping var */
2459 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2460 if (strcasecmp(name
, http_fields
[i
]) == 0)
2461 return ((http_field_t
)i
);
2463 return (HTTP_FIELD_UNKNOWN
);
2469 * 'http_read_ssl()' - Read from a SSL/TLS connection.
2472 static int /* O - Bytes read */
2473 http_read_ssl(http_t
*http
, /* I - Connection to server */
2474 char *buf
, /* I - Buffer to store data */
2475 int len
) /* I - Length of buffer */
2477 # if defined(HAVE_LIBSSL)
2478 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
2480 # elif defined(HAVE_GNUTLS)
2481 return (gnutls_record_recv(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
2483 # elif defined(HAVE_CDSASSL)
2484 int result
; /* Return value */
2485 OSStatus error
; /* Error info */
2486 size_t processed
; /* Number of bytes processed */
2489 error
= SSLRead(((http_tls_t
*)http
->tls
)->session
, buf
, len
, &processed
);
2494 result
= (int)processed
;
2496 case errSSLClosedGraceful
:
2499 case errSSLWouldBlock
:
2501 result
= (int)processed
;
2515 # endif /* HAVE_LIBSSL */
2517 #endif /* HAVE_SSL */
2521 * 'http_send()' - Send a request with all fields and the trailing blank line.
2524 static int /* O - 0 on success, non-zero on error */
2525 http_send(http_t
*http
, /* I - Connection to server */
2526 http_state_t request
, /* I - Request code */
2527 const char *uri
) /* I - URI */
2529 int i
; /* Looping var */
2530 char buf
[1024]; /* Encoded URI buffer */
2531 static const char * const codes
[] =
2532 { /* Request code strings */
2549 DEBUG_printf(("http_send(http=%p, request=HTTP_%s, uri=\"%s\")\n",
2550 http
, codes
[request
], uri
));
2552 if (http
== NULL
|| uri
== NULL
)
2556 * Set the User-Agent field if it isn't already...
2559 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
2560 httpSetField(http
, HTTP_FIELD_USER_AGENT
, CUPS_MINIMAL
);
2563 * Encode the URI as needed...
2566 _httpEncodeURI(buf
, uri
, sizeof(buf
));
2569 * See if we had an error the last time around; if so, reconnect...
2572 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
2573 if (httpReconnect(http
))
2577 * Flush any written data that is pending...
2581 httpFlushWrite(http
);
2584 * Send the request header...
2587 http
->state
= request
;
2588 http
->data_encoding
= HTTP_ENCODE_FIELDS
;
2590 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
2593 http
->status
= HTTP_CONTINUE
;
2596 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
2598 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
2599 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
2601 #endif /* HAVE_SSL */
2603 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
2605 http
->status
= HTTP_ERROR
;
2609 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2610 if (http
->fields
[i
][0] != '\0')
2612 DEBUG_printf(("%s: %s\n", http_fields
[i
], httpGetField(http
, i
)));
2614 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
],
2615 httpGetField(http
, i
)) < 1)
2617 http
->status
= HTTP_ERROR
;
2623 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
2625 http
->status
= HTTP_ERROR
;
2629 if (http
->expect
== HTTP_CONTINUE
&&
2630 (http
->state
== HTTP_POST_RECV
|| http
->state
== HTTP_PUT_RECV
))
2631 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
2633 http
->status
= HTTP_ERROR
;
2637 if (httpPrintf(http
, "\r\n") < 1)
2639 http
->status
= HTTP_ERROR
;
2643 httpFlushWrite(http
);
2644 httpGetLength2(http
);
2645 httpClearFields(http
);
2648 * The Kerberos and AuthRef authentication strings can only be used once...
2651 if (http
->field_authorization
&& http
->authstring
&&
2652 (!strncmp(http
->authstring
, "Negotiate", 9) ||
2653 !strncmp(http
->authstring
, "AuthRef", 7)))
2655 http
->_authstring
[0] = '\0';
2657 if (http
->authstring
!= http
->_authstring
)
2658 free(http
->authstring
);
2660 http
->authstring
= http
->_authstring
;
2669 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
2672 static int /* O - Status of connection */
2673 http_setup_ssl(http_t
*http
) /* I - Connection to server */
2676 SSL_CTX
*context
; /* Context for encryption */
2677 SSL
*conn
; /* Connection for encryption */
2678 BIO
*bio
; /* BIO data */
2679 # elif defined(HAVE_GNUTLS)
2680 http_tls_t
*conn
; /* TLS session object */
2681 gnutls_certificate_client_credentials
*credentials
;
2682 /* TLS credentials */
2683 # elif defined(HAVE_CDSASSL)
2684 OSStatus error
; /* Error code */
2685 http_tls_t
*conn
; /* CDSA connection information */
2686 # endif /* HAVE_LIBSSL */
2689 DEBUG_printf(("http_setup_ssl(http=%p)\n", http
));
2692 context
= SSL_CTX_new(SSLv23_client_method());
2694 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
2696 bio
= BIO_new(_httpBIOMethods());
2697 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
2699 conn
= SSL_new(context
);
2700 SSL_set_bio(conn
, bio
, bio
);
2702 if (SSL_connect(conn
) != 1)
2705 unsigned long error
; /* Error code */
2707 while ((error
= ERR_get_error()) != 0)
2708 printf("http_setup_ssl: %s\n", ERR_error_string(error
, NULL
));
2711 SSL_CTX_free(context
);
2715 http
->error
= WSAGetLastError();
2717 http
->error
= errno
;
2719 http
->status
= HTTP_ERROR
;
2721 return (HTTP_ERROR
);
2724 # elif defined(HAVE_GNUTLS)
2725 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
2727 http
->error
= errno
;
2728 http
->status
= HTTP_ERROR
;
2733 credentials
= (gnutls_certificate_client_credentials
*)
2734 malloc(sizeof(gnutls_certificate_client_credentials
));
2735 if (credentials
== NULL
)
2739 http
->error
= errno
;
2740 http
->status
= HTTP_ERROR
;
2745 gnutls_certificate_allocate_credentials(credentials
);
2747 gnutls_init(&(conn
->session
), GNUTLS_CLIENT
);
2748 gnutls_set_default_priority(conn
->session
);
2749 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
2750 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)http
);
2751 gnutls_transport_set_pull_function(conn
->session
, _httpReadGNUTLS
);
2752 gnutls_transport_set_push_function(conn
->session
, _httpWriteGNUTLS
);
2754 if ((gnutls_handshake(conn
->session
)) != GNUTLS_E_SUCCESS
)
2756 http
->error
= errno
;
2757 http
->status
= HTTP_ERROR
;
2762 conn
->credentials
= credentials
;
2764 # elif defined(HAVE_CDSASSL)
2765 conn
= (http_tls_t
*)calloc(1, sizeof(http_tls_t
));
2770 if ((error
= SSLNewContext(false, &conn
->session
)))
2772 http
->error
= error
;
2773 http
->status
= HTTP_ERROR
;
2780 * Use a union to resolve warnings about int/pointer size mismatches...
2783 error
= SSLSetConnection(conn
->session
, http
);
2786 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
2789 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
2792 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
2795 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
2799 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
2805 http
->error
= error
;
2806 http
->status
= HTTP_ERROR
;
2808 SSLDisposeContext(conn
->session
);
2814 # endif /* HAVE_CDSASSL */
2819 #endif /* HAVE_SSL */
2824 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
2828 http_shutdown_ssl(http_t
*http
) /* I - Connection to server */
2831 SSL_CTX
*context
; /* Context for encryption */
2832 SSL
*conn
; /* Connection for encryption */
2835 conn
= (SSL
*)(http
->tls
);
2836 context
= SSL_get_SSL_CTX(conn
);
2839 SSL_CTX_free(context
);
2842 # elif defined(HAVE_GNUTLS)
2843 http_tls_t
*conn
; /* Encryption session */
2844 gnutls_certificate_client_credentials
*credentials
;
2845 /* TLS credentials */
2848 conn
= (http_tls_t
*)(http
->tls
);
2849 credentials
= (gnutls_certificate_client_credentials
*)(conn
->credentials
);
2851 gnutls_bye(conn
->session
, GNUTLS_SHUT_RDWR
);
2852 gnutls_deinit(conn
->session
);
2853 gnutls_certificate_free_credentials(*credentials
);
2857 # elif defined(HAVE_CDSASSL)
2858 http_tls_t
*conn
; /* CDSA connection information */
2861 conn
= (http_tls_t
*)(http
->tls
);
2863 while (SSLClose(conn
->session
) == errSSLWouldBlock
)
2866 SSLDisposeContext(conn
->session
);
2868 if (conn
->certsArray
)
2869 CFRelease(conn
->certsArray
);
2872 # endif /* HAVE_LIBSSL */
2876 #endif /* HAVE_SSL */
2881 * 'http_upgrade()' - Force upgrade to TLS encryption.
2884 static int /* O - Status of connection */
2885 http_upgrade(http_t
*http
) /* I - Connection to server */
2887 int ret
; /* Return value */
2888 http_t myhttp
; /* Local copy of HTTP data */
2891 DEBUG_printf(("http_upgrade(%p)\n", http
));
2894 * Copy the HTTP data to a local variable so we can do the OPTIONS
2895 * request without interfering with the existing request data...
2898 memcpy(&myhttp
, http
, sizeof(myhttp
));
2901 * Send an OPTIONS request to the server, requiring SSL or TLS
2902 * encryption on the link...
2905 http
->field_authorization
= NULL
; /* Don't free the auth string */
2907 httpClearFields(http
);
2908 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
2909 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0, SSL/2.0, SSL/3.0");
2911 if ((ret
= httpOptions(http
, "*")) == 0)
2914 * Wait for the secure connection...
2917 while (httpUpdate(http
) == HTTP_CONTINUE
);
2923 * Restore the HTTP request data...
2926 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
2927 http
->data_encoding
= myhttp
.data_encoding
;
2928 http
->data_remaining
= myhttp
.data_remaining
;
2929 http
->_data_remaining
= myhttp
._data_remaining
;
2930 http
->expect
= myhttp
.expect
;
2931 http
->field_authorization
= myhttp
.field_authorization
;
2932 http
->digest_tries
= myhttp
.digest_tries
;
2935 * See if we actually went secure...
2941 * Server does not support HTTP upgrade...
2944 DEBUG_puts("Server does not support HTTP upgrade!");
2947 closesocket(http
->fd
);
2959 #endif /* HAVE_SSL */
2963 * 'http_wait()' - Wait for data available on a connection.
2966 static int /* O - 1 if data is available, 0 otherwise */
2967 http_wait(http_t
*http
, /* I - Connection to server */
2968 int msec
, /* I - Milliseconds to wait */
2969 int usessl
) /* I - Use SSL context? */
2972 struct pollfd pfd
; /* Polled file descriptor */
2974 fd_set input_set
; /* select() input set */
2975 struct timeval timeout
; /* Timeout */
2976 #endif /* HAVE_POLL */
2977 int nfds
; /* Result from select()/poll() */
2980 DEBUG_printf(("http_wait(http=%p, msec=%d)\n", http
, msec
));
2986 * Check the SSL/TLS buffers for data first...
2990 if (http
->tls
&& usessl
)
2993 if (SSL_pending((SSL
*)(http
->tls
)))
2995 # elif defined(HAVE_GNUTLS)
2996 if (gnutls_record_check_pending(((http_tls_t
*)(http
->tls
))->session
))
2998 # elif defined(HAVE_CDSASSL)
2999 size_t bytes
; /* Bytes that are available */
3001 if (!SSLGetBufferedReadSize(((http_tls_t
*)http
->tls
)->session
, &bytes
) && bytes
> 0)
3003 # endif /* HAVE_LIBSSL */
3005 #endif /* HAVE_SSL */
3008 * Then try doing a select() or poll() to poll the socket...
3013 pfd
.events
= POLLIN
;
3015 while ((nfds
= poll(&pfd
, 1, msec
)) < 0 && errno
== EINTR
);
3020 FD_ZERO(&input_set
);
3021 FD_SET(http
->fd
, &input_set
);
3023 DEBUG_printf(("http_wait: msec=%d, http->fd=%d\n", msec
, http
->fd
));
3027 timeout
.tv_sec
= msec
/ 1000;
3028 timeout
.tv_usec
= (msec
% 1000) * 1000;
3030 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
3033 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
3035 DEBUG_printf(("http_wait: select() returned %d...\n", nfds
));
3038 while (nfds
< 0 && WSAGetLastError() == WSAEINTR
);
3040 while (nfds
< 0 && errno
== EINTR
);
3042 #endif /* HAVE_POLL */
3044 DEBUG_printf(("http_wait: returning with nfds=%d...\n", nfds
));
3051 * 'http_write()' - Write a buffer to a HTTP connection.
3054 static int /* O - Number of bytes written */
3055 http_write(http_t
*http
, /* I - Connection to server */
3056 const char *buffer
, /* I - Buffer for data */
3057 int length
) /* I - Number of bytes to write */
3059 int tbytes
, /* Total bytes sent */
3060 bytes
; /* Bytes sent */
3069 bytes
= http_write_ssl(http
, buffer
, length
);
3071 #endif /* HAVE_SSL */
3072 bytes
= send(http
->fd
, buffer
, length
, 0);
3077 if (WSAGetLastError() != http
->error
)
3079 http
->error
= WSAGetLastError();
3085 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
3087 http
->error
= errno
;
3092 DEBUG_puts("http_write: error writing data...\n");
3105 printf("http_write: wrote %d bytes: \n", tbytes
);
3106 for (i
= 0, buffer
-= tbytes
; i
< tbytes
; i
+= 16)
3110 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
3111 printf(" %02X", buffer
[i
+ j
] & 255);
3120 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
3122 ch
= buffer
[i
+ j
] & 255;
3124 if (ch
< ' ' || ch
== 127)
3139 * 'http_write_chunk()' - Write a chunked buffer.
3142 static int /* O - Number bytes written */
3143 http_write_chunk(http_t
*http
, /* I - Connection to server */
3144 const char *buffer
, /* I - Buffer to write */
3145 int length
) /* I - Length of buffer */
3147 char header
[255]; /* Chunk header */
3148 int bytes
; /* Bytes written */
3150 DEBUG_printf(("http_write_chunk(http=%p, buffer=%p, length=%d)\n",
3151 http
, buffer
, length
));
3154 * Write the chunk header, data, and trailer.
3157 sprintf(header
, "%x\r\n", length
);
3158 if (http_write(http
, header
, (int)strlen(header
)) < 0)
3160 DEBUG_puts(" http_write of length failed!");
3164 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
3166 DEBUG_puts(" http_write of buffer failed!");
3170 if (http_write(http
, "\r\n", 2) < 0)
3172 DEBUG_puts(" http_write of CR LF failed!");
3182 * 'http_write_ssl()' - Write to a SSL/TLS connection.
3185 static int /* O - Bytes written */
3186 http_write_ssl(http_t
*http
, /* I - Connection to server */
3187 const char *buf
, /* I - Buffer holding data */
3188 int len
) /* I - Length of buffer */
3190 # if defined(HAVE_LIBSSL)
3191 return (SSL_write((SSL
*)(http
->tls
), buf
, len
));
3193 # elif defined(HAVE_GNUTLS)
3194 return (gnutls_record_send(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
3195 # elif defined(HAVE_CDSASSL)
3196 int result
; /* Return value */
3197 OSStatus error
; /* Error info */
3198 size_t processed
; /* Number of bytes processed */
3201 error
= SSLWrite(((http_tls_t
*)http
->tls
)->session
, buf
, len
, &processed
);
3206 result
= (int)processed
;
3208 case errSSLClosedGraceful
:
3211 case errSSLWouldBlock
:
3213 result
= (int)processed
;
3227 # endif /* HAVE_LIBSSL */
3229 #endif /* HAVE_SSL */
3233 * End of "$Id: http.c 6724 2007-07-25 20:39:33Z mike $".