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=%d)\n",
1296 http
, buffer
, 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", bytes
));
1414 memcpy(buffer
, http
->buffer
, length
);
1415 http
->used
-= (int)length
;
1418 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
1423 if (!http
->blocking
&& !httpWait(http
, 10000))
1426 bytes
= (ssize_t
)http_read_ssl(http
, buffer
, (int)length
);
1428 #endif /* HAVE_SSL */
1431 if (!http
->blocking
&& !httpWait(http
, 10000))
1434 DEBUG_printf(("httpRead2: reading %d bytes from socket...\n", length
));
1437 bytes
= (ssize_t
)recv(http
->fd
, buffer
, (int)length
, 0);
1439 while ((bytes
= recv(http
->fd
, buffer
, length
, 0)) < 0)
1444 DEBUG_printf(("httpRead2: read %d bytes from socket...\n", bytes
));
1449 http
->data_remaining
-= bytes
;
1451 if (http
->data_remaining
<= INT_MAX
)
1452 http
->_data_remaining
= (int)http
->data_remaining
;
1454 http
->_data_remaining
= INT_MAX
;
1459 http
->error
= WSAGetLastError();
1464 http
->error
= errno
;
1469 http
->error
= EPIPE
;
1473 if (http
->data_remaining
== 0)
1475 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1476 httpGets(len
, sizeof(len
), http
);
1478 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
1480 if (http
->state
== HTTP_POST_RECV
)
1483 http
->state
= HTTP_WAITING
;
1490 printf("httpRead2: Read %d bytes:\n", bytes
);
1491 for (i
= 0; i
< bytes
; i
+= 16)
1495 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1496 printf(" %02X", buffer
[i
+ j
] & 255);
1505 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1507 ch
= buffer
[i
+ j
] & 255;
1509 if (ch
< ' ' || ch
>= 127)
1523 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
1525 * '_httpReadCDSA()' - Read function for the CDSA library.
1528 OSStatus
/* O - -1 on error, 0 on success */
1530 SSLConnectionRef connection
, /* I - SSL/TLS connection */
1531 void *data
, /* I - Data buffer */
1532 size_t *dataLength
) /* IO - Number of bytes */
1534 OSStatus result
; /* Return value */
1535 ssize_t bytes
; /* Number of bytes read */
1536 http_t
*http
; /* HTTP connection */
1539 http
= (http_t
*)connection
;
1541 if (!http
->blocking
)
1544 * Make sure we have data before we read...
1547 if (!http_wait(http
, 10000, 0))
1549 http
->error
= ETIMEDOUT
;
1556 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
1558 while (bytes
== -1 && errno
== EINTR
);
1560 if (bytes
== *dataLength
)
1566 *dataLength
= bytes
;
1567 result
= errSSLWouldBlock
;
1574 result
= errSSLClosedGraceful
;
1575 else if (errno
== EAGAIN
)
1576 result
= errSSLWouldBlock
;
1578 result
= errSSLClosedAbort
;
1583 #endif /* HAVE_SSL && HAVE_CDSASSL */
1586 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
1588 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
1591 ssize_t
/* O - Number of bytes read or -1 on error */
1593 gnutls_transport_ptr ptr
, /* I - Connection to server */
1594 void *data
, /* I - Buffer */
1595 size_t length
) /* I - Number of bytes to read */
1597 http_t
*http
; /* HTTP connection */
1600 http
= (http_t
*)ptr
;
1602 if (!http
->blocking
)
1605 * Make sure we have data before we read...
1608 if (!http_wait(http
, 10000, 0))
1610 http
->error
= ETIMEDOUT
;
1615 return (recv(http
->fd
, data
, length
, 0));
1617 #endif /* HAVE_SSL && HAVE_GNUTLS */
1621 * 'httpReconnect()' - Reconnect to a HTTP server.
1624 int /* O - 0 on success, non-zero on failure */
1625 httpReconnect(http_t
*http
) /* I - Connection to server */
1627 http_addrlist_t
*addr
; /* Connected address */
1630 DEBUG_printf(("httpReconnect(http=%p)\n", http
));
1637 http_shutdown_ssl(http
);
1638 #endif /* HAVE_SSL */
1641 * Close any previously open socket...
1647 closesocket(http
->fd
);
1656 * Connect to the server...
1659 if ((addr
= httpAddrConnect(http
->addrlist
, &(http
->fd
))) == NULL
)
1662 * Unable to connect...
1666 http
->error
= WSAGetLastError();
1668 http
->error
= errno
;
1670 http
->status
= HTTP_ERROR
;
1675 http
->hostaddr
= &(addr
->addr
);
1677 http
->status
= HTTP_CONTINUE
;
1680 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
1683 * Always do encryption via SSL.
1686 if (http_setup_ssl(http
) != 0)
1689 closesocket(http
->fd
);
1697 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
1698 return (http_upgrade(http
));
1699 #endif /* HAVE_SSL */
1706 * 'httpSetAuthString()' - Set the current authorization string.
1708 * This function just stores a copy of the current authorization string in
1709 * the HTTP connection object. You must still call httpSetField() to set
1710 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
1711 * httpHead(), httpOptions(), httpPost, or httpPut().
1717 httpSetAuthString(http_t
*http
, /* I - Connection to server */
1718 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
1719 const char *data
) /* I - Auth data (NULL for none) */
1722 * Range check input...
1728 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
1729 free(http
->authstring
);
1731 http
->authstring
= http
->_authstring
;
1736 * Set the current authorization string...
1739 int len
= (int)strlen(scheme
) + (data
? (int)strlen(data
) + 1 : 0) + 1;
1742 if (len
> (int)sizeof(http
->_authstring
))
1744 if ((temp
= malloc(len
)) == NULL
)
1745 len
= sizeof(http
->_authstring
);
1747 http
->authstring
= temp
;
1751 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
1753 strlcpy(http
->authstring
, scheme
, len
);
1758 * Clear the current authorization string...
1761 http
->_authstring
[0] = '\0';
1767 * 'httpSetCookie()' - Set the cookie value(s)...
1769 * @since CUPS 1.1.19@
1773 httpSetCookie(http_t
*http
, /* I - Connection */
1774 const char *cookie
) /* I - Cookie string */
1783 http
->cookie
= strdup(cookie
);
1785 http
->cookie
= NULL
;
1790 * 'httpSetExpect()' - Set the Expect: header in a request.
1792 * Currently only HTTP_CONTINUE is supported for the "expect" argument.
1798 httpSetExpect(http_t
*http
, /* I - Connection to server */
1799 http_status_t expect
) /* I - HTTP status to expect (HTTP_CONTINUE) */
1802 http
->expect
= expect
;
1807 * 'httpSetField()' - Set the value of an HTTP header.
1811 httpSetField(http_t
*http
, /* I - Connection to server */
1812 http_field_t field
, /* I - Field index */
1813 const char *value
) /* I - Value */
1816 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
1817 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
1821 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
1824 * Special case for Authorization: as its contents can be
1825 * longer than HTTP_MAX_VALUE
1828 if (field
== HTTP_FIELD_AUTHORIZATION
)
1830 if (http
->field_authorization
)
1831 free(http
->field_authorization
);
1833 http
->field_authorization
= strdup(value
);
1839 * 'httpSetLength()' - Set the content-length and content-encoding.
1845 httpSetLength(http_t
*http
, /* I - Connection to server */
1846 size_t length
) /* I - Length (0 for chunked) */
1853 strcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked");
1854 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
1858 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
1859 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
1860 CUPS_LLFMT
, CUPS_LLCAST length
);
1866 * 'httpTrace()' - Send an TRACE request to the server.
1869 int /* O - Status of call (0 = success) */
1870 httpTrace(http_t
*http
, /* I - Connection to server */
1871 const char *uri
) /* I - URI for trace */
1873 return (http_send(http
, HTTP_TRACE
, uri
));
1878 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1881 http_status_t
/* O - HTTP status */
1882 httpUpdate(http_t
*http
) /* I - Connection to server */
1884 char line
[32768], /* Line from connection... */
1885 *value
; /* Pointer to value on line */
1886 http_field_t field
; /* Field index */
1887 int major
, minor
, /* HTTP version numbers */
1888 status
; /* Request status */
1891 DEBUG_printf(("httpUpdate(http=%p), state=%d\n", http
, http
->state
));
1894 * Flush pending data, if any...
1899 DEBUG_puts(" flushing buffer...");
1901 if (httpFlushWrite(http
) < 0)
1902 return (HTTP_ERROR
);
1906 * If we haven't issued any commands, then there is nothing to "update"...
1909 if (http
->state
== HTTP_WAITING
)
1910 return (HTTP_CONTINUE
);
1913 * Grab all of the lines we can from the connection...
1916 while (httpGets(line
, sizeof(line
), http
) != NULL
)
1918 DEBUG_printf(("httpUpdate: Got \"%s\"\n", line
));
1920 if (line
[0] == '\0')
1923 * Blank line means the start of the data section (if any). Return
1924 * the result code, too...
1926 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
1927 * Instead, we just return HTTP_CONTINUE to the caller and keep on
1931 if (http
->status
== HTTP_CONTINUE
)
1932 return (http
->status
);
1934 if (http
->status
< HTTP_BAD_REQUEST
)
1935 http
->digest_tries
= 0;
1938 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
1940 if (http_setup_ssl(http
) != 0)
1943 closesocket(http
->fd
);
1948 return (HTTP_ERROR
);
1951 return (HTTP_CONTINUE
);
1953 #endif /* HAVE_SSL */
1955 httpGetLength2(http
);
1957 switch (http
->state
)
1961 case HTTP_POST_RECV
:
1964 case HTTP_POST_SEND
:
1969 http
->state
= HTTP_WAITING
;
1973 return (http
->status
);
1975 else if (strncmp(line
, "HTTP/", 5) == 0)
1978 * Got the beginning of a response...
1981 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &status
) != 3)
1982 return (HTTP_ERROR
);
1984 http
->version
= (http_version_t
)(major
* 100 + minor
);
1985 http
->status
= (http_status_t
)status
;
1987 else if ((value
= strchr(line
, ':')) != NULL
)
1994 while (isspace(*value
& 255))
1998 * Be tolerants of servers that send unknown attribute fields...
2001 if (!strcasecmp(line
, "expect"))
2004 * "Expect: 100-continue" or similar...
2007 http
->expect
= (http_status_t
)atoi(value
);
2009 else if (!strcasecmp(line
, "cookie"))
2012 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
2015 httpSetCookie(http
, value
);
2017 else if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
2019 DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line
));
2023 httpSetField(http
, field
, value
);
2027 http
->status
= HTTP_ERROR
;
2028 return (HTTP_ERROR
);
2033 * See if there was an error...
2036 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
2037 return (http
->status
);
2041 DEBUG_printf(("httpUpdate: socket error %d - %s\n", http
->error
,
2042 strerror(http
->error
)));
2043 http
->status
= HTTP_ERROR
;
2044 return (HTTP_ERROR
);
2048 * If we haven't already returned, then there is nothing new...
2051 return (HTTP_CONTINUE
);
2056 * 'httpWait()' - Wait for data available on a connection.
2058 * @since CUPS 1.1.19@
2061 int /* O - 1 if data is available, 0 otherwise */
2062 httpWait(http_t
*http
, /* I - Connection to server */
2063 int msec
) /* I - Milliseconds to wait */
2066 * First see if there is data in the buffer...
2076 * Flush pending data, if any...
2081 if (httpFlushWrite(http
) < 0)
2086 * If not, check the SSL/TLS buffers and do a select() on the connection...
2089 return (http_wait(http
, msec
, 1));
2094 * 'httpWrite()' - Write data to a HTTP connection.
2096 * This function is deprecated. Use the httpWrite2() function which can
2097 * write more than 2GB of data.
2102 int /* O - Number of bytes written */
2103 httpWrite(http_t
*http
, /* I - Connection to server */
2104 const char *buffer
, /* I - Buffer for data */
2105 int length
) /* I - Number of bytes to write */
2107 return ((int)httpWrite2(http
, buffer
, length
));
2112 * 'httpWrite2()' - Write data to a HTTP connection.
2117 ssize_t
/* O - Number of bytes written */
2118 httpWrite2(http_t
*http
, /* I - Connection to server */
2119 const char *buffer
, /* I - Buffer for data */
2120 size_t length
) /* I - Number of bytes to write */
2122 ssize_t bytes
; /* Bytes written */
2125 DEBUG_printf(("httpWrite(http=%p, buffer=%p, length=%d)\n", http
,
2129 * Range check input...
2132 if (http
== NULL
|| buffer
== NULL
)
2136 * Mark activity on the connection...
2139 http
->activity
= time(NULL
);
2142 * Buffer small writes for better performance...
2147 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
2149 DEBUG_printf((" flushing buffer (wused=%d, length=%d)\n",
2150 http
->wused
, length
));
2152 httpFlushWrite(http
);
2155 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
))
2158 * Write to buffer...
2161 DEBUG_printf((" copying %d bytes to wbuffer...\n", length
));
2163 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
2164 http
->wused
+= (int)length
;
2165 bytes
= (ssize_t
)length
;
2170 * Otherwise write the data directly...
2173 DEBUG_printf((" writing %d bytes to socket...\n", length
));
2175 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2176 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
2178 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
2180 DEBUG_printf((" wrote %d bytes...\n", bytes
));
2183 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
2184 http
->data_remaining
-= bytes
;
2190 * Handle end-of-request processing...
2193 if ((http
->data_encoding
== HTTP_ENCODE_CHUNKED
&& length
== 0) ||
2194 (http
->data_encoding
== HTTP_ENCODE_LENGTH
&& http
->data_remaining
== 0))
2197 * Finished with the transfer; unless we are sending POST or PUT
2201 DEBUG_puts("httpWrite: changing states...");
2204 httpFlushWrite(http
);
2206 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2209 * Send a 0-length chunk at the end of the request...
2212 http_write(http
, "0\r\n\r\n", 5);
2215 * Reset the data state...
2218 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
2219 http
->data_remaining
= 0;
2222 if (http
->state
== HTTP_POST_RECV
)
2224 else if (http
->state
== HTTP_PUT_RECV
)
2225 http
->state
= HTTP_STATUS
;
2227 http
->state
= HTTP_WAITING
;
2234 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2236 * '_httpWriteCDSA()' - Write function for the CDSA library.
2239 OSStatus
/* O - -1 on error, 0 on success */
2241 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2242 const void *data
, /* I - Data buffer */
2243 size_t *dataLength
) /* IO - Number of bytes */
2245 OSStatus result
; /* Return value */
2246 ssize_t bytes
; /* Number of bytes read */
2247 http_t
*http
; /* HTTP connection */
2250 http
= (http_t
*)connection
;
2254 bytes
= write(http
->fd
, data
, *dataLength
);
2256 while (bytes
== -1 && errno
== EINTR
);
2258 if (bytes
== *dataLength
)
2262 else if (bytes
>= 0)
2264 *dataLength
= bytes
;
2265 result
= errSSLWouldBlock
;
2271 if (errno
== EAGAIN
)
2272 result
= errSSLWouldBlock
;
2274 result
= errSSLClosedAbort
;
2279 #endif /* HAVE_SSL && HAVE_CDSASSL */
2282 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2284 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
2287 ssize_t
/* O - Number of bytes written or -1 on error */
2289 gnutls_transport_ptr ptr
, /* I - Connection to server */
2290 const void *data
, /* I - Data buffer */
2291 size_t length
) /* I - Number of bytes to write */
2293 return (send(((http_t
*)ptr
)->fd
, data
, length
, 0));
2295 #endif /* HAVE_SSL && HAVE_GNUTLS */
2298 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
2300 * 'http_bio_ctrl()' - Control the HTTP connection.
2303 static long /* O - Result/data */
2304 http_bio_ctrl(BIO
*h
, /* I - BIO data */
2305 int cmd
, /* I - Control command */
2306 long arg1
, /* I - First argument */
2307 void *arg2
) /* I - Second argument */
2314 case BIO_CTRL_RESET
:
2318 case BIO_C_SET_FILE_PTR
:
2323 case BIO_C_GET_FILE_PTR
:
2326 *((void **)arg2
) = h
->ptr
;
2333 case BIO_CTRL_FLUSH
:
2340 * 'http_bio_free()' - Free OpenSSL data.
2343 static int /* O - 1 on success, 0 on failure */
2344 http_bio_free(BIO
*h
) /* I - BIO data */
2360 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
2363 static int /* O - 1 on success, 0 on failure */
2364 http_bio_new(BIO
*h
) /* I - BIO data */
2379 * 'http_bio_puts()' - Send a string for OpenSSL.
2382 static int /* O - Bytes written */
2383 http_bio_puts(BIO
*h
, /* I - BIO data */
2384 const char *str
) /* I - String to write */
2387 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
2389 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
2395 * 'http_bio_read()' - Read data for OpenSSL.
2398 static int /* O - Bytes read */
2399 http_bio_read(BIO
*h
, /* I - BIO data */
2400 char *buf
, /* I - Buffer */
2401 int size
) /* I - Number of bytes to read */
2403 http_t
*http
; /* HTTP connection */
2406 http
= (http_t
*)h
->ptr
;
2408 if (!http
->blocking
)
2411 * Make sure we have data before we read...
2414 if (!http_wait(http
, 10000, 0))
2417 http
->error
= WSAETIMEDOUT
;
2419 http
->error
= ETIMEDOUT
;
2426 return (recv(http
->fd
, buf
, size
, 0));
2431 * 'http_bio_write()' - Write data for OpenSSL.
2434 static int /* O - Bytes written */
2435 http_bio_write(BIO
*h
, /* I - BIO data */
2436 const char *buf
, /* I - Buffer to write */
2437 int num
) /* I - Number of bytes to write */
2439 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
2441 #endif /* HAVE_SSL && HAVE_LIBSSL */
2445 * 'http_field()' - Return the field index for a field name.
2448 static http_field_t
/* O - Field index */
2449 http_field(const char *name
) /* I - String name */
2451 int i
; /* Looping var */
2454 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2455 if (strcasecmp(name
, http_fields
[i
]) == 0)
2456 return ((http_field_t
)i
);
2458 return (HTTP_FIELD_UNKNOWN
);
2464 * 'http_read_ssl()' - Read from a SSL/TLS connection.
2467 static int /* O - Bytes read */
2468 http_read_ssl(http_t
*http
, /* I - Connection to server */
2469 char *buf
, /* I - Buffer to store data */
2470 int len
) /* I - Length of buffer */
2472 # if defined(HAVE_LIBSSL)
2473 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
2475 # elif defined(HAVE_GNUTLS)
2476 return (gnutls_record_recv(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
2478 # elif defined(HAVE_CDSASSL)
2479 int result
; /* Return value */
2480 OSStatus error
; /* Error info */
2481 size_t processed
; /* Number of bytes processed */
2484 error
= SSLRead(((http_tls_t
*)http
->tls
)->session
, buf
, len
, &processed
);
2489 result
= (int)processed
;
2491 case errSSLClosedGraceful
:
2494 case errSSLWouldBlock
:
2496 result
= (int)processed
;
2510 # endif /* HAVE_LIBSSL */
2512 #endif /* HAVE_SSL */
2516 * 'http_send()' - Send a request with all fields and the trailing blank line.
2519 static int /* O - 0 on success, non-zero on error */
2520 http_send(http_t
*http
, /* I - Connection to server */
2521 http_state_t request
, /* I - Request code */
2522 const char *uri
) /* I - URI */
2524 int i
; /* Looping var */
2525 char *ptr
, /* Pointer in buffer */
2526 buf
[1024]; /* Encoded URI buffer */
2527 static const char * const codes
[] =
2528 { /* Request code strings */
2543 static const char hex
[] = "0123456789ABCDEF";
2547 DEBUG_printf(("http_send(http=%p, request=HTTP_%s, uri=\"%s\")\n",
2548 http
, codes
[request
], uri
));
2550 if (http
== NULL
|| uri
== NULL
)
2554 * Set the User-Agent field if it isn't already...
2557 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
2558 httpSetField(http
, HTTP_FIELD_USER_AGENT
, CUPS_MINIMAL
);
2561 * Encode the URI as needed...
2564 for (ptr
= buf
; *uri
!= '\0' && ptr
< (buf
+ sizeof(buf
) - 1); uri
++)
2565 if (*uri
<= ' ' || *uri
>= 127)
2567 if (ptr
< (buf
+ sizeof(buf
) - 1))
2569 if (ptr
< (buf
+ sizeof(buf
) - 1))
2570 *ptr
++ = hex
[(*uri
>> 4) & 15];
2571 if (ptr
< (buf
+ sizeof(buf
) - 1))
2572 *ptr
++ = hex
[*uri
& 15];
2580 * See if we had an error the last time around; if so, reconnect...
2583 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
2584 if (httpReconnect(http
))
2588 * Flush any written data that is pending...
2592 httpFlushWrite(http
);
2595 * Send the request header...
2598 http
->state
= request
;
2599 http
->data_encoding
= HTTP_ENCODE_FIELDS
;
2601 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
2604 http
->status
= HTTP_CONTINUE
;
2607 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
2609 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
2610 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
2612 #endif /* HAVE_SSL */
2614 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
2616 http
->status
= HTTP_ERROR
;
2620 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2621 if (http
->fields
[i
][0] != '\0')
2623 DEBUG_printf(("%s: %s\n", http_fields
[i
], httpGetField(http
, i
)));
2625 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
],
2626 httpGetField(http
, i
)) < 1)
2628 http
->status
= HTTP_ERROR
;
2634 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
2636 http
->status
= HTTP_ERROR
;
2640 if (http
->expect
== HTTP_CONTINUE
&&
2641 (http
->state
== HTTP_POST_RECV
|| http
->state
== HTTP_PUT_RECV
))
2642 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
2644 http
->status
= HTTP_ERROR
;
2648 if (httpPrintf(http
, "\r\n") < 1)
2650 http
->status
= HTTP_ERROR
;
2654 httpFlushWrite(http
);
2655 httpGetLength2(http
);
2656 httpClearFields(http
);
2659 * The Kerberos and AuthRef authentication strings can only be used once...
2662 if (http
->field_authorization
&& http
->authstring
&&
2663 (!strncmp(http
->authstring
, "Negotiate", 9) ||
2664 !strncmp(http
->authstring
, "AuthRef", 7)))
2666 http
->_authstring
[0] = '\0';
2668 if (http
->authstring
!= http
->_authstring
)
2669 free(http
->authstring
);
2671 http
->authstring
= http
->_authstring
;
2680 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
2683 static int /* O - Status of connection */
2684 http_setup_ssl(http_t
*http
) /* I - Connection to server */
2687 SSL_CTX
*context
; /* Context for encryption */
2688 SSL
*conn
; /* Connection for encryption */
2689 BIO
*bio
; /* BIO data */
2690 # elif defined(HAVE_GNUTLS)
2691 http_tls_t
*conn
; /* TLS session object */
2692 gnutls_certificate_client_credentials
*credentials
;
2693 /* TLS credentials */
2694 # elif defined(HAVE_CDSASSL)
2695 OSStatus error
; /* Error code */
2696 http_tls_t
*conn
; /* CDSA connection information */
2697 # endif /* HAVE_LIBSSL */
2700 DEBUG_printf(("http_setup_ssl(http=%p)\n", http
));
2703 context
= SSL_CTX_new(SSLv23_client_method());
2705 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
2707 bio
= BIO_new(_httpBIOMethods());
2708 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
2710 conn
= SSL_new(context
);
2711 SSL_set_bio(conn
, bio
, bio
);
2713 if (SSL_connect(conn
) != 1)
2716 unsigned long error
; /* Error code */
2718 while ((error
= ERR_get_error()) != 0)
2719 printf("http_setup_ssl: %s\n", ERR_error_string(error
, NULL
));
2722 SSL_CTX_free(context
);
2726 http
->error
= WSAGetLastError();
2728 http
->error
= errno
;
2730 http
->status
= HTTP_ERROR
;
2732 return (HTTP_ERROR
);
2735 # elif defined(HAVE_GNUTLS)
2736 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
2738 http
->error
= errno
;
2739 http
->status
= HTTP_ERROR
;
2744 credentials
= (gnutls_certificate_client_credentials
*)
2745 malloc(sizeof(gnutls_certificate_client_credentials
));
2746 if (credentials
== NULL
)
2750 http
->error
= errno
;
2751 http
->status
= HTTP_ERROR
;
2756 gnutls_certificate_allocate_credentials(credentials
);
2758 gnutls_init(&(conn
->session
), GNUTLS_CLIENT
);
2759 gnutls_set_default_priority(conn
->session
);
2760 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
2761 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)http
);
2762 gnutls_transport_set_pull_function(conn
->session
, _httpReadGNUTLS
);
2763 gnutls_transport_set_push_function(conn
->session
, _httpWriteGNUTLS
);
2765 if ((gnutls_handshake(conn
->session
)) != GNUTLS_E_SUCCESS
)
2767 http
->error
= errno
;
2768 http
->status
= HTTP_ERROR
;
2773 conn
->credentials
= credentials
;
2775 # elif defined(HAVE_CDSASSL)
2776 conn
= (http_tls_t
*)calloc(1, sizeof(http_tls_t
));
2781 if ((error
= SSLNewContext(false, &conn
->session
)))
2783 http
->error
= error
;
2784 http
->status
= HTTP_ERROR
;
2791 * Use a union to resolve warnings about int/pointer size mismatches...
2794 error
= SSLSetConnection(conn
->session
, http
);
2797 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
2800 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
2803 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
2806 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
2810 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
2816 http
->error
= error
;
2817 http
->status
= HTTP_ERROR
;
2819 SSLDisposeContext(conn
->session
);
2825 # endif /* HAVE_CDSASSL */
2830 #endif /* HAVE_SSL */
2835 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
2839 http_shutdown_ssl(http_t
*http
) /* I - Connection to server */
2842 SSL_CTX
*context
; /* Context for encryption */
2843 SSL
*conn
; /* Connection for encryption */
2846 conn
= (SSL
*)(http
->tls
);
2847 context
= SSL_get_SSL_CTX(conn
);
2850 SSL_CTX_free(context
);
2853 # elif defined(HAVE_GNUTLS)
2854 http_tls_t
*conn
; /* Encryption session */
2855 gnutls_certificate_client_credentials
*credentials
;
2856 /* TLS credentials */
2859 conn
= (http_tls_t
*)(http
->tls
);
2860 credentials
= (gnutls_certificate_client_credentials
*)(conn
->credentials
);
2862 gnutls_bye(conn
->session
, GNUTLS_SHUT_RDWR
);
2863 gnutls_deinit(conn
->session
);
2864 gnutls_certificate_free_credentials(*credentials
);
2868 # elif defined(HAVE_CDSASSL)
2869 http_tls_t
*conn
; /* CDSA connection information */
2872 conn
= (http_tls_t
*)(http
->tls
);
2874 while (SSLClose(conn
->session
) == errSSLWouldBlock
)
2877 SSLDisposeContext(conn
->session
);
2879 if (conn
->certsArray
)
2880 CFRelease(conn
->certsArray
);
2883 # endif /* HAVE_LIBSSL */
2887 #endif /* HAVE_SSL */
2892 * 'http_upgrade()' - Force upgrade to TLS encryption.
2895 static int /* O - Status of connection */
2896 http_upgrade(http_t
*http
) /* I - Connection to server */
2898 int ret
; /* Return value */
2899 http_t myhttp
; /* Local copy of HTTP data */
2902 DEBUG_printf(("http_upgrade(%p)\n", http
));
2905 * Copy the HTTP data to a local variable so we can do the OPTIONS
2906 * request without interfering with the existing request data...
2909 memcpy(&myhttp
, http
, sizeof(myhttp
));
2912 * Send an OPTIONS request to the server, requiring SSL or TLS
2913 * encryption on the link...
2916 http
->field_authorization
= NULL
; /* Don't free the auth string */
2918 httpClearFields(http
);
2919 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
2920 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0, SSL/2.0, SSL/3.0");
2922 if ((ret
= httpOptions(http
, "*")) == 0)
2925 * Wait for the secure connection...
2928 while (httpUpdate(http
) == HTTP_CONTINUE
);
2934 * Restore the HTTP request data...
2937 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
2938 http
->data_encoding
= myhttp
.data_encoding
;
2939 http
->data_remaining
= myhttp
.data_remaining
;
2940 http
->_data_remaining
= myhttp
._data_remaining
;
2941 http
->expect
= myhttp
.expect
;
2942 http
->field_authorization
= myhttp
.field_authorization
;
2943 http
->digest_tries
= myhttp
.digest_tries
;
2946 * See if we actually went secure...
2952 * Server does not support HTTP upgrade...
2955 DEBUG_puts("Server does not support HTTP upgrade!");
2958 closesocket(http
->fd
);
2970 #endif /* HAVE_SSL */
2974 * 'http_wait()' - Wait for data available on a connection.
2977 static int /* O - 1 if data is available, 0 otherwise */
2978 http_wait(http_t
*http
, /* I - Connection to server */
2979 int msec
, /* I - Milliseconds to wait */
2980 int usessl
) /* I - Use SSL context? */
2983 struct pollfd pfd
; /* Polled file descriptor */
2985 fd_set input_set
; /* select() input set */
2986 struct timeval timeout
; /* Timeout */
2987 #endif /* HAVE_POLL */
2988 int nfds
; /* Result from select()/poll() */
2991 DEBUG_printf(("http_wait(http=%p, msec=%d)\n", http
, msec
));
2997 * Check the SSL/TLS buffers for data first...
3001 if (http
->tls
&& usessl
)
3004 if (SSL_pending((SSL
*)(http
->tls
)))
3006 # elif defined(HAVE_GNUTLS)
3007 if (gnutls_record_check_pending(((http_tls_t
*)(http
->tls
))->session
))
3009 # elif defined(HAVE_CDSASSL)
3010 size_t bytes
; /* Bytes that are available */
3012 if (!SSLGetBufferedReadSize(((http_tls_t
*)http
->tls
)->session
, &bytes
) && bytes
> 0)
3014 # endif /* HAVE_LIBSSL */
3016 #endif /* HAVE_SSL */
3019 * Then try doing a select() or poll() to poll the socket...
3024 pfd
.events
= POLLIN
;
3026 while ((nfds
= poll(&pfd
, 1, msec
)) < 0 && errno
== EINTR
);
3031 FD_ZERO(&input_set
);
3032 FD_SET(http
->fd
, &input_set
);
3034 DEBUG_printf(("http_wait: msec=%d, http->fd=%d\n", msec
, http
->fd
));
3038 timeout
.tv_sec
= msec
/ 1000;
3039 timeout
.tv_usec
= (msec
% 1000) * 1000;
3041 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
3044 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
3046 DEBUG_printf(("http_wait: select() returned %d...\n", nfds
));
3049 while (nfds
< 0 && WSAGetLastError() == WSAEINTR
);
3051 while (nfds
< 0 && errno
== EINTR
);
3053 #endif /* HAVE_POLL */
3055 DEBUG_printf(("http_wait: returning with nfds=%d...\n", nfds
));
3062 * 'http_write()' - Write a buffer to a HTTP connection.
3065 static int /* O - Number of bytes written */
3066 http_write(http_t
*http
, /* I - Connection to server */
3067 const char *buffer
, /* I - Buffer for data */
3068 int length
) /* I - Number of bytes to write */
3070 int tbytes
, /* Total bytes sent */
3071 bytes
; /* Bytes sent */
3080 bytes
= http_write_ssl(http
, buffer
, length
);
3082 #endif /* HAVE_SSL */
3083 bytes
= send(http
->fd
, buffer
, length
, 0);
3088 if (WSAGetLastError() != http
->error
)
3090 http
->error
= WSAGetLastError();
3096 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
3098 http
->error
= errno
;
3103 DEBUG_puts("http_write: error writing data...\n");
3116 printf("http_write: wrote %d bytes: \n", tbytes
);
3117 for (i
= 0, buffer
-= tbytes
; i
< tbytes
; i
+= 16)
3121 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
3122 printf(" %02X", buffer
[i
+ j
] & 255);
3131 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
3133 ch
= buffer
[i
+ j
] & 255;
3135 if (ch
< ' ' || ch
== 127)
3150 * 'http_write_chunk()' - Write a chunked buffer.
3153 static int /* O - Number bytes written */
3154 http_write_chunk(http_t
*http
, /* I - Connection to server */
3155 const char *buffer
, /* I - Buffer to write */
3156 int length
) /* I - Length of buffer */
3158 char header
[255]; /* Chunk header */
3159 int bytes
; /* Bytes written */
3161 DEBUG_printf(("http_write_chunk(http=%p, buffer=%p, length=%d)\n",
3162 http
, buffer
, length
));
3165 * Write the chunk header, data, and trailer.
3168 sprintf(header
, "%x\r\n", length
);
3169 if (http_write(http
, header
, (int)strlen(header
)) < 0)
3171 DEBUG_puts(" http_write of length failed!");
3175 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
3177 DEBUG_puts(" http_write of buffer failed!");
3181 if (http_write(http
, "\r\n", 2) < 0)
3183 DEBUG_puts(" http_write of CR LF failed!");
3193 * 'http_write_ssl()' - Write to a SSL/TLS connection.
3196 static int /* O - Bytes written */
3197 http_write_ssl(http_t
*http
, /* I - Connection to server */
3198 const char *buf
, /* I - Buffer holding data */
3199 int len
) /* I - Length of buffer */
3201 # if defined(HAVE_LIBSSL)
3202 return (SSL_write((SSL
*)(http
->tls
), buf
, len
));
3204 # elif defined(HAVE_GNUTLS)
3205 return (gnutls_record_send(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
3206 # elif defined(HAVE_CDSASSL)
3207 int result
; /* Return value */
3208 OSStatus error
; /* Error info */
3209 size_t processed
; /* Number of bytes processed */
3212 error
= SSLWrite(((http_tls_t
*)http
->tls
)->session
, buf
, len
, &processed
);
3217 result
= (int)processed
;
3219 case errSSLClosedGraceful
:
3222 case errSSLWouldBlock
:
3224 result
= (int)processed
;
3238 # endif /* HAVE_LIBSSL */
3240 #endif /* HAVE_SSL */
3244 * End of "$Id: http.c 6724 2007-07-25 20:39:33Z mike $".