msvcrt: Mark function that are only called from assembly as hidden.
[wine.git] / dlls / winhttp / net.c
blobc9aa6d48b27536446431507971a17bf2a4b0b73f
1 /*
2 * Copyright 2008 Hans Leidekker for CodeWeavers
3 * Copyright 2013 Jacek Caban for CodeWeavers
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 #include "config.h"
21 #include "wine/port.h"
23 #include <stdarg.h>
24 #include <stdio.h>
25 #include <errno.h>
26 #include <assert.h>
28 #include <sys/types.h>
29 #ifdef HAVE_SYS_SOCKET_H
30 # include <sys/socket.h>
31 #endif
32 #ifdef HAVE_SYS_IOCTL_H
33 # include <sys/ioctl.h>
34 #endif
35 #ifdef HAVE_SYS_FILIO_H
36 # include <sys/filio.h>
37 #endif
38 #ifdef HAVE_POLL_H
39 # include <poll.h>
40 #endif
42 #define NONAMELESSUNION
44 #include "wine/debug.h"
45 #include "wine/library.h"
47 #include "windef.h"
48 #include "winbase.h"
49 #include "winhttp.h"
50 #include "wincrypt.h"
51 #include "schannel.h"
53 #include "winhttp_private.h"
55 /* to avoid conflicts with the Unix socket headers */
56 #define USE_WS_PREFIX
57 #include "winsock2.h"
59 WINE_DEFAULT_DEBUG_CHANNEL(winhttp);
61 #ifndef HAVE_GETADDRINFO
63 /* critical section to protect non-reentrant gethostbyname() */
64 static CRITICAL_SECTION cs_gethostbyname;
65 static CRITICAL_SECTION_DEBUG critsect_debug =
67 0, 0, &cs_gethostbyname,
68 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
69 0, 0, { (DWORD_PTR)(__FILE__ ": cs_gethostbyname") }
71 static CRITICAL_SECTION cs_gethostbyname = { &critsect_debug, -1, 0, 0, 0, 0 };
73 #endif
75 /* translate a unix error code into a winsock error code */
76 static int sock_get_error( int err )
78 #if !defined(__MINGW32__) && !defined (_MSC_VER)
79 switch (err)
81 case EINTR: return WSAEINTR;
82 case EBADF: return WSAEBADF;
83 case EPERM:
84 case EACCES: return WSAEACCES;
85 case EFAULT: return WSAEFAULT;
86 case EINVAL: return WSAEINVAL;
87 case EMFILE: return WSAEMFILE;
88 case EWOULDBLOCK: return WSAEWOULDBLOCK;
89 case EINPROGRESS: return WSAEINPROGRESS;
90 case EALREADY: return WSAEALREADY;
91 case ENOTSOCK: return WSAENOTSOCK;
92 case EDESTADDRREQ: return WSAEDESTADDRREQ;
93 case EMSGSIZE: return WSAEMSGSIZE;
94 case EPROTOTYPE: return WSAEPROTOTYPE;
95 case ENOPROTOOPT: return WSAENOPROTOOPT;
96 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
97 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
98 case EOPNOTSUPP: return WSAEOPNOTSUPP;
99 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
100 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
101 case EADDRINUSE: return WSAEADDRINUSE;
102 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
103 case ENETDOWN: return WSAENETDOWN;
104 case ENETUNREACH: return WSAENETUNREACH;
105 case ENETRESET: return WSAENETRESET;
106 case ECONNABORTED: return WSAECONNABORTED;
107 case EPIPE:
108 case ECONNRESET: return WSAECONNRESET;
109 case ENOBUFS: return WSAENOBUFS;
110 case EISCONN: return WSAEISCONN;
111 case ENOTCONN: return WSAENOTCONN;
112 case ESHUTDOWN: return WSAESHUTDOWN;
113 case ETOOMANYREFS: return WSAETOOMANYREFS;
114 case ETIMEDOUT: return WSAETIMEDOUT;
115 case ECONNREFUSED: return WSAECONNREFUSED;
116 case ELOOP: return WSAELOOP;
117 case ENAMETOOLONG: return WSAENAMETOOLONG;
118 case EHOSTDOWN: return WSAEHOSTDOWN;
119 case EHOSTUNREACH: return WSAEHOSTUNREACH;
120 case ENOTEMPTY: return WSAENOTEMPTY;
121 #ifdef EPROCLIM
122 case EPROCLIM: return WSAEPROCLIM;
123 #endif
124 #ifdef EUSERS
125 case EUSERS: return WSAEUSERS;
126 #endif
127 #ifdef EDQUOT
128 case EDQUOT: return WSAEDQUOT;
129 #endif
130 #ifdef ESTALE
131 case ESTALE: return WSAESTALE;
132 #endif
133 #ifdef EREMOTE
134 case EREMOTE: return WSAEREMOTE;
135 #endif
136 default: errno = err; perror( "sock_set_error" ); return WSAEFAULT;
138 #endif
139 return err;
142 static int sock_send(int fd, const void *msg, size_t len, int flags)
144 int ret;
147 ret = send(fd, msg, len, flags);
149 while(ret == -1 && errno == EINTR);
150 return ret;
153 static int sock_recv(int fd, void *msg, size_t len, int flags)
155 int ret;
158 ret = recv(fd, msg, len, flags);
160 while(ret == -1 && errno == EINTR);
161 return ret;
164 static DWORD netconn_verify_cert( PCCERT_CONTEXT cert, WCHAR *server, DWORD security_flags )
166 HCERTSTORE store = cert->hCertStore;
167 BOOL ret;
168 CERT_CHAIN_PARA chainPara = { sizeof(chainPara), { 0 } };
169 PCCERT_CHAIN_CONTEXT chain;
170 char oid_server_auth[] = szOID_PKIX_KP_SERVER_AUTH;
171 char *server_auth[] = { oid_server_auth };
172 DWORD err = ERROR_SUCCESS;
174 TRACE("verifying %s\n", debugstr_w( server ));
175 chainPara.RequestedUsage.Usage.cUsageIdentifier = 1;
176 chainPara.RequestedUsage.Usage.rgpszUsageIdentifier = server_auth;
177 if ((ret = CertGetCertificateChain( NULL, cert, NULL, store, &chainPara,
178 CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT,
179 NULL, &chain )))
181 if (chain->TrustStatus.dwErrorStatus)
183 static const DWORD supportedErrors =
184 CERT_TRUST_IS_NOT_TIME_VALID |
185 CERT_TRUST_IS_UNTRUSTED_ROOT |
186 CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
188 if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_NOT_TIME_VALID)
190 if (!(security_flags & SECURITY_FLAG_IGNORE_CERT_DATE_INVALID))
191 err = ERROR_WINHTTP_SECURE_CERT_DATE_INVALID;
193 else if (chain->TrustStatus.dwErrorStatus &
194 CERT_TRUST_IS_UNTRUSTED_ROOT)
196 if (!(security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA))
197 err = ERROR_WINHTTP_SECURE_INVALID_CA;
199 else if ((chain->TrustStatus.dwErrorStatus &
200 CERT_TRUST_IS_OFFLINE_REVOCATION) ||
201 (chain->TrustStatus.dwErrorStatus &
202 CERT_TRUST_REVOCATION_STATUS_UNKNOWN))
203 err = ERROR_WINHTTP_SECURE_CERT_REV_FAILED;
204 else if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_REVOKED)
205 err = ERROR_WINHTTP_SECURE_CERT_REVOKED;
206 else if (chain->TrustStatus.dwErrorStatus &
207 CERT_TRUST_IS_NOT_VALID_FOR_USAGE)
209 if (!(security_flags & SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE))
210 err = ERROR_WINHTTP_SECURE_CERT_WRONG_USAGE;
212 else if (chain->TrustStatus.dwErrorStatus & ~supportedErrors)
213 err = ERROR_WINHTTP_SECURE_INVALID_CERT;
215 if (!err)
217 CERT_CHAIN_POLICY_PARA policyPara;
218 SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslExtraPolicyPara;
219 CERT_CHAIN_POLICY_STATUS policyStatus;
220 CERT_CHAIN_CONTEXT chainCopy;
222 /* Clear chain->TrustStatus.dwErrorStatus so
223 * CertVerifyCertificateChainPolicy will verify additional checks
224 * rather than stopping with an existing, ignored error.
226 memcpy(&chainCopy, chain, sizeof(chainCopy));
227 chainCopy.TrustStatus.dwErrorStatus = 0;
228 sslExtraPolicyPara.u.cbSize = sizeof(sslExtraPolicyPara);
229 sslExtraPolicyPara.dwAuthType = AUTHTYPE_SERVER;
230 sslExtraPolicyPara.pwszServerName = server;
231 sslExtraPolicyPara.fdwChecks = security_flags;
232 policyPara.cbSize = sizeof(policyPara);
233 policyPara.dwFlags = 0;
234 policyPara.pvExtraPolicyPara = &sslExtraPolicyPara;
235 ret = CertVerifyCertificateChainPolicy( CERT_CHAIN_POLICY_SSL,
236 &chainCopy, &policyPara,
237 &policyStatus );
238 /* Any error in the policy status indicates that the
239 * policy couldn't be verified.
241 if (ret && policyStatus.dwError)
243 if (policyStatus.dwError == CERT_E_CN_NO_MATCH)
244 err = ERROR_WINHTTP_SECURE_CERT_CN_INVALID;
245 else
246 err = ERROR_WINHTTP_SECURE_INVALID_CERT;
249 CertFreeCertificateChain( chain );
251 else
252 err = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
253 TRACE("returning %08x\n", err);
254 return err;
257 static SecHandle cred_handle;
258 static BOOL cred_handle_initialized;
260 static CRITICAL_SECTION init_sechandle_cs;
261 static CRITICAL_SECTION_DEBUG init_sechandle_cs_debug = {
262 0, 0, &init_sechandle_cs,
263 { &init_sechandle_cs_debug.ProcessLocksList,
264 &init_sechandle_cs_debug.ProcessLocksList },
265 0, 0, { (DWORD_PTR)(__FILE__ ": init_sechandle_cs") }
267 static CRITICAL_SECTION init_sechandle_cs = { &init_sechandle_cs_debug, -1, 0, 0, 0, 0 };
269 static BOOL ensure_cred_handle(void)
271 BOOL ret = TRUE;
273 EnterCriticalSection(&init_sechandle_cs);
275 if(!cred_handle_initialized) {
276 SECURITY_STATUS res;
278 res = AcquireCredentialsHandleW(NULL, (WCHAR*)UNISP_NAME_W, SECPKG_CRED_OUTBOUND, NULL, NULL,
279 NULL, NULL, &cred_handle, NULL);
280 if(res == SEC_E_OK) {
281 cred_handle_initialized = TRUE;
282 }else {
283 WARN("AcquireCredentialsHandleW failed: %u\n", res);
284 ret = FALSE;
288 LeaveCriticalSection(&init_sechandle_cs);
289 return ret;
292 void netconn_unload( void )
294 if(cred_handle_initialized)
295 FreeCredentialsHandle(&cred_handle);
296 DeleteCriticalSection(&init_sechandle_cs);
297 #ifndef HAVE_GETADDRINFO
298 DeleteCriticalSection(&cs_gethostbyname);
299 #endif
302 netconn_t *netconn_create( hostdata_t *host, const struct sockaddr_storage *sockaddr, int timeout )
304 netconn_t *conn;
305 unsigned int addr_len;
306 BOOL ret = FALSE;
307 int res;
308 ULONG state;
310 conn = heap_alloc_zero(sizeof(*conn));
311 if (!conn) return NULL;
312 conn->host = host;
313 conn->sockaddr = *sockaddr;
314 if ((conn->socket = socket( sockaddr->ss_family, SOCK_STREAM, 0 )) == -1)
316 WARN("unable to create socket (%s)\n", strerror(errno));
317 set_last_error( sock_get_error( errno ) );
318 heap_free(conn);
319 return NULL;
322 switch (conn->sockaddr.ss_family)
324 case AF_INET:
325 addr_len = sizeof(struct sockaddr_in);
326 break;
327 case AF_INET6:
328 addr_len = sizeof(struct sockaddr_in6);
329 break;
330 default:
331 assert(0);
334 if (timeout > 0)
336 state = 1;
337 ioctlsocket( conn->socket, FIONBIO, &state );
340 for (;;)
342 res = 0;
343 if (connect( conn->socket, (const struct sockaddr *)&conn->sockaddr, addr_len ) < 0)
345 res = sock_get_error( errno );
346 if (res == WSAEWOULDBLOCK || res == WSAEINPROGRESS)
348 struct pollfd pfd;
350 pfd.fd = conn->socket;
351 pfd.events = POLLOUT;
352 for (;;)
354 res = 0;
355 if (poll( &pfd, 1, timeout ) > 0)
357 ret = TRUE;
358 break;
360 else
362 res = sock_get_error( errno );
363 if (res != WSAEINTR) break;
367 if (res != WSAEINTR) break;
369 else
371 ret = TRUE;
372 break;
375 if (timeout > 0)
377 state = 0;
378 ioctlsocket( conn->socket, FIONBIO, &state );
380 if (!ret)
382 WARN("unable to connect to host (%d)\n", res);
383 set_last_error( res );
384 netconn_close( conn );
385 return NULL;
387 return conn;
390 BOOL netconn_close( netconn_t *conn )
392 int res;
394 if (conn->secure)
396 heap_free( conn->peek_msg_mem );
397 heap_free(conn->ssl_buf);
398 heap_free(conn->extra_buf);
399 DeleteSecurityContext(&conn->ssl_ctx);
401 res = closesocket( conn->socket );
402 release_host( conn->host );
403 heap_free(conn);
404 if (res == -1)
406 set_last_error( sock_get_error( errno ) );
407 return FALSE;
409 return TRUE;
412 BOOL netconn_secure_connect( netconn_t *conn, WCHAR *hostname, DWORD security_flags )
414 SecBuffer out_buf = {0, SECBUFFER_TOKEN, NULL}, in_bufs[2] = {{0, SECBUFFER_TOKEN}, {0, SECBUFFER_EMPTY}};
415 SecBufferDesc out_desc = {SECBUFFER_VERSION, 1, &out_buf}, in_desc = {SECBUFFER_VERSION, 2, in_bufs};
416 BYTE *read_buf;
417 SIZE_T read_buf_size = 2048;
418 ULONG attrs = 0;
419 CtxtHandle ctx;
420 SSIZE_T size;
421 const CERT_CONTEXT *cert;
422 SECURITY_STATUS status;
423 DWORD res = ERROR_SUCCESS;
425 const DWORD isc_req_flags = ISC_REQ_ALLOCATE_MEMORY|ISC_REQ_USE_SESSION_KEY|ISC_REQ_CONFIDENTIALITY
426 |ISC_REQ_SEQUENCE_DETECT|ISC_REQ_REPLAY_DETECT|ISC_REQ_MANUAL_CRED_VALIDATION;
428 if(!ensure_cred_handle())
429 return FALSE;
431 read_buf = heap_alloc(read_buf_size);
432 if(!read_buf)
433 return FALSE;
435 status = InitializeSecurityContextW(&cred_handle, NULL, hostname, isc_req_flags, 0, 0, NULL, 0,
436 &ctx, &out_desc, &attrs, NULL);
438 assert(status != SEC_E_OK);
440 while(status == SEC_I_CONTINUE_NEEDED || status == SEC_E_INCOMPLETE_MESSAGE) {
441 if(out_buf.cbBuffer) {
442 assert(status == SEC_I_CONTINUE_NEEDED);
444 TRACE("sending %u bytes\n", out_buf.cbBuffer);
446 size = sock_send(conn->socket, out_buf.pvBuffer, out_buf.cbBuffer, 0);
447 if(size != out_buf.cbBuffer) {
448 ERR("send failed\n");
449 res = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
450 break;
453 FreeContextBuffer(out_buf.pvBuffer);
454 out_buf.pvBuffer = NULL;
455 out_buf.cbBuffer = 0;
458 if(status == SEC_I_CONTINUE_NEEDED) {
459 assert(in_bufs[1].cbBuffer < read_buf_size);
461 memmove(read_buf, (BYTE*)in_bufs[0].pvBuffer+in_bufs[0].cbBuffer-in_bufs[1].cbBuffer, in_bufs[1].cbBuffer);
462 in_bufs[0].cbBuffer = in_bufs[1].cbBuffer;
464 in_bufs[1].BufferType = SECBUFFER_EMPTY;
465 in_bufs[1].cbBuffer = 0;
466 in_bufs[1].pvBuffer = NULL;
469 assert(in_bufs[0].BufferType == SECBUFFER_TOKEN);
470 assert(in_bufs[1].BufferType == SECBUFFER_EMPTY);
472 if(in_bufs[0].cbBuffer + 1024 > read_buf_size) {
473 BYTE *new_read_buf;
475 new_read_buf = heap_realloc(read_buf, read_buf_size + 1024);
476 if(!new_read_buf) {
477 status = E_OUTOFMEMORY;
478 break;
481 in_bufs[0].pvBuffer = read_buf = new_read_buf;
482 read_buf_size += 1024;
485 size = sock_recv(conn->socket, read_buf+in_bufs[0].cbBuffer, read_buf_size-in_bufs[0].cbBuffer, 0);
486 if(size < 1) {
487 WARN("recv error\n");
488 status = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
489 break;
492 TRACE("recv %lu bytes\n", size);
494 in_bufs[0].cbBuffer += size;
495 in_bufs[0].pvBuffer = read_buf;
496 status = InitializeSecurityContextW(&cred_handle, &ctx, hostname, isc_req_flags, 0, 0, &in_desc,
497 0, NULL, &out_desc, &attrs, NULL);
498 TRACE("InitializeSecurityContext ret %08x\n", status);
500 if(status == SEC_E_OK) {
501 if(in_bufs[1].BufferType == SECBUFFER_EXTRA)
502 FIXME("SECBUFFER_EXTRA not supported\n");
504 status = QueryContextAttributesW(&ctx, SECPKG_ATTR_STREAM_SIZES, &conn->ssl_sizes);
505 if(status != SEC_E_OK) {
506 WARN("Could not get sizes\n");
507 break;
510 status = QueryContextAttributesW(&ctx, SECPKG_ATTR_REMOTE_CERT_CONTEXT, (void*)&cert);
511 if(status == SEC_E_OK) {
512 res = netconn_verify_cert(cert, hostname, security_flags);
513 CertFreeCertificateContext(cert);
514 if(res != ERROR_SUCCESS) {
515 WARN("cert verify failed: %u\n", res);
516 break;
518 }else {
519 WARN("Could not get cert\n");
520 break;
523 conn->ssl_buf = heap_alloc(conn->ssl_sizes.cbHeader + conn->ssl_sizes.cbMaximumMessage + conn->ssl_sizes.cbTrailer);
524 if(!conn->ssl_buf) {
525 res = GetLastError();
526 break;
531 heap_free(read_buf);
533 if(status != SEC_E_OK || res != ERROR_SUCCESS) {
534 WARN("Failed to initialize security context failed: %08x\n", status);
535 heap_free(conn->ssl_buf);
536 conn->ssl_buf = NULL;
537 DeleteSecurityContext(&ctx);
538 set_last_error(res ? res : ERROR_WINHTTP_SECURE_CHANNEL_ERROR);
539 return FALSE;
543 TRACE("established SSL connection\n");
544 conn->secure = TRUE;
545 conn->ssl_ctx = ctx;
546 return TRUE;
549 static BOOL send_ssl_chunk(netconn_t *conn, const void *msg, size_t size)
551 SecBuffer bufs[4] = {
552 {conn->ssl_sizes.cbHeader, SECBUFFER_STREAM_HEADER, conn->ssl_buf},
553 {size, SECBUFFER_DATA, conn->ssl_buf+conn->ssl_sizes.cbHeader},
554 {conn->ssl_sizes.cbTrailer, SECBUFFER_STREAM_TRAILER, conn->ssl_buf+conn->ssl_sizes.cbHeader+size},
555 {0, SECBUFFER_EMPTY, NULL}
557 SecBufferDesc buf_desc = {SECBUFFER_VERSION, sizeof(bufs)/sizeof(*bufs), bufs};
558 SECURITY_STATUS res;
560 memcpy(bufs[1].pvBuffer, msg, size);
561 res = EncryptMessage(&conn->ssl_ctx, 0, &buf_desc, 0);
562 if(res != SEC_E_OK) {
563 WARN("EncryptMessage failed\n");
564 return FALSE;
567 if(sock_send(conn->socket, conn->ssl_buf, bufs[0].cbBuffer+bufs[1].cbBuffer+bufs[2].cbBuffer, 0) < 1) {
568 WARN("send failed\n");
569 return FALSE;
572 return TRUE;
575 BOOL netconn_send( netconn_t *conn, const void *msg, size_t len, int *sent )
577 if (conn->secure)
579 const BYTE *ptr = msg;
580 size_t chunk_size;
582 *sent = 0;
584 while(len) {
585 chunk_size = min(len, conn->ssl_sizes.cbMaximumMessage);
586 if(!send_ssl_chunk(conn, ptr, chunk_size))
587 return FALSE;
589 *sent += chunk_size;
590 ptr += chunk_size;
591 len -= chunk_size;
594 return TRUE;
596 if ((*sent = sock_send( conn->socket, msg, len, 0 )) == -1)
598 set_last_error( sock_get_error( errno ) );
599 return FALSE;
601 return TRUE;
604 static BOOL read_ssl_chunk(netconn_t *conn, void *buf, SIZE_T buf_size, SIZE_T *ret_size, BOOL *eof)
606 const SIZE_T ssl_buf_size = conn->ssl_sizes.cbHeader+conn->ssl_sizes.cbMaximumMessage+conn->ssl_sizes.cbTrailer;
607 SecBuffer bufs[4];
608 SecBufferDesc buf_desc = {SECBUFFER_VERSION, sizeof(bufs)/sizeof(*bufs), bufs};
609 SSIZE_T size, buf_len;
610 unsigned int i;
611 SECURITY_STATUS res;
613 assert(conn->extra_len < ssl_buf_size);
615 if(conn->extra_len) {
616 memcpy(conn->ssl_buf, conn->extra_buf, conn->extra_len);
617 buf_len = conn->extra_len;
618 conn->extra_len = 0;
619 heap_free(conn->extra_buf);
620 conn->extra_buf = NULL;
621 }else {
622 buf_len = sock_recv(conn->socket, conn->ssl_buf+conn->extra_len, ssl_buf_size-conn->extra_len, 0);
623 if(buf_len < 0) {
624 WARN("recv failed\n");
625 return FALSE;
628 if(!buf_len) {
629 *eof = TRUE;
630 return TRUE;
634 *ret_size = 0;
635 *eof = FALSE;
637 do {
638 memset(bufs, 0, sizeof(bufs));
639 bufs[0].BufferType = SECBUFFER_DATA;
640 bufs[0].cbBuffer = buf_len;
641 bufs[0].pvBuffer = conn->ssl_buf;
643 res = DecryptMessage(&conn->ssl_ctx, &buf_desc, 0, NULL);
644 switch(res) {
645 case SEC_E_OK:
646 break;
647 case SEC_I_CONTEXT_EXPIRED:
648 TRACE("context expired\n");
649 *eof = TRUE;
650 return TRUE;
651 case SEC_E_INCOMPLETE_MESSAGE:
652 assert(buf_len < ssl_buf_size);
654 size = sock_recv(conn->socket, conn->ssl_buf+buf_len, ssl_buf_size-buf_len, 0);
655 if(size < 1)
656 return FALSE;
658 buf_len += size;
659 continue;
660 default:
661 WARN("failed: %08x\n", res);
662 return FALSE;
664 } while(res != SEC_E_OK);
666 for(i=0; i < sizeof(bufs)/sizeof(*bufs); i++) {
667 if(bufs[i].BufferType == SECBUFFER_DATA) {
668 size = min(buf_size, bufs[i].cbBuffer);
669 memcpy(buf, bufs[i].pvBuffer, size);
670 if(size < bufs[i].cbBuffer) {
671 assert(!conn->peek_len);
672 conn->peek_msg_mem = conn->peek_msg = heap_alloc(bufs[i].cbBuffer - size);
673 if(!conn->peek_msg)
674 return FALSE;
675 conn->peek_len = bufs[i].cbBuffer-size;
676 memcpy(conn->peek_msg, (char*)bufs[i].pvBuffer+size, conn->peek_len);
679 *ret_size = size;
683 for(i=0; i < sizeof(bufs)/sizeof(*bufs); i++) {
684 if(bufs[i].BufferType == SECBUFFER_EXTRA) {
685 conn->extra_buf = heap_alloc(bufs[i].cbBuffer);
686 if(!conn->extra_buf)
687 return FALSE;
689 conn->extra_len = bufs[i].cbBuffer;
690 memcpy(conn->extra_buf, bufs[i].pvBuffer, conn->extra_len);
694 return TRUE;
697 BOOL netconn_recv( netconn_t *conn, void *buf, size_t len, int flags, int *recvd )
699 *recvd = 0;
700 if (!len) return TRUE;
702 if (conn->secure)
704 SIZE_T size, cread;
705 BOOL res, eof;
707 if (conn->peek_msg)
709 *recvd = min( len, conn->peek_len );
710 memcpy( buf, conn->peek_msg, *recvd );
711 conn->peek_len -= *recvd;
712 conn->peek_msg += *recvd;
714 if (conn->peek_len == 0)
716 heap_free( conn->peek_msg_mem );
717 conn->peek_msg_mem = NULL;
718 conn->peek_msg = NULL;
720 /* check if we have enough data from the peek buffer */
721 if (!(flags & MSG_WAITALL) || *recvd == len) return TRUE;
723 size = *recvd;
725 do {
726 res = read_ssl_chunk(conn, (BYTE*)buf+size, len-size, &cread, &eof);
727 if(!res) {
728 WARN("read_ssl_chunk failed\n");
729 if(!size)
730 return FALSE;
731 break;
734 if(eof) {
735 TRACE("EOF\n");
736 break;
739 size += cread;
740 }while(!size || ((flags & MSG_WAITALL) && size < len));
742 TRACE("received %ld bytes\n", size);
743 *recvd = size;
744 return TRUE;
746 if ((*recvd = sock_recv( conn->socket, buf, len, flags )) == -1)
748 set_last_error( sock_get_error( errno ) );
749 return FALSE;
751 return TRUE;
754 ULONG netconn_query_data_available( netconn_t *conn )
756 return conn->secure ? conn->peek_len : 0;
759 DWORD netconn_set_timeout( netconn_t *netconn, BOOL send, int value )
761 struct timeval tv;
763 /* value is in milliseconds, convert to struct timeval */
764 tv.tv_sec = value / 1000;
765 tv.tv_usec = (value % 1000) * 1000;
767 if (setsockopt( netconn->socket, SOL_SOCKET, send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv, sizeof(tv) ) == -1)
769 WARN("setsockopt failed (%s)\n", strerror( errno ));
770 return sock_get_error( errno );
772 return ERROR_SUCCESS;
775 BOOL netconn_is_alive( netconn_t *netconn )
777 #ifdef MSG_DONTWAIT
778 ssize_t len;
779 BYTE b;
781 len = recv( netconn->socket, &b, 1, MSG_PEEK | MSG_DONTWAIT );
782 return len == 1 || (len == -1 && errno == EWOULDBLOCK);
783 #elif defined(__MINGW32__) || defined(_MSC_VER)
784 ULONG mode;
785 int len;
786 char b;
788 mode = 1;
789 if(!ioctlsocket(netconn->socket, FIONBIO, &mode))
790 return FALSE;
792 len = recv(netconn->socket, &b, 1, MSG_PEEK);
794 mode = 0;
795 if(!ioctlsocket(netconn->socket, FIONBIO, &mode))
796 return FALSE;
798 return len == 1 || (len == -1 && WSAGetLastError() == WSAEWOULDBLOCK);
799 #else
800 FIXME("not supported on this platform\n");
801 return TRUE;
802 #endif
805 static DWORD resolve_hostname( const WCHAR *hostnameW, INTERNET_PORT port, struct sockaddr_storage *sa )
807 char *hostname;
808 #ifdef HAVE_GETADDRINFO
809 struct addrinfo *res, hints;
810 int ret;
811 #else
812 struct hostent *he;
813 struct sockaddr_in *sin = (struct sockaddr_in *)sa;
814 #endif
816 if (!(hostname = strdupWA( hostnameW ))) return ERROR_OUTOFMEMORY;
818 #ifdef HAVE_GETADDRINFO
819 memset( &hints, 0, sizeof(struct addrinfo) );
820 /* Prefer IPv4 to IPv6 addresses, since some web servers do not listen on
821 * their IPv6 addresses even though they have IPv6 addresses in the DNS.
823 hints.ai_family = AF_INET;
825 ret = getaddrinfo( hostname, NULL, &hints, &res );
826 if (ret != 0)
828 TRACE("failed to get IPv4 address of %s (%s), retrying with IPv6\n", debugstr_w(hostnameW), gai_strerror(ret));
829 hints.ai_family = AF_INET6;
830 ret = getaddrinfo( hostname, NULL, &hints, &res );
831 if (ret != 0)
833 TRACE("failed to get address of %s (%s)\n", debugstr_w(hostnameW), gai_strerror(ret));
834 heap_free( hostname );
835 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
838 heap_free( hostname );
839 memcpy( sa, res->ai_addr, res->ai_addrlen );
840 /* Copy port */
841 switch (res->ai_family)
843 case AF_INET:
844 ((struct sockaddr_in *)sa)->sin_port = htons( port );
845 break;
846 case AF_INET6:
847 ((struct sockaddr_in6 *)sa)->sin6_port = htons( port );
848 break;
851 freeaddrinfo( res );
852 return ERROR_SUCCESS;
853 #else
854 EnterCriticalSection( &cs_gethostbyname );
856 he = gethostbyname( hostname );
857 heap_free( hostname );
858 if (!he)
860 TRACE("failed to get address of %s (%d)\n", debugstr_w(hostnameW), h_errno);
861 LeaveCriticalSection( &cs_gethostbyname );
862 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
864 memset( sa, 0, sizeof(struct sockaddr_in) );
865 memcpy( &sin->sin_addr, he->h_addr, he->h_length );
866 sin->sin_family = he->h_addrtype;
867 sin->sin_port = htons( port );
869 LeaveCriticalSection( &cs_gethostbyname );
870 return ERROR_SUCCESS;
871 #endif
874 struct resolve_args
876 const WCHAR *hostname;
877 INTERNET_PORT port;
878 struct sockaddr_storage *sa;
881 static DWORD CALLBACK resolve_proc( LPVOID arg )
883 struct resolve_args *ra = arg;
884 return resolve_hostname( ra->hostname, ra->port, ra->sa );
887 BOOL netconn_resolve( WCHAR *hostname, INTERNET_PORT port, struct sockaddr_storage *sa, int timeout )
889 DWORD ret;
891 if (timeout)
893 DWORD status;
894 HANDLE thread;
895 struct resolve_args ra;
897 ra.hostname = hostname;
898 ra.port = port;
899 ra.sa = sa;
901 thread = CreateThread( NULL, 0, resolve_proc, &ra, 0, NULL );
902 if (!thread) return FALSE;
904 status = WaitForSingleObject( thread, timeout );
905 if (status == WAIT_OBJECT_0) GetExitCodeThread( thread, &ret );
906 else ret = ERROR_WINHTTP_TIMEOUT;
907 CloseHandle( thread );
909 else ret = resolve_hostname( hostname, port, sa );
911 if (ret)
913 set_last_error( ret );
914 return FALSE;
916 return TRUE;
919 const void *netconn_get_certificate( netconn_t *conn )
921 const CERT_CONTEXT *ret;
922 SECURITY_STATUS res;
924 if (!conn->secure) return NULL;
925 res = QueryContextAttributesW(&conn->ssl_ctx, SECPKG_ATTR_REMOTE_CERT_CONTEXT, (void*)&ret);
926 return res == SEC_E_OK ? ret : NULL;
929 int netconn_get_cipher_strength( netconn_t *conn )
931 SecPkgContext_ConnectionInfo conn_info;
932 SECURITY_STATUS res;
934 if (!conn->secure) return 0;
935 res = QueryContextAttributesW(&conn->ssl_ctx, SECPKG_ATTR_CONNECTION_INFO, (void*)&conn_info);
936 if(res != SEC_E_OK)
937 WARN("QueryContextAttributesW failed: %08x\n", res);
938 return res == SEC_E_OK ? conn_info.dwCipherStrength : 0;