2 * "$Id: http.c 7850 2008-08-20 00:07:25Z mike $"
4 * HTTP routines for the Common UNIX Printing System (CUPS).
6 * Copyright 2007-2009 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 the
26 * httpClearCookie() - Clear the cookie value(s).
27 * httpClearFields() - Clear HTTP request fields.
28 * httpClose() - Close an HTTP connection...
29 * httpConnectEncrypt() - Connect to a HTTP server using encryption.
30 * _httpCreate() - Create an unconnected HTTP connection.
31 * httpDelete() - Send a DELETE request to the server.
32 * httpEncryption() - Set the required encryption on the link.
33 * httpError() - Get the last error on a connection.
34 * httpFlush() - Flush data from a HTTP connection.
35 * httpFlushWrite() - Flush data in write buffer.
36 * httpGet() - Send a GET request to the server.
37 * httpGetAuthString() - Get the current authorization string.
38 * httpGetBlocking() - Get the blocking/non-block state of a connection.
39 * httpGetCookie() - Get any cookie data from the response.
40 * httpGetFd() - Get the file descriptor associated with a
42 * httpGetField() - Get a field value from a request/response.
43 * httpGetLength() - Get the amount of data remaining from the
44 * content-length or transfer-encoding fields.
45 * httpGetLength2() - Get the amount of data remaining from the
46 * content-length or transfer-encoding fields.
47 * httpGetStatus() - Get the status of the last HTTP request.
48 * httpGetSubField() - Get a sub-field value.
49 * httpGetSubField2() - Get a sub-field value.
50 * httpGets() - Get a line of text from a HTTP connection.
51 * httpHead() - Send a HEAD request to the server.
52 * httpInitialize() - Initialize the HTTP interface library and set the
53 * default HTTP proxy (if any).
54 * httpOptions() - Send an OPTIONS request to the server.
55 * httpPost() - Send a POST request to the server.
56 * httpPrintf() - Print a formatted string to a HTTP connection.
57 * httpPut() - Send a PUT request to the server.
58 * httpRead() - Read data from a HTTP connection.
59 * httpRead2() - Read data from a HTTP connection.
60 * _httpReadCDSA() - Read function for the CDSA library.
61 * _httpReadGNUTLS() - Read function for the GNU TLS library.
62 * httpReconnect() - Reconnect to a HTTP server.
63 * httpSetAuthString() - Set the current authorization string.
64 * httpSetCookie() - Set the cookie value(s)...
65 * httpSetExpect() - Set the Expect: header in a request.
66 * httpSetField() - Set the value of an HTTP header.
67 * httpSetLength() - Set the content-length and content-encoding.
68 * httpTrace() - Send an TRACE request to the server.
69 * httpUpdate() - Update the current HTTP state for incoming data.
70 * _httpWait() - Wait for data available on a connection (no flush).
71 * httpWait() - Wait for data available on a connection.
72 * httpWrite() - Write data to a HTTP connection.
73 * httpWrite2() - Write data to a HTTP connection.
74 * _httpWriteCDSA() - Write function for the CDSA library.
75 * _httpWriteGNUTLS() - Write function for the GNU TLS library.
76 * http_bio_ctrl() - Control the HTTP connection.
77 * http_bio_free() - Free OpenSSL data.
78 * http_bio_new() - Initialize an OpenSSL BIO structure.
79 * http_bio_puts() - Send a string for OpenSSL.
80 * http_bio_read() - Read data for OpenSSL.
81 * http_bio_write() - Write data for OpenSSL.
82 * http_debug_hex() - Do a hex dump of a buffer.
83 * http_field() - Return the field index for a field name.
84 * http_read_ssl() - Read from a SSL/TLS connection.
85 * http_send() - Send a request with all fields and the trailing
87 * http_setup_ssl() - Set up SSL/TLS support on a connection.
88 * http_shutdown_ssl() - Shut down SSL/TLS on a connection.
89 * http_upgrade() - Force upgrade to TLS encryption.
90 * http_write() - Write a buffer to a HTTP connection.
91 * http_write_chunk() - Write a chunked buffer.
92 * http_write_ssl() - Write to a SSL/TLS connection.
96 * Include necessary headers...
99 #include "http-private.h"
107 # include <sys/time.h>
108 # include <sys/resource.h>
111 # include <sys/poll.h>
112 #endif /* HAVE_POLL */
116 * Some operating systems have done away with the Fxxxx constants for
117 * the fcntl() call; this works around that "feature"...
121 # define FNONBLK O_NONBLOCK
122 #endif /* !FNONBLK */
130 static void http_debug_hex(const char *prefix
, const char *buffer
,
133 static http_field_t
http_field(const char *name
);
134 static int http_send(http_t
*http
, http_state_t request
,
136 static int http_write(http_t
*http
, const char *buffer
,
138 static int http_write_chunk(http_t
*http
, const char *buffer
,
141 static int http_read_ssl(http_t
*http
, char *buf
, int len
);
142 static int http_setup_ssl(http_t
*http
);
143 static void http_shutdown_ssl(http_t
*http
);
144 static int http_upgrade(http_t
*http
);
145 static int http_write_ssl(http_t
*http
, const char *buf
, int len
);
146 #endif /* HAVE_SSL */
153 static const char * const http_fields
[] =
170 "If-Unmodified-since",
184 static const char * const http_states
[] =
204 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
206 * BIO methods for OpenSSL...
209 static int http_bio_write(BIO
*h
, const char *buf
, int num
);
210 static int http_bio_read(BIO
*h
, char *buf
, int size
);
211 static int http_bio_puts(BIO
*h
, const char *str
);
212 static long http_bio_ctrl(BIO
*h
, int cmd
, long arg1
, void *arg2
);
213 static int http_bio_new(BIO
*h
);
214 static int http_bio_free(BIO
*data
);
216 static BIO_METHOD http_bio_methods
=
223 NULL
, /* http_bio_gets, */
232 * '_httpBIOMethods()' - Get the OpenSSL BIO methods for HTTP connections.
235 BIO_METHOD
* /* O - BIO methods for OpenSSL */
236 _httpBIOMethods(void)
238 return (&http_bio_methods
);
240 #endif /* HAVE_SSL && HAVE_LIBSSL */
244 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
248 httpBlocking(http_t
*http
, /* I - Connection to server */
249 int b
) /* I - 1 = blocking, 0 = non-blocking */
257 * 'httpCheck()' - Check to see if there is a pending response from the server.
260 int /* O - 0 = no data, 1 = data available */
261 httpCheck(http_t
*http
) /* I - Connection to server */
263 return (httpWait(http
, 0));
268 * 'httpClearCookie()' - Clear the cookie value(s).
270 * @since CUPS 1.1.19/Mac OS X 10.3@
274 httpClearCookie(http_t
*http
) /* I - Connection to server */
288 * 'httpClearFields()' - Clear HTTP request fields.
292 httpClearFields(http_t
*http
) /* I - Connection to server */
296 memset(http
->fields
, 0, sizeof(http
->fields
));
297 if (http
->hostname
[0] == '/')
298 httpSetField(http
, HTTP_FIELD_HOST
, "localhost");
300 httpSetField(http
, HTTP_FIELD_HOST
, http
->hostname
);
302 if (http
->field_authorization
)
304 free(http
->field_authorization
);
305 http
->field_authorization
= NULL
;
308 http
->expect
= (http_status_t
)0;
314 * 'httpClose()' - Close an HTTP connection...
318 httpClose(http_t
*http
) /* I - Connection to server */
321 OM_uint32 minor_status
; /* Minor status code */
322 #endif /* HAVE_GSSAPI */
325 DEBUG_printf(("httpClose(http=%p)", http
));
330 httpAddrFreeList(http
->addrlist
);
337 http_shutdown_ssl(http
);
338 #endif /* HAVE_SSL */
341 closesocket(http
->fd
);
347 if (http
->gssctx
!= GSS_C_NO_CONTEXT
)
348 gss_delete_sec_context(&minor_status
, &http
->gssctx
, GSS_C_NO_BUFFER
);
350 if (http
->gssname
!= GSS_C_NO_NAME
)
351 gss_release_name(&minor_status
, &http
->gssname
);
352 #endif /* HAVE_GSSAPI */
354 #ifdef HAVE_AUTHORIZATION_H
356 AuthorizationFree(http
->auth_ref
, kAuthorizationFlagDefaults
);
357 #endif /* HAVE_AUTHORIZATION_H */
359 httpClearFields(http
);
361 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
362 free(http
->authstring
);
369 * 'httpConnect()' - Connect to a HTTP server.
371 * This function is deprecated - use @link httpConnectEncrypt@ instead.
376 http_t
* /* O - New HTTP connection */
377 httpConnect(const char *host
, /* I - Host to connect to */
378 int port
) /* I - Port number */
380 return (httpConnectEncrypt(host
, port
, HTTP_ENCRYPT_IF_REQUESTED
));
385 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
388 http_t
* /* O - New HTTP connection */
390 const char *host
, /* I - Host to connect to */
391 int port
, /* I - Port number */
392 http_encryption_t encryption
) /* I - Type of encryption to use */
394 http_t
*http
; /* New HTTP connection */
397 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)",
398 host
, port
, encryption
));
401 * Create the HTTP structure...
404 if ((http
= _httpCreate(host
, port
, encryption
)) == NULL
)
408 * Connect to the remote system...
411 if (!httpReconnect(http
))
415 * Could not connect to any known address - bail out!
418 httpAddrFreeList(http
->addrlist
);
427 * '_httpCreate()' - Create an unconnected HTTP connection.
430 http_t
* /* O - HTTP connection */
432 const char *host
, /* I - Hostname */
433 int port
, /* I - Port number */
434 http_encryption_t encryption
) /* I - Encryption to use */
436 http_t
*http
; /* New HTTP connection */
437 http_addrlist_t
*addrlist
; /* Host address data */
438 char service
[255]; /* Service name */
441 DEBUG_printf(("4_httpCreate(host=\"%s\", port=%d, encryption=%d)",
442 host
, port
, encryption
));
453 sprintf(service
, "%d", port
);
455 if ((addrlist
= httpAddrGetList(host
, AF_UNSPEC
, service
)) == NULL
)
459 * Allocate memory for the structure...
462 if ((http
= calloc(sizeof(http_t
), 1)) == NULL
)
464 httpAddrFreeList(addrlist
);
469 * Initialize the HTTP data...
472 http
->activity
= time(NULL
);
473 http
->addrlist
= addrlist
;
477 http
->gssctx
= GSS_C_NO_CONTEXT
;
478 http
->gssname
= GSS_C_NO_NAME
;
479 #endif /* HAVE_GSSAPI */
480 http
->version
= HTTP_1_1
;
482 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
484 if (port
== 443) /* Always use encryption for https */
485 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
487 http
->encryption
= encryption
;
490 * Return the new structure...
498 * 'httpDelete()' - Send a DELETE request to the server.
501 int /* O - Status of call (0 = success) */
502 httpDelete(http_t
*http
, /* I - Connection to server */
503 const char *uri
) /* I - URI to delete */
505 return (http_send(http
, HTTP_DELETE
, uri
));
510 * 'httpEncryption()' - Set the required encryption on the link.
513 int /* O - -1 on error, 0 on success */
514 httpEncryption(http_t
*http
, /* I - Connection to server */
515 http_encryption_t e
) /* I - New encryption preference */
517 DEBUG_printf(("httpEncryption(http=%p, e=%d)", http
, e
));
523 http
->encryption
= e
;
525 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
526 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
527 return (httpReconnect(http
));
528 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
529 return (http_upgrade(http
));
533 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
537 #endif /* HAVE_SSL */
542 * 'httpError()' - Get the last error on a connection.
545 int /* O - Error code (errno) value */
546 httpError(http_t
*http
) /* I - Connection to server */
549 return (http
->error
);
556 * 'httpFlush()' - Flush data from a HTTP connection.
560 httpFlush(http_t
*http
) /* I - Connection to server */
562 char buffer
[8192]; /* Junk buffer */
563 int blocking
; /* To block or not to block */
566 DEBUG_printf(("httpFlush(http=%p), state=%s", http
,
567 http_states
[http
->state
]));
570 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
573 blocking
= http
->blocking
;
577 * Read any data we can...
580 while (httpRead2(http
, buffer
, sizeof(buffer
)) > 0);
583 * Restore blocking and reset the connection if we didn't get all of
584 * the remaining data...
587 http
->blocking
= blocking
;
589 if (http
->state
!= HTTP_WAITING
&& http
->fd
>= 0)
592 * Didn't get the data back, so close the current connection.
595 http
->state
= HTTP_WAITING
;
599 http_shutdown_ssl(http
);
600 #endif /* HAVE_SSL */
603 closesocket(http
->fd
);
614 * 'httpFlushWrite()' - Flush data in write buffer.
616 * @since CUPS 1.2/Mac OS X 10.5@
619 int /* O - Bytes written or -1 on error */
620 httpFlushWrite(http_t
*http
) /* I - Connection to server */
622 int bytes
; /* Bytes written */
625 DEBUG_printf(("httpFlushWrite(http=%p)", http
));
627 if (!http
|| !http
->wused
)
630 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
631 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
633 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
642 * 'httpGet()' - Send a GET request to the server.
645 int /* O - Status of call (0 = success) */
646 httpGet(http_t
*http
, /* I - Connection to server */
647 const char *uri
) /* I - URI to get */
649 return (http_send(http
, HTTP_GET
, uri
));
654 * 'httpGetAuthString()' - Get the current authorization string.
656 * The authorization string is set by cupsDoAuthentication() and
657 * httpSetAuthString(). Use httpGetAuthString() to retrieve the
658 * string to use with httpSetField() for the HTTP_FIELD_AUTHORIZATION
661 * @since CUPS 1.3/Mac OS X 10.5@
664 char * /* O - Authorization string */
665 httpGetAuthString(http_t
*http
) /* I - Connection to server */
668 return (http
->authstring
);
675 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
677 * @since CUPS 1.2/Mac OS X 10.5@
680 int /* O - 1 if blocking, 0 if non-blocking */
681 httpGetBlocking(http_t
*http
) /* I - Connection to server */
683 return (http
? http
->blocking
: 0);
688 * 'httpGetCookie()' - Get any cookie data from the response.
690 * @since CUPS 1.1.19/Mac OS X 10.3@
693 const char * /* O - Cookie data or NULL */
694 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
696 return (http
? http
->cookie
: NULL
);
701 * 'httpGetFd()' - Get the file descriptor associated with a connection.
703 * @since CUPS 1.2/Mac OS X 10.5@
706 int /* O - File descriptor or -1 if none */
707 httpGetFd(http_t
*http
) /* I - Connection to server */
709 return (http
? http
->fd
: -1);
714 * 'httpGetField()' - Get a field value from a request/response.
717 const char * /* O - Field value */
718 httpGetField(http_t
*http
, /* I - Connection to server */
719 http_field_t field
) /* I - Field to get */
721 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
723 else if (field
== HTTP_FIELD_AUTHORIZATION
&&
724 http
->field_authorization
)
727 * Special case for WWW-Authenticate: as its contents can be
728 * longer than HTTP_MAX_VALUE...
731 return (http
->field_authorization
);
734 return (http
->fields
[field
]);
739 * 'httpGetLength()' - Get the amount of data remaining from the
740 * content-length or transfer-encoding fields.
742 * This function is deprecated and will not return lengths larger than
743 * 2^31 - 1; use httpGetLength2() instead.
748 int /* O - Content length */
749 httpGetLength(http_t
*http
) /* I - Connection to server */
752 * Get the read content length and return the 32-bit value.
757 httpGetLength2(http
);
759 return (http
->_data_remaining
);
767 * 'httpGetLength2()' - Get the amount of data remaining from the
768 * content-length or transfer-encoding fields.
770 * This function returns the complete content length, even for
771 * content larger than 2^31 - 1.
773 * @since CUPS 1.2/Mac OS X 10.5@
776 off_t
/* O - Content length */
777 httpGetLength2(http_t
*http
) /* I - Connection to server */
779 DEBUG_printf(("2httpGetLength2(http=%p), state=%s", http
,
780 http_states
[http
->state
]));
785 if (!strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
787 DEBUG_puts("4httpGetLength2: chunked request!");
789 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
790 http
->data_remaining
= 0;
794 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
797 * The following is a hack for HTTP servers that don't send a
798 * content-length or transfer-encoding field...
800 * If there is no content-length then the connection must close
801 * after the transfer is complete...
804 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
807 * Default content length is 0 for errors and 2^31-1 for other
808 * successful requests...
811 if (http
->status
>= HTTP_MULTIPLE_CHOICES
)
812 http
->data_remaining
= 0;
814 http
->data_remaining
= 2147483647;
817 http
->data_remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
820 DEBUG_printf(("4httpGetLength2: content_length=" CUPS_LLFMT
,
821 CUPS_LLCAST http
->data_remaining
));
824 if (http
->data_remaining
<= INT_MAX
)
825 http
->_data_remaining
= (int)http
->data_remaining
;
827 http
->_data_remaining
= INT_MAX
;
829 return (http
->data_remaining
);
834 * 'httpGetStatus()' - Get the status of the last HTTP request.
836 * @since CUPS 1.2/Mac OS X 10.5@
839 http_status_t
/* O - HTTP status */
840 httpGetStatus(http_t
*http
) /* I - Connection to server */
842 return (http
? http
->status
: HTTP_ERROR
);
847 * 'httpGetSubField()' - Get a sub-field value.
852 char * /* O - Value or NULL */
853 httpGetSubField(http_t
*http
, /* I - Connection to server */
854 http_field_t field
, /* I - Field index */
855 const char *name
, /* I - Name of sub-field */
856 char *value
) /* O - Value string */
858 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
863 * 'httpGetSubField2()' - Get a sub-field value.
865 * @since CUPS 1.2/Mac OS X 10.5@
868 char * /* O - Value or NULL */
869 httpGetSubField2(http_t
*http
, /* I - Connection to server */
870 http_field_t field
, /* I - Field index */
871 const char *name
, /* I - Name of sub-field */
872 char *value
, /* O - Value string */
873 int valuelen
) /* I - Size of value buffer */
875 const char *fptr
; /* Pointer into field */
876 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
877 *ptr
, /* Pointer into string buffer */
878 *end
; /* End of value buffer */
880 DEBUG_printf(("2httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, "
881 "valuelen=%d)", http
, field
, name
, value
, valuelen
));
883 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
884 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
887 end
= value
+ valuelen
- 1;
889 for (fptr
= http
->fields
[field
]; *fptr
;)
892 * Skip leading whitespace...
895 while (isspace(*fptr
& 255))
905 * Get the sub-field name...
909 *fptr
&& *fptr
!= '=' && !isspace(*fptr
& 255) &&
910 ptr
< (temp
+ sizeof(temp
) - 1);
915 DEBUG_printf(("4httpGetSubField2: name=\"%s\"", temp
));
918 * Skip trailing chars up to the '='...
921 while (isspace(*fptr
& 255))
931 * Skip = and leading whitespace...
936 while (isspace(*fptr
& 255))
942 * Read quoted string...
945 for (ptr
= value
, fptr
++;
946 *fptr
&& *fptr
!= '\"' && ptr
< end
;
951 while (*fptr
&& *fptr
!= '\"')
960 * Read unquoted string...
964 *fptr
&& !isspace(*fptr
& 255) && *fptr
!= ',' && ptr
< end
;
969 while (*fptr
&& !isspace(*fptr
& 255) && *fptr
!= ',')
973 DEBUG_printf(("4httpGetSubField2: value=\"%s\"", value
));
976 * See if this is the one...
979 if (!strcmp(name
, temp
))
981 DEBUG_printf(("3httpGetSubField2: Returning \"%s\"", value
));
988 DEBUG_puts("3httpGetSubField2: Returning NULL");
995 * 'httpGets()' - Get a line of text from a HTTP connection.
998 char * /* O - Line or NULL */
999 httpGets(char *line
, /* I - Line to read into */
1000 int length
, /* I - Max length of buffer */
1001 http_t
*http
) /* I - Connection to server */
1003 char *lineptr
, /* Pointer into line */
1004 *lineend
, /* End of line */
1005 *bufptr
, /* Pointer into input buffer */
1006 *bufend
; /* Pointer to end of buffer */
1007 int bytes
, /* Number of bytes read */
1008 eol
; /* End-of-line? */
1011 DEBUG_printf(("2httpGets(line=%p, length=%d, http=%p)", line
, length
, http
));
1013 if (http
== NULL
|| line
== NULL
)
1017 * Read a line from the buffer...
1022 lineend
= line
+ length
- 1;
1025 while (lineptr
< lineend
)
1028 * Pre-load the buffer as needed...
1037 while (http
->used
== 0)
1040 * No newline; see if there is more data to be read...
1043 if (!http
->blocking
&& !_httpWait(http
, 10000, 1))
1045 DEBUG_puts("3httpGets: Timed out!");
1047 http
->error
= WSAETIMEDOUT
;
1049 http
->error
= ETIMEDOUT
;
1056 bytes
= http_read_ssl(http
, http
->buffer
+ http
->used
,
1057 HTTP_MAX_BUFFER
- http
->used
);
1059 #endif /* HAVE_SSL */
1060 bytes
= recv(http
->fd
, http
->buffer
+ http
->used
,
1061 HTTP_MAX_BUFFER
- http
->used
, 0);
1063 DEBUG_printf(("4httpGets: read %d bytes...", bytes
));
1068 * Nope, can't get a line this time...
1072 if (WSAGetLastError() != http
->error
)
1074 http
->error
= WSAGetLastError();
1078 DEBUG_printf(("3httpGets: recv() error %d!", WSAGetLastError()));
1080 DEBUG_printf(("3httpGets: recv() error %d!", errno
));
1082 if (errno
== EINTR
|| errno
== EAGAIN
)
1084 else if (errno
!= http
->error
)
1086 http
->error
= errno
;
1093 else if (bytes
== 0)
1095 http
->error
= EPIPE
;
1101 * Yup, update the amount used...
1104 http
->used
+= bytes
;
1108 * Now copy as much of the current line as possible...
1111 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1112 lineptr
< lineend
&& bufptr
< bufend
;)
1114 if (*bufptr
== 0x0a)
1120 else if (*bufptr
== 0x0d)
1123 *lineptr
++ = *bufptr
++;
1126 http
->used
-= (int)(bufptr
- http
->buffer
);
1128 memmove(http
->buffer
, bufptr
, http
->used
);
1136 http
->activity
= time(NULL
);
1140 DEBUG_printf(("3httpGets: Returning \"%s\"", line
));
1146 DEBUG_puts("3httpGets: No new line available!");
1153 * 'httpHead()' - Send a HEAD request to the server.
1156 int /* O - Status of call (0 = success) */
1157 httpHead(http_t
*http
, /* I - Connection to server */
1158 const char *uri
) /* I - URI for head */
1160 DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", http
, uri
));
1161 return (http_send(http
, HTTP_HEAD
, uri
));
1166 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1167 * default HTTP proxy (if any).
1171 httpInitialize(void)
1175 struct timeval curtime
; /* Current time in microseconds */
1176 # endif /* !WIN32 */
1177 int i
; /* Looping var */
1178 unsigned char data
[1024]; /* Seed data */
1179 #endif /* HAVE_LIBSSL */
1182 WSADATA winsockdata
; /* WinSock data */
1183 static int initialized
= 0; /* Has WinSock been initialized? */
1187 WSAStartup(MAKEWORD(1,1), &winsockdata
);
1188 #elif !defined(SO_NOSIGPIPE)
1190 * Ignore SIGPIPE signals...
1194 sigset(SIGPIPE
, SIG_IGN
);
1195 # elif defined(HAVE_SIGACTION)
1196 struct sigaction action
; /* POSIX sigaction data */
1199 memset(&action
, 0, sizeof(action
));
1200 action
.sa_handler
= SIG_IGN
;
1201 sigaction(SIGPIPE
, &action
, NULL
);
1203 signal(SIGPIPE
, SIG_IGN
);
1204 # endif /* !SO_NOSIGPIPE */
1208 gnutls_global_init();
1209 #endif /* HAVE_GNUTLS */
1212 SSL_load_error_strings();
1216 * Using the current time is a dubious random seed, but on some systems
1217 * it is the best we can do (on others, this seed isn't even used...)
1222 gettimeofday(&curtime
, NULL
);
1223 srand(curtime
.tv_sec
+ curtime
.tv_usec
);
1226 for (i
= 0; i
< sizeof(data
); i
++)
1229 RAND_seed(data
, sizeof(data
));
1230 #endif /* HAVE_LIBSSL */
1235 * 'httpOptions()' - Send an OPTIONS request to the server.
1238 int /* O - Status of call (0 = success) */
1239 httpOptions(http_t
*http
, /* I - Connection to server */
1240 const char *uri
) /* I - URI for options */
1242 return (http_send(http
, HTTP_OPTIONS
, uri
));
1247 * 'httpPost()' - Send a POST request to the server.
1250 int /* O - Status of call (0 = success) */
1251 httpPost(http_t
*http
, /* I - Connection to server */
1252 const char *uri
) /* I - URI for post */
1254 return (http_send(http
, HTTP_POST
, uri
));
1259 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1264 int /* O - Number of bytes written */
1265 httpPrintf(http_t
*http
, /* I - Connection to server */
1266 const char *format
, /* I - printf-style format string */
1267 ...) /* I - Additional args as needed */
1269 int bytes
; /* Number of bytes to write */
1270 char buf
[16384]; /* Buffer for formatted string */
1271 va_list ap
; /* Variable argument pointer */
1274 DEBUG_printf(("2httpPrintf(http=%p, format=\"%s\", ...)", http
, format
));
1276 va_start(ap
, format
);
1277 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1280 DEBUG_printf(("3httpPrintf: %s", buf
));
1282 if (http
->data_encoding
== HTTP_ENCODE_FIELDS
)
1283 return (httpWrite2(http
, buf
, bytes
));
1288 DEBUG_puts("4httpPrintf: flushing existing data...");
1290 if (httpFlushWrite(http
) < 0)
1294 return (http_write(http
, buf
, bytes
));
1300 * 'httpPut()' - Send a PUT request to the server.
1303 int /* O - Status of call (0 = success) */
1304 httpPut(http_t
*http
, /* I - Connection to server */
1305 const char *uri
) /* I - URI to put */
1307 DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", http
, uri
));
1308 return (http_send(http
, HTTP_PUT
, uri
));
1313 * 'httpRead()' - Read data from a HTTP connection.
1315 * This function is deprecated. Use the httpRead2() function which can
1316 * read more than 2GB of data.
1321 int /* O - Number of bytes read */
1322 httpRead(http_t
*http
, /* I - Connection to server */
1323 char *buffer
, /* I - Buffer for data */
1324 int length
) /* I - Maximum number of bytes */
1326 return ((int)httpRead2(http
, buffer
, length
));
1331 * 'httpRead2()' - Read data from a HTTP connection.
1333 * @since CUPS 1.2/Mac OS X 10.5@
1336 ssize_t
/* O - Number of bytes read */
1337 httpRead2(http_t
*http
, /* I - Connection to server */
1338 char *buffer
, /* I - Buffer for data */
1339 size_t length
) /* I - Maximum number of bytes */
1341 ssize_t bytes
; /* Bytes read */
1342 char len
[32]; /* Length string */
1345 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1346 http
, buffer
, CUPS_LLCAST length
));
1348 if (http
== NULL
|| buffer
== NULL
)
1351 http
->activity
= time(NULL
);
1357 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1358 http
->data_remaining
<= 0)
1360 DEBUG_puts("2httpRead2: Getting chunk length...");
1362 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1364 DEBUG_puts("1httpRead2: Could not get length!");
1368 http
->data_remaining
= strtoll(len
, NULL
, 16);
1369 if (http
->data_remaining
< 0)
1371 DEBUG_puts("1httpRead2: Negative chunk length!");
1376 DEBUG_printf(("2httpRead2: data_remaining=" CUPS_LLFMT
,
1377 CUPS_LLCAST http
->data_remaining
));
1379 if (http
->data_remaining
<= 0)
1382 * A zero-length chunk ends a transfer; unless we are reading POST
1386 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1387 httpGets(len
, sizeof(len
), http
);
1389 if (http
->state
== HTTP_POST_RECV
)
1392 http
->state
= HTTP_WAITING
;
1395 * Prevent future reads for this request...
1398 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1402 else if (length
> (size_t)http
->data_remaining
)
1403 length
= (size_t)http
->data_remaining
;
1405 if (http
->used
== 0 && length
<= 256)
1408 * Buffer small reads for better performance...
1411 if (!http
->blocking
&& !httpWait(http
, 10000))
1414 if (http
->data_remaining
> sizeof(http
->buffer
))
1415 bytes
= sizeof(http
->buffer
);
1417 bytes
= http
->data_remaining
;
1421 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1423 #endif /* HAVE_SSL */
1425 DEBUG_printf(("2httpRead2: reading %d bytes from socket into buffer...",
1428 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1430 DEBUG_printf(("2httpRead2: read %d bytes from socket into buffer...",
1439 http
->error
= WSAGetLastError();
1442 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1444 http
->error
= errno
;
1451 http
->error
= EPIPE
;
1458 if (length
> (size_t)http
->used
)
1459 length
= (size_t)http
->used
;
1461 bytes
= (ssize_t
)length
;
1463 DEBUG_printf(("2httpRead2: grabbing %d bytes from input buffer...",
1466 memcpy(buffer
, http
->buffer
, length
);
1467 http
->used
-= (int)length
;
1470 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
1475 if (!http
->blocking
&& !httpWait(http
, 10000))
1478 bytes
= (ssize_t
)http_read_ssl(http
, buffer
, (int)length
);
1480 #endif /* HAVE_SSL */
1483 if (!http
->blocking
&& !httpWait(http
, 10000))
1486 DEBUG_printf(("2httpRead2: reading " CUPS_LLFMT
" bytes from socket...",
1487 CUPS_LLCAST length
));
1490 bytes
= (ssize_t
)recv(http
->fd
, buffer
, (int)length
, 0);
1492 while ((bytes
= recv(http
->fd
, buffer
, length
, 0)) < 0)
1493 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1497 DEBUG_printf(("2httpRead2: read " CUPS_LLFMT
" bytes from socket...",
1498 CUPS_LLCAST bytes
));
1503 http
->data_remaining
-= bytes
;
1505 if (http
->data_remaining
<= INT_MAX
)
1506 http
->_data_remaining
= (int)http
->data_remaining
;
1508 http
->_data_remaining
= INT_MAX
;
1513 http
->error
= WSAGetLastError();
1515 if (errno
== EINTR
|| errno
== EAGAIN
)
1518 http
->error
= errno
;
1523 http
->error
= EPIPE
;
1527 if (http
->data_remaining
== 0)
1529 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1530 httpGets(len
, sizeof(len
), http
);
1532 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
1534 if (http
->state
== HTTP_POST_RECV
)
1537 http
->state
= HTTP_WAITING
;
1542 http_debug_hex("httpRead2", buffer
, (int)bytes
);
1549 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
1551 * '_httpReadCDSA()' - Read function for the CDSA library.
1554 OSStatus
/* O - -1 on error, 0 on success */
1556 SSLConnectionRef connection
, /* I - SSL/TLS connection */
1557 void *data
, /* I - Data buffer */
1558 size_t *dataLength
) /* IO - Number of bytes */
1560 OSStatus result
; /* Return value */
1561 ssize_t bytes
; /* Number of bytes read */
1562 http_t
*http
; /* HTTP connection */
1565 http
= (http_t
*)connection
;
1567 if (!http
->blocking
)
1570 * Make sure we have data before we read...
1573 if (!_httpWait(http
, 10000, 0))
1575 http
->error
= ETIMEDOUT
;
1582 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
1584 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
1586 if (bytes
== *dataLength
)
1592 *dataLength
= bytes
;
1593 result
= errSSLWouldBlock
;
1600 result
= errSSLClosedGraceful
;
1601 else if (errno
== EAGAIN
)
1602 result
= errSSLWouldBlock
;
1604 result
= errSSLClosedAbort
;
1609 #endif /* HAVE_SSL && HAVE_CDSASSL */
1612 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
1614 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
1617 ssize_t
/* O - Number of bytes read or -1 on error */
1619 gnutls_transport_ptr ptr
, /* I - Connection to server */
1620 void *data
, /* I - Buffer */
1621 size_t length
) /* I - Number of bytes to read */
1623 http_t
*http
; /* HTTP connection */
1626 http
= (http_t
*)ptr
;
1628 if (!http
->blocking
)
1631 * Make sure we have data before we read...
1634 if (!_httpWait(http
, 10000, 0))
1636 http
->error
= ETIMEDOUT
;
1641 return (recv(http
->fd
, data
, length
, 0));
1643 #endif /* HAVE_SSL && HAVE_GNUTLS */
1647 * 'httpReconnect()' - Reconnect to a HTTP server.
1650 int /* O - 0 on success, non-zero on failure */
1651 httpReconnect(http_t
*http
) /* I - Connection to server */
1653 http_addrlist_t
*addr
; /* Connected address */
1655 http_addrlist_t
*current
; /* Current address */
1656 char temp
[256]; /* Temporary address string */
1660 DEBUG_printf(("httpReconnect(http=%p)", http
));
1668 DEBUG_puts("2httpReconnect: Shutting down SSL/TLS...");
1669 http_shutdown_ssl(http
);
1671 #endif /* HAVE_SSL */
1674 * Close any previously open socket...
1679 DEBUG_printf(("2httpReconnect: Closing socket %d...", http
->fd
));
1682 closesocket(http
->fd
);
1691 * Connect to the server...
1695 for (current
= http
->addrlist
; current
; current
= current
->next
)
1696 DEBUG_printf(("2httpReconnect: Address %s:%d",
1697 httpAddrString(&(current
->addr
), temp
, sizeof(temp
)),
1698 _httpAddrPort(&(current
->addr
))));
1701 if ((addr
= httpAddrConnect(http
->addrlist
, &(http
->fd
))) == NULL
)
1704 * Unable to connect...
1708 http
->error
= WSAGetLastError();
1710 http
->error
= errno
;
1712 http
->status
= HTTP_ERROR
;
1714 DEBUG_printf(("1httpReconnect: httpAddrConnect failed: %s",
1715 strerror(http
->error
)));
1720 DEBUG_printf(("2httpReconnect: New socket=%d", http
->fd
));
1722 http
->hostaddr
= &(addr
->addr
);
1724 http
->status
= HTTP_CONTINUE
;
1727 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
1730 * Always do encryption via SSL.
1733 if (http_setup_ssl(http
) != 0)
1736 closesocket(http
->fd
);
1744 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
1745 return (http_upgrade(http
));
1746 #endif /* HAVE_SSL */
1748 DEBUG_printf(("1httpReconnect: Connected to %s:%d...",
1749 httpAddrString(http
->hostaddr
, temp
, sizeof(temp
)),
1750 _httpAddrPort(http
->hostaddr
)));
1757 * 'httpSetAuthString()' - Set the current authorization string.
1759 * This function just stores a copy of the current authorization string in
1760 * the HTTP connection object. You must still call httpSetField() to set
1761 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
1762 * httpHead(), httpOptions(), httpPost, or httpPut().
1764 * @since CUPS 1.3/Mac OS X 10.5@
1768 httpSetAuthString(http_t
*http
, /* I - Connection to server */
1769 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
1770 const char *data
) /* I - Auth data (NULL for none) */
1773 * Range check input...
1779 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
1780 free(http
->authstring
);
1782 http
->authstring
= http
->_authstring
;
1787 * Set the current authorization string...
1790 int len
= (int)strlen(scheme
) + (data
? (int)strlen(data
) + 1 : 0) + 1;
1793 if (len
> (int)sizeof(http
->_authstring
))
1795 if ((temp
= malloc(len
)) == NULL
)
1796 len
= sizeof(http
->_authstring
);
1798 http
->authstring
= temp
;
1802 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
1804 strlcpy(http
->authstring
, scheme
, len
);
1809 * Clear the current authorization string...
1812 http
->_authstring
[0] = '\0';
1818 * 'httpSetCookie()' - Set the cookie value(s)...
1820 * @since CUPS 1.1.19/Mac OS X 10.3@
1824 httpSetCookie(http_t
*http
, /* I - Connection */
1825 const char *cookie
) /* I - Cookie string */
1834 http
->cookie
= strdup(cookie
);
1836 http
->cookie
= NULL
;
1841 * 'httpSetExpect()' - Set the Expect: header in a request.
1843 * Currently only HTTP_CONTINUE is supported for the "expect" argument.
1845 * @since CUPS 1.2/Mac OS X 10.5@
1849 httpSetExpect(http_t
*http
, /* I - Connection to server */
1850 http_status_t expect
) /* I - HTTP status to expect (HTTP_CONTINUE) */
1853 http
->expect
= expect
;
1858 * 'httpSetField()' - Set the value of an HTTP header.
1862 httpSetField(http_t
*http
, /* I - Connection to server */
1863 http_field_t field
, /* I - Field index */
1864 const char *value
) /* I - Value */
1867 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
1868 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
1872 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
1874 if (field
== HTTP_FIELD_AUTHORIZATION
)
1877 * Special case for Authorization: as its contents can be
1878 * longer than HTTP_MAX_VALUE
1881 if (http
->field_authorization
)
1882 free(http
->field_authorization
);
1884 http
->field_authorization
= strdup(value
);
1886 else if (field
== HTTP_FIELD_HOST
)
1889 * Special-case for Host: as we don't want a trailing "." on the hostname and
1890 * need to bracket IPv6 numeric addresses.
1893 char *ptr
= strchr(value
, ':');
1895 if (value
[0] != '[' && ptr
&& strchr(ptr
+ 1, ':'))
1898 * Bracket IPv6 numeric addresses...
1900 * This is slightly inefficient (basically copying twice), but is an edge
1901 * case and not worth optimizing...
1904 snprintf(http
->fields
[HTTP_FIELD_HOST
],
1905 sizeof(http
->fields
[HTTP_FIELD_HOST
]), "[%s]", value
);
1910 * Check for a trailing dot on the hostname...
1913 ptr
= http
->fields
[HTTP_FIELD_HOST
];
1917 ptr
+= strlen(ptr
) - 1;
1928 * 'httpSetLength()' - Set the content-length and content-encoding.
1930 * @since CUPS 1.2/Mac OS X 10.5@
1934 httpSetLength(http_t
*http
, /* I - Connection to server */
1935 size_t length
) /* I - Length (0 for chunked) */
1942 strcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked");
1943 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
1947 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
1948 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
1949 CUPS_LLFMT
, CUPS_LLCAST length
);
1955 * 'httpTrace()' - Send an TRACE request to the server.
1958 int /* O - Status of call (0 = success) */
1959 httpTrace(http_t
*http
, /* I - Connection to server */
1960 const char *uri
) /* I - URI for trace */
1962 return (http_send(http
, HTTP_TRACE
, uri
));
1967 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1970 http_status_t
/* O - HTTP status */
1971 httpUpdate(http_t
*http
) /* I - Connection to server */
1973 char line
[32768], /* Line from connection... */
1974 *value
; /* Pointer to value on line */
1975 http_field_t field
; /* Field index */
1976 int major
, minor
, /* HTTP version numbers */
1977 status
; /* Request status */
1980 DEBUG_printf(("httpUpdate(http=%p), state=%s", http
,
1981 http_states
[http
->state
]));
1984 * Flush pending data, if any...
1989 DEBUG_puts("2httpUpdate: flushing buffer...");
1991 if (httpFlushWrite(http
) < 0)
1992 return (HTTP_ERROR
);
1996 * If we haven't issued any commands, then there is nothing to "update"...
1999 if (http
->state
== HTTP_WAITING
)
2000 return (HTTP_CONTINUE
);
2003 * Grab all of the lines we can from the connection...
2006 while (httpGets(line
, sizeof(line
), http
) != NULL
)
2008 DEBUG_printf(("2httpUpdate: Got \"%s\"", line
));
2010 if (line
[0] == '\0')
2013 * Blank line means the start of the data section (if any). Return
2014 * the result code, too...
2016 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
2017 * Instead, we just return HTTP_CONTINUE to the caller and keep on
2021 if (http
->status
== HTTP_CONTINUE
)
2022 return (http
->status
);
2024 if (http
->status
< HTTP_BAD_REQUEST
)
2025 http
->digest_tries
= 0;
2028 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
2030 if (http_setup_ssl(http
) != 0)
2033 closesocket(http
->fd
);
2038 return (HTTP_ERROR
);
2041 return (HTTP_CONTINUE
);
2043 #endif /* HAVE_SSL */
2045 httpGetLength2(http
);
2047 switch (http
->state
)
2051 case HTTP_POST_RECV
:
2054 case HTTP_POST_SEND
:
2059 http
->state
= HTTP_WAITING
;
2063 return (http
->status
);
2065 else if (!strncmp(line
, "HTTP/", 5))
2068 * Got the beginning of a response...
2071 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &status
) != 3)
2072 return (HTTP_ERROR
);
2074 http
->version
= (http_version_t
)(major
* 100 + minor
);
2075 http
->status
= (http_status_t
)status
;
2077 else if ((value
= strchr(line
, ':')) != NULL
)
2084 while (isspace(*value
& 255))
2088 * Be tolerants of servers that send unknown attribute fields...
2091 if (!strcasecmp(line
, "expect"))
2094 * "Expect: 100-continue" or similar...
2097 http
->expect
= (http_status_t
)atoi(value
);
2099 else if (!strcasecmp(line
, "cookie"))
2102 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
2105 httpSetCookie(http
, value
);
2107 else if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
2109 DEBUG_printf(("1httpUpdate: unknown field %s seen!", line
));
2113 httpSetField(http
, field
, value
);
2117 DEBUG_printf(("1httpUpdate: Bad response line \"%s\"!", line
));
2118 http
->status
= HTTP_ERROR
;
2119 return (HTTP_ERROR
);
2124 * See if there was an error...
2127 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
2129 DEBUG_printf(("1httpUpdate: Returning status %d...", http
->status
));
2130 return (http
->status
);
2135 DEBUG_printf(("1httpUpdate: socket error %d - %s", http
->error
,
2136 strerror(http
->error
)));
2137 http
->status
= HTTP_ERROR
;
2138 return (HTTP_ERROR
);
2142 * If we haven't already returned, then there is nothing new...
2145 return (HTTP_CONTINUE
);
2150 * '_httpWait()' - Wait for data available on a connection (no flush).
2153 int /* O - 1 if data is available, 0 otherwise */
2154 _httpWait(http_t
*http
, /* I - Connection to server */
2155 int msec
, /* I - Milliseconds to wait */
2156 int usessl
) /* I - Use SSL context? */
2159 struct pollfd pfd
; /* Polled file descriptor */
2161 fd_set input_set
; /* select() input set */
2162 struct timeval timeout
; /* Timeout */
2163 #endif /* HAVE_POLL */
2164 int nfds
; /* Result from select()/poll() */
2167 DEBUG_printf(("4_httpWait(http=%p, msec=%d, usessl=%d)", http
, msec
, usessl
));
2173 * Check the SSL/TLS buffers for data first...
2177 if (http
->tls
&& usessl
)
2180 if (SSL_pending((SSL
*)(http
->tls
)))
2182 # elif defined(HAVE_GNUTLS)
2183 if (gnutls_record_check_pending(((http_tls_t
*)(http
->tls
))->session
))
2185 # elif defined(HAVE_CDSASSL)
2186 size_t bytes
; /* Bytes that are available */
2188 if (!SSLGetBufferedReadSize(((http_tls_t
*)(http
->tls
))->session
, &bytes
) &&
2191 # endif /* HAVE_LIBSSL */
2193 #endif /* HAVE_SSL */
2196 * Then try doing a select() or poll() to poll the socket...
2201 pfd
.events
= POLLIN
;
2203 while ((nfds
= poll(&pfd
, 1, msec
)) < 0 &&
2204 (errno
== EINTR
|| errno
== EAGAIN
));
2209 FD_ZERO(&input_set
);
2210 FD_SET(http
->fd
, &input_set
);
2212 DEBUG_printf(("6_httpWait: msec=%d, http->fd=%d", msec
, http
->fd
));
2216 timeout
.tv_sec
= msec
/ 1000;
2217 timeout
.tv_usec
= (msec
% 1000) * 1000;
2219 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
2222 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
2224 DEBUG_printf(("6_httpWait: select() returned %d...", nfds
));
2227 while (nfds
< 0 && WSAGetLastError() == WSAEINTR
);
2229 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
2231 #endif /* HAVE_POLL */
2233 DEBUG_printf(("5_httpWait: returning with nfds=%d...", nfds
));
2240 * 'httpWait()' - Wait for data available on a connection.
2242 * @since CUPS 1.1.19/Mac OS X 10.3@
2245 int /* O - 1 if data is available, 0 otherwise */
2246 httpWait(http_t
*http
, /* I - Connection to server */
2247 int msec
) /* I - Milliseconds to wait */
2250 * First see if there is data in the buffer...
2260 * Flush pending data, if any...
2265 if (httpFlushWrite(http
) < 0)
2270 * If not, check the SSL/TLS buffers and do a select() on the connection...
2273 return (_httpWait(http
, msec
, 1));
2278 * 'httpWrite()' - Write data to a HTTP connection.
2280 * This function is deprecated. Use the httpWrite2() function which can
2281 * write more than 2GB of data.
2286 int /* O - Number of bytes written */
2287 httpWrite(http_t
*http
, /* I - Connection to server */
2288 const char *buffer
, /* I - Buffer for data */
2289 int length
) /* I - Number of bytes to write */
2291 return ((int)httpWrite2(http
, buffer
, length
));
2296 * 'httpWrite2()' - Write data to a HTTP connection.
2298 * @since CUPS 1.2/Mac OS X 10.5@
2301 ssize_t
/* O - Number of bytes written */
2302 httpWrite2(http_t
*http
, /* I - Connection to server */
2303 const char *buffer
, /* I - Buffer for data */
2304 size_t length
) /* I - Number of bytes to write */
2306 ssize_t bytes
; /* Bytes written */
2309 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
2310 buffer
, CUPS_LLCAST length
));
2313 * Range check input...
2316 if (http
== NULL
|| buffer
== NULL
)
2320 * Mark activity on the connection...
2323 http
->activity
= time(NULL
);
2326 * Buffer small writes for better performance...
2331 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
2333 DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
2334 CUPS_LLFMT
")", http
->wused
, CUPS_LLCAST length
));
2336 httpFlushWrite(http
);
2339 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
) &&
2340 length
< sizeof(http
->wbuffer
))
2343 * Write to buffer...
2346 DEBUG_printf(("2httpWrite2: Copying " CUPS_LLFMT
" bytes to wbuffer...",
2347 CUPS_LLCAST length
));
2349 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
2350 http
->wused
+= (int)length
;
2351 bytes
= (ssize_t
)length
;
2356 * Otherwise write the data directly...
2359 DEBUG_printf(("2httpWrite2: Writing " CUPS_LLFMT
" bytes to socket...",
2360 CUPS_LLCAST length
));
2362 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2363 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
2365 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
2367 DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT
" bytes...",
2368 CUPS_LLCAST bytes
));
2371 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
2372 http
->data_remaining
-= bytes
;
2378 * Handle end-of-request processing...
2381 if ((http
->data_encoding
== HTTP_ENCODE_CHUNKED
&& length
== 0) ||
2382 (http
->data_encoding
== HTTP_ENCODE_LENGTH
&& http
->data_remaining
== 0))
2385 * Finished with the transfer; unless we are sending POST or PUT
2389 DEBUG_puts("2httpWrite: changing states...");
2392 httpFlushWrite(http
);
2394 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2397 * Send a 0-length chunk at the end of the request...
2400 http_write(http
, "0\r\n\r\n", 5);
2403 * Reset the data state...
2406 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
2407 http
->data_remaining
= 0;
2410 if (http
->state
== HTTP_POST_RECV
)
2412 else if (http
->state
== HTTP_PUT_RECV
)
2413 http
->state
= HTTP_STATUS
;
2415 http
->state
= HTTP_WAITING
;
2422 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2424 * '_httpWriteCDSA()' - Write function for the CDSA library.
2427 OSStatus
/* O - -1 on error, 0 on success */
2429 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2430 const void *data
, /* I - Data buffer */
2431 size_t *dataLength
) /* IO - Number of bytes */
2433 OSStatus result
; /* Return value */
2434 ssize_t bytes
; /* Number of bytes read */
2435 http_t
*http
; /* HTTP connection */
2438 http
= (http_t
*)connection
;
2442 bytes
= write(http
->fd
, data
, *dataLength
);
2444 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
2446 if (bytes
== *dataLength
)
2450 else if (bytes
>= 0)
2452 *dataLength
= bytes
;
2453 result
= errSSLWouldBlock
;
2459 if (errno
== EAGAIN
)
2460 result
= errSSLWouldBlock
;
2462 result
= errSSLClosedAbort
;
2467 #endif /* HAVE_SSL && HAVE_CDSASSL */
2470 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2472 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
2475 ssize_t
/* O - Number of bytes written or -1 on error */
2477 gnutls_transport_ptr ptr
, /* I - Connection to server */
2478 const void *data
, /* I - Data buffer */
2479 size_t length
) /* I - Number of bytes to write */
2481 return (send(((http_t
*)ptr
)->fd
, data
, length
, 0));
2483 #endif /* HAVE_SSL && HAVE_GNUTLS */
2486 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
2488 * 'http_bio_ctrl()' - Control the HTTP connection.
2491 static long /* O - Result/data */
2492 http_bio_ctrl(BIO
*h
, /* I - BIO data */
2493 int cmd
, /* I - Control command */
2494 long arg1
, /* I - First argument */
2495 void *arg2
) /* I - Second argument */
2502 case BIO_CTRL_RESET
:
2506 case BIO_C_SET_FILE_PTR
:
2511 case BIO_C_GET_FILE_PTR
:
2514 *((void **)arg2
) = h
->ptr
;
2521 case BIO_CTRL_FLUSH
:
2528 * 'http_bio_free()' - Free OpenSSL data.
2531 static int /* O - 1 on success, 0 on failure */
2532 http_bio_free(BIO
*h
) /* I - BIO data */
2548 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
2551 static int /* O - 1 on success, 0 on failure */
2552 http_bio_new(BIO
*h
) /* I - BIO data */
2567 * 'http_bio_puts()' - Send a string for OpenSSL.
2570 static int /* O - Bytes written */
2571 http_bio_puts(BIO
*h
, /* I - BIO data */
2572 const char *str
) /* I - String to write */
2575 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
2577 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
2583 * 'http_bio_read()' - Read data for OpenSSL.
2586 static int /* O - Bytes read */
2587 http_bio_read(BIO
*h
, /* I - BIO data */
2588 char *buf
, /* I - Buffer */
2589 int size
) /* I - Number of bytes to read */
2591 http_t
*http
; /* HTTP connection */
2594 http
= (http_t
*)h
->ptr
;
2596 if (!http
->blocking
)
2599 * Make sure we have data before we read...
2602 if (!_httpWait(http
, 10000, 0))
2605 http
->error
= WSAETIMEDOUT
;
2607 http
->error
= ETIMEDOUT
;
2614 return (recv(http
->fd
, buf
, size
, 0));
2619 * 'http_bio_write()' - Write data for OpenSSL.
2622 static int /* O - Bytes written */
2623 http_bio_write(BIO
*h
, /* I - BIO data */
2624 const char *buf
, /* I - Buffer to write */
2625 int num
) /* I - Number of bytes to write */
2627 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
2629 #endif /* HAVE_SSL && HAVE_LIBSSL */
2634 * 'http_debug_hex()' - Do a hex dump of a buffer.
2638 http_debug_hex(const char *prefix
, /* I - Prefix for line */
2639 const char *buffer
, /* I - Buffer to dump */
2640 int bytes
) /* I - Bytes to dump */
2642 int i
, j
, /* Looping vars */
2643 ch
; /* Current character */
2644 char line
[255], /* Line buffer */
2645 *start
, /* Start of line after prefix */
2646 *ptr
; /* Pointer into line */
2649 if (_cups_debug_fd
< 0 || _cups_debug_level
< 6)
2652 DEBUG_printf(("6%s: %d bytes:\n", prefix
, bytes
));
2654 snprintf(line
, sizeof(line
), "6%s: ", prefix
);
2655 start
= line
+ strlen(line
);
2657 for (i
= 0; i
< bytes
; i
+= 16)
2659 for (j
= 0, ptr
= start
; j
< 16 && (i
+ j
) < bytes
; j
++, ptr
+= 2)
2660 sprintf(ptr
, "%02X", buffer
[i
+ j
] & 255);
2672 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
2674 ch
= buffer
[i
+ j
] & 255;
2676 if (ch
< ' ' || ch
>= 127)
2690 * 'http_field()' - Return the field index for a field name.
2693 static http_field_t
/* O - Field index */
2694 http_field(const char *name
) /* I - String name */
2696 int i
; /* Looping var */
2699 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2700 if (strcasecmp(name
, http_fields
[i
]) == 0)
2701 return ((http_field_t
)i
);
2703 return (HTTP_FIELD_UNKNOWN
);
2709 * 'http_read_ssl()' - Read from a SSL/TLS connection.
2712 static int /* O - Bytes read */
2713 http_read_ssl(http_t
*http
, /* I - Connection to server */
2714 char *buf
, /* I - Buffer to store data */
2715 int len
) /* I - Length of buffer */
2717 # if defined(HAVE_LIBSSL)
2718 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
2720 # elif defined(HAVE_GNUTLS)
2721 ssize_t result
; /* Return value */
2724 result
= gnutls_record_recv(((http_tls_t
*)(http
->tls
))->session
, buf
, len
);
2726 if (result
< 0 && !errno
)
2729 * Convert GNU TLS error to errno value...
2734 case GNUTLS_E_INTERRUPTED
:
2738 case GNUTLS_E_AGAIN
:
2750 return ((int)result
);
2752 # elif defined(HAVE_CDSASSL)
2753 int result
; /* Return value */
2754 OSStatus error
; /* Error info */
2755 size_t processed
; /* Number of bytes processed */
2758 error
= SSLRead(((http_tls_t
*)http
->tls
)->session
, buf
, len
, &processed
);
2763 result
= (int)processed
;
2765 case errSSLClosedGraceful
:
2768 case errSSLWouldBlock
:
2770 result
= (int)processed
;
2784 # endif /* HAVE_LIBSSL */
2786 #endif /* HAVE_SSL */
2790 * 'http_send()' - Send a request with all fields and the trailing blank line.
2793 static int /* O - 0 on success, non-zero on error */
2794 http_send(http_t
*http
, /* I - Connection to server */
2795 http_state_t request
, /* I - Request code */
2796 const char *uri
) /* I - URI */
2798 int i
; /* Looping var */
2799 char buf
[1024]; /* Encoded URI buffer */
2800 static const char * const codes
[] =
2801 { /* Request code strings */
2818 DEBUG_printf(("7http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
2819 http
, codes
[request
], uri
));
2821 if (http
== NULL
|| uri
== NULL
)
2825 * Set the User-Agent field if it isn't already...
2828 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
2829 httpSetField(http
, HTTP_FIELD_USER_AGENT
, CUPS_MINIMAL
);
2832 * Encode the URI as needed...
2835 _httpEncodeURI(buf
, uri
, sizeof(buf
));
2838 * See if we had an error the last time around; if so, reconnect...
2841 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
2842 if (httpReconnect(http
))
2846 * Flush any written data that is pending...
2851 if (httpFlushWrite(http
) < 0)
2852 if (httpReconnect(http
))
2857 * Send the request header...
2860 http
->state
= request
;
2861 http
->data_encoding
= HTTP_ENCODE_FIELDS
;
2863 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
2866 http
->status
= HTTP_CONTINUE
;
2869 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
2871 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
2872 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
2874 #endif /* HAVE_SSL */
2876 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
2878 http
->status
= HTTP_ERROR
;
2882 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2883 if (http
->fields
[i
][0] != '\0')
2885 DEBUG_printf(("9http_send: %s: %s", http_fields
[i
],
2886 httpGetField(http
, i
)));
2888 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
],
2889 httpGetField(http
, i
)) < 1)
2891 http
->status
= HTTP_ERROR
;
2897 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
2899 http
->status
= HTTP_ERROR
;
2903 if (http
->expect
== HTTP_CONTINUE
&&
2904 (http
->state
== HTTP_POST_RECV
|| http
->state
== HTTP_PUT_RECV
))
2905 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
2907 http
->status
= HTTP_ERROR
;
2911 if (httpPrintf(http
, "\r\n") < 1)
2913 http
->status
= HTTP_ERROR
;
2917 if (httpFlushWrite(http
) < 0)
2920 httpGetLength2(http
);
2921 httpClearFields(http
);
2924 * The Kerberos and AuthRef authentication strings can only be used once...
2927 if (http
->field_authorization
&& http
->authstring
&&
2928 (!strncmp(http
->authstring
, "Negotiate", 9) ||
2929 !strncmp(http
->authstring
, "AuthRef", 7)))
2931 http
->_authstring
[0] = '\0';
2933 if (http
->authstring
!= http
->_authstring
)
2934 free(http
->authstring
);
2936 http
->authstring
= http
->_authstring
;
2945 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
2948 static int /* O - Status of connection */
2949 http_setup_ssl(http_t
*http
) /* I - Connection to server */
2952 SSL_CTX
*context
; /* Context for encryption */
2953 SSL
*conn
; /* Connection for encryption */
2954 BIO
*bio
; /* BIO data */
2955 # elif defined(HAVE_GNUTLS)
2956 http_tls_t
*conn
; /* TLS session object */
2957 gnutls_certificate_client_credentials
*credentials
;
2958 /* TLS credentials */
2959 # elif defined(HAVE_CDSASSL)
2960 OSStatus error
; /* Error code */
2961 http_tls_t
*conn
; /* CDSA connection information */
2962 # endif /* HAVE_LIBSSL */
2965 DEBUG_printf(("7http_setup_ssl(http=%p)", http
));
2968 context
= SSL_CTX_new(SSLv23_client_method());
2970 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
2972 bio
= BIO_new(_httpBIOMethods());
2973 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
2975 conn
= SSL_new(context
);
2976 SSL_set_bio(conn
, bio
, bio
);
2978 if (SSL_connect(conn
) != 1)
2981 unsigned long error
; /* Error code */
2983 while ((error
= ERR_get_error()) != 0)
2984 DEBUG_printf(("8http_setup_ssl: %s", ERR_error_string(error
, NULL
)));
2987 SSL_CTX_free(context
);
2991 http
->error
= WSAGetLastError();
2993 http
->error
= errno
;
2995 http
->status
= HTTP_ERROR
;
2997 return (HTTP_ERROR
);
3000 # elif defined(HAVE_GNUTLS)
3001 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
3003 http
->error
= errno
;
3004 http
->status
= HTTP_ERROR
;
3009 credentials
= (gnutls_certificate_client_credentials
*)
3010 malloc(sizeof(gnutls_certificate_client_credentials
));
3011 if (credentials
== NULL
)
3015 http
->error
= errno
;
3016 http
->status
= HTTP_ERROR
;
3021 gnutls_certificate_allocate_credentials(credentials
);
3023 gnutls_init(&(conn
->session
), GNUTLS_CLIENT
);
3024 gnutls_set_default_priority(conn
->session
);
3025 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
3026 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)http
);
3027 gnutls_transport_set_pull_function(conn
->session
, _httpReadGNUTLS
);
3028 gnutls_transport_set_push_function(conn
->session
, _httpWriteGNUTLS
);
3030 if ((gnutls_handshake(conn
->session
)) != GNUTLS_E_SUCCESS
)
3032 http
->error
= errno
;
3033 http
->status
= HTTP_ERROR
;
3035 gnutls_deinit(conn
->session
);
3036 gnutls_certificate_free_credentials(*credentials
);
3043 conn
->credentials
= credentials
;
3045 # elif defined(HAVE_CDSASSL)
3046 conn
= (http_tls_t
*)calloc(1, sizeof(http_tls_t
));
3051 if ((error
= SSLNewContext(false, &conn
->session
)))
3053 http
->error
= error
;
3054 http
->status
= HTTP_ERROR
;
3061 * Use a union to resolve warnings about int/pointer size mismatches...
3064 error
= SSLSetConnection(conn
->session
, http
);
3067 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
3070 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
3073 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
3076 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
3080 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
3086 http
->error
= error
;
3087 http
->status
= HTTP_ERROR
;
3089 SSLDisposeContext(conn
->session
);
3095 # endif /* HAVE_CDSASSL */
3100 #endif /* HAVE_SSL */
3105 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
3109 http_shutdown_ssl(http_t
*http
) /* I - Connection to server */
3112 SSL_CTX
*context
; /* Context for encryption */
3113 SSL
*conn
; /* Connection for encryption */
3116 conn
= (SSL
*)(http
->tls
);
3117 context
= SSL_get_SSL_CTX(conn
);
3120 SSL_CTX_free(context
);
3123 # elif defined(HAVE_GNUTLS)
3124 http_tls_t
*conn
; /* Encryption session */
3125 gnutls_certificate_client_credentials
*credentials
;
3126 /* TLS credentials */
3129 conn
= (http_tls_t
*)(http
->tls
);
3130 credentials
= (gnutls_certificate_client_credentials
*)(conn
->credentials
);
3132 gnutls_bye(conn
->session
, GNUTLS_SHUT_RDWR
);
3133 gnutls_deinit(conn
->session
);
3134 gnutls_certificate_free_credentials(*credentials
);
3138 # elif defined(HAVE_CDSASSL)
3139 http_tls_t
*conn
; /* CDSA connection information */
3142 conn
= (http_tls_t
*)(http
->tls
);
3144 while (SSLClose(conn
->session
) == errSSLWouldBlock
)
3147 SSLDisposeContext(conn
->session
);
3149 if (conn
->certsArray
)
3150 CFRelease(conn
->certsArray
);
3153 # endif /* HAVE_LIBSSL */
3157 #endif /* HAVE_SSL */
3162 * 'http_upgrade()' - Force upgrade to TLS encryption.
3165 static int /* O - Status of connection */
3166 http_upgrade(http_t
*http
) /* I - Connection to server */
3168 int ret
; /* Return value */
3169 http_t myhttp
; /* Local copy of HTTP data */
3172 DEBUG_printf(("7http_upgrade(%p)", http
));
3175 * Flush the connection to make sure any previous "Upgrade" message
3182 * Copy the HTTP data to a local variable so we can do the OPTIONS
3183 * request without interfering with the existing request data...
3186 memcpy(&myhttp
, http
, sizeof(myhttp
));
3189 * Send an OPTIONS request to the server, requiring SSL or TLS
3190 * encryption on the link...
3193 http
->field_authorization
= NULL
; /* Don't free the auth string */
3195 httpClearFields(http
);
3196 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
3197 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0, SSL/2.0, SSL/3.0");
3199 if ((ret
= httpOptions(http
, "*")) == 0)
3202 * Wait for the secure connection...
3205 while (httpUpdate(http
) == HTTP_CONTINUE
);
3209 * Restore the HTTP request data...
3212 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
3213 http
->data_encoding
= myhttp
.data_encoding
;
3214 http
->data_remaining
= myhttp
.data_remaining
;
3215 http
->_data_remaining
= myhttp
._data_remaining
;
3216 http
->expect
= myhttp
.expect
;
3217 http
->field_authorization
= myhttp
.field_authorization
;
3218 http
->digest_tries
= myhttp
.digest_tries
;
3221 * See if we actually went secure...
3227 * Server does not support HTTP upgrade...
3230 DEBUG_puts("8http_upgrade: Server does not support HTTP upgrade!");
3233 closesocket(http
->fd
);
3245 #endif /* HAVE_SSL */
3249 * 'http_write()' - Write a buffer to a HTTP connection.
3252 static int /* O - Number of bytes written */
3253 http_write(http_t
*http
, /* I - Connection to server */
3254 const char *buffer
, /* I - Buffer for data */
3255 int length
) /* I - Number of bytes to write */
3257 int tbytes
, /* Total bytes sent */
3258 bytes
; /* Bytes sent */
3268 bytes
= http_write_ssl(http
, buffer
, length
);
3270 #endif /* HAVE_SSL */
3271 bytes
= send(http
->fd
, buffer
, length
, 0);
3276 if (WSAGetLastError() != http
->error
)
3278 http
->error
= WSAGetLastError();
3282 if (errno
== EINTR
|| errno
== EAGAIN
)
3284 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
3286 http
->error
= errno
;
3291 DEBUG_puts("8http_write: error writing data...");
3302 http_debug_hex("http_write", buffer
- tbytes
, tbytes
);
3310 * 'http_write_chunk()' - Write a chunked buffer.
3313 static int /* O - Number bytes written */
3314 http_write_chunk(http_t
*http
, /* I - Connection to server */
3315 const char *buffer
, /* I - Buffer to write */
3316 int length
) /* I - Length of buffer */
3318 char header
[255]; /* Chunk header */
3319 int bytes
; /* Bytes written */
3322 DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=%d)",
3323 http
, buffer
, length
));
3326 * Write the chunk header, data, and trailer.
3329 sprintf(header
, "%x\r\n", length
);
3330 if (http_write(http
, header
, (int)strlen(header
)) < 0)
3332 DEBUG_puts("8http_write_chunk: http_write of length failed!");
3336 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
3338 DEBUG_puts("8http_write_chunk: http_write of buffer failed!");
3342 if (http_write(http
, "\r\n", 2) < 0)
3344 DEBUG_puts("8http_write_chunk: http_write of CR LF failed!");
3354 * 'http_write_ssl()' - Write to a SSL/TLS connection.
3357 static int /* O - Bytes written */
3358 http_write_ssl(http_t
*http
, /* I - Connection to server */
3359 const char *buf
, /* I - Buffer holding data */
3360 int len
) /* I - Length of buffer */
3362 # if defined(HAVE_LIBSSL)
3363 return (SSL_write((SSL
*)(http
->tls
), buf
, len
));
3365 # elif defined(HAVE_GNUTLS)
3366 ssize_t result
; /* Return value */
3368 result
= gnutls_record_send(((http_tls_t
*)(http
->tls
))->session
, buf
, len
);
3370 if (result
< 0 && !errno
)
3373 * Convert GNU TLS error to errno value...
3378 case GNUTLS_E_INTERRUPTED
:
3382 case GNUTLS_E_AGAIN
:
3394 return ((int)result
);
3396 # elif defined(HAVE_CDSASSL)
3397 int result
; /* Return value */
3398 OSStatus error
; /* Error info */
3399 size_t processed
; /* Number of bytes processed */
3402 error
= SSLWrite(((http_tls_t
*)http
->tls
)->session
, buf
, len
, &processed
);
3407 result
= (int)processed
;
3409 case errSSLClosedGraceful
:
3412 case errSSLWouldBlock
:
3414 result
= (int)processed
;
3428 # endif /* HAVE_LIBSSL */
3430 #endif /* HAVE_SSL */
3434 * End of "$Id: http.c 7850 2008-08-20 00:07:25Z mike $".