4 * HTTP routines for the Common UNIX Printing System (CUPS).
6 * Copyright 1997-2005 by Easy Software Products, all rights reserved.
8 * These coded instructions, statements, and computer programs are the
9 * property of Easy Software Products and are protected by Federal
10 * copyright law. Distribution and use rights are outlined in the file
11 * "LICENSE.txt" which should have been included with this file. If this
12 * file is missing or damaged please contact Easy Software Products
15 * Attn: CUPS Licensing Information
16 * Easy Software Products
17 * 44141 Airport View Drive, Suite 204
18 * Hollywood, Maryland 20636 USA
20 * Voice: (301) 373-9600
21 * EMail: cups-info@cups.org
22 * WWW: http://www.cups.org
24 * This file is subject to the Apple OS-Developed Software exception.
28 * httpCheck() - Check to see if there is a pending response from
30 * httpClearCookie() - Clear the cookie value(s).
31 * httpClose() - Close an HTTP connection...
32 * httpConnect() - Connect to a HTTP server.
33 * httpConnectEncrypt() - Connect to a HTTP server using encryption.
34 * httpDecode64() - Base64-decode a string.
35 * httpDecode64_2() - Base64-decode a string.
36 * httpDelete() - Send a DELETE request to the server.
37 * httpEncode64() - Base64-encode a string.
38 * httpEncode64_2() - Base64-encode a string.
39 * httpEncryption() - Set the required encryption on the link.
40 * httpFlush() - Flush data from a HTTP connection.
41 * httpFlushWrite() - Flush data in write buffer.
42 * httpGet() - Send a GET request to the server.
43 * httpGetDateString() - Get a formatted date/time string from a time value.
44 * httpGetDateString2() - Get a formatted date/time string from a time value.
45 * httpGetDateTime() - Get a time value from a formatted date/time string.
46 * httpGetLength() - Get the amount of data remaining from the
47 * content-length or transfer-encoding fields.
48 * httpGetSubField() - Get a sub-field value.
49 * httpGets() - Get a line of text from a HTTP connection.
50 * httpHead() - Send a HEAD request to the server.
51 * httpInitialize() - Initialize the HTTP interface library and set the
52 * default HTTP proxy (if any).
53 * httpOptions() - Send an OPTIONS request to the server.
54 * httpPost() - Send a POST request to the server.
55 * httpPrintf() - Print a formatted string to a HTTP connection.
56 * httpPut() - Send a PUT request to the server.
57 * httpRead() - Read data from a HTTP connection.
58 * httpReconnect() - Reconnect to a HTTP server...
59 * httpSetCookie() - Set the cookie value(s)...
60 * httpSetField() - Set the value of an HTTP header.
61 * httpTrace() - Send an TRACE request to the server.
62 * httpUpdate() - Update the current HTTP state for incoming data.
63 * httpWait() - Wait for data available on a connection.
64 * httpWrite() - Write data to a HTTP connection.
65 * http_field() - Return the field index for a field name.
66 * http_read_ssl() - Read from a SSL/TLS connection.
67 * http_send() - Send a request with all fields and the trailing
69 * http_setup_ssl() - Set up SSL/TLS on a connection.
70 * http_shutdown_ssl() - Shut down SSL/TLS on a connection.
71 * http_upgrade() - Force upgrade to TLS encryption.
72 * http_wait() - Wait for data available on a connection.
73 * http_write() - Write data to a connection.
74 * http_write_ssl() - Write to a SSL/TLS connection.
75 * http_read_cdsa() - Read function for CDSA decryption code.
76 * http_write_cdsa() - Write function for CDSA encryption code.
80 * Include necessary headers...
83 #include "http-private.h"
91 # include <sys/time.h>
92 # include <sys/resource.h>
97 * Some operating systems have done away with the Fxxxx constants for
98 * the fcntl() call; this works around that "feature"...
102 # define FNONBLK O_NONBLOCK
103 #endif /* !FNONBLK */
110 static http_field_t
http_field(const char *name
);
111 static int http_send(http_t
*http
, http_state_t request
,
113 static int http_wait(http_t
*http
, int msec
);
114 static int http_write(http_t
*http
, const char *buffer
,
116 static int http_write_chunk(http_t
*http
, const char *buffer
,
120 static OSStatus
http_read_cdsa(SSLConnectionRef connection
, void *data
, size_t *dataLength
);
121 # endif /* HAVE_CDSASSL */
122 static int http_read_ssl(http_t
*http
, char *buf
, int len
);
123 static int http_setup_ssl(http_t
*http
);
124 static void http_shutdown_ssl(http_t
*http
);
125 static int http_upgrade(http_t
*http
);
127 static OSStatus
http_write_cdsa(SSLConnectionRef connection
, const void *data
, size_t *dataLength
);
128 # endif /* HAVE_CDSASSL */
129 static int http_write_ssl(http_t
*http
, const char *buf
, int len
);
130 #endif /* HAVE_SSL */
137 static const char * const http_fields
[] =
154 "If-Unmodified-since",
167 static const char * const http_days
[7] =
177 static const char * const http_months
[12] =
195 * 'httpCheck()' - Check to see if there is a pending response from the server.
198 int /* O - 0 = no data, 1 = data available */
199 httpCheck(http_t
*http
) /* I - HTTP connection */
201 return (httpWait(http
, 0));
206 * 'httpClearCookie()' - Clear the cookie value(s).
210 httpClearCookie(http_t
*http
) /* I - Connection */
224 * 'httpClose()' - Close an HTTP connection...
228 httpClose(http_t
*http
) /* I - Connection to close */
230 DEBUG_printf(("httpClose(http=%p)\n", http
));
236 free(http
->input_set
);
243 http_shutdown_ssl(http
);
244 #endif /* HAVE_SSL */
247 closesocket(http
->fd
);
257 * 'httpConnect()' - Connect to a HTTP server.
260 http_t
* /* O - New HTTP connection */
261 httpConnect(const char *host
, /* I - Host to connect to */
262 int port
) /* I - Port number */
264 http_encryption_t encryption
; /* Type of encryption to use */
268 * Set the default encryption status...
272 encryption
= HTTP_ENCRYPT_ALWAYS
;
274 encryption
= HTTP_ENCRYPT_IF_REQUESTED
;
276 return (httpConnectEncrypt(host
, port
, encryption
));
281 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
284 http_t
* /* O - New HTTP connection */
286 const char *host
, /* I - Host to connect to */
287 int port
, /* I - Port number */
288 http_encryption_t encryption
) /* I - Type of encryption to use */
290 int i
; /* Looping var */
291 http_t
*http
; /* New HTTP connection */
292 struct hostent
*hostaddr
; /* Host address data */
295 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encrypt=%d)\n",
296 host
? host
: "(null)", port
, encrypt
));
307 if ((hostaddr
= httpGetHostByName(host
)) == NULL
)
310 * This hack to make users that don't have a localhost entry in
311 * their hosts file or DNS happy...
314 if (strcasecmp(host
, "localhost") != 0)
316 else if ((hostaddr
= httpGetHostByName("127.0.0.1")) == NULL
)
321 * Verify that it is an IPv4, IPv6, or domain address...
324 if ((hostaddr
->h_addrtype
!= AF_INET
|| hostaddr
->h_length
!= 4)
326 && (hostaddr
->h_addrtype
!= AF_INET6
|| hostaddr
->h_length
!= 16)
327 #endif /* AF_INET6 */
329 && (hostaddr
->h_addrtype
!= AF_LOCAL
)
330 #endif /* AF_LOCAL */
335 * Allocate memory for the structure...
338 http
= calloc(sizeof(http_t
), 1);
342 http
->version
= HTTP_1_1
;
344 http
->activity
= time(NULL
);
348 * Set the encryption status...
351 if (port
== 443) /* Always use encryption for https */
352 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
354 http
->encryption
= encryption
;
357 * Loop through the addresses we have until one of them connects...
360 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
362 for (i
= 0; hostaddr
->h_addr_list
[i
]; i
++)
365 * Load the address...
368 httpAddrLoad(hostaddr
, port
, i
, &(http
->hostaddr
));
371 * Connect to the remote system...
374 if (!httpReconnect(http
))
379 * Could not connect to any known address - bail out!
388 * 'httpDecode64()' - Base64-decode a string.
391 char * /* O - Decoded string */
392 httpDecode64(char *out
, /* I - String to write to */
393 const char *in
) /* I - String to read from */
395 int outlen
; /* Output buffer length */
399 * Use the old maximum buffer size for binary compatibility...
404 return (httpDecode64_2(out
, &outlen
, in
));
409 * 'httpDecode64_2()' - Base64-decode a string.
412 char * /* O - Decoded string */
413 httpDecode64_2(char *out
, /* I - String to write to */
414 int *outlen
, /* IO - Size of output string */
415 const char *in
) /* I - String to read from */
417 int pos
, /* Bit position */
418 base64
; /* Value of this character */
419 char *outptr
, /* Output pointer */
420 *outend
; /* End of output buffer */
424 * Range check input...
427 if (!out
|| !outlen
|| *outlen
< 1 || !in
|| !*in
)
431 * Convert from base-64 to bytes...
434 for (outptr
= out
, outend
= out
+ *outlen
- 1, pos
= 0; *in
!= '\0'; in
++)
437 * Decode this character into a number from 0 to 63...
440 if (*in
>= 'A' && *in
<= 'Z')
442 else if (*in
>= 'a' && *in
<= 'z')
443 base64
= *in
- 'a' + 26;
444 else if (*in
>= '0' && *in
<= '9')
445 base64
= *in
- '0' + 52;
456 * Store the result in the appropriate chars...
463 *outptr
= base64
<< 2;
468 *outptr
++ |= (base64
>> 4) & 3;
470 *outptr
= (base64
<< 4) & 255;
475 *outptr
++ |= (base64
>> 2) & 15;
477 *outptr
= (base64
<< 6) & 255;
491 * Return the decoded string and size...
494 *outlen
= (int)(outptr
- out
);
501 * 'httpDelete()' - Send a DELETE request to the server.
504 int /* O - Status of call (0 = success) */
505 httpDelete(http_t
*http
, /* I - HTTP data */
506 const char *uri
) /* I - URI to delete */
508 return (http_send(http
, HTTP_DELETE
, uri
));
513 * 'httpEncode64()' - Base64-encode a string.
516 char * /* O - Encoded string */
517 httpEncode64(char *out
, /* I - String to write to */
518 const char *in
) /* I - String to read from */
520 return (httpEncode64_2(out
, 512, in
, strlen(in
)));
525 * 'httpEncode64_2()' - Base64-encode a string.
528 char * /* O - Encoded string */
529 httpEncode64_2(char *out
, /* I - String to write to */
530 int outlen
, /* I - Size of output string */
531 const char *in
, /* I - String to read from */
532 int inlen
) /* I - Size of input string */
534 char *outptr
, /* Output pointer */
535 *outend
; /* End of output buffer */
536 static const char base64
[] = /* Base64 characters... */
538 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
539 "abcdefghijklmnopqrstuvwxyz"
546 * Range check input...
549 if (!out
|| outlen
< 1 || !in
|| inlen
< 1)
553 * Convert bytes to base-64...
556 for (outptr
= out
, outend
= out
+ outlen
- 1; inlen
> 0; in
++, inlen
--)
559 * Encode the up to 3 characters as 4 Base64 numbers...
563 *outptr
++ = base64
[(in
[0] & 255) >> 2];
565 *outptr
++ = base64
[(((in
[0] & 255) << 4) | ((in
[1] & 255) >> 4)) & 63];
579 *outptr
++ = base64
[(((in
[0] & 255) << 2) | ((in
[1] & 255) >> 6)) & 63];
591 *outptr
++ = base64
[in
[0] & 63];
597 * Return the encoded string...
605 * 'httpEncryption()' - Set the required encryption on the link.
608 int /* O - -1 on error, 0 on success */
609 httpEncryption(http_t
*http
, /* I - HTTP data */
610 http_encryption_t e
) /* I - New encryption preference */
612 DEBUG_printf(("httpEncryption(http=%p, e=%d)\n", http
, e
));
618 http
->encryption
= e
;
620 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
621 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
622 return (httpReconnect(http
));
623 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
624 return (http_upgrade(http
));
628 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
632 #endif /* HAVE_SSL */
637 * 'httpFlush()' - Flush data from a HTTP connection.
641 httpFlush(http_t
*http
) /* I - HTTP data */
643 char buffer
[8192]; /* Junk buffer */
646 DEBUG_printf(("httpFlush(http=%p), state=%d\n", http
, http
->state
));
648 while (httpRead(http
, buffer
, sizeof(buffer
)) > 0);
653 * 'httpFlushWrite()' - Flush data in write buffer.
656 int /* O - Bytes written or -1 on error */
657 httpFlushWrite(http_t
*http
) /* I - HTTP data */
659 int bytes
; /* Bytes written */
662 DEBUG_printf(("httpFlushWrite(http=%p)\n", http
));
664 if (!http
|| !http
->wused
)
667 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
668 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
670 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
679 * 'httpGet()' - Send a GET request to the server.
682 int /* O - Status of call (0 = success) */
683 httpGet(http_t
*http
, /* I - HTTP data */
684 const char *uri
) /* I - URI to get */
686 return (http_send(http
, HTTP_GET
, uri
));
691 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
696 const char * /* O - Date/time string */
697 httpGetDateString(time_t t
) /* I - UNIX time */
699 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
702 return (httpGetDateString2(t
, cg
->http_date
, sizeof(cg
->http_date
)));
707 * 'httpGetDateString2()' - Get a formatted date/time string from a time value.
710 const char * /* O - Date/time string */
711 httpGetDateString2(time_t t
, /* I - UNIX time */
712 char *s
, /* I - String buffer */
713 int slen
) /* I - Size of string buffer */
715 struct tm
*tdate
; /* UNIX date/time data */
719 snprintf(s
, slen
, "%s, %02d %s %d %02d:%02d:%02d GMT",
720 http_days
[tdate
->tm_wday
], tdate
->tm_mday
,
721 http_months
[tdate
->tm_mon
], tdate
->tm_year
+ 1900,
722 tdate
->tm_hour
, tdate
->tm_min
, tdate
->tm_sec
);
729 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
732 time_t /* O - UNIX time */
733 httpGetDateTime(const char *s
) /* I - Date/time string */
735 int i
; /* Looping var */
736 char mon
[16]; /* Abbreviated month name */
737 int day
, year
; /* Day of month and year */
738 int hour
, min
, sec
; /* Time */
739 int days
; /* Number of days since 1970 */
740 static const int normal_days
[] = /* Days to a month, normal years */
741 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
742 static const int leap_days
[] = /* Days to a month, leap years */
743 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 };
746 DEBUG_printf(("httpGetDateTime(s=\"%s\")\n", s
));
749 * Extract the date and time from the formatted string...
752 if (sscanf(s
, "%*s%d%15s%d%d:%d:%d", &day
, mon
, &year
, &hour
, &min
, &sec
) < 6)
755 DEBUG_printf((" day=%d, mon=\"%s\", year=%d, hour=%d, min=%d, sec=%d\n",
756 day
, mon
, year
, hour
, min
, sec
));
759 * Convert the month name to a number from 0 to 11.
762 for (i
= 0; i
< 12; i
++)
763 if (!strcasecmp(mon
, http_months
[i
]))
769 DEBUG_printf((" i=%d\n", i
));
772 * Now convert the date and time to a UNIX time value in seconds since
773 * 1970. We can't use mktime() since the timezone may not be UTC but
774 * the date/time string *is* UTC.
777 if ((year
& 3) == 0 && ((year
% 100) != 0 || (year
% 400) == 0))
778 days
= leap_days
[i
] + day
- 1;
780 days
= normal_days
[i
] + day
- 1;
782 DEBUG_printf((" days=%d\n", days
));
784 days
+= (year
- 1970) * 365 + /* 365 days per year (normally) */
785 ((year
- 1) / 4 - 492) - /* + leap days */
786 ((year
- 1) / 100 - 19) + /* - 100 year days */
787 ((year
- 1) / 400 - 4); /* + 400 year days */
789 DEBUG_printf((" days=%d\n", days
));
791 return (days
* 86400 + hour
* 3600 + min
* 60 + sec
);
796 * 'httpGetSubField()' - Get a sub-field value.
799 char * /* O - Value or NULL */
800 httpGetSubField(http_t
*http
, /* I - HTTP data */
801 http_field_t field
, /* I - Field index */
802 const char *name
, /* I - Name of sub-field */
803 char *value
) /* O - Value string */
805 const char *fptr
; /* Pointer into field */
806 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
807 *ptr
; /* Pointer into string buffer */
810 DEBUG_printf(("httpGetSubField(http=%p, field=%d, name=\"%s\", value=%p)\n",
811 http
, field
, name
, value
));
814 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
815 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
816 name
== NULL
|| value
== NULL
)
819 for (fptr
= http
->fields
[field
]; *fptr
;)
822 * Skip leading whitespace...
825 while (isspace(*fptr
& 255))
835 * Get the sub-field name...
839 *fptr
&& *fptr
!= '=' && !isspace(*fptr
& 255) && ptr
< (temp
+ sizeof(temp
) - 1);
844 DEBUG_printf(("httpGetSubField: name=\"%s\"\n", temp
));
847 * Skip trailing chars up to the '='...
850 while (isspace(*fptr
& 255))
860 * Skip = and leading whitespace...
865 while (isspace(*fptr
& 255))
871 * Read quoted string...
874 for (ptr
= value
, fptr
++;
875 *fptr
&& *fptr
!= '\"' && ptr
< (value
+ HTTP_MAX_VALUE
- 1);
880 while (*fptr
&& *fptr
!= '\"')
889 * Read unquoted string...
893 *fptr
&& !isspace(*fptr
& 255) && *fptr
!= ',' && ptr
< (value
+ HTTP_MAX_VALUE
- 1);
898 while (*fptr
&& !isspace(*fptr
& 255) && *fptr
!= ',')
902 DEBUG_printf(("httpGetSubField: value=\"%s\"\n", value
));
905 * See if this is the one...
908 if (strcmp(name
, temp
) == 0)
919 * 'httpGetLength()' - Get the amount of data remaining from the
920 * content-length or transfer-encoding fields.
923 int /* O - Content length */
924 httpGetLength(http_t
*http
) /* I - HTTP data */
926 DEBUG_printf(("httpGetLength(http=%p), state=%d\n", http
, http
->state
));
928 if (!strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
930 DEBUG_puts("httpGetLength: chunked request!");
932 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
933 http
->data_remaining
= 0;
937 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
940 * The following is a hack for HTTP servers that don't send a
941 * content-length or transfer-encoding field...
943 * If there is no content-length then the connection must close
944 * after the transfer is complete...
947 if (http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] == '\0')
948 http
->data_remaining
= 2147483647;
950 http
->data_remaining
= atoi(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
]);
952 DEBUG_printf(("httpGetLength: content_length=%d\n", http
->data_remaining
));
955 return (http
->data_remaining
);
960 * 'httpGets()' - Get a line of text from a HTTP connection.
963 char * /* O - Line or NULL */
964 httpGets(char *line
, /* I - Line to read into */
965 int length
, /* I - Max length of buffer */
966 http_t
*http
) /* I - HTTP data */
968 char *lineptr
, /* Pointer into line */
969 *bufptr
, /* Pointer into input buffer */
970 *bufend
; /* Pointer to end of buffer */
971 int bytes
; /* Number of bytes read */
974 DEBUG_printf(("httpGets(line=%p, length=%d, http=%p)\n", line
, length
, http
));
976 if (http
== NULL
|| line
== NULL
)
980 * Pre-scan the buffer and see if there is a newline in there...
991 bufptr
= http
->buffer
;
992 bufend
= http
->buffer
+ http
->used
;
994 while (bufptr
< bufend
)
1000 if (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
)
1003 * No newline; see if there is more data to be read...
1006 if (!http
->blocking
&& !http_wait(http
, 1000))
1011 bytes
= http_read_ssl(http
, bufend
, HTTP_MAX_BUFFER
- http
->used
);
1013 #endif /* HAVE_SSL */
1014 bytes
= recv(http
->fd
, bufend
, HTTP_MAX_BUFFER
- http
->used
, 0);
1016 DEBUG_printf(("httpGets: read %d bytes...\n", bytes
));
1021 * Nope, can't get a line this time...
1025 if (WSAGetLastError() != http
->error
)
1027 http
->error
= WSAGetLastError();
1031 DEBUG_printf(("httpGets: recv() error %d!\n", WSAGetLastError()));
1033 DEBUG_printf(("httpGets: recv() error %d!\n", errno
));
1037 else if (errno
!= http
->error
)
1039 http
->error
= errno
;
1046 else if (bytes
== 0)
1048 http
->error
= EPIPE
;
1054 * Yup, update the amount used and the end pointer...
1057 http
->used
+= bytes
;
1062 while (bufptr
>= bufend
&& http
->used
< HTTP_MAX_BUFFER
);
1064 http
->activity
= time(NULL
);
1067 * Read a line from the buffer...
1071 bufptr
= http
->buffer
;
1075 while (bufptr
< bufend
&& bytes
< length
)
1079 if (*bufptr
== 0x0a)
1084 else if (*bufptr
== 0x0d)
1087 *lineptr
++ = *bufptr
++;
1094 http
->used
-= bytes
;
1096 memmove(http
->buffer
, bufptr
, http
->used
);
1098 DEBUG_printf(("httpGets: Returning \"%s\"\n", line
));
1102 DEBUG_puts("httpGets: No new line available!");
1109 * 'httpHead()' - Send a HEAD request to the server.
1112 int /* O - Status of call (0 = success) */
1113 httpHead(http_t
*http
, /* I - HTTP data */
1114 const char *uri
) /* I - URI for head */
1116 return (http_send(http
, HTTP_HEAD
, uri
));
1121 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1122 * default HTTP proxy (if any).
1126 httpInitialize(void)
1130 struct timeval curtime
; /* Current time in microseconds */
1131 # endif /* !WIN32 */
1132 int i
; /* Looping var */
1133 unsigned char data
[1024]; /* Seed data */
1134 #endif /* HAVE_LIBSSL */
1137 WSADATA winsockdata
; /* WinSock data */
1138 static int initialized
= 0; /* Has WinSock been initialized? */
1142 WSAStartup(MAKEWORD(1,1), &winsockdata
);
1143 #elif defined(HAVE_SIGSET)
1144 sigset(SIGPIPE
, SIG_IGN
);
1145 #elif defined(HAVE_SIGACTION)
1146 struct sigaction action
; /* POSIX sigaction data */
1150 * Ignore SIGPIPE signals...
1153 memset(&action
, 0, sizeof(action
));
1154 action
.sa_handler
= SIG_IGN
;
1155 sigaction(SIGPIPE
, &action
, NULL
);
1157 signal(SIGPIPE
, SIG_IGN
);
1161 gnutls_global_init();
1162 #endif /* HAVE_GNUTLS */
1165 SSL_load_error_strings();
1169 * Using the current time is a dubious random seed, but on some systems
1170 * it is the best we can do (on others, this seed isn't even used...)
1175 gettimeofday(&curtime
, NULL
);
1176 srand(curtime
.tv_sec
+ curtime
.tv_usec
);
1179 for (i
= 0; i
< sizeof(data
); i
++)
1180 data
[i
] = rand(); /* Yes, this is a poor source of random data... */
1182 RAND_seed(&data
, sizeof(data
));
1183 #endif /* HAVE_LIBSSL */
1188 * 'httpOptions()' - Send an OPTIONS request to the server.
1191 int /* O - Status of call (0 = success) */
1192 httpOptions(http_t
*http
, /* I - HTTP data */
1193 const char *uri
) /* I - URI for options */
1195 return (http_send(http
, HTTP_OPTIONS
, uri
));
1200 * 'httpPost()' - Send a POST request to the server.
1203 int /* O - Status of call (0 = success) */
1204 httpPost(http_t
*http
, /* I - HTTP data */
1205 const char *uri
) /* I - URI for post */
1207 return (http_send(http
, HTTP_POST
, uri
));
1212 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1215 int /* O - Number of bytes written */
1216 httpPrintf(http_t
*http
, /* I - HTTP data */
1217 const char *format
, /* I - printf-style format string */
1218 ...) /* I - Additional args as needed */
1220 int bytes
; /* Number of bytes to write */
1221 char buf
[16384]; /* Buffer for formatted string */
1222 va_list ap
; /* Variable argument pointer */
1225 DEBUG_printf(("httpPrintf(http=%p, format=\"%s\", ...)\n", http
, format
));
1227 va_start(ap
, format
);
1228 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1231 DEBUG_printf(("httpPrintf: %s", buf
));
1234 httpFlushWrite(http
);
1236 return (http_write(http
, buf
, bytes
));
1241 * 'httpPut()' - Send a PUT request to the server.
1244 int /* O - Status of call (0 = success) */
1245 httpPut(http_t
*http
, /* I - HTTP data */
1246 const char *uri
) /* I - URI to put */
1248 return (http_send(http
, HTTP_PUT
, uri
));
1253 * 'httpRead()' - Read data from a HTTP connection.
1256 int /* O - Number of bytes read */
1257 httpRead(http_t
*http
, /* I - HTTP data */
1258 char *buffer
, /* I - Buffer for data */
1259 int length
) /* I - Maximum number of bytes */
1261 int bytes
; /* Bytes read */
1262 char len
[32]; /* Length string */
1265 DEBUG_printf(("httpRead(http=%p, buffer=%p, length=%d)\n",
1266 http
, buffer
, length
));
1268 if (http
== NULL
|| buffer
== NULL
)
1271 http
->activity
= time(NULL
);
1276 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1277 http
->data_remaining
<= 0)
1279 DEBUG_puts("httpRead: Getting chunk length...");
1281 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1283 DEBUG_puts("httpRead: Could not get length!");
1287 http
->data_remaining
= strtol(len
, NULL
, 16);
1288 if (http
->data_remaining
< 0)
1290 DEBUG_puts("httpRead: Negative chunk length!");
1295 DEBUG_printf(("httpRead: data_remaining=%d\n", http
->data_remaining
));
1297 if (http
->data_remaining
<= 0)
1300 * A zero-length chunk ends a transfer; unless we are reading POST
1304 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1305 httpGets(len
, sizeof(len
), http
);
1307 if (http
->state
== HTTP_POST_RECV
)
1310 http
->state
= HTTP_WAITING
;
1313 * Prevent future reads for this request...
1316 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1320 else if (length
> http
->data_remaining
)
1321 length
= http
->data_remaining
;
1323 if (http
->used
== 0 && length
<= 256)
1326 * Buffer small reads for better performance...
1329 if (!http
->blocking
&& !httpWait(http
, 1000))
1332 if (http
->data_remaining
> sizeof(http
->buffer
))
1333 bytes
= sizeof(http
->buffer
);
1335 bytes
= http
->data_remaining
;
1339 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1341 #endif /* HAVE_SSL */
1343 DEBUG_printf(("httpRead: reading %d bytes from socket into buffer...\n",
1346 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1348 DEBUG_printf(("httpRead: read %d bytes from socket into buffer...\n",
1357 http
->error
= WSAGetLastError();
1362 http
->error
= errno
;
1369 http
->error
= EPIPE
;
1376 if (length
> http
->used
)
1377 length
= http
->used
;
1381 DEBUG_printf(("httpRead: grabbing %d bytes from input buffer...\n", bytes
));
1383 memcpy(buffer
, http
->buffer
, length
);
1384 http
->used
-= length
;
1387 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
1392 if (!http
->blocking
&& !httpWait(http
, 1000))
1395 bytes
= http_read_ssl(http
, buffer
, length
);
1397 #endif /* HAVE_SSL */
1400 if (!http
->blocking
&& !httpWait(http
, 1000))
1403 DEBUG_printf(("httpRead: reading %d bytes from socket...\n", length
));
1405 while ((bytes
= recv(http
->fd
, buffer
, length
, 0)) < 0)
1409 DEBUG_printf(("httpRead: read %d bytes from socket...\n", bytes
));
1413 http
->data_remaining
-= bytes
;
1417 http
->error
= WSAGetLastError();
1422 http
->error
= errno
;
1427 http
->error
= EPIPE
;
1431 if (http
->data_remaining
== 0)
1433 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1434 httpGets(len
, sizeof(len
), http
);
1436 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
1438 if (http
->state
== HTTP_POST_RECV
)
1441 http
->state
= HTTP_WAITING
;
1448 printf("httpRead: Read %d bytes:\n", bytes
);
1449 for (i
= 0; i
< bytes
; i
+= 16)
1453 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1454 printf(" %02X", buffer
[i
+ j
] & 255);
1463 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
1465 ch
= buffer
[i
+ j
] & 255;
1467 if (ch
< ' ' || ch
== 127)
1482 * 'httpReconnect()' - Reconnect to a HTTP server...
1485 int /* O - 0 on success, non-zero on failure */
1486 httpReconnect(http_t
*http
) /* I - HTTP data */
1488 int val
; /* Socket option value */
1489 int status
; /* Connect status */
1492 DEBUG_printf(("httpReconnect(http=%p)\n", http
));
1499 http_shutdown_ssl(http
);
1500 #endif /* HAVE_SSL */
1503 * Close any previously open socket...
1508 closesocket(http
->fd
);
1514 * Create the socket and set options to allow reuse.
1517 if ((http
->fd
= socket(http
->hostaddr
.addr
.sa_family
, SOCK_STREAM
, 0)) < 0)
1520 http
->error
= WSAGetLastError();
1522 http
->error
= errno
;
1524 http
->status
= HTTP_ERROR
;
1529 fcntl(http
->fd
, F_SETFD
, FD_CLOEXEC
); /* Close this socket when starting *
1530 * other processes... */
1531 #endif /* FD_CLOEXEC */
1534 setsockopt(http
->fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *)&val
, sizeof(val
));
1538 setsockopt(http
->fd
, SOL_SOCKET
, SO_REUSEPORT
, &val
, sizeof(val
));
1539 #endif /* SO_REUSEPORT */
1542 * Using TCP_NODELAY improves responsiveness, especially on systems
1543 * with a slow loopback interface... Since we write large buffers
1544 * when sending print files and requests, there shouldn't be any
1545 * performance penalty for this...
1550 setsockopt(http
->fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&val
, sizeof(val
));
1552 setsockopt(http
->fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
1556 * Connect to the server...
1560 if (http
->hostaddr
.addr
.sa_family
== AF_INET6
)
1561 status
= connect(http
->fd
, (struct sockaddr
*)&(http
->hostaddr
),
1562 sizeof(http
->hostaddr
.ipv6
));
1564 #endif /* AF_INET6 */
1566 if (http
->hostaddr
.addr
.sa_family
== AF_LOCAL
)
1567 status
= connect(http
->fd
, (struct sockaddr
*)&(http
->hostaddr
),
1568 SUN_LEN(&(http
->hostaddr
.un
)));
1570 #endif /* AF_LOCAL */
1571 status
= connect(http
->fd
, (struct sockaddr
*)&(http
->hostaddr
),
1572 sizeof(http
->hostaddr
.ipv4
));
1577 http
->error
= WSAGetLastError();
1579 http
->error
= errno
;
1581 http
->status
= HTTP_ERROR
;
1584 closesocket(http
->fd
);
1595 http
->status
= HTTP_CONTINUE
;
1598 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
1601 * Always do encryption via SSL.
1604 if (http_setup_ssl(http
) != 0)
1607 closesocket(http
->fd
);
1615 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
1616 return (http_upgrade(http
));
1617 #endif /* HAVE_SSL */
1624 * 'httpSetCookie()' - Set the cookie value(s)...
1628 httpSetCookie(http_t
*http
, /* I - Connection */
1629 const char *cookie
) /* I - Cookie string */
1638 http
->cookie
= strdup(cookie
);
1640 http
->cookie
= NULL
;
1645 * 'httpSetField()' - Set the value of an HTTP header.
1649 httpSetField(http_t
*http
, /* I - HTTP data */
1650 http_field_t field
, /* I - Field index */
1651 const char *value
) /* I - Value */
1654 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
1655 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
1659 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
1664 * 'httpTrace()' - Send an TRACE request to the server.
1667 int /* O - Status of call (0 = success) */
1668 httpTrace(http_t
*http
, /* I - HTTP data */
1669 const char *uri
) /* I - URI for trace */
1671 return (http_send(http
, HTTP_TRACE
, uri
));
1676 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1679 http_status_t
/* O - HTTP status */
1680 httpUpdate(http_t
*http
) /* I - HTTP data */
1682 char line
[16384], /* Line from connection... */
1683 *value
; /* Pointer to value on line */
1684 http_field_t field
; /* Field index */
1685 int major
, minor
, /* HTTP version numbers */
1686 status
; /* Request status */
1689 DEBUG_printf(("httpUpdate(http=%p), state=%d\n", http
, http
->state
));
1692 * Flush pending data, if any...
1696 httpFlushWrite(http
);
1699 * If we haven't issued any commands, then there is nothing to "update"...
1702 if (http
->state
== HTTP_WAITING
)
1703 return (HTTP_CONTINUE
);
1706 * Grab all of the lines we can from the connection...
1709 while (httpGets(line
, sizeof(line
), http
) != NULL
)
1711 DEBUG_printf(("httpUpdate: Got \"%s\"\n", line
));
1713 if (line
[0] == '\0')
1716 * Blank line means the start of the data section (if any). Return
1717 * the result code, too...
1719 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
1720 * Instead, we just return HTTP_CONTINUE to the caller and keep on
1724 if (http
->status
== HTTP_CONTINUE
)
1725 return (http
->status
);
1727 if (http
->status
< HTTP_BAD_REQUEST
)
1728 http
->digest_tries
= 0;
1731 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
1733 if (http_setup_ssl(http
) != 0)
1736 closesocket(http
->fd
);
1741 return (HTTP_ERROR
);
1744 return (HTTP_CONTINUE
);
1746 #endif /* HAVE_SSL */
1748 httpGetLength(http
);
1750 switch (http
->state
)
1754 case HTTP_POST_RECV
:
1757 case HTTP_POST_SEND
:
1761 http
->state
= HTTP_WAITING
;
1765 return (http
->status
);
1767 else if (strncmp(line
, "HTTP/", 5) == 0)
1770 * Got the beginning of a response...
1773 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &status
) != 3)
1774 return (HTTP_ERROR
);
1776 http
->version
= (http_version_t
)(major
* 100 + minor
);
1777 http
->status
= (http_status_t
)status
;
1779 else if ((value
= strchr(line
, ':')) != NULL
)
1786 while (isspace(*value
& 255))
1790 * Be tolerants of servers that send unknown attribute fields...
1793 if (!strcasecmp(line
, "expect"))
1796 * "Expect: 100-continue" or similar...
1799 http
->expect
= (http_status_t
)atoi(value
);
1801 else if (!strcasecmp(line
, "cookie"))
1804 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
1807 httpSetCookie(http
, value
);
1809 else if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
1811 DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line
));
1815 httpSetField(http
, field
, value
);
1819 http
->status
= HTTP_ERROR
;
1820 return (HTTP_ERROR
);
1825 * See if there was an error...
1828 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
1829 return (http
->status
);
1833 DEBUG_printf(("httpUpdate: socket error %d - %s\n", http
->error
,
1834 strerror(http
->error
)));
1835 http
->status
= HTTP_ERROR
;
1836 return (HTTP_ERROR
);
1840 * If we haven't already returned, then there is nothing new...
1843 return (HTTP_CONTINUE
);
1848 * 'httpWait()' - Wait for data available on a connection.
1851 int /* O - 1 if data is available, 0 otherwise */
1852 httpWait(http_t
*http
, /* I - HTTP data */
1853 int msec
) /* I - Milliseconds to wait */
1856 * First see if there is data in the buffer...
1866 * If not, check the SSL/TLS buffers and do a select() on the connection...
1869 return (http_wait(http
, msec
));
1874 * 'httpWrite()' - Write data to a HTTP connection.
1877 int /* O - Number of bytes written */
1878 httpWrite(http_t
*http
, /* I - HTTP data */
1879 const char *buffer
, /* I - Buffer for data */
1880 int length
) /* I - Number of bytes to write */
1882 int bytes
; /* Bytes written */
1886 * Range check input...
1889 if (http
== NULL
|| buffer
== NULL
)
1893 * Mark activity on the connection...
1896 http
->activity
= time(NULL
);
1899 * Buffer small writes for better performance...
1904 if ((length
+ http
->wused
) > sizeof(http
->wbuffer
))
1905 httpFlushWrite(http
);
1907 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
))
1910 * Write to buffer...
1913 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
1914 http
->wused
+= length
;
1920 * Otherwise write the data directly...
1923 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1924 length
= http_write_chunk(http
, buffer
, length
);
1926 length
= http_write(http
, buffer
, length
);
1929 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
1930 http
->data_remaining
-= bytes
;
1934 * Handle end-of-request processing...
1937 if ((http
->data_encoding
== HTTP_ENCODE_CHUNKED
&& length
== 0) ||
1938 (http
->data_encoding
== HTTP_ENCODE_LENGTH
&& http
->data_remaining
== 0))
1941 * Finished with the transfer; unless we are sending POST or PUT
1945 DEBUG_puts("httpWrite: changing states...");
1948 httpFlushWrite(http
);
1950 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1953 * Send a 0-length chunk at the end of the request...
1956 http_write(http
, "0\r\n\r\n", 5);
1959 * Reset the data state...
1962 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1963 http
->data_remaining
= 0;
1966 if (http
->state
== HTTP_POST_RECV
)
1968 else if (http
->state
== HTTP_PUT_RECV
)
1969 http
->state
= HTTP_STATUS
;
1971 http
->state
= HTTP_WAITING
;
1979 * 'http_field()' - Return the field index for a field name.
1982 static http_field_t
/* O - Field index */
1983 http_field(const char *name
) /* I - String name */
1985 int i
; /* Looping var */
1988 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
1989 if (strcasecmp(name
, http_fields
[i
]) == 0)
1990 return ((http_field_t
)i
);
1992 return (HTTP_FIELD_UNKNOWN
);
1996 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
1998 * 'http_read_cdsa()' - Read function for CDSA decryption code.
2001 static OSStatus
/* O - -1 on error, 0 on success */
2003 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2004 void *data
, /* I - Data buffer */
2005 size_t *dataLength
) /* IO - Number of bytes */
2007 ssize_t bytes
; /* Number of bytes read */
2010 bytes
= recv((int)connection
, data
, *dataLength
, 0);
2013 *dataLength
= bytes
;
2019 #endif /* HAVE_SSL && HAVE_CDSASSL */
2024 * 'http_read_ssl()' - Read from a SSL/TLS connection.
2027 static int /* O - Bytes read */
2028 http_read_ssl(http_t
*http
, /* I - HTTP data */
2029 char *buf
, /* I - Buffer to store data */
2030 int len
) /* I - Length of buffer */
2032 # if defined(HAVE_LIBSSL)
2033 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
2035 # elif defined(HAVE_GNUTLS)
2036 return (gnutls_record_recv(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
2038 # elif defined(HAVE_CDSASSL)
2039 OSStatus error
; /* Error info */
2040 size_t processed
; /* Number of bytes processed */
2043 error
= SSLRead((SSLContextRef
)http
->tls
, buf
, len
, &processed
);
2049 http
->error
= error
;
2053 # endif /* HAVE_LIBSSL */
2055 #endif /* HAVE_SSL */
2059 * 'http_send()' - Send a request with all fields and the trailing blank line.
2062 static int /* O - 0 on success, non-zero on error */
2063 http_send(http_t
*http
, /* I - HTTP data */
2064 http_state_t request
, /* I - Request code */
2065 const char *uri
) /* I - URI */
2067 int i
; /* Looping var */
2068 char *ptr
, /* Pointer in buffer */
2069 buf
[1024]; /* Encoded URI buffer */
2070 static const char * const codes
[] =
2071 { /* Request code strings */
2086 static const char hex
[] = "0123456789ABCDEF";
2090 DEBUG_printf(("http_send(http=%p, request=HTTP_%s, uri=\"%s\")\n",
2091 http
, codes
[request
], uri
));
2093 if (http
== NULL
|| uri
== NULL
)
2097 * Encode the URI as needed...
2100 for (ptr
= buf
; *uri
!= '\0' && ptr
< (buf
+ sizeof(buf
) - 1); uri
++)
2101 if (*uri
<= ' ' || *uri
>= 127)
2103 if (ptr
< (buf
+ sizeof(buf
) - 1))
2105 if (ptr
< (buf
+ sizeof(buf
) - 1))
2106 *ptr
++ = hex
[(*uri
>> 4) & 15];
2107 if (ptr
< (buf
+ sizeof(buf
) - 1))
2108 *ptr
++ = hex
[*uri
& 15];
2116 * See if we had an error the last time around; if so, reconnect...
2119 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
2120 httpReconnect(http
);
2123 * Send the request header...
2126 http
->state
= request
;
2127 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
2130 http
->status
= HTTP_CONTINUE
;
2133 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
2135 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
2136 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
2138 #endif /* HAVE_SSL */
2140 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
2142 http
->status
= HTTP_ERROR
;
2146 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
2147 if (http
->fields
[i
][0] != '\0')
2149 DEBUG_printf(("%s: %s\n", http_fields
[i
], http
->fields
[i
]));
2151 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], http
->fields
[i
]) < 1)
2153 http
->status
= HTTP_ERROR
;
2158 if (httpPrintf(http
, "\r\n") < 1)
2160 http
->status
= HTTP_ERROR
;
2164 httpGetLength(http
);
2165 httpClearFields(http
);
2173 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
2176 static int /* O - Status of connection */
2177 http_setup_ssl(http_t
*http
) /* I - HTTP data */
2180 SSL_CTX
*context
; /* Context for encryption */
2181 SSL
*conn
; /* Connection for encryption */
2182 # elif defined(HAVE_GNUTLS)
2183 http_tls_t
*conn
; /* TLS session object */
2184 gnutls_certificate_client_credentials
*credentials
;
2185 /* TLS credentials */
2186 # elif defined(HAVE_CDSASSL)
2187 SSLContextRef conn
; /* Context for encryption */
2188 OSStatus error
; /* Error info */
2189 # endif /* HAVE_LIBSSL */
2192 DEBUG_printf(("http_setup_ssl(http=%p)\n", http
));
2195 context
= SSL_CTX_new(SSLv23_client_method());
2197 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
2199 conn
= SSL_new(context
);
2201 SSL_set_fd(conn
, http
->fd
);
2202 if (SSL_connect(conn
) != 1)
2205 unsigned long error
; /* Error code */
2207 while ((error
= ERR_get_error()) != 0)
2208 printf("http_setup_ssl: %s\n", ERR_error_string(error
, NULL
));
2211 SSL_CTX_free(context
);
2215 http
->error
= WSAGetLastError();
2217 http
->error
= errno
;
2219 http
->status
= HTTP_ERROR
;
2221 return (HTTP_ERROR
);
2224 # elif defined(HAVE_GNUTLS)
2225 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
2229 http
->error
= errno
;
2230 http
->status
= HTTP_ERROR
;
2235 credentials
= (gnutls_certificate_client_credentials
*)
2236 malloc(sizeof(gnutls_certificate_client_credentials
));
2237 if (credentials
== NULL
)
2241 http
->error
= errno
;
2242 http
->status
= HTTP_ERROR
;
2247 gnutls_certificate_allocate_credentials(credentials
);
2249 gnutls_init(&(conn
->session
), GNUTLS_CLIENT
);
2250 gnutls_set_default_priority(conn
->session
);
2251 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
2252 gnutls_transport_set_ptr(conn
->session
, http
->fd
);
2254 if ((gnutls_handshake(conn
->session
)) != GNUTLS_E_SUCCESS
)
2256 http
->error
= errno
;
2257 http
->status
= HTTP_ERROR
;
2262 conn
->credentials
= credentials
;
2264 # elif defined(HAVE_CDSASSL)
2265 error
= SSLNewContext(false, &conn
);
2268 error
= SSLSetIOFuncs(conn
, http_read_cdsa
, http_write_cdsa
);
2271 error
= SSLSetConnection(conn
, (SSLConnectionRef
)http
->fd
);
2274 error
= SSLSetAllowsExpiredCerts(conn
, true);
2277 error
= SSLSetAllowsAnyRoot(conn
, true);
2280 error
= SSLHandshake(conn
);
2284 http
->error
= error
;
2285 http
->status
= HTTP_ERROR
;
2287 SSLDisposeContext(conn
);
2293 # endif /* HAVE_CDSASSL */
2298 #endif /* HAVE_SSL */
2303 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
2307 http_shutdown_ssl(http_t
*http
) /* I - HTTP data */
2310 SSL_CTX
*context
; /* Context for encryption */
2311 SSL
*conn
; /* Connection for encryption */
2314 conn
= (SSL
*)(http
->tls
);
2315 context
= SSL_get_SSL_CTX(conn
);
2318 SSL_CTX_free(context
);
2321 # elif defined(HAVE_GNUTLS)
2322 http_tls_t
*conn
; /* Encryption session */
2323 gnutls_certificate_client_credentials
*credentials
;
2324 /* TLS credentials */
2327 conn
= (http_tls_t
*)(http
->tls
);
2328 credentials
= (gnutls_certificate_client_credentials
*)(conn
->credentials
);
2330 gnutls_bye(conn
->session
, GNUTLS_SHUT_RDWR
);
2331 gnutls_deinit(conn
->session
);
2332 gnutls_certificate_free_credentials(*credentials
);
2336 # elif defined(HAVE_CDSASSL)
2337 SSLClose((SSLContextRef
)http
->tls
);
2338 SSLDisposeContext((SSLContextRef
)http
->tls
);
2339 # endif /* HAVE_LIBSSL */
2343 #endif /* HAVE_SSL */
2348 * 'http_upgrade()' - Force upgrade to TLS encryption.
2351 static int /* O - Status of connection */
2352 http_upgrade(http_t
*http
) /* I - HTTP data */
2354 int ret
; /* Return value */
2355 http_t myhttp
; /* Local copy of HTTP data */
2358 DEBUG_printf(("http_upgrade(%p)\n", http
));
2361 * Copy the HTTP data to a local variable so we can do the OPTIONS
2362 * request without interfering with the existing request data...
2365 memcpy(&myhttp
, http
, sizeof(myhttp
));
2368 * Send an OPTIONS request to the server, requiring SSL or TLS
2369 * encryption on the link...
2372 httpClearFields(&myhttp
);
2373 httpSetField(&myhttp
, HTTP_FIELD_CONNECTION
, "upgrade");
2374 httpSetField(&myhttp
, HTTP_FIELD_UPGRADE
, "TLS/1.0, SSL/2.0, SSL/3.0");
2376 if ((ret
= httpOptions(&myhttp
, "*")) == 0)
2379 * Wait for the secure connection...
2382 while (httpUpdate(&myhttp
) == HTTP_CONTINUE
);
2388 * Copy the HTTP data back over, if any...
2391 http
->fd
= myhttp
.fd
;
2392 http
->error
= myhttp
.error
;
2393 http
->activity
= myhttp
.activity
;
2394 http
->status
= myhttp
.status
;
2395 http
->version
= myhttp
.version
;
2396 http
->keep_alive
= myhttp
.keep_alive
;
2397 http
->used
= myhttp
.used
;
2400 memcpy(http
->buffer
, myhttp
.buffer
, http
->used
);
2402 http
->auth_type
= myhttp
.auth_type
;
2403 http
->nonce_count
= myhttp
.nonce_count
;
2405 memcpy(http
->nonce
, myhttp
.nonce
, sizeof(http
->nonce
));
2407 http
->tls
= myhttp
.tls
;
2408 http
->encryption
= myhttp
.encryption
;
2411 * See if we actually went secure...
2417 * Server does not support HTTP upgrade...
2420 DEBUG_puts("Server does not support HTTP upgrade!");
2423 closesocket(http
->fd
);
2435 #endif /* HAVE_SSL */
2439 * 'http_wait()' - Wait for data available on a connection.
2442 static int /* O - 1 if data is available, 0 otherwise */
2443 http_wait(http_t
*http
, /* I - HTTP data */
2444 int msec
) /* I - Milliseconds to wait */
2447 struct rlimit limit
; /* Runtime limit */
2449 struct timeval timeout
; /* Timeout */
2450 int nfds
; /* Result from select() */
2451 int set_size
; /* Size of select set */
2454 DEBUG_printf(("http_wait(http=%p, msec=%d)\n", http
, msec
));
2457 * Check the SSL/TLS buffers for data first...
2464 if (SSL_pending((SSL
*)(http
->tls
)))
2466 # elif defined(HAVE_GNUTLS)
2467 if (gnutls_record_check_pending(((http_tls_t
*)(http
->tls
))->session
))
2469 # elif defined(HAVE_CDSASSL)
2470 size_t bytes
; /* Bytes that are available */
2472 if (!SSLGetBufferedReadSize((SSLContextRef
)http
->tls
, &bytes
) && bytes
> 0)
2474 # endif /* HAVE_LIBSSL */
2476 #endif /* HAVE_SSL */
2479 * Then try doing a select() to poll the socket...
2482 if (!http
->input_set
)
2486 * Windows has a fixed-size select() structure, different (surprise,
2487 * surprise!) from all UNIX implementations. Just allocate this
2488 * fixed structure...
2491 http
->input_set
= calloc(1, sizeof(fd_set
));
2494 * Allocate the select() input set based upon the max number of file
2495 * descriptors available for this process...
2498 getrlimit(RLIMIT_NOFILE
, &limit
);
2500 set_size
= (limit
.rlim_cur
+ 31) / 8 + 4;
2501 if (set_size
< sizeof(fd_set
))
2502 set_size
= sizeof(fd_set
);
2504 http
->input_set
= calloc(1, set_size
);
2507 if (!http
->input_set
)
2513 FD_SET(http
->fd
, http
->input_set
);
2517 timeout
.tv_sec
= msec
/ 1000;
2518 timeout
.tv_usec
= (msec
% 1000) * 1000;
2520 nfds
= select(http
->fd
+ 1, http
->input_set
, NULL
, NULL
, &timeout
);
2523 nfds
= select(http
->fd
+ 1, http
->input_set
, NULL
, NULL
, NULL
);
2526 while (nfds
< 0 && WSAGetLastError() == WSAEINTR
);
2528 while (nfds
< 0 && errno
== EINTR
);
2531 FD_CLR(http
->fd
, http
->input_set
);
2538 * 'http_write()' - Write a buffer to a HTTP connection.
2541 static int /* O - Number of bytes written */
2542 http_write(http_t
*http
, /* I - HTTP data */
2543 const char *buffer
, /* I - Buffer for data */
2544 int length
) /* I - Number of bytes to write */
2546 int tbytes
, /* Total bytes sent */
2547 bytes
; /* Bytes sent */
2556 bytes
= http_write_ssl(http
, buffer
, length
);
2558 #endif /* HAVE_SSL */
2559 bytes
= send(http
->fd
, buffer
, length
, 0);
2564 if (WSAGetLastError() != http
->error
)
2566 http
->error
= WSAGetLastError();
2572 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
2574 http
->error
= errno
;
2579 DEBUG_puts("http_write: error writing data...\n");
2592 printf("http_write: wrote %d bytes: \n", tbytes
);
2593 for (i
= 0, buffer
-= tbytes
; i
< tbytes
; i
+= 16)
2597 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
2598 printf(" %02X", buffer
[i
+ j
] & 255);
2607 for (j
= 0; j
< 16 && (i
+ j
) < tbytes
; j
++)
2609 ch
= buffer
[i
+ j
] & 255;
2611 if (ch
< ' ' || ch
== 127)
2625 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2627 * 'http_write_cdsa()' - Write function for CDSA encryption code.
2630 static OSStatus
/* O - -1 on error, 0 on success */
2632 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2633 const void *data
, /* I - Data buffer */
2634 size_t *dataLength
) /* IO - Number of bytes */
2636 ssize_t bytes
; /* Number of write written */
2639 bytes
= write((int)connection
, data
, *dataLength
);
2642 *dataLength
= bytes
;
2648 #endif /* HAVE_SSL && HAVE_CDSASSL */
2652 * 'http_write_chunk()' - Write a chunked buffer.
2655 static int /* O - Number bytes written */
2656 http_write_chunk(http_t
*http
, /* I - HTTP data */
2657 const char *buffer
, /* I - Buffer to write */
2658 int length
) /* I - Length of buffer */
2660 char header
[255]; /* Chunk header */
2661 int bytes
; /* Bytes written */
2663 DEBUG_printf(("http_write_chunk(http=%p, buffer=%p, length=%d)\n",
2664 http
, buffer
, length
));
2667 * Write the chunk header, data, and trailer.
2670 sprintf(header
, "%x\r\n", length
);
2671 if (http_write(http
, header
, strlen(header
)) < 0)
2674 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
2677 if (http_write(http
, "\r\n", 2) < 0)
2686 * 'http_write_ssl()' - Write to a SSL/TLS connection.
2689 static int /* O - Bytes written */
2690 http_write_ssl(http_t
*http
, /* I - HTTP data */
2691 const char *buf
, /* I - Buffer holding data */
2692 int len
) /* I - Length of buffer */
2694 # if defined(HAVE_LIBSSL)
2695 return (SSL_write((SSL
*)(http
->tls
), buf
, len
));
2697 # elif defined(HAVE_GNUTLS)
2698 return (gnutls_record_send(((http_tls_t
*)(http
->tls
))->session
, buf
, len
));
2699 # elif defined(HAVE_CDSASSL)
2700 OSStatus error
; /* Error info */
2701 size_t processed
; /* Number of bytes processed */
2704 error
= SSLWrite((SSLContextRef
)http
->tls
, buf
, len
, &processed
);
2710 http
->error
= error
;
2713 # endif /* HAVE_LIBSSL */
2715 #endif /* HAVE_SSL */