2 * "$Id: http.c 6649 2007-07-11 21:46:42Z mike $"
4 * HTTP routines for the Common UNIX Printing System (CUPS).
6 * Copyright 2007 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * This file contains Kerberos support code, copyright 2006 by
12 * These coded instructions, statements, and computer programs are the
13 * property of Apple Inc. and are protected by Federal copyright
14 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
15 * which should have been included with this file. If this file is
16 * file is missing or damaged, see the license at "http://www.cups.org/".
18 * This file is subject to the Apple OS-Developed Software exception.
22 * _httpBIOMethods() - Get the OpenSSL BIO methods for HTTP connections.
23 * httpBlocking() - Set blocking/non-blocking behavior on a connection.
24 * httpCheck() - Check to see if there is a pending response from
26 * httpClearCookie() - Clear the cookie value(s).
27 * httpClearFields() - Clear HTTP request fields.
28 * httpClose() - Close an HTTP connection...
29 * httpConnect() - Connect to a HTTP server.
30 * httpConnectEncrypt() - Connect to a HTTP server using encryption.
31 * httpDelete() - Send a DELETE request to the server.
32 * httpEncryption() - Set the required encryption on the link.
33 * httpError() - Get the last error on a connection.
34 * httpFlush() - Flush data from a HTTP connection.
35 * httpFlushWrite() - Flush data in write buffer.
36 * httpGet() - Send a GET request to the server.
37 * httpGetBlocking() - Get the blocking/non-block state of a connection.
38 * httpGetCookie() - Get any cookie data from the response.
39 * httpGetFd() - Get the file descriptor associated with a
41 * httpGetField() - Get a field value from a request/response.
42 * httpGetLength() - Get the amount of data remaining from the
43 * content-length or transfer-encoding fields.
44 * httpGetLength2() - Get the amount of data remaining from the
45 * content-length or transfer-encoding fields.
46 * httpGetStatus() - Get the status of the last HTTP request.
47 * httpGetSubField() - Get a sub-field value.
48 * httpGets() - Get a line of text from a HTTP connection.
49 * httpHead() - Send a HEAD request to the server.
50 * httpInitialize() - Initialize the HTTP interface library and set the
51 * default HTTP proxy (if any).
52 * httpOptions() - Send an OPTIONS request to the server.
53 * httpPost() - Send a POST request to the server.
54 * httpPrintf() - Print a formatted string to a HTTP connection.
55 * httpPut() - Send a PUT request to the server.
56 * httpRead() - Read data from a HTTP connection.
57 * httpRead2() - Read data from a HTTP connection.
58 * _httpReadCDSA() - Read function for the CDSA library.
59 * _httpReadGNUTLS() - Read function for the GNU TLS library.
60 * httpReconnect() - Reconnect to a HTTP server...
61 * httpSetCookie() - Set the cookie value(s)...
62 * httpSetExpect() - Set the Expect: header in a request.
63 * httpSetField() - Set the value of an HTTP header.
64 * httpSetLength() - Set the content-length and transfer-encoding.
65 * httpTrace() - Send an TRACE request to the server.
66 * httpUpdate() - Update the current HTTP state for incoming data.
67 * httpWait() - Wait for data available on a connection.
68 * httpWrite() - Write data to a HTTP connection.
69 * httpWrite2() - Write data to a HTTP connection.
70 * _httpWriteCDSA() - Write function for the CDSA library.
71 * _httpWriteGNUTLS() - Write function for the GNU TLS library.
72 * http_bio_ctrl() - Control the HTTP connection.
73 * http_bio_free() - Free OpenSSL data.
74 * http_bio_new() - Initialize an OpenSSL BIO structure.
75 * http_bio_puts() - Send a string for OpenSSL.
76 * http_bio_read() - Read data for OpenSSL.
77 * http_bio_write() - Write data for OpenSSL.
78 * http_field() - Return the field index for a field name.
79 * http_read_ssl() - Read from a SSL/TLS connection.
80 * http_send() - Send a request with all fields and the trailing
82 * http_setup_ssl() - Set up SSL/TLS on a connection.
83 * http_shutdown_ssl() - Shut down SSL/TLS on a connection.
84 * http_upgrade() - Force upgrade to TLS encryption.
85 * http_wait() - Wait for data available on a connection.
86 * http_write() - Write data to a connection.
87 * http_write_ssl() - Write to a SSL/TLS connection.
91 * Include necessary headers...
94 #include "http-private.h"
102 # include <sys/time.h>
103 # include <sys/resource.h>
106 # include <sys/poll.h>
107 #endif /* HAVE_POLL */
111 * Some operating systems have done away with the Fxxxx constants for
112 * the fcntl() call; this works around that "feature"...
116 # define FNONBLK O_NONBLOCK
117 #endif /* !FNONBLK */
124 static http_field_t
http_field(const char *name
);
125 static int http_send(http_t
*http
, http_state_t request
,
127 static int http_wait(http_t
*http
, int msec
, int usessl
);
128 static int http_write(http_t
*http
, const char *buffer
,
130 static int http_write_chunk(http_t
*http
, const char *buffer
,
133 static int http_read_ssl(http_t
*http
, char *buf
, int len
);
134 static int http_setup_ssl(http_t
*http
);
135 static void http_shutdown_ssl(http_t
*http
);
136 static int http_upgrade(http_t
*http
);
137 static int http_write_ssl(http_t
*http
, const char *buf
, int len
);
138 #endif /* HAVE_SSL */
145 static const char * const http_fields
[] =
162 "If-Unmodified-since",
177 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
179 * BIO methods for OpenSSL...
182 static int http_bio_write(BIO
*h
, const char *buf
, int num
);
183 static int http_bio_read(BIO
*h
, char *buf
, int size
);
184 static int http_bio_puts(BIO
*h
, const char *str
);
185 static long http_bio_ctrl(BIO
*h
, int cmd
, long arg1
, void *arg2
);
186 static int http_bio_new(BIO
*h
);
187 static int http_bio_free(BIO
*data
);
189 static BIO_METHOD http_bio_methods
=
196 NULL
, /* http_bio_gets, */
205 * '_httpBIOMethods()' - Get the OpenSSL BIO methods for HTTP connections.
208 BIO_METHOD
* /* O - BIO methods for OpenSSL */
209 _httpBIOMethods(void)
211 return (&http_bio_methods
);
213 #endif /* HAVE_SSL && HAVE_LIBSSL */
217 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
221 httpBlocking(http_t
*http
, /* I - HTTP connection */
222 int b
) /* I - 1 = blocking, 0 = non-blocking */
230 * 'httpCheck()' - Check to see if there is a pending response from the server.
233 int /* O - 0 = no data, 1 = data available */
234 httpCheck(http_t
*http
) /* I - HTTP connection */
236 return (httpWait(http
, 0));
241 * 'httpClearCookie()' - Clear the cookie value(s).
243 * @since CUPS 1.1.19@
247 httpClearCookie(http_t
*http
) /* I - HTTP connection */
261 * 'httpClearFields()' - Clear HTTP request fields.
265 httpClearFields(http_t
*http
) /* I - HTTP connection */
269 memset(http
->fields
, 0, sizeof(http
->fields
));
270 if (http
->hostname
[0] == '/')
271 httpSetField(http
, HTTP_FIELD_HOST
, "localhost");
273 httpSetField(http
, HTTP_FIELD_HOST
, http
->hostname
);
275 if (http
->field_authorization
)
277 free(http
->field_authorization
);
278 http
->field_authorization
= NULL
;
281 http
->expect
= (http_status_t
)0;
287 * 'httpClose()' - Close an HTTP connection...
291 httpClose(http_t
*http
) /* I - HTTP connection */
294 OM_uint32 minor_status
, /* Minor status code */
295 major_status
; /* Major status code */
296 #endif /* HAVE_GSSAPI */
299 DEBUG_printf(("httpClose(http=%p)\n", http
));
304 httpAddrFreeList(http
->addrlist
);
311 http_shutdown_ssl(http
);
312 #endif /* HAVE_SSL */
315 closesocket(http
->fd
);
321 if (http
->gssctx
!= GSS_C_NO_CONTEXT
)
322 major_status
= gss_delete_sec_context(&minor_status
, &http
->gssctx
,
325 if (http
->gssname
!= GSS_C_NO_NAME
)
326 major_status
= gss_release_name(&minor_status
, &http
->gssname
);
327 #endif /* HAVE_GSSAPI */
329 #ifdef HAVE_AUTHORIZATION_H
331 AuthorizationFree(http
->auth_ref
, kAuthorizationFlagDefaults
);
332 #endif /* HAVE_AUTHORIZATION_H */
334 httpClearFields(http
);
336 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
337 free(http
->authstring
);
344 * 'httpConnect()' - Connect to a HTTP server.
347 http_t
* /* O - New HTTP connection */
348 httpConnect(const char *host
, /* I - Host to connect to */
349 int port
) /* I - Port number */
351 http_encryption_t encryption
; /* Type of encryption to use */
355 * Set the default encryption status...
359 encryption
= HTTP_ENCRYPT_ALWAYS
;
361 encryption
= HTTP_ENCRYPT_IF_REQUESTED
;
363 return (httpConnectEncrypt(host
, port
, encryption
));
368 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
371 http_t
* /* O - New HTTP connection */
373 const char *host
, /* I - Host to connect to */
374 int port
, /* I - Port number */
375 http_encryption_t encryption
) /* I - Type of encryption to use */
377 http_t
*http
; /* New HTTP connection */
378 http_addrlist_t
*addrlist
; /* Host address data */
379 char service
[255]; /* Service name */
382 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)\n",
383 host
? host
: "(null)", port
, encryption
));
394 sprintf(service
, "%d", port
);
396 if ((addrlist
= httpAddrGetList(host
, AF_UNSPEC
, service
)) == NULL
)
400 * Allocate memory for the structure...
403 http
= calloc(sizeof(http_t
), 1);
407 http
->version
= HTTP_1_1
;
409 http
->activity
= time(NULL
);
413 http
->gssctx
= GSS_C_NO_CONTEXT
;
414 http
->gssname
= GSS_C_NO_NAME
;
415 #endif /* HAVE_GSSAPI */
418 * Set the encryption status...
421 if (port
== 443) /* Always use encryption for https */
422 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
424 http
->encryption
= encryption
;
427 * Loop through the addresses we have until one of them connects...
430 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
433 * Connect to the remote system...
436 http
->addrlist
= addrlist
;
438 if (!httpReconnect(http
))
442 * Could not connect to any known address - bail out!
445 httpAddrFreeList(addrlist
);
454 * 'httpDelete()' - Send a DELETE request to the server.
457 int /* O - Status of call (0 = success) */
458 httpDelete(http_t
*http
, /* I - HTTP connection */
459 const char *uri
) /* I - URI to delete */
461 return (http_send(http
, HTTP_DELETE
, uri
));
466 * 'httpEncryption()' - Set the required encryption on the link.
469 int /* O - -1 on error, 0 on success */
470 httpEncryption(http_t
*http
, /* I - HTTP connection */
471 http_encryption_t e
) /* I - New encryption preference */
473 DEBUG_printf(("httpEncryption(http=%p, e=%d)\n", http
, e
));
479 http
->encryption
= e
;
481 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
482 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
483 return (httpReconnect(http
));
484 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
485 return (http_upgrade(http
));
489 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
493 #endif /* HAVE_SSL */
498 * 'httpError()' - Get the last error on a connection.
501 int /* O - Error code (errno) value */
502 httpError(http_t
*http
) /* I - HTTP connection */
505 return (http
->error
);
512 * 'httpFlush()' - Flush data from a HTTP connection.
516 httpFlush(http_t
*http
) /* I - HTTP connection */
518 char buffer
[8192]; /* Junk buffer */
519 int blocking
; /* To block or not to block */
522 DEBUG_printf(("httpFlush(http=%p), state=%d\n", http
, http
->state
));
525 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
528 blocking
= http
->blocking
;
532 * Read any data we can...
535 while (httpRead2(http
, buffer
, sizeof(buffer
)) > 0);
538 * Restore blocking and reset the connection if we didn't get all of
539 * the remaining data...
542 http
->blocking
= blocking
;
544 if (http
->state
!= HTTP_WAITING
&& http
->fd
>= 0)
547 * Didn't get the data back, so close the current connection.
550 http
->state
= HTTP_WAITING
;
554 http_shutdown_ssl(http
);
555 #endif /* HAVE_SSL */
558 closesocket(http
->fd
);
569 * 'httpFlushWrite()' - Flush data in write buffer.
574 int /* O - Bytes written or -1 on error */
575 httpFlushWrite(http_t
*http
) /* I - HTTP connection */
577 int bytes
; /* Bytes written */
580 DEBUG_printf(("httpFlushWrite(http=%p)\n", http
));
582 if (!http
|| !http
->wused
)
585 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
586 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
588 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
597 * 'httpGet()' - Send a GET request to the server.
600 int /* O - Status of call (0 = success) */
601 httpGet(http_t
*http
, /* I - HTTP connection */
602 const char *uri
) /* I - URI to get */
604 return (http_send(http
, HTTP_GET
, uri
));
609 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
614 int /* O - 1 if blocking, 0 if non-blocking */
615 httpGetBlocking(http_t
*http
) /* I - HTTP connection */
617 return (http
? http
->blocking
: 0);
622 * 'httpGetCookie()' - Get any cookie data from the response.
624 * @since CUPS 1.1.19@
627 const char * /* O - Cookie data or NULL */
628 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
630 return (http
? http
->cookie
: NULL
);
635 * 'httpGetFd()' - Get the file descriptor associated with a connection.
640 int /* O - File descriptor or -1 if none */
641 httpGetFd(http_t
*http
) /* I - HTTP connection */
643 return (http
? http
->fd
: -1);
648 * 'httpGetField()' - Get a field value from a request/response.
651 const char * /* O - Field value */
652 httpGetField(http_t
*http
, /* I - HTTP connection */
653 http_field_t field
) /* I - Field to get */
655 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
657 else if (field
== HTTP_FIELD_AUTHORIZATION
&&
658 http
->field_authorization
)
661 * Special case for WWW-Authenticate: as its contents can be
662 * longer than HTTP_MAX_VALUE...
665 return (http
->field_authorization
);
668 return (http
->fields
[field
]);
673 * 'httpGetLength()' - Get the amount of data remaining from the
674 * content-length or transfer-encoding fields.
676 * This function is deprecated and will not return lengths larger than
677 * 2^31 - 1; use httpGetLength2() instead.
682 int /* O - Content length */
683 httpGetLength(http_t
*http
) /* I - HTTP connection */
686 * Get the read content length and return the 32-bit value.
691 httpGetLength2(http
);
693 return (http
->_data_remaining
);
701 * 'httpGetLength2()' - Get the amount of data remaining from the
702 * content-length or transfer-encoding fields.
704 * This function returns the complete content length, even for
705 * content larger than 2^31 - 1.
710 off_t
/* O - Content length */
711 httpGetLength2(http_t
*http
) /* I - HTTP connection */
713 DEBUG_printf(("httpGetLength2(http=%p), state=%d\n", http
, http
->state
));
718 if (!strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
720 DEBUG_puts("httpGetLength2: chunked request!");
722 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
723 http
->data_remaining
= 0;
727 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
730 * The following is a hack for HTTP servers that don't send a
731 * content-length or transfer-encoding field...
733 * If there is no content-length then the connection must close
734 * after the transfer is complete...
737 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
740 * Default content length is 0 for errors and 2^31-1 for other
741 * successful requests...
744 if (http
->status
>= HTTP_MULTIPLE_CHOICES
)
745 http
->data_remaining
= 0;
747 http
->data_remaining
= 2147483647;
750 http
->data_remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
753 DEBUG_printf(("httpGetLength2: content_length=" CUPS_LLFMT
"\n",
754 CUPS_LLCAST http
->data_remaining
));
757 if (http
->data_remaining
<= INT_MAX
)
758 http
->_data_remaining
= (int)http
->data_remaining
;
760 http
->_data_remaining
= INT_MAX
;
762 return (http
->data_remaining
);
767 * 'httpGetStatus()' - Get the status of the last HTTP request.
772 http_status_t
/* O - HTTP status */
773 httpGetStatus(http_t
*http
) /* I - HTTP connection */
775 return (http
? http
->status
: HTTP_ERROR
);
780 * 'httpGetSubField()' - Get a sub-field value.
785 char * /* O - Value or NULL */
786 httpGetSubField(http_t
*http
, /* I - HTTP connection */
787 http_field_t field
, /* I - Field index */
788 const char *name
, /* I - Name of sub-field */
789 char *value
) /* O - Value string */
791 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
796 * 'httpGetSubField2()' - Get a sub-field value.
801 char * /* O - Value or NULL */
802 httpGetSubField2(http_t
*http
, /* I - HTTP connection */
803 http_field_t field
, /* I - Field index */
804 const char *name
, /* I - Name of sub-field */
805 char *value
, /* O - Value string */
806 int valuelen
) /* I - Size of value buffer */
808 const char *fptr
; /* Pointer into field */
809 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
810 *ptr
, /* Pointer into string buffer */
811 *end
; /* End of value buffer */
813 DEBUG_printf(("httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, valuelen=%d)\n",
814 http
, field
, name
, value
, valuelen
));
816 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
817 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
820 end
= value
+ valuelen
- 1;
822 for (fptr
= http
->fields
[field
]; *fptr
;)
825 * Skip leading whitespace...
828 while (isspace(*fptr
& 255))
838 * Get the sub-field name...
842 *fptr
&& *fptr
!= '=' && !isspace(*fptr
& 255) &&
843 ptr
< (temp
+ sizeof(temp
) - 1);
848 DEBUG_printf(("httpGetSubField: name=\"%s\"\n", temp
));
851 * Skip trailing chars up to the '='...
854 while (isspace(*fptr
& 255))
864 * Skip = and leading whitespace...
869 while (isspace(*fptr
& 255))
875 * Read quoted string...
878 for (ptr
= value
, fptr
++;
879 *fptr
&& *fptr
!= '\"' && ptr
< end
;
884 while (*fptr
&& *fptr
!= '\"')
893 * Read unquoted string...
897 *fptr
&& !isspace(*fptr
& 255) && *fptr
!= ',' && ptr
< end
;
902 while (*fptr
&& !isspace(*fptr
& 255) && *fptr
!= ',')
906 DEBUG_printf(("httpGetSubField: value=\"%s\"\n", value
));
909 * See if this is the one...
912 if (!strcmp(name
, temp
))
923 * 'httpGets()' - Get a line of text from a HTTP connection.
926 char * /* O - Line or NULL */
927 httpGets(char *line
, /* I - Line to read into */
928 int length
, /* I - Max length of buffer */
929 http_t
*http
) /* I - HTTP connection */
931 char *lineptr
, /* Pointer into line */
932 *lineend
, /* End of line */
933 *bufptr
, /* Pointer into input buffer */
934 *bufend
; /* Pointer to end of buffer */
935 int bytes
, /* Number of bytes read */
936 eol
; /* End-of-line? */
939 DEBUG_printf(("httpGets(line=%p, length=%d, http=%p)\n", line
, length
, http
));
941 if (http
== NULL
|| line
== NULL
)
945 * Read a line from the buffer...
949 lineend
= line
+ length
- 1;
952 while (lineptr
< lineend
)
955 * Pre-load the buffer as needed...
964 while (http
->used
== 0)
967 * No newline; see if there is more data to be read...
970 if (!http
->blocking
&& !http_wait(http
, 10000, 1))
972 DEBUG_puts("httpGets: Timed out!");
974 http
->error
= WSAETIMEDOUT
;
976 http
->error
= ETIMEDOUT
;
983 bytes
= http_read_ssl(http
, http
->buffer
+ http
->used
,
984 HTTP_MAX_BUFFER
- http
->used
);
986 #endif /* HAVE_SSL */
987 bytes
= recv(http
->fd
, http
->buffer
+ http
->used
,
988 HTTP_MAX_BUFFER
- http
->used
, 0);
990 DEBUG_printf(("httpGets: read %d bytes...\n", bytes
));
995 * Nope, can't get a line this time...
999 if (WSAGetLastError() != http
->error
)
1001 http
->error
= WSAGetLastError();
1005 DEBUG_printf(("httpGets: recv() error %d!\n", WSAGetLastError()));
1007 DEBUG_printf(("httpGets: recv() error %d!\n", errno
));
1011 else if (errno
!= http
->error
)
1013 http
->error
= errno
;
1020 else if (bytes
== 0)
1022 http
->error
= EPIPE
;
1028 * Yup, update the amount used...
1031 http
->used
+= bytes
;
1035 * Now copy as much of the current line as possible...
1038 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1039 lineptr
< lineend
&& bufptr
< bufend
;)
1041 if (*bufptr
== 0x0a)
1047 else if (*bufptr
== 0x0d)
1050 *lineptr
++ = *bufptr
++;
1053 http
->used
-= (int)(bufptr
- http
->buffer
);
1055 memmove(http
->buffer
, bufptr
, http
->used
);
1063 http
->activity
= time(NULL
);
1067 DEBUG_printf(("httpGets: Returning \"%s\"\n", line
));
1073 DEBUG_puts("httpGets: No new line available!");
1080 * 'httpHead()' - Send a HEAD request to the server.
1083 int /* O - Status of call (0 = success) */
1084 httpHead(http_t
*http
, /* I - HTTP connection */
1085 const char *uri
) /* I - URI for head */
1087 return (http_send(http
, HTTP_HEAD
, uri
));
1092 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1093 * default HTTP proxy (if any).
1097 httpInitialize(void)
1101 struct timeval curtime
; /* Current time in microseconds */
1102 # endif /* !WIN32 */
1103 int i
; /* Looping var */
1104 unsigned char data
[1024]; /* Seed data */
1105 #endif /* HAVE_LIBSSL */
1108 WSADATA winsockdata
; /* WinSock data */
1109 static int initialized
= 0; /* Has WinSock been initialized? */
1113 WSAStartup(MAKEWORD(1,1), &winsockdata
);
1114 #elif !defined(SO_NOSIGPIPE)
1116 * Ignore SIGPIPE signals...
1120 sigset(SIGPIPE
, SIG_IGN
);
1121 # elif defined(HAVE_SIGACTION)
1122 struct sigaction action
; /* POSIX sigaction data */
1125 memset(&action
, 0, sizeof(action
));
1126 action
.sa_handler
= SIG_IGN
;
1127 sigaction(SIGPIPE
, &action
, NULL
);
1129 signal(SIGPIPE
, SIG_IGN
);
1130 # endif /* !SO_NOSIGPIPE */
1134 gnutls_global_init();
1135 #endif /* HAVE_GNUTLS */
1138 SSL_load_error_strings();
1142 * Using the current time is a dubious random seed, but on some systems
1143 * it is the best we can do (on others, this seed isn't even used...)
1148 gettimeofday(&curtime
, NULL
);
1149 srand(curtime
.tv_sec
+ curtime
.tv_usec
);
1152 for (i
= 0; i
< sizeof(data
); i
++)
1153 data
[i
] = rand(); /* Yes, this is a poor source of random data... */
1155 RAND_seed(&data
, sizeof(data
));
1156 #endif /* HAVE_LIBSSL */
1161 * 'httpOptions()' - Send an OPTIONS request to the server.
1164 int /* O - Status of call (0 = success) */
1165 httpOptions(http_t
*http
, /* I - HTTP connection */
1166 const char *uri
) /* I - URI for options */
1168 return (http_send(http
, HTTP_OPTIONS
, uri
));
1173 * 'httpPost()' - Send a POST request to the server.
1176 int /* O - Status of call (0 = success) */
1177 httpPost(http_t
*http
, /* I - HTTP connection */
1178 const char *uri
) /* I - URI for post */
1180 return (http_send(http
, HTTP_POST
, uri
));
1185 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1190 int /* O - Number of bytes written */
1191 httpPrintf(http_t
*http
, /* I - HTTP connection */
1192 const char *format
, /* I - printf-style format string */
1193 ...) /* I - Additional args as needed */
1195 int bytes
; /* Number of bytes to write */
1196 char buf
[16384]; /* Buffer for formatted string */
1197 va_list ap
; /* Variable argument pointer */
1200 DEBUG_printf(("httpPrintf(http=%p, format=\"%s\", ...)\n", http
, format
));
1202 va_start(ap
, format
);
1203 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1206 DEBUG_printf(("httpPrintf: %s", buf
));
1208 if (http
->data_encoding
== HTTP_ENCODE_FIELDS
)
1209 return (httpWrite2(http
, buf
, bytes
));
1214 DEBUG_puts(" flushing existing data...");
1216 if (httpFlushWrite(http
) < 0)
1220 return (http_write(http
, buf
, bytes
));
1226 * 'httpPut()' - Send a PUT request to the server.
1229 int /* O - Status of call (0 = success) */
1230 httpPut(http_t
*http
, /* I - HTTP connection */
1231 const char *uri
) /* I - URI to put */
1233 return (http_send(http
, HTTP_PUT
, uri
));
1238 * 'httpRead()' - Read data from a HTTP connection.
1240 * This function is deprecated. Use the httpRead2() function which can
1241 * read more than 2GB of data.
1246 int /* O - Number of bytes read */
1247 httpRead(http_t
*http
, /* I - HTTP connection */
1248 char *buffer
, /* I - Buffer for data */
1249 int length
) /* I - Maximum number of bytes */
1251 return ((int)httpRead2(http
, buffer
, length
));
1256 * 'httpRead2()' - Read data from a HTTP connection.
1261 ssize_t
/* O - Number of bytes read */
1262 httpRead2(http_t
*http
, /* I - HTTP connection */
1263 char *buffer
, /* I - Buffer for data */
1264 size_t length
) /* I - Maximum number of bytes */
1266 ssize_t bytes
; /* Bytes read */
1267 char len
[32]; /* Length string */
1270 DEBUG_printf(("httpRead(http=%p, buffer=%p, length=%d)\n",
1271 http
, buffer
, length
));
1273 if (http
== NULL
|| buffer
== NULL
)
1276 http
->activity
= time(NULL
);
1281 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1282 http
->data_remaining
<= 0)
1284 DEBUG_puts("httpRead2: Getting chunk length...");
1286 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1288 DEBUG_puts("httpRead2: Could not get length!");
1292 http
->data_remaining
= strtoll(len
, NULL
, 16);
1293 if (http
->data_remaining
< 0)
1295 DEBUG_puts("httpRead2: Negative chunk length!");
1300 DEBUG_printf(("httpRead2: data_remaining=" CUPS_LLFMT
"\n",
1301 CUPS_LLCAST http
->data_remaining
));
1303 if (http
->data_remaining
<= 0)
1306 * A zero-length chunk ends a transfer; unless we are reading POST
1310 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1311 httpGets(len
, sizeof(len
), http
);
1313 if (http
->state
== HTTP_POST_RECV
)
1316 http
->state
= HTTP_WAITING
;
1319 * Prevent future reads for this request...
1322 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1326 else if (length
> (size_t)http
->data_remaining
)
1327 length
= (size_t)http
->data_remaining
;
1329 if (http
->used
== 0 && length
<= 256)
1332 * Buffer small reads for better performance...
1335 if (!http
->blocking
&& !httpWait(http
, 10000))
1338 if (http
->data_remaining
> sizeof(http
->buffer
))
1339 bytes
= sizeof(http
->buffer
);
1341 bytes
= http
->data_remaining
;
1345 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1347 #endif /* HAVE_SSL */
1349 DEBUG_printf(("httpRead2: reading %d bytes from socket into buffer...\n",
1352 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1354 DEBUG_printf(("httpRead2: read %d bytes from socket into buffer...\n",
1363 http
->error
= WSAGetLastError();
1368 http
->error
= errno
;
1375 http
->error
= EPIPE
;
1382 if (length
> (size_t)http
->used
)
1383 length
= (size_t)http
->used
;
1385 bytes
= (ssize_t
)length
;
1387 DEBUG_printf(("httpRead2: grabbing %d bytes from input buffer...\n", bytes
));
1389 memcpy(buffer
, http
->buffer
, length
);
1390 http
->used
-= (int)length
;
1393 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
1398 if (!http
->blocking
&& !httpWait(http
, 10000))
1401 bytes
= (ssize_t
)http_read_ssl(http
, buffer
, (int)length
);
1403 #endif /* HAVE_SSL */
1406 if (!http
->blocking
&& !httpWait(http
, 10000))
1409 DEBUG_printf(("httpRead2: reading %d bytes from socket...\n", length
));
1412 bytes
= (ssize_t
)recv(http
->fd
, buffer
, (int)length
, 0);
1414 while ((bytes
= recv(http
->fd
, buffer
, length
, 0)) < 0)
1419 DEBUG_printf(("httpRead2: read %d bytes from socket...\n", bytes
));
1424 http
->data_remaining
-= bytes
;
1426 if (http
->data_remaining
<= INT_MAX
)
1427 http
->_data_remaining
= (int)http
->data_remaining
;
1429 http
->_data_remaining
= INT_MAX
;
1434 http
->error
= WSAGetLastError();
1439 http
->error
= errno
;
1444 http
->error
= EPIPE
;
1448 if (http
->data_remaining
== 0)
1450 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1451 httpGets(len
, sizeof(len
), http
);
1453 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
1455 if (http
->state
== HTTP_POST_RECV
)
1458 http
->state
= HTTP_WAITING
;
1465 printf("httpRead2: Read %d bytes:\n", bytes
);
1466 for (i
= 0; i
< bytes
; i
+= 16)
1470 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1471 printf(" %02X", buffer
[i
+ j
] & 255);
1480 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1482 ch
= buffer
[i
+ j
] & 255;
1484 if (ch
< ' ' || ch
>= 127)
1498 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
1500 * '_httpReadCDSA()' - Read function for the CDSA library.
1503 OSStatus
/* O - -1 on error, 0 on success */
1505 SSLConnectionRef connection
, /* I - SSL/TLS connection */
1506 void *data
, /* I - Data buffer */
1507 size_t *dataLength
) /* IO - Number of bytes */
1509 OSStatus result
; /* Return value */
1510 ssize_t bytes
; /* Number of bytes read */
1511 http_t
*http
; /* HTTP connection */
1514 http
= (http_t
*)connection
;
1516 if (!http
->blocking
)
1519 * Make sure we have data before we read...
1522 if (!http_wait(http
, 10000, 0))
1524 http
->error
= ETIMEDOUT
;
1531 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
1533 while (bytes
== -1 && errno
== EINTR
);
1535 if (bytes
== *dataLength
)
1541 *dataLength
= bytes
;
1542 result
= errSSLWouldBlock
;
1549 result
= errSSLClosedGraceful
;
1550 else if (errno
== EAGAIN
)
1551 result
= errSSLWouldBlock
;
1553 result
= errSSLClosedAbort
;
1558 #endif /* HAVE_SSL && HAVE_CDSASSL */
1561 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
1563 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
1566 ssize_t
/* O - Number of bytes read or -1 on error */
1568 gnutls_transport_ptr ptr
, /* I - HTTP connection */
1569 void *data
, /* I - Buffer */
1570 size_t length
) /* I - Number of bytes to read */
1572 http_t
*http
; /* HTTP connection */
1575 http
= (http_t
*)ptr
;
1577 if (!http
->blocking
)
1580 * Make sure we have data before we read...
1583 if (!http_wait(http
, 10000, 0))
1585 http
->error
= ETIMEDOUT
;
1590 return (recv(http
->fd
, data
, length
, 0));
1592 #endif /* HAVE_SSL && HAVE_GNUTLS */
1596 * 'httpReconnect()' - Reconnect to a HTTP server.
1599 int /* O - 0 on success, non-zero on failure */
1600 httpReconnect(http_t
*http
) /* I - HTTP connection */
1602 http_addrlist_t
*addr
; /* Connected address */
1605 DEBUG_printf(("httpReconnect(http=%p)\n", http
));
1612 http_shutdown_ssl(http
);
1613 #endif /* HAVE_SSL */
1616 * Close any previously open socket...
1622 closesocket(http
->fd
);
1631 * Connect to the server...
1634 if ((addr
= httpAddrConnect(http
->addrlist
, &(http
->fd
))) == NULL
)
1637 * Unable to connect...
1641 http
->error
= WSAGetLastError();
1643 http
->error
= errno
;
1645 http
->status
= HTTP_ERROR
;
1650 http
->hostaddr
= &(addr
->addr
);
1652 http
->status
= HTTP_CONTINUE
;
1655 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
1658 * Always do encryption via SSL.
1661 if (http_setup_ssl(http
) != 0)
1664 closesocket(http
->fd
);
1672 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
1673 return (http_upgrade(http
));
1674 #endif /* HAVE_SSL */
1681 * 'httpSetCookie()' - Set the cookie value(s)...
1683 * @since CUPS 1.1.19@
1687 httpSetCookie(http_t
*http
, /* I - Connection */
1688 const char *cookie
) /* I - Cookie string */
1697 http
->cookie
= strdup(cookie
);
1699 http
->cookie
= NULL
;
1704 * 'httpSetExpect()' - Set the Expect: header in a request.
1706 * Currently only HTTP_CONTINUE is supported for the "expect" argument.
1712 httpSetExpect(http_t
*http
, /* I - HTTP connection */
1713 http_status_t expect
) /* I - HTTP status to expect (HTTP_CONTINUE) */
1716 http
->expect
= expect
;
1721 * 'httpSetField()' - Set the value of an HTTP header.
1725 httpSetField(http_t
*http
, /* I - HTTP connection */
1726 http_field_t field
, /* I - Field index */
1727 const char *value
) /* I - Value */
1730 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
1731 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
1735 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
1738 * Special case for Authorization: as its contents can be
1739 * longer than HTTP_MAX_VALUE
1742 if (field
== HTTP_FIELD_AUTHORIZATION
)
1744 if (http
->field_authorization
)
1745 free(http
->field_authorization
);
1747 http
->field_authorization
= strdup(value
);
1753 * 'httpSetLength()' - Set the content-length and content-encoding.
1759 httpSetLength(http_t
*http
, /* I - HTTP connection */
1760 size_t length
) /* I - Length (0 for chunked) */
1767 strcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked");
1768 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
1772 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
1773 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
1774 CUPS_LLFMT
, CUPS_LLCAST length
);
1780 * 'httpTrace()' - Send an TRACE request to the server.
1783 int /* O - Status of call (0 = success) */
1784 httpTrace(http_t
*http
, /* I - HTTP connection */
1785 const char *uri
) /* I - URI for trace */
1787 return (http_send(http
, HTTP_TRACE
, uri
));
1792 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1795 http_status_t
/* O - HTTP status */
1796 httpUpdate(http_t
*http
) /* I - HTTP connection */
1798 char line
[32768], /* Line from connection... */
1799 *value
; /* Pointer to value on line */
1800 http_field_t field
; /* Field index */
1801 int major
, minor
, /* HTTP version numbers */
1802 status
; /* Request status */
1805 DEBUG_printf(("httpUpdate(http=%p), state=%d\n", http
, http
->state
));
1808 * Flush pending data, if any...
1813 DEBUG_puts(" flushing buffer...");
1815 if (httpFlushWrite(http
) < 0)
1816 return (HTTP_ERROR
);
1820 * If we haven't issued any commands, then there is nothing to "update"...
1823 if (http
->state
== HTTP_WAITING
)
1824 return (HTTP_CONTINUE
);
1827 * Grab all of the lines we can from the connection...
1830 while (httpGets(line
, sizeof(line
), http
) != NULL
)
1832 DEBUG_printf(("httpUpdate: Got \"%s\"\n", line
));
1834 if (line
[0] == '\0')
1837 * Blank line means the start of the data section (if any). Return
1838 * the result code, too...
1840 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
1841 * Instead, we just return HTTP_CONTINUE to the caller and keep on
1845 if (http
->status
== HTTP_CONTINUE
)
1846 return (http
->status
);
1848 if (http
->status
< HTTP_BAD_REQUEST
)
1849 http
->digest_tries
= 0;
1852 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
1854 if (http_setup_ssl(http
) != 0)
1857 closesocket(http
->fd
);
1862 return (HTTP_ERROR
);
1865 return (HTTP_CONTINUE
);
1867 #endif /* HAVE_SSL */
1869 httpGetLength2(http
);
1871 switch (http
->state
)
1875 case HTTP_POST_RECV
:
1878 case HTTP_POST_SEND
:
1883 http
->state
= HTTP_WAITING
;
1887 return (http
->status
);
1889 else if (strncmp(line
, "HTTP/", 5) == 0)
1892 * Got the beginning of a response...
1895 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &status
) != 3)
1896 return (HTTP_ERROR
);
1898 http
->version
= (http_version_t
)(major
* 100 + minor
);
1899 http
->status
= (http_status_t
)status
;
1901 else if ((value
= strchr(line
, ':')) != NULL
)
1908 while (isspace(*value
& 255))
1912 * Be tolerants of servers that send unknown attribute fields...
1915 if (!strcasecmp(line
, "expect"))
1918 * "Expect: 100-continue" or similar...
1921 http
->expect
= (http_status_t
)atoi(value
);
1923 else if (!strcasecmp(line
, "cookie"))
1926 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
1929 httpSetCookie(http
, value
);
1931 else if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
1933 DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line
));
1937 httpSetField(http
, field
, value
);
1941 http
->status
= HTTP_ERROR
;
1942 return (HTTP_ERROR
);
1947 * See if there was an error...
1950 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
1951 return (http
->status
);
1955 DEBUG_printf(("httpUpdate: socket error %d - %s\n", http
->error
,
1956 strerror(http
->error
)));
1957 http
->status
= HTTP_ERROR
;
1958 return (HTTP_ERROR
);
1962 * If we haven't already returned, then there is nothing new...
1965 return (HTTP_CONTINUE
);
1970 * 'httpWait()' - Wait for data available on a connection.
1972 * @since CUPS 1.1.19@
1975 int /* O - 1 if data is available, 0 otherwise */
1976 httpWait(http_t
*http
, /* I - HTTP connection */
1977 int msec
) /* I - Milliseconds to wait */
1980 * First see if there is data in the buffer...
1990 * Flush pending data, if any...
1995 if (httpFlushWrite(http
) < 0)
2000 * If not, check the SSL/TLS buffers and do a select() on the connection...
2003 return (http_wait(http
, msec
, 1));
2008 * 'httpWrite()' - Write data to a HTTP connection.
2010 * This function is deprecated. Use the httpWrite2() function which can
2011 * write more than 2GB of data.
2016 int /* O - Number of bytes written */
2017 httpWrite(http_t
*http
, /* I - HTTP connection */
2018 const char *buffer
, /* I - Buffer for data */
2019 int length
) /* I - Number of bytes to write */
2021 return ((int)httpWrite2(http
, buffer
, length
));
2026 * 'httpWrite2()' - Write data to a HTTP connection.
2031 ssize_t
/* O - Number of bytes written */
2032 httpWrite2(http_t
*http
, /* I - HTTP connection */
2033 const char *buffer
, /* I - Buffer for data */
2034 size_t length
) /* I - Number of bytes to write */
2036 ssize_t bytes
; /* Bytes written */
2039 DEBUG_printf(("httpWrite(http=%p, buffer=%p, length=%d)\n", http
,
2043 * Range check input...
2046 if (http
== NULL
|| buffer
== NULL
)
2050 * Mark activity on the connection...
2053 http
->activity
= time(NULL
);
2056 * Buffer small writes for better performance...
2061 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
2063 DEBUG_printf((" flushing buffer (wused=%d, length=%d)\n",
2064 http
->wused
, length
));
2066 httpFlushWrite(http
);
2069 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
))
2072 * Write to buffer...
2075 DEBUG_printf((" copying %d bytes to wbuffer...\n", length
));
2077 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
2078 http
->wused
+= (int)length
;
2079 bytes
= (ssize_t
)length
;
2084 * Otherwise write the data directly...
2087 DEBUG_printf((" writing %d bytes to socket...\n", length
));
2089 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2090 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
2092 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
2094 DEBUG_printf((" wrote %d bytes...\n", bytes
));
2097 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
2098 http
->data_remaining
-= bytes
;
2104 * Handle end-of-request processing...
2107 if ((http
->data_encoding
== HTTP_ENCODE_CHUNKED
&& length
== 0) ||
2108 (http
->data_encoding
== HTTP_ENCODE_LENGTH
&& http
->data_remaining
== 0))
2111 * Finished with the transfer; unless we are sending POST or PUT
2115 DEBUG_puts("httpWrite: changing states...");
2118 httpFlushWrite(http
);
2120 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2123 * Send a 0-length chunk at the end of the request...
2126 http_write(http
, "0\r\n\r\n", 5);
2129 * Reset the data state...
2132 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
2133 http
->data_remaining
= 0;
2136 if (http
->state
== HTTP_POST_RECV
)
2138 else if (http
->state
== HTTP_PUT_RECV
)
2139 http
->state
= HTTP_STATUS
;
2141 http
->state
= HTTP_WAITING
;
2148 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2150 * '_httpWriteCDSA()' - Write function for the CDSA library.
2153 OSStatus
/* O - -1 on error, 0 on success */
2155 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2156 const void *data
, /* I - Data buffer */
2157 size_t *dataLength
) /* IO - Number of bytes */
2159 OSStatus result
; /* Return value */
2160 ssize_t bytes
; /* Number of bytes read */
2161 http_t
*http
; /* HTTP connection */
2164 http
= (http_t
*)connection
;
2168 bytes
= write(http
->fd
, data
, *dataLength
);
2170 while (bytes
== -1 && errno
== EINTR
);
2172 if (bytes
== *dataLength
)
2176 else if (bytes
>= 0)
2178 *dataLength
= bytes
;
2179 result
= errSSLWouldBlock
;
2185 if (errno
== EAGAIN
)
2186 result
= errSSLWouldBlock
;
2188 result
= errSSLClosedAbort
;
2193 #endif /* HAVE_SSL && HAVE_CDSASSL */
2196 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2198 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
2201 ssize_t
/* O - Number of bytes written or -1 on error */
2203 gnutls_transport_ptr ptr
, /* I - HTTP connection */
2204 const void *data
, /* I - Data buffer */
2205 size_t length
) /* I - Number of bytes to write */
2207 return (send(((http_t
*)ptr
)->fd
, data
, length
, 0));
2209 #endif /* HAVE_SSL && HAVE_GNUTLS */
2212 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
2214 * 'http_bio_ctrl()' - Control the HTTP connection.
2217 static long /* O - Result/data */
2218 http_bio_ctrl(BIO
*h
, /* I - BIO data */
2219 int cmd
, /* I - Control command */
2220 long arg1
, /* I - First argument */
2221 void *arg2
) /* I - Second argument */
2228 case BIO_CTRL_RESET
:
2232 case BIO_C_SET_FILE_PTR
:
2237 case BIO_C_GET_FILE_PTR
:
2240 *((void **)arg2
) = h
->ptr
;
2247 case BIO_CTRL_FLUSH
:
2254 * 'http_bio_free()' - Free OpenSSL data.
2257 static int /* O - 1 on success, 0 on failure */
2258 http_bio_free(BIO
*h
) /* I - BIO data */
2274 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
2277 static int /* O - 1 on success, 0 on failure */
2278 http_bio_new(BIO
*h
) /* I - BIO data */
2293 * 'http_bio_puts()' - Send a string for OpenSSL.
2296 static int /* O - Bytes written */
2297 http_bio_puts(BIO
*h
, /* I - BIO data */
2298 const char *str
) /* I - String to write */
2301 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
2303 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
2309 * 'http_bio_read()' - Read data for OpenSSL.
2312 static int /* O - Bytes read */
2313 http_bio_read(BIO
*h
, /* I - BIO data */
2314 char *buf
, /* I - Buffer */
2315 int size
) /* I - Number of bytes to read */
2317 http_t
*http
; /* HTTP connection */
2320 http
= (http_t
*)h
->ptr
;
2322 if (!http
->blocking
)
2325 * Make sure we have data before we read...
2328 if (!http_wait(http
, 10000, 0))
2331 http
->error
= WSAETIMEDOUT
;
2333 http
->error
= ETIMEDOUT
;
2340 return (recv(http
->fd
, buf
, size
, 0));
2345 * 'http_bio_write()' - Write data for OpenSSL.
2348 static int /* O - Bytes written */
2349 http_bio_write(BIO
*h
, /* I - BIO data */
2350 const char *buf
, /* I - Buffer to write */
2351 int num
) /* I - Number of bytes to write */
2353 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
2355 #endif /* HAVE_SSL && HAVE_LIBSSL */
2359 * 'http_field()' - Return the field index for a field name.
2362 static http_field_t
/* O - Field index */
2363 http_field(const char *name
) /* I - String name */
2365 int i
; /* Looping var */
2368 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2369 if (strcasecmp(name
, http_fields
[i
]) == 0)
2370 return ((http_field_t
)i
);
2372 return (HTTP_FIELD_UNKNOWN
);
2378 * 'http_read_ssl()' - Read from a SSL/TLS connection.
2381 static int /* O - Bytes read */
2382 http_read_ssl(http_t
*http
, /* I - HTTP connection */
2383 char *buf
, /* I - Buffer to store data */
2384 int len
) /* I - Length of buffer */
2386 # if defined(HAVE_LIBSSL)
2387 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
2389 # elif defined(HAVE_GNUTLS)
2390 return (gnutls_record_recv(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
2392 # elif defined(HAVE_CDSASSL)
2393 int result
; /* Return value */
2394 OSStatus error
; /* Error info */
2395 size_t processed
; /* Number of bytes processed */
2398 error
= SSLRead(((http_tls_t
*)http
->tls
)->session
, buf
, len
, &processed
);
2403 result
= (int)processed
;
2405 case errSSLClosedGraceful
:
2408 case errSSLWouldBlock
:
2410 result
= (int)processed
;
2424 # endif /* HAVE_LIBSSL */
2426 #endif /* HAVE_SSL */
2430 * 'http_send()' - Send a request with all fields and the trailing blank line.
2433 static int /* O - 0 on success, non-zero on error */
2434 http_send(http_t
*http
, /* I - HTTP connection */
2435 http_state_t request
, /* I - Request code */
2436 const char *uri
) /* I - URI */
2438 int i
; /* Looping var */
2439 char *ptr
, /* Pointer in buffer */
2440 buf
[1024]; /* Encoded URI buffer */
2441 static const char * const codes
[] =
2442 { /* Request code strings */
2457 static const char hex
[] = "0123456789ABCDEF";
2461 DEBUG_printf(("http_send(http=%p, request=HTTP_%s, uri=\"%s\")\n",
2462 http
, codes
[request
], uri
));
2464 if (http
== NULL
|| uri
== NULL
)
2468 * Set the User-Agent field if it isn't already...
2471 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
2472 httpSetField(http
, HTTP_FIELD_USER_AGENT
, CUPS_MINIMAL
);
2475 * Encode the URI as needed...
2478 for (ptr
= buf
; *uri
!= '\0' && ptr
< (buf
+ sizeof(buf
) - 1); uri
++)
2479 if (*uri
<= ' ' || *uri
>= 127)
2481 if (ptr
< (buf
+ sizeof(buf
) - 1))
2483 if (ptr
< (buf
+ sizeof(buf
) - 1))
2484 *ptr
++ = hex
[(*uri
>> 4) & 15];
2485 if (ptr
< (buf
+ sizeof(buf
) - 1))
2486 *ptr
++ = hex
[*uri
& 15];
2494 * See if we had an error the last time around; if so, reconnect...
2497 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
2498 if (httpReconnect(http
))
2502 * Flush any written data that is pending...
2506 httpFlushWrite(http
);
2509 * Send the request header...
2512 http
->state
= request
;
2513 http
->data_encoding
= HTTP_ENCODE_FIELDS
;
2515 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
2518 http
->status
= HTTP_CONTINUE
;
2521 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
2523 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
2524 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
2526 #endif /* HAVE_SSL */
2528 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
2530 http
->status
= HTTP_ERROR
;
2534 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2535 if (http
->fields
[i
][0] != '\0')
2537 DEBUG_printf(("%s: %s\n", http_fields
[i
], httpGetField(http
, i
)));
2539 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
],
2540 httpGetField(http
, i
)) < 1)
2542 http
->status
= HTTP_ERROR
;
2548 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
2550 http
->status
= HTTP_ERROR
;
2554 if (http
->expect
== HTTP_CONTINUE
&&
2555 (http
->state
== HTTP_POST_RECV
|| http
->state
== HTTP_PUT_RECV
))
2556 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
2558 http
->status
= HTTP_ERROR
;
2562 if (httpPrintf(http
, "\r\n") < 1)
2564 http
->status
= HTTP_ERROR
;
2568 httpFlushWrite(http
);
2569 httpGetLength2(http
);
2570 httpClearFields(http
);
2573 * The Kerberos and AuthRef authentication strings can only be used once...
2576 if (http
->field_authorization
&& http
->authstring
&&
2577 (!strncmp(http
->authstring
, "Negotiate", 9) ||
2578 !strncmp(http
->authstring
, "AuthRef", 7)))
2580 http
->_authstring
[0] = '\0';
2582 if (http
->authstring
!= http
->_authstring
)
2583 free(http
->authstring
);
2585 http
->authstring
= http
->_authstring
;
2594 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
2597 static int /* O - Status of connection */
2598 http_setup_ssl(http_t
*http
) /* I - HTTP connection */
2601 SSL_CTX
*context
; /* Context for encryption */
2602 SSL
*conn
; /* Connection for encryption */
2603 BIO
*bio
; /* BIO data */
2604 # elif defined(HAVE_GNUTLS)
2605 http_tls_t
*conn
; /* TLS session object */
2606 gnutls_certificate_client_credentials
*credentials
;
2607 /* TLS credentials */
2608 # elif defined(HAVE_CDSASSL)
2609 OSStatus error
; /* Error code */
2610 http_tls_t
*conn
; /* CDSA connection information */
2611 # endif /* HAVE_LIBSSL */
2614 DEBUG_printf(("http_setup_ssl(http=%p)\n", http
));
2617 context
= SSL_CTX_new(SSLv23_client_method());
2619 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
2621 bio
= BIO_new(_httpBIOMethods());
2622 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
2624 conn
= SSL_new(context
);
2625 SSL_set_bio(conn
, bio
, bio
);
2627 if (SSL_connect(conn
) != 1)
2630 unsigned long error
; /* Error code */
2632 while ((error
= ERR_get_error()) != 0)
2633 printf("http_setup_ssl: %s\n", ERR_error_string(error
, NULL
));
2636 SSL_CTX_free(context
);
2640 http
->error
= WSAGetLastError();
2642 http
->error
= errno
;
2644 http
->status
= HTTP_ERROR
;
2646 return (HTTP_ERROR
);
2649 # elif defined(HAVE_GNUTLS)
2650 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
2652 http
->error
= errno
;
2653 http
->status
= HTTP_ERROR
;
2658 credentials
= (gnutls_certificate_client_credentials
*)
2659 malloc(sizeof(gnutls_certificate_client_credentials
));
2660 if (credentials
== NULL
)
2664 http
->error
= errno
;
2665 http
->status
= HTTP_ERROR
;
2670 gnutls_certificate_allocate_credentials(credentials
);
2672 gnutls_init(&(conn
->session
), GNUTLS_CLIENT
);
2673 gnutls_set_default_priority(conn
->session
);
2674 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
2675 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)http
);
2676 gnutls_transport_set_pull_function(conn
->session
, _httpReadGNUTLS
);
2677 gnutls_transport_set_push_function(conn
->session
, _httpWriteGNUTLS
);
2679 if ((gnutls_handshake(conn
->session
)) != GNUTLS_E_SUCCESS
)
2681 http
->error
= errno
;
2682 http
->status
= HTTP_ERROR
;
2687 conn
->credentials
= credentials
;
2689 # elif defined(HAVE_CDSASSL)
2690 conn
= (http_tls_t
*)calloc(1, sizeof(http_tls_t
));
2695 if ((error
= SSLNewContext(false, &conn
->session
)))
2697 http
->error
= error
;
2698 http
->status
= HTTP_ERROR
;
2705 * Use a union to resolve warnings about int/pointer size mismatches...
2708 error
= SSLSetConnection(conn
->session
, http
);
2711 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
2714 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
2717 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
2720 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
2724 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
2730 http
->error
= error
;
2731 http
->status
= HTTP_ERROR
;
2733 SSLDisposeContext(conn
->session
);
2739 # endif /* HAVE_CDSASSL */
2744 #endif /* HAVE_SSL */
2749 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
2753 http_shutdown_ssl(http_t
*http
) /* I - HTTP connection */
2756 SSL_CTX
*context
; /* Context for encryption */
2757 SSL
*conn
; /* Connection for encryption */
2760 conn
= (SSL
*)(http
->tls
);
2761 context
= SSL_get_SSL_CTX(conn
);
2764 SSL_CTX_free(context
);
2767 # elif defined(HAVE_GNUTLS)
2768 http_tls_t
*conn
; /* Encryption session */
2769 gnutls_certificate_client_credentials
*credentials
;
2770 /* TLS credentials */
2773 conn
= (http_tls_t
*)(http
->tls
);
2774 credentials
= (gnutls_certificate_client_credentials
*)(conn
->credentials
);
2776 gnutls_bye(conn
->session
, GNUTLS_SHUT_RDWR
);
2777 gnutls_deinit(conn
->session
);
2778 gnutls_certificate_free_credentials(*credentials
);
2782 # elif defined(HAVE_CDSASSL)
2783 http_tls_t
*conn
; /* CDSA connection information */
2786 conn
= (http_tls_t
*)(http
->tls
);
2788 while (SSLClose(conn
->session
) == errSSLWouldBlock
)
2791 SSLDisposeContext(conn
->session
);
2793 if (conn
->certsArray
)
2794 CFRelease(conn
->certsArray
);
2797 # endif /* HAVE_LIBSSL */
2801 #endif /* HAVE_SSL */
2806 * 'http_upgrade()' - Force upgrade to TLS encryption.
2809 static int /* O - Status of connection */
2810 http_upgrade(http_t
*http
) /* I - HTTP connection */
2812 int ret
; /* Return value */
2813 http_t myhttp
; /* Local copy of HTTP data */
2816 DEBUG_printf(("http_upgrade(%p)\n", http
));
2819 * Copy the HTTP data to a local variable so we can do the OPTIONS
2820 * request without interfering with the existing request data...
2823 memcpy(&myhttp
, http
, sizeof(myhttp
));
2826 * Send an OPTIONS request to the server, requiring SSL or TLS
2827 * encryption on the link...
2830 http
->field_authorization
= NULL
; /* Don't free the auth string */
2832 httpClearFields(http
);
2833 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
2834 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0, SSL/2.0, SSL/3.0");
2836 if ((ret
= httpOptions(http
, "*")) == 0)
2839 * Wait for the secure connection...
2842 while (httpUpdate(http
) == HTTP_CONTINUE
);
2848 * Restore the HTTP request data...
2851 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
2852 http
->data_encoding
= myhttp
.data_encoding
;
2853 http
->data_remaining
= myhttp
.data_remaining
;
2854 http
->_data_remaining
= myhttp
._data_remaining
;
2855 http
->expect
= myhttp
.expect
;
2856 http
->field_authorization
= myhttp
.field_authorization
;
2857 http
->digest_tries
= myhttp
.digest_tries
;
2860 * See if we actually went secure...
2866 * Server does not support HTTP upgrade...
2869 DEBUG_puts("Server does not support HTTP upgrade!");
2872 closesocket(http
->fd
);
2884 #endif /* HAVE_SSL */
2888 * 'http_wait()' - Wait for data available on a connection.
2891 static int /* O - 1 if data is available, 0 otherwise */
2892 http_wait(http_t
*http
, /* I - HTTP connection */
2893 int msec
, /* I - Milliseconds to wait */
2894 int usessl
) /* I - Use SSL context? */
2897 struct pollfd pfd
; /* Polled file descriptor */
2899 fd_set input_set
; /* select() input set */
2900 struct timeval timeout
; /* Timeout */
2901 #endif /* HAVE_POLL */
2902 int nfds
; /* Result from select()/poll() */
2905 DEBUG_printf(("http_wait(http=%p, msec=%d)\n", http
, msec
));
2911 * Check the SSL/TLS buffers for data first...
2915 if (http
->tls
&& usessl
)
2918 if (SSL_pending((SSL
*)(http
->tls
)))
2920 # elif defined(HAVE_GNUTLS)
2921 if (gnutls_record_check_pending(((http_tls_t
*)(http
->tls
))->session
))
2923 # elif defined(HAVE_CDSASSL)
2924 size_t bytes
; /* Bytes that are available */
2926 if (!SSLGetBufferedReadSize(((http_tls_t
*)http
->tls
)->session
, &bytes
) && bytes
> 0)
2928 # endif /* HAVE_LIBSSL */
2930 #endif /* HAVE_SSL */
2933 * Then try doing a select() or poll() to poll the socket...
2938 pfd
.events
= POLLIN
;
2940 while ((nfds
= poll(&pfd
, 1, msec
)) < 0 && errno
== EINTR
);
2945 FD_ZERO(&input_set
);
2946 FD_SET(http
->fd
, &input_set
);
2948 DEBUG_printf(("http_wait: msec=%d, http->fd=%d\n", msec
, http
->fd
));
2952 timeout
.tv_sec
= msec
/ 1000;
2953 timeout
.tv_usec
= (msec
% 1000) * 1000;
2955 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
2958 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
2960 DEBUG_printf(("http_wait: select() returned %d...\n", nfds
));
2963 while (nfds
< 0 && WSAGetLastError() == WSAEINTR
);
2965 while (nfds
< 0 && errno
== EINTR
);
2967 #endif /* HAVE_POLL */
2969 DEBUG_printf(("http_wait: returning with nfds=%d...\n", nfds
));
2976 * 'http_write()' - Write a buffer to a HTTP connection.
2979 static int /* O - Number of bytes written */
2980 http_write(http_t
*http
, /* I - HTTP connection */
2981 const char *buffer
, /* I - Buffer for data */
2982 int length
) /* I - Number of bytes to write */
2984 int tbytes
, /* Total bytes sent */
2985 bytes
; /* Bytes sent */
2994 bytes
= http_write_ssl(http
, buffer
, length
);
2996 #endif /* HAVE_SSL */
2997 bytes
= send(http
->fd
, buffer
, length
, 0);
3002 if (WSAGetLastError() != http
->error
)
3004 http
->error
= WSAGetLastError();
3010 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
3012 http
->error
= errno
;
3017 DEBUG_puts("http_write: error writing data...\n");
3030 printf("http_write: wrote %d bytes: \n", tbytes
);
3031 for (i
= 0, buffer
-= tbytes
; i
< tbytes
; i
+= 16)
3035 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
3036 printf(" %02X", buffer
[i
+ j
] & 255);
3045 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
3047 ch
= buffer
[i
+ j
] & 255;
3049 if (ch
< ' ' || ch
== 127)
3064 * 'http_write_chunk()' - Write a chunked buffer.
3067 static int /* O - Number bytes written */
3068 http_write_chunk(http_t
*http
, /* I - HTTP connection */
3069 const char *buffer
, /* I - Buffer to write */
3070 int length
) /* I - Length of buffer */
3072 char header
[255]; /* Chunk header */
3073 int bytes
; /* Bytes written */
3075 DEBUG_printf(("http_write_chunk(http=%p, buffer=%p, length=%d)\n",
3076 http
, buffer
, length
));
3079 * Write the chunk header, data, and trailer.
3082 sprintf(header
, "%x\r\n", length
);
3083 if (http_write(http
, header
, (int)strlen(header
)) < 0)
3085 DEBUG_puts(" http_write of length failed!");
3089 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
3091 DEBUG_puts(" http_write of buffer failed!");
3095 if (http_write(http
, "\r\n", 2) < 0)
3097 DEBUG_puts(" http_write of CR LF failed!");
3107 * 'http_write_ssl()' - Write to a SSL/TLS connection.
3110 static int /* O - Bytes written */
3111 http_write_ssl(http_t
*http
, /* I - HTTP connection */
3112 const char *buf
, /* I - Buffer holding data */
3113 int len
) /* I - Length of buffer */
3115 # if defined(HAVE_LIBSSL)
3116 return (SSL_write((SSL
*)(http
->tls
), buf
, len
));
3118 # elif defined(HAVE_GNUTLS)
3119 return (gnutls_record_send(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
3120 # elif defined(HAVE_CDSASSL)
3121 int result
; /* Return value */
3122 OSStatus error
; /* Error info */
3123 size_t processed
; /* Number of bytes processed */
3126 error
= SSLWrite(((http_tls_t
*)http
->tls
)->session
, buf
, len
, &processed
);
3131 result
= (int)processed
;
3133 case errSSLClosedGraceful
:
3136 case errSSLWouldBlock
:
3138 result
= (int)processed
;
3152 # endif /* HAVE_LIBSSL */
3154 #endif /* HAVE_SSL */
3158 * End of "$Id: http.c 6649 2007-07-11 21:46:42Z mike $".