2 * "$Id: http.c 6191 2007-01-10 16:48:37Z mike $"
4 * HTTP routines for the Common UNIX Printing System (CUPS).
6 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
8 * These coded instructions, statements, and computer programs are the
9 * property of Easy Software Products and are protected by Federal
10 * copyright law. Distribution and use rights are outlined in the file
11 * "LICENSE.txt" which should have been included with this file. If this
12 * file is missing or damaged please contact Easy Software Products
15 * Attn: CUPS Licensing Information
16 * Easy Software Products
17 * 44141 Airport View Drive, Suite 204
18 * Hollywood, Maryland 20636 USA
20 * Voice: (301) 373-9600
21 * EMail: cups-info@cups.org
22 * WWW: http://www.cups.org
24 * This file is subject to the Apple OS-Developed Software exception.
28 * _httpBIOMethods() - Get the OpenSSL BIO methods for HTTP connections.
29 * httpBlocking() - Set blocking/non-blocking behavior on a connection.
30 * httpCheck() - Check to see if there is a pending response from
32 * httpClearCookie() - Clear the cookie value(s).
33 * httpClearFields() - Clear HTTP request fields.
34 * httpClose() - Close an HTTP connection...
35 * httpConnect() - Connect to a HTTP server.
36 * httpConnectEncrypt() - Connect to a HTTP server using encryption.
37 * httpDelete() - Send a DELETE request to the server.
38 * httpEncryption() - Set the required encryption on the link.
39 * httpError() - Get the last error on a connection.
40 * httpFlush() - Flush data from a HTTP connection.
41 * httpFlushWrite() - Flush data in write buffer.
42 * httpGet() - Send a GET request to the server.
43 * httpGetBlocking() - Get the blocking/non-block state of a connection.
44 * httpGetCookie() - Get any cookie data from the response.
45 * httpGetFd() - Get the file descriptor associated with a
47 * httpGetField() - Get a field value from a request/response.
48 * httpGetLength() - Get the amount of data remaining from the
49 * content-length or transfer-encoding fields.
50 * httpGetLength2() - Get the amount of data remaining from the
51 * content-length or transfer-encoding fields.
52 * httpGetStatus() - Get the status of the last HTTP request.
53 * httpGetSubField() - Get a sub-field value.
54 * httpGets() - Get a line of text from a HTTP connection.
55 * httpHead() - Send a HEAD request to the server.
56 * httpInitialize() - Initialize the HTTP interface library and set the
57 * default HTTP proxy (if any).
58 * httpOptions() - Send an OPTIONS request to the server.
59 * httpPost() - Send a POST request to the server.
60 * httpPrintf() - Print a formatted string to a HTTP connection.
61 * httpPut() - Send a PUT request to the server.
62 * httpRead() - Read data from a HTTP connection.
63 * httpRead2() - Read data from a HTTP connection.
64 * _httpReadCDSA() - Read function for the CDSA library.
65 * _httpReadGNUTLS() - Read function for the GNU TLS library.
66 * httpReconnect() - Reconnect to a HTTP server...
67 * httpSetCookie() - Set the cookie value(s)...
68 * httpSetExpect() - Set the Expect: header in a request.
69 * httpSetField() - Set the value of an HTTP header.
70 * httpSetLength() - Set the content-length and transfer-encoding.
71 * httpTrace() - Send an TRACE request to the server.
72 * httpUpdate() - Update the current HTTP state for incoming data.
73 * httpWait() - Wait for data available on a connection.
74 * httpWrite() - Write data to a HTTP connection.
75 * httpWrite2() - Write data to a HTTP connection.
76 * _httpWriteCDSA() - Write function for the CDSA library.
77 * _httpWriteGNUTLS() - Write function for the GNU TLS library.
78 * http_bio_ctrl() - Control the HTTP connection.
79 * http_bio_free() - Free OpenSSL data.
80 * http_bio_new() - Initialize an OpenSSL BIO structure.
81 * http_bio_puts() - Send a string for OpenSSL.
82 * http_bio_read() - Read data for OpenSSL.
83 * http_bio_write() - Write data for OpenSSL.
84 * http_field() - Return the field index for a field name.
85 * http_read_ssl() - Read from a SSL/TLS connection.
86 * http_send() - Send a request with all fields and the trailing
88 * http_setup_ssl() - Set up SSL/TLS on a connection.
89 * http_shutdown_ssl() - Shut down SSL/TLS on a connection.
90 * http_upgrade() - Force upgrade to TLS encryption.
91 * http_wait() - Wait for data available on a connection.
92 * http_write() - Write data to a connection.
93 * http_write_ssl() - Write to a SSL/TLS connection.
97 * Include necessary headers...
100 #include "http-private.h"
108 # include <sys/time.h>
109 # include <sys/resource.h>
114 * Some operating systems have done away with the Fxxxx constants for
115 * the fcntl() call; this works around that "feature"...
119 # define FNONBLK O_NONBLOCK
120 #endif /* !FNONBLK */
127 static http_field_t
http_field(const char *name
);
128 static int http_send(http_t
*http
, http_state_t request
,
130 static int http_wait(http_t
*http
, int msec
, int usessl
);
131 static int http_write(http_t
*http
, const char *buffer
,
133 static int http_write_chunk(http_t
*http
, const char *buffer
,
136 static int http_read_ssl(http_t
*http
, char *buf
, int len
);
137 static int http_setup_ssl(http_t
*http
);
138 static void http_shutdown_ssl(http_t
*http
);
139 static int http_upgrade(http_t
*http
);
140 static int http_write_ssl(http_t
*http
, const char *buf
, int len
);
141 #endif /* HAVE_SSL */
148 static const char * const http_fields
[] =
165 "If-Unmodified-since",
180 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
182 * BIO methods for OpenSSL...
185 static int http_bio_write(BIO
*h
, const char *buf
, int num
);
186 static int http_bio_read(BIO
*h
, char *buf
, int size
);
187 static int http_bio_puts(BIO
*h
, const char *str
);
188 static long http_bio_ctrl(BIO
*h
, int cmd
, long arg1
, void *arg2
);
189 static int http_bio_new(BIO
*h
);
190 static int http_bio_free(BIO
*data
);
192 static BIO_METHOD http_bio_methods
=
199 NULL
, /* http_bio_gets, */
208 * '_httpBIOMethods()' - Get the OpenSSL BIO methods for HTTP connections.
211 BIO_METHOD
* /* O - BIO methods for OpenSSL */
212 _httpBIOMethods(void)
214 return (&http_bio_methods
);
216 #endif /* HAVE_SSL && HAVE_LIBSSL */
220 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
224 httpBlocking(http_t
*http
, /* I - HTTP connection */
225 int b
) /* I - 1 = blocking, 0 = non-blocking */
233 * 'httpCheck()' - Check to see if there is a pending response from the server.
236 int /* O - 0 = no data, 1 = data available */
237 httpCheck(http_t
*http
) /* I - HTTP connection */
239 return (httpWait(http
, 0));
244 * 'httpClearCookie()' - Clear the cookie value(s).
246 * @since CUPS 1.1.19@
250 httpClearCookie(http_t
*http
) /* I - HTTP connection */
264 * 'httpClearFields()' - Clear HTTP request fields.
268 httpClearFields(http_t
*http
) /* I - HTTP connection */
272 memset(http
->fields
, 0, sizeof(http
->fields
));
273 if (http
->hostname
[0] == '/')
274 httpSetField(http
, HTTP_FIELD_HOST
, "localhost");
276 httpSetField(http
, HTTP_FIELD_HOST
, http
->hostname
);
278 http
->expect
= (http_status_t
)0;
284 * 'httpClose()' - Close an HTTP connection...
288 httpClose(http_t
*http
) /* I - HTTP connection */
290 DEBUG_printf(("httpClose(http=%p)\n", http
));
295 httpAddrFreeList(http
->addrlist
);
298 free(http
->input_set
);
305 http_shutdown_ssl(http
);
306 #endif /* HAVE_SSL */
309 closesocket(http
->fd
);
319 * 'httpConnect()' - Connect to a HTTP server.
322 http_t
* /* O - New HTTP connection */
323 httpConnect(const char *host
, /* I - Host to connect to */
324 int port
) /* I - Port number */
326 http_encryption_t encryption
; /* Type of encryption to use */
330 * Set the default encryption status...
334 encryption
= HTTP_ENCRYPT_ALWAYS
;
336 encryption
= HTTP_ENCRYPT_IF_REQUESTED
;
338 return (httpConnectEncrypt(host
, port
, encryption
));
343 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
346 http_t
* /* O - New HTTP connection */
348 const char *host
, /* I - Host to connect to */
349 int port
, /* I - Port number */
350 http_encryption_t encryption
) /* I - Type of encryption to use */
352 http_t
*http
; /* New HTTP connection */
353 http_addrlist_t
*addrlist
; /* Host address data */
354 char service
[255]; /* Service name */
357 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)\n",
358 host
? host
: "(null)", port
, encryption
));
369 sprintf(service
, "%d", port
);
371 if ((addrlist
= httpAddrGetList(host
, AF_UNSPEC
, service
)) == NULL
)
375 * Allocate memory for the structure...
378 http
= calloc(sizeof(http_t
), 1);
382 http
->version
= HTTP_1_1
;
384 http
->activity
= time(NULL
);
388 * Set the encryption status...
391 if (port
== 443) /* Always use encryption for https */
392 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
394 http
->encryption
= encryption
;
397 * Loop through the addresses we have until one of them connects...
400 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
403 * Connect to the remote system...
406 http
->addrlist
= addrlist
;
408 if (!httpReconnect(http
))
412 * Could not connect to any known address - bail out!
415 httpAddrFreeList(addrlist
);
424 * 'httpDelete()' - Send a DELETE request to the server.
427 int /* O - Status of call (0 = success) */
428 httpDelete(http_t
*http
, /* I - HTTP connection */
429 const char *uri
) /* I - URI to delete */
431 return (http_send(http
, HTTP_DELETE
, uri
));
436 * 'httpEncryption()' - Set the required encryption on the link.
439 int /* O - -1 on error, 0 on success */
440 httpEncryption(http_t
*http
, /* I - HTTP connection */
441 http_encryption_t e
) /* I - New encryption preference */
443 DEBUG_printf(("httpEncryption(http=%p, e=%d)\n", http
, e
));
449 http
->encryption
= e
;
451 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
452 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
453 return (httpReconnect(http
));
454 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
455 return (http_upgrade(http
));
459 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
463 #endif /* HAVE_SSL */
468 * 'httpError()' - Get the last error on a connection.
471 int /* O - Error code (errno) value */
472 httpError(http_t
*http
) /* I - HTTP connection */
475 return (http
->error
);
482 * 'httpFlush()' - Flush data from a HTTP connection.
486 httpFlush(http_t
*http
) /* I - HTTP connection */
488 char buffer
[8192]; /* Junk buffer */
489 int blocking
; /* To block or not to block */
492 DEBUG_printf(("httpFlush(http=%p), state=%d\n", http
, http
->state
));
495 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
498 blocking
= http
->blocking
;
502 * Read any data we can...
505 while (httpRead2(http
, buffer
, sizeof(buffer
)) > 0);
508 * Restore blocking and reset the connection if we didn't get all of
509 * the remaining data...
512 http
->blocking
= blocking
;
514 if (http
->state
!= HTTP_WAITING
&& http
->fd
>= 0)
517 * Didn't get the data back, so close the current connection.
520 http
->state
= HTTP_WAITING
;
524 http_shutdown_ssl(http
);
525 #endif /* HAVE_SSL */
528 closesocket(http
->fd
);
539 * 'httpFlushWrite()' - Flush data in write buffer.
544 int /* O - Bytes written or -1 on error */
545 httpFlushWrite(http_t
*http
) /* I - HTTP connection */
547 int bytes
; /* Bytes written */
550 DEBUG_printf(("httpFlushWrite(http=%p)\n", http
));
552 if (!http
|| !http
->wused
)
555 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
556 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
558 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
567 * 'httpGet()' - Send a GET request to the server.
570 int /* O - Status of call (0 = success) */
571 httpGet(http_t
*http
, /* I - HTTP connection */
572 const char *uri
) /* I - URI to get */
574 return (http_send(http
, HTTP_GET
, uri
));
579 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
584 int /* O - 1 if blocking, 0 if non-blocking */
585 httpGetBlocking(http_t
*http
) /* I - HTTP connection */
587 return (http
? http
->blocking
: 0);
592 * 'httpGetCookie()' - Get any cookie data from the response.
594 * @since CUPS 1.1.19@
597 const char * /* O - Cookie data or NULL */
598 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
600 return (http
? http
->cookie
: NULL
);
605 * 'httpGetFd()' - Get the file descriptor associated with a connection.
610 int /* O - File descriptor or -1 if none */
611 httpGetFd(http_t
*http
) /* I - HTTP connection */
613 return (http
? http
->fd
: -1);
618 * 'httpGetField()' - Get a field value from a request/response.
621 const char * /* O - Field value */
622 httpGetField(http_t
*http
, /* I - HTTP connection */
623 http_field_t field
) /* I - Field to get */
625 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
628 return (http
->fields
[field
]);
633 * 'httpGetLength()' - Get the amount of data remaining from the
634 * content-length or transfer-encoding fields.
636 * This function is deprecated and will not return lengths larger than
637 * 2^31 - 1; use httpGetLength2() instead.
642 int /* O - Content length */
643 httpGetLength(http_t
*http
) /* I - HTTP connection */
646 * Get the read content length and return the 32-bit value.
651 httpGetLength2(http
);
653 return (http
->_data_remaining
);
661 * 'httpGetLength2()' - Get the amount of data remaining from the
662 * content-length or transfer-encoding fields.
664 * This function returns the complete content length, even for
665 * content larger than 2^31 - 1.
670 off_t
/* O - Content length */
671 httpGetLength2(http_t
*http
) /* I - HTTP connection */
673 DEBUG_printf(("httpGetLength2(http=%p), state=%d\n", http
, http
->state
));
678 if (!strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
680 DEBUG_puts("httpGetLength2: chunked request!");
682 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
683 http
->data_remaining
= 0;
687 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
690 * The following is a hack for HTTP servers that don't send a
691 * content-length or transfer-encoding field...
693 * If there is no content-length then the connection must close
694 * after the transfer is complete...
697 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
700 * Default content length is 0 for errors and 2^31-1 for other
701 * successful requests...
704 if (http
->status
>= HTTP_MULTIPLE_CHOICES
)
705 http
->data_remaining
= 0;
707 http
->data_remaining
= 2147483647;
710 http
->data_remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
713 DEBUG_printf(("httpGetLength2: content_length=" CUPS_LLFMT
"\n",
714 CUPS_LLCAST http
->data_remaining
));
717 if (http
->data_remaining
<= INT_MAX
)
718 http
->_data_remaining
= (int)http
->data_remaining
;
720 http
->_data_remaining
= INT_MAX
;
722 return (http
->data_remaining
);
727 * 'httpGetStatus()' - Get the status of the last HTTP request.
732 http_status_t
/* O - HTTP status */
733 httpGetStatus(http_t
*http
) /* I - HTTP connection */
735 return (http
? http
->status
: HTTP_ERROR
);
740 * 'httpGetSubField()' - Get a sub-field value.
745 char * /* O - Value or NULL */
746 httpGetSubField(http_t
*http
, /* I - HTTP connection */
747 http_field_t field
, /* I - Field index */
748 const char *name
, /* I - Name of sub-field */
749 char *value
) /* O - Value string */
751 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
756 * 'httpGetSubField2()' - Get a sub-field value.
761 char * /* O - Value or NULL */
762 httpGetSubField2(http_t
*http
, /* I - HTTP connection */
763 http_field_t field
, /* I - Field index */
764 const char *name
, /* I - Name of sub-field */
765 char *value
, /* O - Value string */
766 int valuelen
) /* I - Size of value buffer */
768 const char *fptr
; /* Pointer into field */
769 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
770 *ptr
, /* Pointer into string buffer */
771 *end
; /* End of value buffer */
773 DEBUG_printf(("httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, valuelen=%d)\n",
774 http
, field
, name
, value
, valuelen
));
776 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
777 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
780 end
= value
+ valuelen
- 1;
782 for (fptr
= http
->fields
[field
]; *fptr
;)
785 * Skip leading whitespace...
788 while (isspace(*fptr
& 255))
798 * Get the sub-field name...
802 *fptr
&& *fptr
!= '=' && !isspace(*fptr
& 255) &&
803 ptr
< (temp
+ sizeof(temp
) - 1);
808 DEBUG_printf(("httpGetSubField: name=\"%s\"\n", temp
));
811 * Skip trailing chars up to the '='...
814 while (isspace(*fptr
& 255))
824 * Skip = and leading whitespace...
829 while (isspace(*fptr
& 255))
835 * Read quoted string...
838 for (ptr
= value
, fptr
++;
839 *fptr
&& *fptr
!= '\"' && ptr
< end
;
844 while (*fptr
&& *fptr
!= '\"')
853 * Read unquoted string...
857 *fptr
&& !isspace(*fptr
& 255) && *fptr
!= ',' && ptr
< end
;
862 while (*fptr
&& !isspace(*fptr
& 255) && *fptr
!= ',')
866 DEBUG_printf(("httpGetSubField: value=\"%s\"\n", value
));
869 * See if this is the one...
872 if (!strcmp(name
, temp
))
883 * 'httpGets()' - Get a line of text from a HTTP connection.
886 char * /* O - Line or NULL */
887 httpGets(char *line
, /* I - Line to read into */
888 int length
, /* I - Max length of buffer */
889 http_t
*http
) /* I - HTTP connection */
891 char *lineptr
, /* Pointer into line */
892 *lineend
, /* End of line */
893 *bufptr
, /* Pointer into input buffer */
894 *bufend
; /* Pointer to end of buffer */
895 int bytes
, /* Number of bytes read */
896 eol
; /* End-of-line? */
899 DEBUG_printf(("httpGets(line=%p, length=%d, http=%p)\n", line
, length
, http
));
901 if (http
== NULL
|| line
== NULL
)
905 * Read a line from the buffer...
909 lineend
= line
+ length
- 1;
912 while (lineptr
< lineend
)
915 * Pre-load the buffer as needed...
924 while (http
->used
== 0)
927 * No newline; see if there is more data to be read...
930 if (!http
->blocking
&& !http_wait(http
, 10000, 1))
932 DEBUG_puts("httpGets: Timed out!");
934 http
->error
= WSAETIMEDOUT
;
936 http
->error
= ETIMEDOUT
;
943 bytes
= http_read_ssl(http
, http
->buffer
+ http
->used
,
944 HTTP_MAX_BUFFER
- http
->used
);
946 #endif /* HAVE_SSL */
947 bytes
= recv(http
->fd
, http
->buffer
+ http
->used
,
948 HTTP_MAX_BUFFER
- http
->used
, 0);
950 DEBUG_printf(("httpGets: read %d bytes...\n", bytes
));
955 * Nope, can't get a line this time...
959 if (WSAGetLastError() != http
->error
)
961 http
->error
= WSAGetLastError();
965 DEBUG_printf(("httpGets: recv() error %d!\n", WSAGetLastError()));
967 DEBUG_printf(("httpGets: recv() error %d!\n", errno
));
971 else if (errno
!= http
->error
)
988 * Yup, update the amount used...
995 * Now copy as much of the current line as possible...
998 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
999 lineptr
< lineend
&& bufptr
< bufend
;)
1001 if (*bufptr
== 0x0a)
1007 else if (*bufptr
== 0x0d)
1010 *lineptr
++ = *bufptr
++;
1013 http
->used
-= (int)(bufptr
- http
->buffer
);
1015 memmove(http
->buffer
, bufptr
, http
->used
);
1023 http
->activity
= time(NULL
);
1027 DEBUG_printf(("httpGets: Returning \"%s\"\n", line
));
1033 DEBUG_puts("httpGets: No new line available!");
1040 * 'httpHead()' - Send a HEAD request to the server.
1043 int /* O - Status of call (0 = success) */
1044 httpHead(http_t
*http
, /* I - HTTP connection */
1045 const char *uri
) /* I - URI for head */
1047 return (http_send(http
, HTTP_HEAD
, uri
));
1052 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1053 * default HTTP proxy (if any).
1057 httpInitialize(void)
1061 struct timeval curtime
; /* Current time in microseconds */
1062 # endif /* !WIN32 */
1063 int i
; /* Looping var */
1064 unsigned char data
[1024]; /* Seed data */
1065 #endif /* HAVE_LIBSSL */
1068 WSADATA winsockdata
; /* WinSock data */
1069 static int initialized
= 0; /* Has WinSock been initialized? */
1073 WSAStartup(MAKEWORD(1,1), &winsockdata
);
1074 #elif !defined(SO_NOSIGPIPE)
1076 * Ignore SIGPIPE signals...
1080 sigset(SIGPIPE
, SIG_IGN
);
1081 # elif defined(HAVE_SIGACTION)
1082 struct sigaction action
; /* POSIX sigaction data */
1085 memset(&action
, 0, sizeof(action
));
1086 action
.sa_handler
= SIG_IGN
;
1087 sigaction(SIGPIPE
, &action
, NULL
);
1089 signal(SIGPIPE
, SIG_IGN
);
1090 # endif /* !SO_NOSIGPIPE */
1094 gnutls_global_init();
1095 #endif /* HAVE_GNUTLS */
1098 SSL_load_error_strings();
1102 * Using the current time is a dubious random seed, but on some systems
1103 * it is the best we can do (on others, this seed isn't even used...)
1108 gettimeofday(&curtime
, NULL
);
1109 srand(curtime
.tv_sec
+ curtime
.tv_usec
);
1112 for (i
= 0; i
< sizeof(data
); i
++)
1113 data
[i
] = rand(); /* Yes, this is a poor source of random data... */
1115 RAND_seed(&data
, sizeof(data
));
1116 #endif /* HAVE_LIBSSL */
1121 * 'httpOptions()' - Send an OPTIONS request to the server.
1124 int /* O - Status of call (0 = success) */
1125 httpOptions(http_t
*http
, /* I - HTTP connection */
1126 const char *uri
) /* I - URI for options */
1128 return (http_send(http
, HTTP_OPTIONS
, uri
));
1133 * 'httpPost()' - Send a POST request to the server.
1136 int /* O - Status of call (0 = success) */
1137 httpPost(http_t
*http
, /* I - HTTP connection */
1138 const char *uri
) /* I - URI for post */
1140 return (http_send(http
, HTTP_POST
, uri
));
1145 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1150 int /* O - Number of bytes written */
1151 httpPrintf(http_t
*http
, /* I - HTTP connection */
1152 const char *format
, /* I - printf-style format string */
1153 ...) /* I - Additional args as needed */
1155 int bytes
; /* Number of bytes to write */
1156 char buf
[16384]; /* Buffer for formatted string */
1157 va_list ap
; /* Variable argument pointer */
1160 DEBUG_printf(("httpPrintf(http=%p, format=\"%s\", ...)\n", http
, format
));
1162 va_start(ap
, format
);
1163 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1166 DEBUG_printf(("httpPrintf: %s", buf
));
1168 if (http
->data_encoding
== HTTP_ENCODE_FIELDS
)
1169 return (httpWrite2(http
, buf
, bytes
));
1174 DEBUG_puts(" flushing existing data...");
1176 if (httpFlushWrite(http
) < 0)
1180 return (http_write(http
, buf
, bytes
));
1186 * 'httpPut()' - Send a PUT request to the server.
1189 int /* O - Status of call (0 = success) */
1190 httpPut(http_t
*http
, /* I - HTTP connection */
1191 const char *uri
) /* I - URI to put */
1193 return (http_send(http
, HTTP_PUT
, uri
));
1198 * 'httpRead()' - Read data from a HTTP connection.
1200 * This function is deprecated. Use the httpRead2() function which can
1201 * read more than 2GB of data.
1206 int /* O - Number of bytes read */
1207 httpRead(http_t
*http
, /* I - HTTP connection */
1208 char *buffer
, /* I - Buffer for data */
1209 int length
) /* I - Maximum number of bytes */
1211 return ((int)httpRead2(http
, buffer
, length
));
1216 * 'httpRead2()' - Read data from a HTTP connection.
1221 ssize_t
/* O - Number of bytes read */
1222 httpRead2(http_t
*http
, /* I - HTTP connection */
1223 char *buffer
, /* I - Buffer for data */
1224 size_t length
) /* I - Maximum number of bytes */
1226 ssize_t bytes
; /* Bytes read */
1227 char len
[32]; /* Length string */
1230 DEBUG_printf(("httpRead(http=%p, buffer=%p, length=%d)\n",
1231 http
, buffer
, length
));
1233 if (http
== NULL
|| buffer
== NULL
)
1236 http
->activity
= time(NULL
);
1241 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1242 http
->data_remaining
<= 0)
1244 DEBUG_puts("httpRead2: Getting chunk length...");
1246 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1248 DEBUG_puts("httpRead2: Could not get length!");
1252 http
->data_remaining
= strtoll(len
, NULL
, 16);
1253 if (http
->data_remaining
< 0)
1255 DEBUG_puts("httpRead2: Negative chunk length!");
1260 DEBUG_printf(("httpRead2: data_remaining=" CUPS_LLFMT
"\n",
1261 CUPS_LLCAST http
->data_remaining
));
1263 if (http
->data_remaining
<= 0)
1266 * A zero-length chunk ends a transfer; unless we are reading POST
1270 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1271 httpGets(len
, sizeof(len
), http
);
1273 if (http
->state
== HTTP_POST_RECV
)
1276 http
->state
= HTTP_WAITING
;
1279 * Prevent future reads for this request...
1282 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1286 else if (length
> (size_t)http
->data_remaining
)
1287 length
= (size_t)http
->data_remaining
;
1289 if (http
->used
== 0 && length
<= 256)
1292 * Buffer small reads for better performance...
1295 if (!http
->blocking
&& !httpWait(http
, 10000))
1298 if (http
->data_remaining
> sizeof(http
->buffer
))
1299 bytes
= sizeof(http
->buffer
);
1301 bytes
= http
->data_remaining
;
1305 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1307 #endif /* HAVE_SSL */
1309 DEBUG_printf(("httpRead2: reading %d bytes from socket into buffer...\n",
1312 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1314 DEBUG_printf(("httpRead2: read %d bytes from socket into buffer...\n",
1323 http
->error
= WSAGetLastError();
1328 http
->error
= errno
;
1335 http
->error
= EPIPE
;
1342 if (length
> (size_t)http
->used
)
1343 length
= (size_t)http
->used
;
1345 bytes
= (ssize_t
)length
;
1347 DEBUG_printf(("httpRead2: grabbing %d bytes from input buffer...\n", bytes
));
1349 memcpy(buffer
, http
->buffer
, length
);
1350 http
->used
-= (int)length
;
1353 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
1358 if (!http
->blocking
&& !httpWait(http
, 10000))
1361 bytes
= (ssize_t
)http_read_ssl(http
, buffer
, (int)length
);
1363 #endif /* HAVE_SSL */
1366 if (!http
->blocking
&& !httpWait(http
, 10000))
1369 DEBUG_printf(("httpRead2: reading %d bytes from socket...\n", length
));
1372 bytes
= (ssize_t
)recv(http
->fd
, buffer
, (int)length
, 0);
1374 while ((bytes
= recv(http
->fd
, buffer
, length
, 0)) < 0)
1379 DEBUG_printf(("httpRead2: read %d bytes from socket...\n", bytes
));
1384 http
->data_remaining
-= bytes
;
1386 if (http
->data_remaining
<= INT_MAX
)
1387 http
->_data_remaining
= (int)http
->data_remaining
;
1389 http
->_data_remaining
= INT_MAX
;
1394 http
->error
= WSAGetLastError();
1399 http
->error
= errno
;
1404 http
->error
= EPIPE
;
1408 if (http
->data_remaining
== 0)
1410 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1411 httpGets(len
, sizeof(len
), http
);
1413 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
1415 if (http
->state
== HTTP_POST_RECV
)
1418 http
->state
= HTTP_WAITING
;
1425 printf("httpRead2: Read %d bytes:\n", bytes
);
1426 for (i
= 0; i
< bytes
; i
+= 16)
1430 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1431 printf(" %02X", buffer
[i
+ j
] & 255);
1440 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1442 ch
= buffer
[i
+ j
] & 255;
1444 if (ch
< ' ' || ch
>= 127)
1458 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
1460 * '_httpReadCDSA()' - Read function for the CDSA library.
1463 OSStatus
/* O - -1 on error, 0 on success */
1465 SSLConnectionRef connection
, /* I - SSL/TLS connection */
1466 void *data
, /* I - Data buffer */
1467 size_t *dataLength
) /* IO - Number of bytes */
1469 OSStatus result
; /* Return value */
1470 ssize_t bytes
; /* Number of bytes read */
1471 http_t
*http
; /* HTTP connection */
1474 http
= (http_t
*)connection
;
1476 if (!http
->blocking
)
1479 * Make sure we have data before we read...
1482 if (!http_wait(http
, 10000, 0))
1484 http
->error
= ETIMEDOUT
;
1491 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
1493 while (bytes
== -1 && errno
== EINTR
);
1495 if (bytes
== *dataLength
)
1501 *dataLength
= bytes
;
1502 result
= errSSLWouldBlock
;
1509 result
= errSSLClosedGraceful
;
1510 else if (errno
== EAGAIN
)
1511 result
= errSSLWouldBlock
;
1513 result
= errSSLClosedAbort
;
1518 #endif /* HAVE_SSL && HAVE_CDSASSL */
1521 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
1523 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
1526 ssize_t
/* O - Number of bytes read or -1 on error */
1528 gnutls_transport_ptr ptr
, /* I - HTTP connection */
1529 void *data
, /* I - Buffer */
1530 size_t length
) /* I - Number of bytes to read */
1532 http_t
*http
; /* HTTP connection */
1535 http
= (http_t
*)ptr
;
1537 if (!http
->blocking
)
1540 * Make sure we have data before we read...
1543 if (!http_wait(http
, 10000, 0))
1545 http
->error
= ETIMEDOUT
;
1550 return (recv(http
->fd
, data
, length
, 0));
1552 #endif /* HAVE_SSL && HAVE_GNUTLS */
1556 * 'httpReconnect()' - Reconnect to a HTTP server.
1559 int /* O - 0 on success, non-zero on failure */
1560 httpReconnect(http_t
*http
) /* I - HTTP connection */
1562 http_addrlist_t
*addr
; /* Connected address */
1565 DEBUG_printf(("httpReconnect(http=%p)\n", http
));
1572 http_shutdown_ssl(http
);
1573 #endif /* HAVE_SSL */
1576 * Close any previously open socket...
1582 closesocket(http
->fd
);
1591 * Connect to the server...
1594 if ((addr
= httpAddrConnect(http
->addrlist
, &(http
->fd
))) == NULL
)
1597 * Unable to connect...
1601 http
->error
= WSAGetLastError();
1603 http
->error
= errno
;
1605 http
->status
= HTTP_ERROR
;
1610 http
->hostaddr
= &(addr
->addr
);
1612 http
->status
= HTTP_CONTINUE
;
1615 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
1618 * Always do encryption via SSL.
1621 if (http_setup_ssl(http
) != 0)
1624 closesocket(http
->fd
);
1632 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
1633 return (http_upgrade(http
));
1634 #endif /* HAVE_SSL */
1641 * 'httpSetCookie()' - Set the cookie value(s)...
1643 * @since CUPS 1.1.19@
1647 httpSetCookie(http_t
*http
, /* I - Connection */
1648 const char *cookie
) /* I - Cookie string */
1657 http
->cookie
= strdup(cookie
);
1659 http
->cookie
= NULL
;
1664 * 'httpSetExpect()' - Set the Expect: header in a request.
1666 * Currently only HTTP_CONTINUE is supported for the "expect" argument.
1672 httpSetExpect(http_t
*http
, /* I - HTTP connection */
1673 http_status_t expect
) /* I - HTTP status to expect (HTTP_CONTINUE) */
1676 http
->expect
= expect
;
1681 * 'httpSetField()' - Set the value of an HTTP header.
1685 httpSetField(http_t
*http
, /* I - HTTP connection */
1686 http_field_t field
, /* I - Field index */
1687 const char *value
) /* I - Value */
1690 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
1691 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
1695 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
1700 * 'httpSetLength()' - Set the content-length and content-encoding.
1706 httpSetLength(http_t
*http
, /* I - HTTP connection */
1707 size_t length
) /* I - Length (0 for chunked) */
1714 strcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked");
1715 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
1719 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
1720 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
1721 CUPS_LLFMT
, CUPS_LLCAST length
);
1727 * 'httpTrace()' - Send an TRACE request to the server.
1730 int /* O - Status of call (0 = success) */
1731 httpTrace(http_t
*http
, /* I - HTTP connection */
1732 const char *uri
) /* I - URI for trace */
1734 return (http_send(http
, HTTP_TRACE
, uri
));
1739 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1742 http_status_t
/* O - HTTP status */
1743 httpUpdate(http_t
*http
) /* I - HTTP connection */
1745 char line
[32768], /* Line from connection... */
1746 *value
; /* Pointer to value on line */
1747 http_field_t field
; /* Field index */
1748 int major
, minor
, /* HTTP version numbers */
1749 status
; /* Request status */
1752 DEBUG_printf(("httpUpdate(http=%p), state=%d\n", http
, http
->state
));
1755 * Flush pending data, if any...
1760 DEBUG_puts(" flushing buffer...");
1762 if (httpFlushWrite(http
) < 0)
1763 return (HTTP_ERROR
);
1767 * If we haven't issued any commands, then there is nothing to "update"...
1770 if (http
->state
== HTTP_WAITING
)
1771 return (HTTP_CONTINUE
);
1774 * Grab all of the lines we can from the connection...
1777 while (httpGets(line
, sizeof(line
), http
) != NULL
)
1779 DEBUG_printf(("httpUpdate: Got \"%s\"\n", line
));
1781 if (line
[0] == '\0')
1784 * Blank line means the start of the data section (if any). Return
1785 * the result code, too...
1787 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
1788 * Instead, we just return HTTP_CONTINUE to the caller and keep on
1792 if (http
->status
== HTTP_CONTINUE
)
1793 return (http
->status
);
1795 if (http
->status
< HTTP_BAD_REQUEST
)
1796 http
->digest_tries
= 0;
1799 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
1801 if (http_setup_ssl(http
) != 0)
1804 closesocket(http
->fd
);
1809 return (HTTP_ERROR
);
1812 return (HTTP_CONTINUE
);
1814 #endif /* HAVE_SSL */
1816 httpGetLength2(http
);
1818 switch (http
->state
)
1822 case HTTP_POST_RECV
:
1825 case HTTP_POST_SEND
:
1830 http
->state
= HTTP_WAITING
;
1834 return (http
->status
);
1836 else if (strncmp(line
, "HTTP/", 5) == 0)
1839 * Got the beginning of a response...
1842 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &status
) != 3)
1843 return (HTTP_ERROR
);
1845 http
->version
= (http_version_t
)(major
* 100 + minor
);
1846 http
->status
= (http_status_t
)status
;
1848 else if ((value
= strchr(line
, ':')) != NULL
)
1855 while (isspace(*value
& 255))
1859 * Be tolerants of servers that send unknown attribute fields...
1862 if (!strcasecmp(line
, "expect"))
1865 * "Expect: 100-continue" or similar...
1868 http
->expect
= (http_status_t
)atoi(value
);
1870 else if (!strcasecmp(line
, "cookie"))
1873 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
1876 httpSetCookie(http
, value
);
1878 else if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
1880 DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line
));
1884 httpSetField(http
, field
, value
);
1888 http
->status
= HTTP_ERROR
;
1889 return (HTTP_ERROR
);
1894 * See if there was an error...
1897 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
1898 return (http
->status
);
1902 DEBUG_printf(("httpUpdate: socket error %d - %s\n", http
->error
,
1903 strerror(http
->error
)));
1904 http
->status
= HTTP_ERROR
;
1905 return (HTTP_ERROR
);
1909 * If we haven't already returned, then there is nothing new...
1912 return (HTTP_CONTINUE
);
1917 * 'httpWait()' - Wait for data available on a connection.
1919 * @since CUPS 1.1.19@
1922 int /* O - 1 if data is available, 0 otherwise */
1923 httpWait(http_t
*http
, /* I - HTTP connection */
1924 int msec
) /* I - Milliseconds to wait */
1927 * First see if there is data in the buffer...
1937 * Flush pending data, if any...
1942 if (httpFlushWrite(http
) < 0)
1947 * If not, check the SSL/TLS buffers and do a select() on the connection...
1950 return (http_wait(http
, msec
, 1));
1955 * 'httpWrite()' - Write data to a HTTP connection.
1957 * This function is deprecated. Use the httpWrite2() function which can
1958 * write more than 2GB of data.
1963 int /* O - Number of bytes written */
1964 httpWrite(http_t
*http
, /* I - HTTP connection */
1965 const char *buffer
, /* I - Buffer for data */
1966 int length
) /* I - Number of bytes to write */
1968 return ((int)httpWrite2(http
, buffer
, length
));
1973 * 'httpWrite2()' - Write data to a HTTP connection.
1978 ssize_t
/* O - Number of bytes written */
1979 httpWrite2(http_t
*http
, /* I - HTTP connection */
1980 const char *buffer
, /* I - Buffer for data */
1981 size_t length
) /* I - Number of bytes to write */
1983 ssize_t bytes
; /* Bytes written */
1986 DEBUG_printf(("httpWrite(http=%p, buffer=%p, length=%d)\n", http
,
1990 * Range check input...
1993 if (http
== NULL
|| buffer
== NULL
)
1997 * Mark activity on the connection...
2000 http
->activity
= time(NULL
);
2003 * Buffer small writes for better performance...
2008 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
2010 DEBUG_printf((" flushing buffer (wused=%d, length=%d)\n",
2011 http
->wused
, length
));
2013 httpFlushWrite(http
);
2016 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
))
2019 * Write to buffer...
2022 DEBUG_printf((" copying %d bytes to wbuffer...\n", length
));
2024 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
2025 http
->wused
+= (int)length
;
2026 bytes
= (ssize_t
)length
;
2031 * Otherwise write the data directly...
2034 DEBUG_printf((" writing %d bytes to socket...\n", length
));
2036 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2037 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
2039 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
2041 DEBUG_printf((" wrote %d bytes...\n", bytes
));
2044 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
2045 http
->data_remaining
-= bytes
;
2051 * Handle end-of-request processing...
2054 if ((http
->data_encoding
== HTTP_ENCODE_CHUNKED
&& length
== 0) ||
2055 (http
->data_encoding
== HTTP_ENCODE_LENGTH
&& http
->data_remaining
== 0))
2058 * Finished with the transfer; unless we are sending POST or PUT
2062 DEBUG_puts("httpWrite: changing states...");
2065 httpFlushWrite(http
);
2067 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2070 * Send a 0-length chunk at the end of the request...
2073 http_write(http
, "0\r\n\r\n", 5);
2076 * Reset the data state...
2079 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
2080 http
->data_remaining
= 0;
2083 if (http
->state
== HTTP_POST_RECV
)
2085 else if (http
->state
== HTTP_PUT_RECV
)
2086 http
->state
= HTTP_STATUS
;
2088 http
->state
= HTTP_WAITING
;
2095 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2097 * '_httpWriteCDSA()' - Write function for the CDSA library.
2100 OSStatus
/* O - -1 on error, 0 on success */
2102 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2103 const void *data
, /* I - Data buffer */
2104 size_t *dataLength
) /* IO - Number of bytes */
2106 OSStatus result
; /* Return value */
2107 ssize_t bytes
; /* Number of bytes read */
2108 http_t
*http
; /* HTTP connection */
2111 http
= (http_t
*)connection
;
2115 bytes
= write(http
->fd
, data
, *dataLength
);
2117 while (bytes
== -1 && errno
== EINTR
);
2119 if (bytes
== *dataLength
)
2123 else if (bytes
>= 0)
2125 *dataLength
= bytes
;
2126 result
= errSSLWouldBlock
;
2132 if (errno
== EAGAIN
)
2133 result
= errSSLWouldBlock
;
2135 result
= errSSLClosedAbort
;
2140 #endif /* HAVE_SSL && HAVE_CDSASSL */
2143 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2145 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
2148 ssize_t
/* O - Number of bytes written or -1 on error */
2150 gnutls_transport_ptr ptr
, /* I - HTTP connection */
2151 const void *data
, /* I - Data buffer */
2152 size_t length
) /* I - Number of bytes to write */
2154 return (send(((http_t
*)ptr
)->fd
, data
, length
, 0));
2156 #endif /* HAVE_SSL && HAVE_GNUTLS */
2159 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
2161 * 'http_bio_ctrl()' - Control the HTTP connection.
2164 static long /* O - Result/data */
2165 http_bio_ctrl(BIO
*h
, /* I - BIO data */
2166 int cmd
, /* I - Control command */
2167 long arg1
, /* I - First argument */
2168 void *arg2
) /* I - Second argument */
2175 case BIO_CTRL_RESET
:
2179 case BIO_C_SET_FILE_PTR
:
2184 case BIO_C_GET_FILE_PTR
:
2187 *((void **)arg2
) = h
->ptr
;
2194 case BIO_CTRL_FLUSH
:
2201 * 'http_bio_free()' - Free OpenSSL data.
2204 static int /* O - 1 on success, 0 on failure */
2205 http_bio_free(BIO
*h
) /* I - BIO data */
2221 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
2224 static int /* O - 1 on success, 0 on failure */
2225 http_bio_new(BIO
*h
) /* I - BIO data */
2240 * 'http_bio_puts()' - Send a string for OpenSSL.
2243 static int /* O - Bytes written */
2244 http_bio_puts(BIO
*h
, /* I - BIO data */
2245 const char *str
) /* I - String to write */
2248 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
2250 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
2256 * 'http_bio_read()' - Read data for OpenSSL.
2259 static int /* O - Bytes read */
2260 http_bio_read(BIO
*h
, /* I - BIO data */
2261 char *buf
, /* I - Buffer */
2262 int size
) /* I - Number of bytes to read */
2264 http_t
*http
; /* HTTP connection */
2267 http
= (http_t
*)h
->ptr
;
2269 if (!http
->blocking
)
2272 * Make sure we have data before we read...
2275 if (!http_wait(http
, 10000, 0))
2278 http
->error
= WSAETIMEDOUT
;
2280 http
->error
= ETIMEDOUT
;
2287 return (recv(http
->fd
, buf
, size
, 0));
2292 * 'http_bio_write()' - Write data for OpenSSL.
2295 static int /* O - Bytes written */
2296 http_bio_write(BIO
*h
, /* I - BIO data */
2297 const char *buf
, /* I - Buffer to write */
2298 int num
) /* I - Number of bytes to write */
2300 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
2302 #endif /* HAVE_SSL && HAVE_LIBSSL */
2306 * 'http_field()' - Return the field index for a field name.
2309 static http_field_t
/* O - Field index */
2310 http_field(const char *name
) /* I - String name */
2312 int i
; /* Looping var */
2315 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2316 if (strcasecmp(name
, http_fields
[i
]) == 0)
2317 return ((http_field_t
)i
);
2319 return (HTTP_FIELD_UNKNOWN
);
2325 * 'http_read_ssl()' - Read from a SSL/TLS connection.
2328 static int /* O - Bytes read */
2329 http_read_ssl(http_t
*http
, /* I - HTTP connection */
2330 char *buf
, /* I - Buffer to store data */
2331 int len
) /* I - Length of buffer */
2333 # if defined(HAVE_LIBSSL)
2334 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
2336 # elif defined(HAVE_GNUTLS)
2337 return (gnutls_record_recv(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
2339 # elif defined(HAVE_CDSASSL)
2340 int result
; /* Return value */
2341 OSStatus error
; /* Error info */
2342 size_t processed
; /* Number of bytes processed */
2345 error
= SSLRead(((http_tls_t
*)http
->tls
)->session
, buf
, len
, &processed
);
2350 result
= (int)processed
;
2352 case errSSLClosedGraceful
:
2355 case errSSLWouldBlock
:
2357 result
= (int)processed
;
2371 # endif /* HAVE_LIBSSL */
2373 #endif /* HAVE_SSL */
2377 * 'http_send()' - Send a request with all fields and the trailing blank line.
2380 static int /* O - 0 on success, non-zero on error */
2381 http_send(http_t
*http
, /* I - HTTP connection */
2382 http_state_t request
, /* I - Request code */
2383 const char *uri
) /* I - URI */
2385 int i
; /* Looping var */
2386 char *ptr
, /* Pointer in buffer */
2387 buf
[1024]; /* Encoded URI buffer */
2388 static const char * const codes
[] =
2389 { /* Request code strings */
2404 static const char hex
[] = "0123456789ABCDEF";
2408 DEBUG_printf(("http_send(http=%p, request=HTTP_%s, uri=\"%s\")\n",
2409 http
, codes
[request
], uri
));
2411 if (http
== NULL
|| uri
== NULL
)
2415 * Set the User-Agent field if it isn't already...
2418 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
2419 httpSetField(http
, HTTP_FIELD_USER_AGENT
, CUPS_MINIMAL
);
2422 * Encode the URI as needed...
2425 for (ptr
= buf
; *uri
!= '\0' && ptr
< (buf
+ sizeof(buf
) - 1); uri
++)
2426 if (*uri
<= ' ' || *uri
>= 127)
2428 if (ptr
< (buf
+ sizeof(buf
) - 1))
2430 if (ptr
< (buf
+ sizeof(buf
) - 1))
2431 *ptr
++ = hex
[(*uri
>> 4) & 15];
2432 if (ptr
< (buf
+ sizeof(buf
) - 1))
2433 *ptr
++ = hex
[*uri
& 15];
2441 * See if we had an error the last time around; if so, reconnect...
2444 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
2445 if (httpReconnect(http
))
2449 * Flush any written data that is pending...
2453 httpFlushWrite(http
);
2456 * Send the request header...
2459 http
->state
= request
;
2460 http
->data_encoding
= HTTP_ENCODE_FIELDS
;
2462 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
2465 http
->status
= HTTP_CONTINUE
;
2468 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
2470 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
2471 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
2473 #endif /* HAVE_SSL */
2475 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
2477 http
->status
= HTTP_ERROR
;
2481 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2482 if (http
->fields
[i
][0] != '\0')
2484 DEBUG_printf(("%s: %s\n", http_fields
[i
], http
->fields
[i
]));
2486 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], http
->fields
[i
]) < 1)
2488 http
->status
= HTTP_ERROR
;
2494 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
2496 http
->status
= HTTP_ERROR
;
2500 if (http
->expect
== HTTP_CONTINUE
&&
2501 (http
->state
== HTTP_POST_RECV
|| http
->state
== HTTP_PUT_RECV
))
2502 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
2504 http
->status
= HTTP_ERROR
;
2508 if (httpPrintf(http
, "\r\n") < 1)
2510 http
->status
= HTTP_ERROR
;
2514 httpFlushWrite(http
);
2515 httpGetLength2(http
);
2516 httpClearFields(http
);
2524 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
2527 static int /* O - Status of connection */
2528 http_setup_ssl(http_t
*http
) /* I - HTTP connection */
2531 SSL_CTX
*context
; /* Context for encryption */
2532 SSL
*conn
; /* Connection for encryption */
2533 BIO
*bio
; /* BIO data */
2534 # elif defined(HAVE_GNUTLS)
2535 http_tls_t
*conn
; /* TLS session object */
2536 gnutls_certificate_client_credentials
*credentials
;
2537 /* TLS credentials */
2538 # elif defined(HAVE_CDSASSL)
2539 OSStatus error
; /* Error code */
2540 http_tls_t
*conn
; /* CDSA connection information */
2541 # endif /* HAVE_LIBSSL */
2544 DEBUG_printf(("http_setup_ssl(http=%p)\n", http
));
2547 context
= SSL_CTX_new(SSLv23_client_method());
2549 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
2551 bio
= BIO_new(_httpBIOMethods());
2552 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
2554 conn
= SSL_new(context
);
2555 SSL_set_bio(conn
, bio
, bio
);
2557 if (SSL_connect(conn
) != 1)
2560 unsigned long error
; /* Error code */
2562 while ((error
= ERR_get_error()) != 0)
2563 printf("http_setup_ssl: %s\n", ERR_error_string(error
, NULL
));
2566 SSL_CTX_free(context
);
2570 http
->error
= WSAGetLastError();
2572 http
->error
= errno
;
2574 http
->status
= HTTP_ERROR
;
2576 return (HTTP_ERROR
);
2579 # elif defined(HAVE_GNUTLS)
2580 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
2582 http
->error
= errno
;
2583 http
->status
= HTTP_ERROR
;
2588 credentials
= (gnutls_certificate_client_credentials
*)
2589 malloc(sizeof(gnutls_certificate_client_credentials
));
2590 if (credentials
== NULL
)
2594 http
->error
= errno
;
2595 http
->status
= HTTP_ERROR
;
2600 gnutls_certificate_allocate_credentials(credentials
);
2602 gnutls_init(&(conn
->session
), GNUTLS_CLIENT
);
2603 gnutls_set_default_priority(conn
->session
);
2604 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
2605 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)http
);
2606 gnutls_transport_set_pull_function(conn
->session
, _httpReadGNUTLS
);
2607 gnutls_transport_set_push_function(conn
->session
, _httpWriteGNUTLS
);
2609 if ((gnutls_handshake(conn
->session
)) != GNUTLS_E_SUCCESS
)
2611 http
->error
= errno
;
2612 http
->status
= HTTP_ERROR
;
2617 conn
->credentials
= credentials
;
2619 # elif defined(HAVE_CDSASSL)
2620 conn
= (http_tls_t
*)calloc(1, sizeof(http_tls_t
));
2625 if ((error
= SSLNewContext(false, &conn
->session
)))
2627 http
->error
= error
;
2628 http
->status
= HTTP_ERROR
;
2635 * Use a union to resolve warnings about int/pointer size mismatches...
2638 error
= SSLSetConnection(conn
->session
, http
);
2641 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
2644 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
2647 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
2650 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
2654 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
2660 http
->error
= error
;
2661 http
->status
= HTTP_ERROR
;
2663 SSLDisposeContext(conn
->session
);
2669 # endif /* HAVE_CDSASSL */
2674 #endif /* HAVE_SSL */
2679 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
2683 http_shutdown_ssl(http_t
*http
) /* I - HTTP connection */
2686 SSL_CTX
*context
; /* Context for encryption */
2687 SSL
*conn
; /* Connection for encryption */
2690 conn
= (SSL
*)(http
->tls
);
2691 context
= SSL_get_SSL_CTX(conn
);
2694 SSL_CTX_free(context
);
2697 # elif defined(HAVE_GNUTLS)
2698 http_tls_t
*conn
; /* Encryption session */
2699 gnutls_certificate_client_credentials
*credentials
;
2700 /* TLS credentials */
2703 conn
= (http_tls_t
*)(http
->tls
);
2704 credentials
= (gnutls_certificate_client_credentials
*)(conn
->credentials
);
2706 gnutls_bye(conn
->session
, GNUTLS_SHUT_RDWR
);
2707 gnutls_deinit(conn
->session
);
2708 gnutls_certificate_free_credentials(*credentials
);
2712 # elif defined(HAVE_CDSASSL)
2713 http_tls_t
*conn
; /* CDSA connection information */
2716 conn
= (http_tls_t
*)(http
->tls
);
2718 while (SSLClose(conn
->session
) == errSSLWouldBlock
)
2721 SSLDisposeContext(conn
->session
);
2723 if (conn
->certsArray
)
2724 CFRelease(conn
->certsArray
);
2727 # endif /* HAVE_LIBSSL */
2731 #endif /* HAVE_SSL */
2736 * 'http_upgrade()' - Force upgrade to TLS encryption.
2739 static int /* O - Status of connection */
2740 http_upgrade(http_t
*http
) /* I - HTTP connection */
2742 int ret
; /* Return value */
2743 http_t myhttp
; /* Local copy of HTTP data */
2746 DEBUG_printf(("http_upgrade(%p)\n", http
));
2749 * Copy the HTTP data to a local variable so we can do the OPTIONS
2750 * request without interfering with the existing request data...
2753 memcpy(&myhttp
, http
, sizeof(myhttp
));
2756 * Send an OPTIONS request to the server, requiring SSL or TLS
2757 * encryption on the link...
2760 httpClearFields(http
);
2761 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
2762 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0, SSL/2.0, SSL/3.0");
2764 if ((ret
= httpOptions(http
, "*")) == 0)
2767 * Wait for the secure connection...
2770 while (httpUpdate(http
) == HTTP_CONTINUE
);
2776 * Restore the HTTP request data...
2779 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
2780 http
->data_encoding
= myhttp
.data_encoding
;
2781 http
->data_remaining
= myhttp
.data_remaining
;
2782 http
->_data_remaining
= myhttp
._data_remaining
;
2783 http
->expect
= myhttp
.expect
;
2786 * See if we actually went secure...
2792 * Server does not support HTTP upgrade...
2795 DEBUG_puts("Server does not support HTTP upgrade!");
2798 closesocket(http
->fd
);
2810 #endif /* HAVE_SSL */
2814 * 'http_wait()' - Wait for data available on a connection.
2817 static int /* O - 1 if data is available, 0 otherwise */
2818 http_wait(http_t
*http
, /* I - HTTP connection */
2819 int msec
, /* I - Milliseconds to wait */
2820 int usessl
) /* I - Use SSL context? */
2823 struct rlimit limit
; /* Runtime limit */
2824 int set_size
; /* Size of select set */
2826 struct timeval timeout
; /* Timeout */
2827 int nfds
; /* Result from select() */
2830 DEBUG_printf(("http_wait(http=%p, msec=%d)\n", http
, msec
));
2836 * Check the SSL/TLS buffers for data first...
2840 if (http
->tls
&& usessl
)
2843 if (SSL_pending((SSL
*)(http
->tls
)))
2845 # elif defined(HAVE_GNUTLS)
2846 if (gnutls_record_check_pending(((http_tls_t
*)(http
->tls
))->session
))
2848 # elif defined(HAVE_CDSASSL)
2849 size_t bytes
; /* Bytes that are available */
2851 if (!SSLGetBufferedReadSize(((http_tls_t
*)http
->tls
)->session
, &bytes
) && bytes
> 0)
2853 # endif /* HAVE_LIBSSL */
2855 #endif /* HAVE_SSL */
2858 * Then try doing a select() to poll the socket...
2861 if (!http
->input_set
)
2865 * Windows has a fixed-size select() structure, different (surprise,
2866 * surprise!) from all UNIX implementations. Just allocate this
2867 * fixed structure...
2870 http
->input_set
= calloc(1, sizeof(fd_set
));
2873 * Allocate the select() input set based upon the max number of file
2874 * descriptors available for this process...
2877 getrlimit(RLIMIT_NOFILE
, &limit
);
2879 set_size
= (limit
.rlim_cur
+ 31) / 8 + 4;
2880 if (set_size
< sizeof(fd_set
))
2881 set_size
= sizeof(fd_set
);
2883 http
->input_set
= calloc(1, set_size
);
2886 if (!http
->input_set
)
2892 FD_SET(http
->fd
, http
->input_set
);
2894 DEBUG_printf(("http_wait: msec=%d, http->fd=%d\n", msec
, http
->fd
));
2898 timeout
.tv_sec
= msec
/ 1000;
2899 timeout
.tv_usec
= (msec
% 1000) * 1000;
2901 nfds
= select(http
->fd
+ 1, http
->input_set
, NULL
, NULL
, &timeout
);
2904 nfds
= select(http
->fd
+ 1, http
->input_set
, NULL
, NULL
, NULL
);
2906 DEBUG_printf(("http_wait: select() returned %d...\n", nfds
));
2909 while (nfds
< 0 && WSAGetLastError() == WSAEINTR
);
2911 while (nfds
< 0 && errno
== EINTR
);
2914 FD_CLR(http
->fd
, http
->input_set
);
2916 DEBUG_printf(("http_wait: returning with nfds=%d...\n", nfds
));
2923 * 'http_write()' - Write a buffer to a HTTP connection.
2926 static int /* O - Number of bytes written */
2927 http_write(http_t
*http
, /* I - HTTP connection */
2928 const char *buffer
, /* I - Buffer for data */
2929 int length
) /* I - Number of bytes to write */
2931 int tbytes
, /* Total bytes sent */
2932 bytes
; /* Bytes sent */
2941 bytes
= http_write_ssl(http
, buffer
, length
);
2943 #endif /* HAVE_SSL */
2944 bytes
= send(http
->fd
, buffer
, length
, 0);
2949 if (WSAGetLastError() != http
->error
)
2951 http
->error
= WSAGetLastError();
2957 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
2959 http
->error
= errno
;
2964 DEBUG_puts("http_write: error writing data...\n");
2977 printf("http_write: wrote %d bytes: \n", tbytes
);
2978 for (i
= 0, buffer
-= tbytes
; i
< tbytes
; i
+= 16)
2982 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
2983 printf(" %02X", buffer
[i
+ j
] & 255);
2992 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
2994 ch
= buffer
[i
+ j
] & 255;
2996 if (ch
< ' ' || ch
== 127)
3011 * 'http_write_chunk()' - Write a chunked buffer.
3014 static int /* O - Number bytes written */
3015 http_write_chunk(http_t
*http
, /* I - HTTP connection */
3016 const char *buffer
, /* I - Buffer to write */
3017 int length
) /* I - Length of buffer */
3019 char header
[255]; /* Chunk header */
3020 int bytes
; /* Bytes written */
3022 DEBUG_printf(("http_write_chunk(http=%p, buffer=%p, length=%d)\n",
3023 http
, buffer
, length
));
3026 * Write the chunk header, data, and trailer.
3029 sprintf(header
, "%x\r\n", length
);
3030 if (http_write(http
, header
, (int)strlen(header
)) < 0)
3032 DEBUG_puts(" http_write of length failed!");
3036 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
3038 DEBUG_puts(" http_write of buffer failed!");
3042 if (http_write(http
, "\r\n", 2) < 0)
3044 DEBUG_puts(" http_write of CR LF failed!");
3054 * 'http_write_ssl()' - Write to a SSL/TLS connection.
3057 static int /* O - Bytes written */
3058 http_write_ssl(http_t
*http
, /* I - HTTP connection */
3059 const char *buf
, /* I - Buffer holding data */
3060 int len
) /* I - Length of buffer */
3062 # if defined(HAVE_LIBSSL)
3063 return (SSL_write((SSL
*)(http
->tls
), buf
, len
));
3065 # elif defined(HAVE_GNUTLS)
3066 return (gnutls_record_send(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
3067 # elif defined(HAVE_CDSASSL)
3068 int result
; /* Return value */
3069 OSStatus error
; /* Error info */
3070 size_t processed
; /* Number of bytes processed */
3073 error
= SSLWrite(((http_tls_t
*)http
->tls
)->session
, buf
, len
, &processed
);
3078 result
= (int)processed
;
3080 case errSSLClosedGraceful
:
3083 case errSSLWouldBlock
:
3085 result
= (int)processed
;
3099 # endif /* HAVE_LIBSSL */
3101 #endif /* HAVE_SSL */
3105 * End of "$Id: http.c 6191 2007-01-10 16:48:37Z mike $".