2 * "$Id: http.c 6285 2007-02-16 01:10:55Z mike $"
4 * HTTP routines for the Common UNIX Printing System (CUPS).
6 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
8 * This file contains Kerberos support code, copyright 2006 by
11 * These coded instructions, statements, and computer programs are the
12 * property of Easy Software Products and are protected by Federal
13 * copyright law. Distribution and use rights are outlined in the file
14 * "LICENSE.txt" which should have been included with this file. If this
15 * file is missing or damaged please contact Easy Software Products
18 * Attn: CUPS Licensing Information
19 * Easy Software Products
20 * 44141 Airport View Drive, Suite 204
21 * Hollywood, Maryland 20636 USA
23 * Voice: (301) 373-9600
24 * EMail: cups-info@cups.org
25 * WWW: http://www.cups.org
27 * This file is subject to the Apple OS-Developed Software exception.
31 * _httpBIOMethods() - Get the OpenSSL BIO methods for HTTP connections.
32 * httpBlocking() - Set blocking/non-blocking behavior on a connection.
33 * httpCheck() - Check to see if there is a pending response from
35 * httpClearCookie() - Clear the cookie value(s).
36 * httpClearFields() - Clear HTTP request fields.
37 * httpClose() - Close an HTTP connection...
38 * httpConnect() - Connect to a HTTP server.
39 * httpConnectEncrypt() - Connect to a HTTP server using encryption.
40 * httpDelete() - Send a DELETE request to the server.
41 * httpEncryption() - Set the required encryption on the link.
42 * httpError() - Get the last error on a connection.
43 * httpFlush() - Flush data from a HTTP connection.
44 * httpFlushWrite() - Flush data in write buffer.
45 * httpGet() - Send a GET request to the server.
46 * httpGetBlocking() - Get the blocking/non-block state of a connection.
47 * httpGetCookie() - Get any cookie data from the response.
48 * httpGetFd() - Get the file descriptor associated with a
50 * httpGetField() - Get a field value from a request/response.
51 * httpGetLength() - Get the amount of data remaining from the
52 * content-length or transfer-encoding fields.
53 * httpGetLength2() - Get the amount of data remaining from the
54 * content-length or transfer-encoding fields.
55 * httpGetStatus() - Get the status of the last HTTP request.
56 * httpGetSubField() - Get a sub-field value.
57 * httpGets() - Get a line of text from a HTTP connection.
58 * httpHead() - Send a HEAD request to the server.
59 * httpInitialize() - Initialize the HTTP interface library and set the
60 * default HTTP proxy (if any).
61 * httpOptions() - Send an OPTIONS request to the server.
62 * httpPost() - Send a POST request to the server.
63 * httpPrintf() - Print a formatted string to a HTTP connection.
64 * httpPut() - Send a PUT request to the server.
65 * httpRead() - Read data from a HTTP connection.
66 * httpRead2() - Read data from a HTTP connection.
67 * _httpReadCDSA() - Read function for the CDSA library.
68 * _httpReadGNUTLS() - Read function for the GNU TLS library.
69 * httpReconnect() - Reconnect to a HTTP server...
70 * httpSetCookie() - Set the cookie value(s)...
71 * httpSetExpect() - Set the Expect: header in a request.
72 * httpSetField() - Set the value of an HTTP header.
73 * httpSetLength() - Set the content-length and transfer-encoding.
74 * httpTrace() - Send an TRACE request to the server.
75 * httpUpdate() - Update the current HTTP state for incoming data.
76 * httpWait() - Wait for data available on a connection.
77 * httpWrite() - Write data to a HTTP connection.
78 * httpWrite2() - Write data to a HTTP connection.
79 * _httpWriteCDSA() - Write function for the CDSA library.
80 * _httpWriteGNUTLS() - Write function for the GNU TLS library.
81 * http_bio_ctrl() - Control the HTTP connection.
82 * http_bio_free() - Free OpenSSL data.
83 * http_bio_new() - Initialize an OpenSSL BIO structure.
84 * http_bio_puts() - Send a string for OpenSSL.
85 * http_bio_read() - Read data for OpenSSL.
86 * http_bio_write() - Write data for OpenSSL.
87 * http_field() - Return the field index for a field name.
88 * http_read_ssl() - Read from a SSL/TLS connection.
89 * http_send() - Send a request with all fields and the trailing
91 * http_setup_ssl() - Set up SSL/TLS on a connection.
92 * http_shutdown_ssl() - Shut down SSL/TLS on a connection.
93 * http_upgrade() - Force upgrade to TLS encryption.
94 * http_wait() - Wait for data available on a connection.
95 * http_write() - Write data to a connection.
96 * http_write_ssl() - Write to a SSL/TLS connection.
100 * Include necessary headers...
103 #include "http-private.h"
111 # include <sys/time.h>
112 # include <sys/resource.h>
115 # include <sys/poll.h>
116 #endif /* HAVE_POLL */
120 * Some operating systems have done away with the Fxxxx constants for
121 * the fcntl() call; this works around that "feature"...
125 # define FNONBLK O_NONBLOCK
126 #endif /* !FNONBLK */
133 static http_field_t
http_field(const char *name
);
134 static int http_send(http_t
*http
, http_state_t request
,
136 static int http_wait(http_t
*http
, int msec
, int usessl
);
137 static int http_write(http_t
*http
, const char *buffer
,
139 static int http_write_chunk(http_t
*http
, const char *buffer
,
142 static int http_read_ssl(http_t
*http
, char *buf
, int len
);
143 static int http_setup_ssl(http_t
*http
);
144 static void http_shutdown_ssl(http_t
*http
);
145 static int http_upgrade(http_t
*http
);
146 static int http_write_ssl(http_t
*http
, const char *buf
, int len
);
147 #endif /* HAVE_SSL */
154 static const char * const http_fields
[] =
171 "If-Unmodified-since",
186 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
188 * BIO methods for OpenSSL...
191 static int http_bio_write(BIO
*h
, const char *buf
, int num
);
192 static int http_bio_read(BIO
*h
, char *buf
, int size
);
193 static int http_bio_puts(BIO
*h
, const char *str
);
194 static long http_bio_ctrl(BIO
*h
, int cmd
, long arg1
, void *arg2
);
195 static int http_bio_new(BIO
*h
);
196 static int http_bio_free(BIO
*data
);
198 static BIO_METHOD http_bio_methods
=
205 NULL
, /* http_bio_gets, */
214 * '_httpBIOMethods()' - Get the OpenSSL BIO methods for HTTP connections.
217 BIO_METHOD
* /* O - BIO methods for OpenSSL */
218 _httpBIOMethods(void)
220 return (&http_bio_methods
);
222 #endif /* HAVE_SSL && HAVE_LIBSSL */
226 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
230 httpBlocking(http_t
*http
, /* I - HTTP connection */
231 int b
) /* I - 1 = blocking, 0 = non-blocking */
239 * 'httpCheck()' - Check to see if there is a pending response from the server.
242 int /* O - 0 = no data, 1 = data available */
243 httpCheck(http_t
*http
) /* I - HTTP connection */
245 return (httpWait(http
, 0));
250 * 'httpClearCookie()' - Clear the cookie value(s).
252 * @since CUPS 1.1.19@
256 httpClearCookie(http_t
*http
) /* I - HTTP connection */
270 * 'httpClearFields()' - Clear HTTP request fields.
274 httpClearFields(http_t
*http
) /* I - HTTP connection */
278 memset(http
->fields
, 0, sizeof(http
->fields
));
279 if (http
->hostname
[0] == '/')
280 httpSetField(http
, HTTP_FIELD_HOST
, "localhost");
282 httpSetField(http
, HTTP_FIELD_HOST
, http
->hostname
);
284 if (http
->field_authorization
)
286 free(http
->field_authorization
);
287 http
->field_authorization
= NULL
;
290 http
->expect
= (http_status_t
)0;
296 * 'httpClose()' - Close an HTTP connection...
300 httpClose(http_t
*http
) /* I - HTTP connection */
303 OM_uint32 minor_status
, /* Minor status code */
304 major_status
; /* Major status code */
305 #endif /* HAVE_GSSAPI */
308 DEBUG_printf(("httpClose(http=%p)\n", http
));
313 httpAddrFreeList(http
->addrlist
);
320 http_shutdown_ssl(http
);
321 #endif /* HAVE_SSL */
324 closesocket(http
->fd
);
330 if (http
->gssctx
!= GSS_C_NO_CONTEXT
)
331 major_status
= gss_delete_sec_context(&minor_status
, &http
->gssctx
,
334 if (http
->gssname
!= GSS_C_NO_NAME
)
335 major_status
= gss_release_name(&minor_status
, &http
->gssname
);
336 #endif /* HAVE_GSSAPI */
338 httpClearFields(http
);
340 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
341 free(http
->authstring
);
348 * 'httpConnect()' - Connect to a HTTP server.
351 http_t
* /* O - New HTTP connection */
352 httpConnect(const char *host
, /* I - Host to connect to */
353 int port
) /* I - Port number */
355 http_encryption_t encryption
; /* Type of encryption to use */
359 * Set the default encryption status...
363 encryption
= HTTP_ENCRYPT_ALWAYS
;
365 encryption
= HTTP_ENCRYPT_IF_REQUESTED
;
367 return (httpConnectEncrypt(host
, port
, encryption
));
372 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
375 http_t
* /* O - New HTTP connection */
377 const char *host
, /* I - Host to connect to */
378 int port
, /* I - Port number */
379 http_encryption_t encryption
) /* I - Type of encryption to use */
381 http_t
*http
; /* New HTTP connection */
382 http_addrlist_t
*addrlist
; /* Host address data */
383 char service
[255]; /* Service name */
386 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)\n",
387 host
? host
: "(null)", port
, encryption
));
398 sprintf(service
, "%d", port
);
400 if ((addrlist
= httpAddrGetList(host
, AF_UNSPEC
, service
)) == NULL
)
404 * Allocate memory for the structure...
407 http
= calloc(sizeof(http_t
), 1);
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 - HTTP connection */
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 - HTTP connection */
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 - HTTP connection */
509 return (http
->error
);
516 * 'httpFlush()' - Flush data from a HTTP connection.
520 httpFlush(http_t
*http
) /* I - HTTP connection */
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 - HTTP connection */
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 - HTTP connection */
606 const char *uri
) /* I - URI to get */
608 return (http_send(http
, HTTP_GET
, uri
));
613 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
618 int /* O - 1 if blocking, 0 if non-blocking */
619 httpGetBlocking(http_t
*http
) /* I - HTTP connection */
621 return (http
? http
->blocking
: 0);
626 * 'httpGetCookie()' - Get any cookie data from the response.
628 * @since CUPS 1.1.19@
631 const char * /* O - Cookie data or NULL */
632 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
634 return (http
? http
->cookie
: NULL
);
639 * 'httpGetFd()' - Get the file descriptor associated with a connection.
644 int /* O - File descriptor or -1 if none */
645 httpGetFd(http_t
*http
) /* I - HTTP connection */
647 return (http
? http
->fd
: -1);
652 * 'httpGetField()' - Get a field value from a request/response.
655 const char * /* O - Field value */
656 httpGetField(http_t
*http
, /* I - HTTP connection */
657 http_field_t field
) /* I - Field to get */
659 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
661 else if (field
== HTTP_FIELD_AUTHORIZATION
&&
662 http
->field_authorization
)
665 * Special case for WWW-Authenticate: as its contents can be
666 * longer than HTTP_MAX_VALUE...
669 return (http
->field_authorization
);
672 return (http
->fields
[field
]);
677 * 'httpGetLength()' - Get the amount of data remaining from the
678 * content-length or transfer-encoding fields.
680 * This function is deprecated and will not return lengths larger than
681 * 2^31 - 1; use httpGetLength2() instead.
686 int /* O - Content length */
687 httpGetLength(http_t
*http
) /* I - HTTP connection */
690 * Get the read content length and return the 32-bit value.
695 httpGetLength2(http
);
697 return (http
->_data_remaining
);
705 * 'httpGetLength2()' - Get the amount of data remaining from the
706 * content-length or transfer-encoding fields.
708 * This function returns the complete content length, even for
709 * content larger than 2^31 - 1.
714 off_t
/* O - Content length */
715 httpGetLength2(http_t
*http
) /* I - HTTP connection */
717 DEBUG_printf(("httpGetLength2(http=%p), state=%d\n", http
, http
->state
));
722 if (!strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
724 DEBUG_puts("httpGetLength2: chunked request!");
726 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
727 http
->data_remaining
= 0;
731 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
734 * The following is a hack for HTTP servers that don't send a
735 * content-length or transfer-encoding field...
737 * If there is no content-length then the connection must close
738 * after the transfer is complete...
741 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
744 * Default content length is 0 for errors and 2^31-1 for other
745 * successful requests...
748 if (http
->status
>= HTTP_MULTIPLE_CHOICES
)
749 http
->data_remaining
= 0;
751 http
->data_remaining
= 2147483647;
754 http
->data_remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
757 DEBUG_printf(("httpGetLength2: content_length=" CUPS_LLFMT
"\n",
758 CUPS_LLCAST http
->data_remaining
));
761 if (http
->data_remaining
<= INT_MAX
)
762 http
->_data_remaining
= (int)http
->data_remaining
;
764 http
->_data_remaining
= INT_MAX
;
766 return (http
->data_remaining
);
771 * 'httpGetStatus()' - Get the status of the last HTTP request.
776 http_status_t
/* O - HTTP status */
777 httpGetStatus(http_t
*http
) /* I - HTTP connection */
779 return (http
? http
->status
: HTTP_ERROR
);
784 * 'httpGetSubField()' - Get a sub-field value.
789 char * /* O - Value or NULL */
790 httpGetSubField(http_t
*http
, /* I - HTTP connection */
791 http_field_t field
, /* I - Field index */
792 const char *name
, /* I - Name of sub-field */
793 char *value
) /* O - Value string */
795 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
800 * 'httpGetSubField2()' - Get a sub-field value.
805 char * /* O - Value or NULL */
806 httpGetSubField2(http_t
*http
, /* I - HTTP connection */
807 http_field_t field
, /* I - Field index */
808 const char *name
, /* I - Name of sub-field */
809 char *value
, /* O - Value string */
810 int valuelen
) /* I - Size of value buffer */
812 const char *fptr
; /* Pointer into field */
813 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
814 *ptr
, /* Pointer into string buffer */
815 *end
; /* End of value buffer */
817 DEBUG_printf(("httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, valuelen=%d)\n",
818 http
, field
, name
, value
, valuelen
));
820 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
821 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
824 end
= value
+ valuelen
- 1;
826 for (fptr
= http
->fields
[field
]; *fptr
;)
829 * Skip leading whitespace...
832 while (isspace(*fptr
& 255))
842 * Get the sub-field name...
846 *fptr
&& *fptr
!= '=' && !isspace(*fptr
& 255) &&
847 ptr
< (temp
+ sizeof(temp
) - 1);
852 DEBUG_printf(("httpGetSubField: name=\"%s\"\n", temp
));
855 * Skip trailing chars up to the '='...
858 while (isspace(*fptr
& 255))
868 * Skip = and leading whitespace...
873 while (isspace(*fptr
& 255))
879 * Read quoted string...
882 for (ptr
= value
, fptr
++;
883 *fptr
&& *fptr
!= '\"' && ptr
< end
;
888 while (*fptr
&& *fptr
!= '\"')
897 * Read unquoted string...
901 *fptr
&& !isspace(*fptr
& 255) && *fptr
!= ',' && ptr
< end
;
906 while (*fptr
&& !isspace(*fptr
& 255) && *fptr
!= ',')
910 DEBUG_printf(("httpGetSubField: value=\"%s\"\n", value
));
913 * See if this is the one...
916 if (!strcmp(name
, temp
))
927 * 'httpGets()' - Get a line of text from a HTTP connection.
930 char * /* O - Line or NULL */
931 httpGets(char *line
, /* I - Line to read into */
932 int length
, /* I - Max length of buffer */
933 http_t
*http
) /* I - HTTP connection */
935 char *lineptr
, /* Pointer into line */
936 *lineend
, /* End of line */
937 *bufptr
, /* Pointer into input buffer */
938 *bufend
; /* Pointer to end of buffer */
939 int bytes
, /* Number of bytes read */
940 eol
; /* End-of-line? */
943 DEBUG_printf(("httpGets(line=%p, length=%d, http=%p)\n", line
, length
, http
));
945 if (http
== NULL
|| line
== NULL
)
949 * Read a line from the buffer...
953 lineend
= line
+ length
- 1;
956 while (lineptr
< lineend
)
959 * Pre-load the buffer as needed...
968 while (http
->used
== 0)
971 * No newline; see if there is more data to be read...
974 if (!http
->blocking
&& !http_wait(http
, 10000, 1))
976 DEBUG_puts("httpGets: Timed out!");
978 http
->error
= WSAETIMEDOUT
;
980 http
->error
= ETIMEDOUT
;
987 bytes
= http_read_ssl(http
, http
->buffer
+ http
->used
,
988 HTTP_MAX_BUFFER
- http
->used
);
990 #endif /* HAVE_SSL */
991 bytes
= recv(http
->fd
, http
->buffer
+ http
->used
,
992 HTTP_MAX_BUFFER
- http
->used
, 0);
994 DEBUG_printf(("httpGets: read %d bytes...\n", bytes
));
999 * Nope, can't get a line this time...
1003 if (WSAGetLastError() != http
->error
)
1005 http
->error
= WSAGetLastError();
1009 DEBUG_printf(("httpGets: recv() error %d!\n", WSAGetLastError()));
1011 DEBUG_printf(("httpGets: recv() error %d!\n", errno
));
1015 else if (errno
!= http
->error
)
1017 http
->error
= errno
;
1024 else if (bytes
== 0)
1026 http
->error
= EPIPE
;
1032 * Yup, update the amount used...
1035 http
->used
+= bytes
;
1039 * Now copy as much of the current line as possible...
1042 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1043 lineptr
< lineend
&& bufptr
< bufend
;)
1045 if (*bufptr
== 0x0a)
1051 else if (*bufptr
== 0x0d)
1054 *lineptr
++ = *bufptr
++;
1057 http
->used
-= (int)(bufptr
- http
->buffer
);
1059 memmove(http
->buffer
, bufptr
, http
->used
);
1067 http
->activity
= time(NULL
);
1071 DEBUG_printf(("httpGets: Returning \"%s\"\n", line
));
1077 DEBUG_puts("httpGets: No new line available!");
1084 * 'httpHead()' - Send a HEAD request to the server.
1087 int /* O - Status of call (0 = success) */
1088 httpHead(http_t
*http
, /* I - HTTP connection */
1089 const char *uri
) /* I - URI for head */
1091 return (http_send(http
, HTTP_HEAD
, uri
));
1096 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1097 * default HTTP proxy (if any).
1101 httpInitialize(void)
1105 struct timeval curtime
; /* Current time in microseconds */
1106 # endif /* !WIN32 */
1107 int i
; /* Looping var */
1108 unsigned char data
[1024]; /* Seed data */
1109 #endif /* HAVE_LIBSSL */
1112 WSADATA winsockdata
; /* WinSock data */
1113 static int initialized
= 0; /* Has WinSock been initialized? */
1117 WSAStartup(MAKEWORD(1,1), &winsockdata
);
1118 #elif !defined(SO_NOSIGPIPE)
1120 * Ignore SIGPIPE signals...
1124 sigset(SIGPIPE
, SIG_IGN
);
1125 # elif defined(HAVE_SIGACTION)
1126 struct sigaction action
; /* POSIX sigaction data */
1129 memset(&action
, 0, sizeof(action
));
1130 action
.sa_handler
= SIG_IGN
;
1131 sigaction(SIGPIPE
, &action
, NULL
);
1133 signal(SIGPIPE
, SIG_IGN
);
1134 # endif /* !SO_NOSIGPIPE */
1138 gnutls_global_init();
1139 #endif /* HAVE_GNUTLS */
1142 SSL_load_error_strings();
1146 * Using the current time is a dubious random seed, but on some systems
1147 * it is the best we can do (on others, this seed isn't even used...)
1152 gettimeofday(&curtime
, NULL
);
1153 srand(curtime
.tv_sec
+ curtime
.tv_usec
);
1156 for (i
= 0; i
< sizeof(data
); i
++)
1157 data
[i
] = rand(); /* Yes, this is a poor source of random data... */
1159 RAND_seed(&data
, sizeof(data
));
1160 #endif /* HAVE_LIBSSL */
1165 * 'httpOptions()' - Send an OPTIONS request to the server.
1168 int /* O - Status of call (0 = success) */
1169 httpOptions(http_t
*http
, /* I - HTTP connection */
1170 const char *uri
) /* I - URI for options */
1172 return (http_send(http
, HTTP_OPTIONS
, uri
));
1177 * 'httpPost()' - Send a POST request to the server.
1180 int /* O - Status of call (0 = success) */
1181 httpPost(http_t
*http
, /* I - HTTP connection */
1182 const char *uri
) /* I - URI for post */
1184 return (http_send(http
, HTTP_POST
, uri
));
1189 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1194 int /* O - Number of bytes written */
1195 httpPrintf(http_t
*http
, /* I - HTTP connection */
1196 const char *format
, /* I - printf-style format string */
1197 ...) /* I - Additional args as needed */
1199 int bytes
; /* Number of bytes to write */
1200 char buf
[16384]; /* Buffer for formatted string */
1201 va_list ap
; /* Variable argument pointer */
1204 DEBUG_printf(("httpPrintf(http=%p, format=\"%s\", ...)\n", http
, format
));
1206 va_start(ap
, format
);
1207 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1210 DEBUG_printf(("httpPrintf: %s", buf
));
1212 if (http
->data_encoding
== HTTP_ENCODE_FIELDS
)
1213 return (httpWrite2(http
, buf
, bytes
));
1218 DEBUG_puts(" flushing existing data...");
1220 if (httpFlushWrite(http
) < 0)
1224 return (http_write(http
, buf
, bytes
));
1230 * 'httpPut()' - Send a PUT request to the server.
1233 int /* O - Status of call (0 = success) */
1234 httpPut(http_t
*http
, /* I - HTTP connection */
1235 const char *uri
) /* I - URI to put */
1237 return (http_send(http
, HTTP_PUT
, uri
));
1242 * 'httpRead()' - Read data from a HTTP connection.
1244 * This function is deprecated. Use the httpRead2() function which can
1245 * read more than 2GB of data.
1250 int /* O - Number of bytes read */
1251 httpRead(http_t
*http
, /* I - HTTP connection */
1252 char *buffer
, /* I - Buffer for data */
1253 int length
) /* I - Maximum number of bytes */
1255 return ((int)httpRead2(http
, buffer
, length
));
1260 * 'httpRead2()' - Read data from a HTTP connection.
1265 ssize_t
/* O - Number of bytes read */
1266 httpRead2(http_t
*http
, /* I - HTTP connection */
1267 char *buffer
, /* I - Buffer for data */
1268 size_t length
) /* I - Maximum number of bytes */
1270 ssize_t bytes
; /* Bytes read */
1271 char len
[32]; /* Length string */
1274 DEBUG_printf(("httpRead(http=%p, buffer=%p, length=%d)\n",
1275 http
, buffer
, length
));
1277 if (http
== NULL
|| buffer
== NULL
)
1280 http
->activity
= time(NULL
);
1285 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1286 http
->data_remaining
<= 0)
1288 DEBUG_puts("httpRead2: Getting chunk length...");
1290 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1292 DEBUG_puts("httpRead2: Could not get length!");
1296 http
->data_remaining
= strtoll(len
, NULL
, 16);
1297 if (http
->data_remaining
< 0)
1299 DEBUG_puts("httpRead2: Negative chunk length!");
1304 DEBUG_printf(("httpRead2: data_remaining=" CUPS_LLFMT
"\n",
1305 CUPS_LLCAST http
->data_remaining
));
1307 if (http
->data_remaining
<= 0)
1310 * A zero-length chunk ends a transfer; unless we are reading POST
1314 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1315 httpGets(len
, sizeof(len
), http
);
1317 if (http
->state
== HTTP_POST_RECV
)
1320 http
->state
= HTTP_WAITING
;
1323 * Prevent future reads for this request...
1326 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1330 else if (length
> (size_t)http
->data_remaining
)
1331 length
= (size_t)http
->data_remaining
;
1333 if (http
->used
== 0 && length
<= 256)
1336 * Buffer small reads for better performance...
1339 if (!http
->blocking
&& !httpWait(http
, 10000))
1342 if (http
->data_remaining
> sizeof(http
->buffer
))
1343 bytes
= sizeof(http
->buffer
);
1345 bytes
= http
->data_remaining
;
1349 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1351 #endif /* HAVE_SSL */
1353 DEBUG_printf(("httpRead2: reading %d bytes from socket into buffer...\n",
1356 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1358 DEBUG_printf(("httpRead2: read %d bytes from socket into buffer...\n",
1367 http
->error
= WSAGetLastError();
1372 http
->error
= errno
;
1379 http
->error
= EPIPE
;
1386 if (length
> (size_t)http
->used
)
1387 length
= (size_t)http
->used
;
1389 bytes
= (ssize_t
)length
;
1391 DEBUG_printf(("httpRead2: grabbing %d bytes from input buffer...\n", bytes
));
1393 memcpy(buffer
, http
->buffer
, length
);
1394 http
->used
-= (int)length
;
1397 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
1402 if (!http
->blocking
&& !httpWait(http
, 10000))
1405 bytes
= (ssize_t
)http_read_ssl(http
, buffer
, (int)length
);
1407 #endif /* HAVE_SSL */
1410 if (!http
->blocking
&& !httpWait(http
, 10000))
1413 DEBUG_printf(("httpRead2: reading %d bytes from socket...\n", length
));
1416 bytes
= (ssize_t
)recv(http
->fd
, buffer
, (int)length
, 0);
1418 while ((bytes
= recv(http
->fd
, buffer
, length
, 0)) < 0)
1423 DEBUG_printf(("httpRead2: read %d bytes from socket...\n", bytes
));
1428 http
->data_remaining
-= bytes
;
1430 if (http
->data_remaining
<= INT_MAX
)
1431 http
->_data_remaining
= (int)http
->data_remaining
;
1433 http
->_data_remaining
= INT_MAX
;
1438 http
->error
= WSAGetLastError();
1443 http
->error
= errno
;
1448 http
->error
= EPIPE
;
1452 if (http
->data_remaining
== 0)
1454 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1455 httpGets(len
, sizeof(len
), http
);
1457 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
1459 if (http
->state
== HTTP_POST_RECV
)
1462 http
->state
= HTTP_WAITING
;
1469 printf("httpRead2: Read %d bytes:\n", bytes
);
1470 for (i
= 0; i
< bytes
; i
+= 16)
1474 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1475 printf(" %02X", buffer
[i
+ j
] & 255);
1484 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1486 ch
= buffer
[i
+ j
] & 255;
1488 if (ch
< ' ' || ch
>= 127)
1502 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
1504 * '_httpReadCDSA()' - Read function for the CDSA library.
1507 OSStatus
/* O - -1 on error, 0 on success */
1509 SSLConnectionRef connection
, /* I - SSL/TLS connection */
1510 void *data
, /* I - Data buffer */
1511 size_t *dataLength
) /* IO - Number of bytes */
1513 OSStatus result
; /* Return value */
1514 ssize_t bytes
; /* Number of bytes read */
1515 http_t
*http
; /* HTTP connection */
1518 http
= (http_t
*)connection
;
1520 if (!http
->blocking
)
1523 * Make sure we have data before we read...
1526 if (!http_wait(http
, 10000, 0))
1528 http
->error
= ETIMEDOUT
;
1535 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
1537 while (bytes
== -1 && errno
== EINTR
);
1539 if (bytes
== *dataLength
)
1545 *dataLength
= bytes
;
1546 result
= errSSLWouldBlock
;
1553 result
= errSSLClosedGraceful
;
1554 else if (errno
== EAGAIN
)
1555 result
= errSSLWouldBlock
;
1557 result
= errSSLClosedAbort
;
1562 #endif /* HAVE_SSL && HAVE_CDSASSL */
1565 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
1567 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
1570 ssize_t
/* O - Number of bytes read or -1 on error */
1572 gnutls_transport_ptr ptr
, /* I - HTTP connection */
1573 void *data
, /* I - Buffer */
1574 size_t length
) /* I - Number of bytes to read */
1576 http_t
*http
; /* HTTP connection */
1579 http
= (http_t
*)ptr
;
1581 if (!http
->blocking
)
1584 * Make sure we have data before we read...
1587 if (!http_wait(http
, 10000, 0))
1589 http
->error
= ETIMEDOUT
;
1594 return (recv(http
->fd
, data
, length
, 0));
1596 #endif /* HAVE_SSL && HAVE_GNUTLS */
1600 * 'httpReconnect()' - Reconnect to a HTTP server.
1603 int /* O - 0 on success, non-zero on failure */
1604 httpReconnect(http_t
*http
) /* I - HTTP connection */
1606 http_addrlist_t
*addr
; /* Connected address */
1609 DEBUG_printf(("httpReconnect(http=%p)\n", http
));
1616 http_shutdown_ssl(http
);
1617 #endif /* HAVE_SSL */
1620 * Close any previously open socket...
1626 closesocket(http
->fd
);
1635 * Connect to the server...
1638 if ((addr
= httpAddrConnect(http
->addrlist
, &(http
->fd
))) == NULL
)
1641 * Unable to connect...
1645 http
->error
= WSAGetLastError();
1647 http
->error
= errno
;
1649 http
->status
= HTTP_ERROR
;
1654 http
->hostaddr
= &(addr
->addr
);
1656 http
->status
= HTTP_CONTINUE
;
1659 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
1662 * Always do encryption via SSL.
1665 if (http_setup_ssl(http
) != 0)
1668 closesocket(http
->fd
);
1676 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
1677 return (http_upgrade(http
));
1678 #endif /* HAVE_SSL */
1685 * 'httpSetCookie()' - Set the cookie value(s)...
1687 * @since CUPS 1.1.19@
1691 httpSetCookie(http_t
*http
, /* I - Connection */
1692 const char *cookie
) /* I - Cookie string */
1701 http
->cookie
= strdup(cookie
);
1703 http
->cookie
= NULL
;
1708 * 'httpSetExpect()' - Set the Expect: header in a request.
1710 * Currently only HTTP_CONTINUE is supported for the "expect" argument.
1716 httpSetExpect(http_t
*http
, /* I - HTTP connection */
1717 http_status_t expect
) /* I - HTTP status to expect (HTTP_CONTINUE) */
1720 http
->expect
= expect
;
1725 * 'httpSetField()' - Set the value of an HTTP header.
1729 httpSetField(http_t
*http
, /* I - HTTP connection */
1730 http_field_t field
, /* I - Field index */
1731 const char *value
) /* I - Value */
1734 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
1735 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
1739 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
1742 * Special case for Authorization: as its contents can be
1743 * longer than HTTP_MAX_VALUE
1746 if (field
== HTTP_FIELD_AUTHORIZATION
)
1748 if (http
->field_authorization
)
1749 free(http
->field_authorization
);
1751 http
->field_authorization
= strdup(value
);
1757 * 'httpSetLength()' - Set the content-length and content-encoding.
1763 httpSetLength(http_t
*http
, /* I - HTTP connection */
1764 size_t length
) /* I - Length (0 for chunked) */
1771 strcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked");
1772 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
1776 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
1777 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
1778 CUPS_LLFMT
, CUPS_LLCAST length
);
1784 * 'httpTrace()' - Send an TRACE request to the server.
1787 int /* O - Status of call (0 = success) */
1788 httpTrace(http_t
*http
, /* I - HTTP connection */
1789 const char *uri
) /* I - URI for trace */
1791 return (http_send(http
, HTTP_TRACE
, uri
));
1796 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1799 http_status_t
/* O - HTTP status */
1800 httpUpdate(http_t
*http
) /* I - HTTP connection */
1802 char line
[32768], /* Line from connection... */
1803 *value
; /* Pointer to value on line */
1804 http_field_t field
; /* Field index */
1805 int major
, minor
, /* HTTP version numbers */
1806 status
; /* Request status */
1809 DEBUG_printf(("httpUpdate(http=%p), state=%d\n", http
, http
->state
));
1812 * Flush pending data, if any...
1817 DEBUG_puts(" flushing buffer...");
1819 if (httpFlushWrite(http
) < 0)
1820 return (HTTP_ERROR
);
1824 * If we haven't issued any commands, then there is nothing to "update"...
1827 if (http
->state
== HTTP_WAITING
)
1828 return (HTTP_CONTINUE
);
1831 * Grab all of the lines we can from the connection...
1834 while (httpGets(line
, sizeof(line
), http
) != NULL
)
1836 DEBUG_printf(("httpUpdate: Got \"%s\"\n", line
));
1838 if (line
[0] == '\0')
1841 * Blank line means the start of the data section (if any). Return
1842 * the result code, too...
1844 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
1845 * Instead, we just return HTTP_CONTINUE to the caller and keep on
1849 if (http
->status
== HTTP_CONTINUE
)
1850 return (http
->status
);
1852 if (http
->status
< HTTP_BAD_REQUEST
)
1853 http
->digest_tries
= 0;
1856 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
1858 if (http_setup_ssl(http
) != 0)
1861 closesocket(http
->fd
);
1866 return (HTTP_ERROR
);
1869 return (HTTP_CONTINUE
);
1871 #endif /* HAVE_SSL */
1873 httpGetLength2(http
);
1875 switch (http
->state
)
1879 case HTTP_POST_RECV
:
1882 case HTTP_POST_SEND
:
1887 http
->state
= HTTP_WAITING
;
1891 return (http
->status
);
1893 else if (strncmp(line
, "HTTP/", 5) == 0)
1896 * Got the beginning of a response...
1899 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &status
) != 3)
1900 return (HTTP_ERROR
);
1902 http
->version
= (http_version_t
)(major
* 100 + minor
);
1903 http
->status
= (http_status_t
)status
;
1905 else if ((value
= strchr(line
, ':')) != NULL
)
1912 while (isspace(*value
& 255))
1916 * Be tolerants of servers that send unknown attribute fields...
1919 if (!strcasecmp(line
, "expect"))
1922 * "Expect: 100-continue" or similar...
1925 http
->expect
= (http_status_t
)atoi(value
);
1927 else if (!strcasecmp(line
, "cookie"))
1930 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
1933 httpSetCookie(http
, value
);
1935 else if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
1937 DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line
));
1941 httpSetField(http
, field
, value
);
1945 http
->status
= HTTP_ERROR
;
1946 return (HTTP_ERROR
);
1951 * See if there was an error...
1954 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
1955 return (http
->status
);
1959 DEBUG_printf(("httpUpdate: socket error %d - %s\n", http
->error
,
1960 strerror(http
->error
)));
1961 http
->status
= HTTP_ERROR
;
1962 return (HTTP_ERROR
);
1966 * If we haven't already returned, then there is nothing new...
1969 return (HTTP_CONTINUE
);
1974 * 'httpWait()' - Wait for data available on a connection.
1976 * @since CUPS 1.1.19@
1979 int /* O - 1 if data is available, 0 otherwise */
1980 httpWait(http_t
*http
, /* I - HTTP connection */
1981 int msec
) /* I - Milliseconds to wait */
1984 * First see if there is data in the buffer...
1994 * Flush pending data, if any...
1999 if (httpFlushWrite(http
) < 0)
2004 * If not, check the SSL/TLS buffers and do a select() on the connection...
2007 return (http_wait(http
, msec
, 1));
2012 * 'httpWrite()' - Write data to a HTTP connection.
2014 * This function is deprecated. Use the httpWrite2() function which can
2015 * write more than 2GB of data.
2020 int /* O - Number of bytes written */
2021 httpWrite(http_t
*http
, /* I - HTTP connection */
2022 const char *buffer
, /* I - Buffer for data */
2023 int length
) /* I - Number of bytes to write */
2025 return ((int)httpWrite2(http
, buffer
, length
));
2030 * 'httpWrite2()' - Write data to a HTTP connection.
2035 ssize_t
/* O - Number of bytes written */
2036 httpWrite2(http_t
*http
, /* I - HTTP connection */
2037 const char *buffer
, /* I - Buffer for data */
2038 size_t length
) /* I - Number of bytes to write */
2040 ssize_t bytes
; /* Bytes written */
2043 DEBUG_printf(("httpWrite(http=%p, buffer=%p, length=%d)\n", http
,
2047 * Range check input...
2050 if (http
== NULL
|| buffer
== NULL
)
2054 * Mark activity on the connection...
2057 http
->activity
= time(NULL
);
2060 * Buffer small writes for better performance...
2065 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
2067 DEBUG_printf((" flushing buffer (wused=%d, length=%d)\n",
2068 http
->wused
, length
));
2070 httpFlushWrite(http
);
2073 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
))
2076 * Write to buffer...
2079 DEBUG_printf((" copying %d bytes to wbuffer...\n", length
));
2081 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
2082 http
->wused
+= (int)length
;
2083 bytes
= (ssize_t
)length
;
2088 * Otherwise write the data directly...
2091 DEBUG_printf((" writing %d bytes to socket...\n", length
));
2093 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2094 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
2096 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
2098 DEBUG_printf((" wrote %d bytes...\n", bytes
));
2101 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
2102 http
->data_remaining
-= bytes
;
2108 * Handle end-of-request processing...
2111 if ((http
->data_encoding
== HTTP_ENCODE_CHUNKED
&& length
== 0) ||
2112 (http
->data_encoding
== HTTP_ENCODE_LENGTH
&& http
->data_remaining
== 0))
2115 * Finished with the transfer; unless we are sending POST or PUT
2119 DEBUG_puts("httpWrite: changing states...");
2122 httpFlushWrite(http
);
2124 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2127 * Send a 0-length chunk at the end of the request...
2130 http_write(http
, "0\r\n\r\n", 5);
2133 * Reset the data state...
2136 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
2137 http
->data_remaining
= 0;
2140 if (http
->state
== HTTP_POST_RECV
)
2142 else if (http
->state
== HTTP_PUT_RECV
)
2143 http
->state
= HTTP_STATUS
;
2145 http
->state
= HTTP_WAITING
;
2152 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2154 * '_httpWriteCDSA()' - Write function for the CDSA library.
2157 OSStatus
/* O - -1 on error, 0 on success */
2159 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2160 const void *data
, /* I - Data buffer */
2161 size_t *dataLength
) /* IO - Number of bytes */
2163 OSStatus result
; /* Return value */
2164 ssize_t bytes
; /* Number of bytes read */
2165 http_t
*http
; /* HTTP connection */
2168 http
= (http_t
*)connection
;
2172 bytes
= write(http
->fd
, data
, *dataLength
);
2174 while (bytes
== -1 && errno
== EINTR
);
2176 if (bytes
== *dataLength
)
2180 else if (bytes
>= 0)
2182 *dataLength
= bytes
;
2183 result
= errSSLWouldBlock
;
2189 if (errno
== EAGAIN
)
2190 result
= errSSLWouldBlock
;
2192 result
= errSSLClosedAbort
;
2197 #endif /* HAVE_SSL && HAVE_CDSASSL */
2200 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2202 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
2205 ssize_t
/* O - Number of bytes written or -1 on error */
2207 gnutls_transport_ptr ptr
, /* I - HTTP connection */
2208 const void *data
, /* I - Data buffer */
2209 size_t length
) /* I - Number of bytes to write */
2211 return (send(((http_t
*)ptr
)->fd
, data
, length
, 0));
2213 #endif /* HAVE_SSL && HAVE_GNUTLS */
2216 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
2218 * 'http_bio_ctrl()' - Control the HTTP connection.
2221 static long /* O - Result/data */
2222 http_bio_ctrl(BIO
*h
, /* I - BIO data */
2223 int cmd
, /* I - Control command */
2224 long arg1
, /* I - First argument */
2225 void *arg2
) /* I - Second argument */
2232 case BIO_CTRL_RESET
:
2236 case BIO_C_SET_FILE_PTR
:
2241 case BIO_C_GET_FILE_PTR
:
2244 *((void **)arg2
) = h
->ptr
;
2251 case BIO_CTRL_FLUSH
:
2258 * 'http_bio_free()' - Free OpenSSL data.
2261 static int /* O - 1 on success, 0 on failure */
2262 http_bio_free(BIO
*h
) /* I - BIO data */
2278 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
2281 static int /* O - 1 on success, 0 on failure */
2282 http_bio_new(BIO
*h
) /* I - BIO data */
2297 * 'http_bio_puts()' - Send a string for OpenSSL.
2300 static int /* O - Bytes written */
2301 http_bio_puts(BIO
*h
, /* I - BIO data */
2302 const char *str
) /* I - String to write */
2305 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
2307 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
2313 * 'http_bio_read()' - Read data for OpenSSL.
2316 static int /* O - Bytes read */
2317 http_bio_read(BIO
*h
, /* I - BIO data */
2318 char *buf
, /* I - Buffer */
2319 int size
) /* I - Number of bytes to read */
2321 http_t
*http
; /* HTTP connection */
2324 http
= (http_t
*)h
->ptr
;
2326 if (!http
->blocking
)
2329 * Make sure we have data before we read...
2332 if (!http_wait(http
, 10000, 0))
2335 http
->error
= WSAETIMEDOUT
;
2337 http
->error
= ETIMEDOUT
;
2344 return (recv(http
->fd
, buf
, size
, 0));
2349 * 'http_bio_write()' - Write data for OpenSSL.
2352 static int /* O - Bytes written */
2353 http_bio_write(BIO
*h
, /* I - BIO data */
2354 const char *buf
, /* I - Buffer to write */
2355 int num
) /* I - Number of bytes to write */
2357 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
2359 #endif /* HAVE_SSL && HAVE_LIBSSL */
2363 * 'http_field()' - Return the field index for a field name.
2366 static http_field_t
/* O - Field index */
2367 http_field(const char *name
) /* I - String name */
2369 int i
; /* Looping var */
2372 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2373 if (strcasecmp(name
, http_fields
[i
]) == 0)
2374 return ((http_field_t
)i
);
2376 return (HTTP_FIELD_UNKNOWN
);
2382 * 'http_read_ssl()' - Read from a SSL/TLS connection.
2385 static int /* O - Bytes read */
2386 http_read_ssl(http_t
*http
, /* I - HTTP connection */
2387 char *buf
, /* I - Buffer to store data */
2388 int len
) /* I - Length of buffer */
2390 # if defined(HAVE_LIBSSL)
2391 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
2393 # elif defined(HAVE_GNUTLS)
2394 return (gnutls_record_recv(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
2396 # elif defined(HAVE_CDSASSL)
2397 int result
; /* Return value */
2398 OSStatus error
; /* Error info */
2399 size_t processed
; /* Number of bytes processed */
2402 error
= SSLRead(((http_tls_t
*)http
->tls
)->session
, buf
, len
, &processed
);
2407 result
= (int)processed
;
2409 case errSSLClosedGraceful
:
2412 case errSSLWouldBlock
:
2414 result
= (int)processed
;
2428 # endif /* HAVE_LIBSSL */
2430 #endif /* HAVE_SSL */
2434 * 'http_send()' - Send a request with all fields and the trailing blank line.
2437 static int /* O - 0 on success, non-zero on error */
2438 http_send(http_t
*http
, /* I - HTTP connection */
2439 http_state_t request
, /* I - Request code */
2440 const char *uri
) /* I - URI */
2442 int i
; /* Looping var */
2443 char *ptr
, /* Pointer in buffer */
2444 buf
[1024]; /* Encoded URI buffer */
2445 static const char * const codes
[] =
2446 { /* Request code strings */
2461 static const char hex
[] = "0123456789ABCDEF";
2465 DEBUG_printf(("http_send(http=%p, request=HTTP_%s, uri=\"%s\")\n",
2466 http
, codes
[request
], uri
));
2468 if (http
== NULL
|| uri
== NULL
)
2472 * Set the User-Agent field if it isn't already...
2475 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
2476 httpSetField(http
, HTTP_FIELD_USER_AGENT
, CUPS_MINIMAL
);
2479 * Encode the URI as needed...
2482 for (ptr
= buf
; *uri
!= '\0' && ptr
< (buf
+ sizeof(buf
) - 1); uri
++)
2483 if (*uri
<= ' ' || *uri
>= 127)
2485 if (ptr
< (buf
+ sizeof(buf
) - 1))
2487 if (ptr
< (buf
+ sizeof(buf
) - 1))
2488 *ptr
++ = hex
[(*uri
>> 4) & 15];
2489 if (ptr
< (buf
+ sizeof(buf
) - 1))
2490 *ptr
++ = hex
[*uri
& 15];
2498 * See if we had an error the last time around; if so, reconnect...
2501 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
2502 if (httpReconnect(http
))
2506 * Flush any written data that is pending...
2510 httpFlushWrite(http
);
2513 * Send the request header...
2516 http
->state
= request
;
2517 http
->data_encoding
= HTTP_ENCODE_FIELDS
;
2519 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
2522 http
->status
= HTTP_CONTINUE
;
2525 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
2527 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
2528 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
2530 #endif /* HAVE_SSL */
2532 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
2534 http
->status
= HTTP_ERROR
;
2538 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2539 if (http
->fields
[i
][0] != '\0')
2541 DEBUG_printf(("%s: %s\n", http_fields
[i
], httpGetField(http
, i
)));
2543 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
],
2544 httpGetField(http
, i
)) < 1)
2546 http
->status
= HTTP_ERROR
;
2552 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
2554 http
->status
= HTTP_ERROR
;
2558 if (http
->expect
== HTTP_CONTINUE
&&
2559 (http
->state
== HTTP_POST_RECV
|| http
->state
== HTTP_PUT_RECV
))
2560 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
2562 http
->status
= HTTP_ERROR
;
2566 if (httpPrintf(http
, "\r\n") < 1)
2568 http
->status
= HTTP_ERROR
;
2572 httpFlushWrite(http
);
2573 httpGetLength2(http
);
2574 httpClearFields(http
);
2577 * The Kerberos authentication string can only be used once...
2580 if (http
->authstring
&& !strncmp(http
->authstring
, "Negotiate", 9))
2582 http
->_authstring
[0] = '\0';
2584 if (http
->authstring
!= http
->_authstring
)
2585 free(http
->authstring
);
2587 http
->authstring
= http
->_authstring
;
2596 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
2599 static int /* O - Status of connection */
2600 http_setup_ssl(http_t
*http
) /* I - HTTP connection */
2603 SSL_CTX
*context
; /* Context for encryption */
2604 SSL
*conn
; /* Connection for encryption */
2605 BIO
*bio
; /* BIO data */
2606 # elif defined(HAVE_GNUTLS)
2607 http_tls_t
*conn
; /* TLS session object */
2608 gnutls_certificate_client_credentials
*credentials
;
2609 /* TLS credentials */
2610 # elif defined(HAVE_CDSASSL)
2611 OSStatus error
; /* Error code */
2612 http_tls_t
*conn
; /* CDSA connection information */
2613 # endif /* HAVE_LIBSSL */
2616 DEBUG_printf(("http_setup_ssl(http=%p)\n", http
));
2619 context
= SSL_CTX_new(SSLv23_client_method());
2621 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
2623 bio
= BIO_new(_httpBIOMethods());
2624 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
2626 conn
= SSL_new(context
);
2627 SSL_set_bio(conn
, bio
, bio
);
2629 if (SSL_connect(conn
) != 1)
2632 unsigned long error
; /* Error code */
2634 while ((error
= ERR_get_error()) != 0)
2635 printf("http_setup_ssl: %s\n", ERR_error_string(error
, NULL
));
2638 SSL_CTX_free(context
);
2642 http
->error
= WSAGetLastError();
2644 http
->error
= errno
;
2646 http
->status
= HTTP_ERROR
;
2648 return (HTTP_ERROR
);
2651 # elif defined(HAVE_GNUTLS)
2652 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
2654 http
->error
= errno
;
2655 http
->status
= HTTP_ERROR
;
2660 credentials
= (gnutls_certificate_client_credentials
*)
2661 malloc(sizeof(gnutls_certificate_client_credentials
));
2662 if (credentials
== NULL
)
2666 http
->error
= errno
;
2667 http
->status
= HTTP_ERROR
;
2672 gnutls_certificate_allocate_credentials(credentials
);
2674 gnutls_init(&(conn
->session
), GNUTLS_CLIENT
);
2675 gnutls_set_default_priority(conn
->session
);
2676 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
2677 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)http
);
2678 gnutls_transport_set_pull_function(conn
->session
, _httpReadGNUTLS
);
2679 gnutls_transport_set_push_function(conn
->session
, _httpWriteGNUTLS
);
2681 if ((gnutls_handshake(conn
->session
)) != GNUTLS_E_SUCCESS
)
2683 http
->error
= errno
;
2684 http
->status
= HTTP_ERROR
;
2689 conn
->credentials
= credentials
;
2691 # elif defined(HAVE_CDSASSL)
2692 conn
= (http_tls_t
*)calloc(1, sizeof(http_tls_t
));
2697 if ((error
= SSLNewContext(false, &conn
->session
)))
2699 http
->error
= error
;
2700 http
->status
= HTTP_ERROR
;
2707 * Use a union to resolve warnings about int/pointer size mismatches...
2710 error
= SSLSetConnection(conn
->session
, http
);
2713 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
2716 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
2719 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
2722 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
2726 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
2732 http
->error
= error
;
2733 http
->status
= HTTP_ERROR
;
2735 SSLDisposeContext(conn
->session
);
2741 # endif /* HAVE_CDSASSL */
2746 #endif /* HAVE_SSL */
2751 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
2755 http_shutdown_ssl(http_t
*http
) /* I - HTTP connection */
2758 SSL_CTX
*context
; /* Context for encryption */
2759 SSL
*conn
; /* Connection for encryption */
2762 conn
= (SSL
*)(http
->tls
);
2763 context
= SSL_get_SSL_CTX(conn
);
2766 SSL_CTX_free(context
);
2769 # elif defined(HAVE_GNUTLS)
2770 http_tls_t
*conn
; /* Encryption session */
2771 gnutls_certificate_client_credentials
*credentials
;
2772 /* TLS credentials */
2775 conn
= (http_tls_t
*)(http
->tls
);
2776 credentials
= (gnutls_certificate_client_credentials
*)(conn
->credentials
);
2778 gnutls_bye(conn
->session
, GNUTLS_SHUT_RDWR
);
2779 gnutls_deinit(conn
->session
);
2780 gnutls_certificate_free_credentials(*credentials
);
2784 # elif defined(HAVE_CDSASSL)
2785 http_tls_t
*conn
; /* CDSA connection information */
2788 conn
= (http_tls_t
*)(http
->tls
);
2790 while (SSLClose(conn
->session
) == errSSLWouldBlock
)
2793 SSLDisposeContext(conn
->session
);
2795 if (conn
->certsArray
)
2796 CFRelease(conn
->certsArray
);
2799 # endif /* HAVE_LIBSSL */
2803 #endif /* HAVE_SSL */
2808 * 'http_upgrade()' - Force upgrade to TLS encryption.
2811 static int /* O - Status of connection */
2812 http_upgrade(http_t
*http
) /* I - HTTP connection */
2814 int ret
; /* Return value */
2815 http_t myhttp
; /* Local copy of HTTP data */
2818 DEBUG_printf(("http_upgrade(%p)\n", http
));
2821 * Copy the HTTP data to a local variable so we can do the OPTIONS
2822 * request without interfering with the existing request data...
2825 memcpy(&myhttp
, http
, sizeof(myhttp
));
2828 * Send an OPTIONS request to the server, requiring SSL or TLS
2829 * encryption on the link...
2832 http
->field_authorization
= NULL
; /* Don't free the auth string */
2834 httpClearFields(http
);
2835 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
2836 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0, SSL/2.0, SSL/3.0");
2838 if ((ret
= httpOptions(http
, "*")) == 0)
2841 * Wait for the secure connection...
2844 while (httpUpdate(http
) == HTTP_CONTINUE
);
2850 * Restore the HTTP request data...
2853 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
2854 http
->data_encoding
= myhttp
.data_encoding
;
2855 http
->data_remaining
= myhttp
.data_remaining
;
2856 http
->_data_remaining
= myhttp
._data_remaining
;
2857 http
->expect
= myhttp
.expect
;
2858 http
->field_authorization
= myhttp
.field_authorization
;
2861 * See if we actually went secure...
2867 * Server does not support HTTP upgrade...
2870 DEBUG_puts("Server does not support HTTP upgrade!");
2873 closesocket(http
->fd
);
2885 #endif /* HAVE_SSL */
2889 * 'http_wait()' - Wait for data available on a connection.
2892 static int /* O - 1 if data is available, 0 otherwise */
2893 http_wait(http_t
*http
, /* I - HTTP connection */
2894 int msec
, /* I - Milliseconds to wait */
2895 int usessl
) /* I - Use SSL context? */
2898 struct pollfd pfd
; /* Polled file descriptor */
2900 fd_set input_set
; /* select() input set */
2901 struct timeval timeout
; /* Timeout */
2902 #endif /* HAVE_POLL */
2903 int nfds
; /* Result from select()/poll() */
2906 DEBUG_printf(("http_wait(http=%p, msec=%d)\n", http
, msec
));
2912 * Check the SSL/TLS buffers for data first...
2916 if (http
->tls
&& usessl
)
2919 if (SSL_pending((SSL
*)(http
->tls
)))
2921 # elif defined(HAVE_GNUTLS)
2922 if (gnutls_record_check_pending(((http_tls_t
*)(http
->tls
))->session
))
2924 # elif defined(HAVE_CDSASSL)
2925 size_t bytes
; /* Bytes that are available */
2927 if (!SSLGetBufferedReadSize(((http_tls_t
*)http
->tls
)->session
, &bytes
) && bytes
> 0)
2929 # endif /* HAVE_LIBSSL */
2931 #endif /* HAVE_SSL */
2934 * Then try doing a select() or poll() to poll the socket...
2939 pfd
.events
= POLLIN
;
2941 while ((nfds
= poll(&pfd
, 1, msec
)) < 0 && errno
== EINTR
);
2946 FD_ZERO(&input_set
);
2947 FD_SET(http
->fd
, &input_set
);
2949 DEBUG_printf(("http_wait: msec=%d, http->fd=%d\n", msec
, http
->fd
));
2953 timeout
.tv_sec
= msec
/ 1000;
2954 timeout
.tv_usec
= (msec
% 1000) * 1000;
2956 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
2959 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
2961 DEBUG_printf(("http_wait: select() returned %d...\n", nfds
));
2964 while (nfds
< 0 && WSAGetLastError() == WSAEINTR
);
2966 while (nfds
< 0 && errno
== EINTR
);
2968 #endif /* HAVE_POLL */
2970 DEBUG_printf(("http_wait: returning with nfds=%d...\n", nfds
));
2977 * 'http_write()' - Write a buffer to a HTTP connection.
2980 static int /* O - Number of bytes written */
2981 http_write(http_t
*http
, /* I - HTTP connection */
2982 const char *buffer
, /* I - Buffer for data */
2983 int length
) /* I - Number of bytes to write */
2985 int tbytes
, /* Total bytes sent */
2986 bytes
; /* Bytes sent */
2995 bytes
= http_write_ssl(http
, buffer
, length
);
2997 #endif /* HAVE_SSL */
2998 bytes
= send(http
->fd
, buffer
, length
, 0);
3003 if (WSAGetLastError() != http
->error
)
3005 http
->error
= WSAGetLastError();
3011 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
3013 http
->error
= errno
;
3018 DEBUG_puts("http_write: error writing data...\n");
3031 printf("http_write: wrote %d bytes: \n", tbytes
);
3032 for (i
= 0, buffer
-= tbytes
; i
< tbytes
; i
+= 16)
3036 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
3037 printf(" %02X", buffer
[i
+ j
] & 255);
3046 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
3048 ch
= buffer
[i
+ j
] & 255;
3050 if (ch
< ' ' || ch
== 127)
3065 * 'http_write_chunk()' - Write a chunked buffer.
3068 static int /* O - Number bytes written */
3069 http_write_chunk(http_t
*http
, /* I - HTTP connection */
3070 const char *buffer
, /* I - Buffer to write */
3071 int length
) /* I - Length of buffer */
3073 char header
[255]; /* Chunk header */
3074 int bytes
; /* Bytes written */
3076 DEBUG_printf(("http_write_chunk(http=%p, buffer=%p, length=%d)\n",
3077 http
, buffer
, length
));
3080 * Write the chunk header, data, and trailer.
3083 sprintf(header
, "%x\r\n", length
);
3084 if (http_write(http
, header
, (int)strlen(header
)) < 0)
3086 DEBUG_puts(" http_write of length failed!");
3090 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
3092 DEBUG_puts(" http_write of buffer failed!");
3096 if (http_write(http
, "\r\n", 2) < 0)
3098 DEBUG_puts(" http_write of CR LF failed!");
3108 * 'http_write_ssl()' - Write to a SSL/TLS connection.
3111 static int /* O - Bytes written */
3112 http_write_ssl(http_t
*http
, /* I - HTTP connection */
3113 const char *buf
, /* I - Buffer holding data */
3114 int len
) /* I - Length of buffer */
3116 # if defined(HAVE_LIBSSL)
3117 return (SSL_write((SSL
*)(http
->tls
), buf
, len
));
3119 # elif defined(HAVE_GNUTLS)
3120 return (gnutls_record_send(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
3121 # elif defined(HAVE_CDSASSL)
3122 int result
; /* Return value */
3123 OSStatus error
; /* Error info */
3124 size_t processed
; /* Number of bytes processed */
3127 error
= SSLWrite(((http_tls_t
*)http
->tls
)->session
, buf
, len
, &processed
);
3132 result
= (int)processed
;
3134 case errSSLClosedGraceful
:
3137 case errSSLWouldBlock
:
3139 result
= (int)processed
;
3153 # endif /* HAVE_LIBSSL */
3155 #endif /* HAVE_SSL */
3159 * End of "$Id: http.c 6285 2007-02-16 01:10:55Z mike $".