gdiplus: Mark the Graphics object as busy before freeing it.
[wine/multimedia.git] / dlls / wininet / netconnection.c
blob86c9b08cbc6d54f81b3ed775333d859dce12a8c2
1 /*
2 * Wininet - networking layer. Uses unix sockets.
4 * Copyright 2002 TransGaming Technologies Inc.
5 * Copyright 2013 Jacek Caban for CodeWeavers
7 * David Hammerton
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24 #include "config.h"
25 #include "wine/port.h"
27 #define NONAMELESSUNION
29 #if defined(__MINGW32__) || defined (_MSC_VER)
30 #include <ws2tcpip.h>
31 #endif
33 #include <sys/types.h>
34 #ifdef HAVE_POLL_H
35 #include <poll.h>
36 #endif
37 #ifdef HAVE_SYS_POLL_H
38 # include <sys/poll.h>
39 #endif
40 #ifdef HAVE_SYS_TIME_H
41 # include <sys/time.h>
42 #endif
43 #ifdef HAVE_SYS_SOCKET_H
44 # include <sys/socket.h>
45 #endif
46 #ifdef HAVE_SYS_FILIO_H
47 # include <sys/filio.h>
48 #endif
49 #ifdef HAVE_UNISTD_H
50 # include <unistd.h>
51 #endif
52 #ifdef HAVE_SYS_IOCTL_H
53 # include <sys/ioctl.h>
54 #endif
55 #include <time.h>
56 #ifdef HAVE_NETDB_H
57 # include <netdb.h>
58 #endif
59 #ifdef HAVE_NETINET_IN_H
60 # include <netinet/in.h>
61 #endif
62 #ifdef HAVE_NETINET_TCP_H
63 # include <netinet/tcp.h>
64 #endif
66 #include <stdarg.h>
67 #include <stdlib.h>
68 #include <string.h>
69 #include <stdio.h>
70 #include <errno.h>
71 #include <assert.h>
73 #include "wine/library.h"
74 #include "windef.h"
75 #include "winbase.h"
76 #include "wininet.h"
77 #include "winerror.h"
79 #include "wine/debug.h"
80 #include "internet.h"
82 /* To avoid conflicts with the Unix socket headers. we only need it for
83 * the error codes anyway. */
84 #define USE_WS_PREFIX
85 #include "winsock2.h"
87 #define RESPONSE_TIMEOUT 30 /* FROM internet.c */
90 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
92 /* FIXME!!!!!!
93 * This should use winsock - To use winsock the functions will have to change a bit
94 * as they are designed for unix sockets.
97 static DWORD netconn_verify_cert(netconn_t *conn, PCCERT_CONTEXT cert, HCERTSTORE store)
99 BOOL ret;
100 CERT_CHAIN_PARA chainPara = { sizeof(chainPara), { 0 } };
101 PCCERT_CHAIN_CONTEXT chain;
102 char oid_server_auth[] = szOID_PKIX_KP_SERVER_AUTH;
103 char *server_auth[] = { oid_server_auth };
104 DWORD err = ERROR_SUCCESS, errors;
106 static const DWORD supportedErrors =
107 CERT_TRUST_IS_NOT_TIME_VALID |
108 CERT_TRUST_IS_UNTRUSTED_ROOT |
109 CERT_TRUST_IS_PARTIAL_CHAIN |
110 CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
112 TRACE("verifying %s\n", debugstr_w(conn->server->name));
114 chainPara.RequestedUsage.Usage.cUsageIdentifier = 1;
115 chainPara.RequestedUsage.Usage.rgpszUsageIdentifier = server_auth;
116 if (!(ret = CertGetCertificateChain(NULL, cert, NULL, store, &chainPara, 0, NULL, &chain))) {
117 TRACE("failed\n");
118 return GetLastError();
121 errors = chain->TrustStatus.dwErrorStatus;
123 do {
124 /* This seems strange, but that's what tests show */
125 if(errors & CERT_TRUST_IS_PARTIAL_CHAIN) {
126 WARN("ERROR_INTERNET_SEC_CERT_REV_FAILED\n");
127 err = ERROR_INTERNET_SEC_CERT_REV_FAILED;
128 if(conn->mask_errors)
129 conn->security_flags |= _SECURITY_FLAG_CERT_REV_FAILED;
130 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_REVOCATION))
131 break;
134 if (chain->TrustStatus.dwErrorStatus & ~supportedErrors) {
135 WARN("error status %x\n", chain->TrustStatus.dwErrorStatus & ~supportedErrors);
136 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_INVALID_CERT;
137 errors &= supportedErrors;
138 if(!conn->mask_errors)
139 break;
140 WARN("unknown error flags\n");
143 if(errors & CERT_TRUST_IS_NOT_TIME_VALID) {
144 WARN("CERT_TRUST_IS_NOT_TIME_VALID\n");
145 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_CERT_DATE_INVALID)) {
146 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_CERT_DATE_INVALID;
147 if(!conn->mask_errors)
148 break;
149 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_DATE;
151 errors &= ~CERT_TRUST_IS_NOT_TIME_VALID;
154 if(errors & CERT_TRUST_IS_UNTRUSTED_ROOT) {
155 WARN("CERT_TRUST_IS_UNTRUSTED_ROOT\n");
156 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA)) {
157 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_INVALID_CA;
158 if(!conn->mask_errors)
159 break;
160 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CA;
162 errors &= ~CERT_TRUST_IS_UNTRUSTED_ROOT;
165 if(errors & CERT_TRUST_IS_PARTIAL_CHAIN) {
166 WARN("CERT_TRUST_IS_PARTIAL_CHAIN\n");
167 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA)) {
168 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_INVALID_CA;
169 if(!conn->mask_errors)
170 break;
171 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CA;
173 errors &= ~CERT_TRUST_IS_PARTIAL_CHAIN;
176 if(errors & CERT_TRUST_IS_NOT_VALID_FOR_USAGE) {
177 WARN("CERT_TRUST_IS_NOT_VALID_FOR_USAGE\n");
178 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_WRONG_USAGE)) {
179 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_INVALID_CERT;
180 if(!conn->mask_errors)
181 break;
182 WARN("CERT_TRUST_IS_NOT_VALID_FOR_USAGE, unknown error flags\n");
184 errors &= ~CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
187 if(err == ERROR_INTERNET_SEC_CERT_REV_FAILED) {
188 assert(conn->security_flags & SECURITY_FLAG_IGNORE_REVOCATION);
189 err = ERROR_SUCCESS;
191 }while(0);
193 if(!err || conn->mask_errors) {
194 CERT_CHAIN_POLICY_PARA policyPara;
195 SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslExtraPolicyPara;
196 CERT_CHAIN_POLICY_STATUS policyStatus;
197 CERT_CHAIN_CONTEXT chainCopy;
199 /* Clear chain->TrustStatus.dwErrorStatus so
200 * CertVerifyCertificateChainPolicy will verify additional checks
201 * rather than stopping with an existing, ignored error.
203 memcpy(&chainCopy, chain, sizeof(chainCopy));
204 chainCopy.TrustStatus.dwErrorStatus = 0;
205 sslExtraPolicyPara.u.cbSize = sizeof(sslExtraPolicyPara);
206 sslExtraPolicyPara.dwAuthType = AUTHTYPE_SERVER;
207 sslExtraPolicyPara.pwszServerName = conn->server->name;
208 sslExtraPolicyPara.fdwChecks = conn->security_flags;
209 policyPara.cbSize = sizeof(policyPara);
210 policyPara.dwFlags = 0;
211 policyPara.pvExtraPolicyPara = &sslExtraPolicyPara;
212 ret = CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL,
213 &chainCopy, &policyPara, &policyStatus);
214 /* Any error in the policy status indicates that the
215 * policy couldn't be verified.
217 if(ret) {
218 if(policyStatus.dwError == CERT_E_CN_NO_MATCH) {
219 WARN("CERT_E_CN_NO_MATCH\n");
220 if(conn->mask_errors)
221 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CN;
222 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_CERT_CN_INVALID;
223 }else if(policyStatus.dwError) {
224 WARN("policyStatus.dwError %x\n", policyStatus.dwError);
225 if(conn->mask_errors)
226 WARN("unknown error flags for policy status %x\n", policyStatus.dwError);
227 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_INVALID_CERT;
229 }else {
230 err = GetLastError();
234 if(err) {
235 WARN("failed %u\n", err);
236 CertFreeCertificateChain(chain);
237 if(conn->server->cert_chain) {
238 CertFreeCertificateChain(conn->server->cert_chain);
239 conn->server->cert_chain = NULL;
241 if(conn->mask_errors)
242 conn->server->security_flags |= conn->security_flags & _SECURITY_ERROR_FLAGS_MASK;
243 return err;
246 /* FIXME: Reuse cached chain */
247 if(conn->server->cert_chain)
248 CertFreeCertificateChain(chain);
249 else
250 conn->server->cert_chain = chain;
251 return ERROR_SUCCESS;
254 static SecHandle cred_handle, compat_cred_handle;
255 static BOOL cred_handle_initialized, have_compat_cred_handle;
257 static CRITICAL_SECTION init_sechandle_cs;
258 static CRITICAL_SECTION_DEBUG init_sechandle_cs_debug = {
259 0, 0, &init_sechandle_cs,
260 { &init_sechandle_cs_debug.ProcessLocksList,
261 &init_sechandle_cs_debug.ProcessLocksList },
262 0, 0, { (DWORD_PTR)(__FILE__ ": init_sechandle_cs") }
264 static CRITICAL_SECTION init_sechandle_cs = { &init_sechandle_cs_debug, -1, 0, 0, 0, 0 };
266 static BOOL ensure_cred_handle(void)
268 SECURITY_STATUS res = SEC_E_OK;
270 EnterCriticalSection(&init_sechandle_cs);
272 if(!cred_handle_initialized) {
273 SCHANNEL_CRED cred = {SCHANNEL_CRED_VERSION};
274 SecPkgCred_SupportedProtocols prots;
276 res = AcquireCredentialsHandleW(NULL, (WCHAR*)UNISP_NAME_W, SECPKG_CRED_OUTBOUND, NULL, &cred,
277 NULL, NULL, &cred_handle, NULL);
278 if(res == SEC_E_OK) {
279 res = QueryCredentialsAttributesA(&cred_handle, SECPKG_ATTR_SUPPORTED_PROTOCOLS, &prots);
280 if(res != SEC_E_OK || (prots.grbitProtocol & SP_PROT_TLS1_1PLUS_CLIENT)) {
281 cred.grbitEnabledProtocols = prots.grbitProtocol & ~SP_PROT_TLS1_1PLUS_CLIENT;
282 res = AcquireCredentialsHandleW(NULL, (WCHAR*)UNISP_NAME_W, SECPKG_CRED_OUTBOUND, NULL, &cred,
283 NULL, NULL, &compat_cred_handle, NULL);
284 have_compat_cred_handle = res == SEC_E_OK;
288 cred_handle_initialized = res == SEC_E_OK;
291 LeaveCriticalSection(&init_sechandle_cs);
293 if(res != SEC_E_OK) {
294 WARN("Failed: %08x\n", res);
295 return FALSE;
298 return TRUE;
301 static DWORD create_netconn_socket(server_t *server, netconn_t *netconn, DWORD timeout)
303 int result;
304 ULONG flag;
306 assert(server->addr_len);
307 result = netconn->socket = socket(server->addr.ss_family, SOCK_STREAM, 0);
308 if(result != -1) {
309 flag = 1;
310 ioctlsocket(netconn->socket, FIONBIO, &flag);
311 result = connect(netconn->socket, (struct sockaddr*)&server->addr, server->addr_len);
312 if(result == -1)
314 if (sock_get_error(errno) == WSAEINPROGRESS) {
315 struct pollfd pfd;
316 int res;
318 pfd.fd = netconn->socket;
319 pfd.events = POLLOUT;
320 res = poll(&pfd, 1, timeout);
321 if (!res)
323 closesocket(netconn->socket);
324 netconn->socket = -1;
325 return ERROR_INTERNET_CANNOT_CONNECT;
327 else if (res > 0)
329 int err;
330 socklen_t len = sizeof(err);
331 if (!getsockopt(netconn->socket, SOL_SOCKET, SO_ERROR, (void *)&err, &len) && !err)
332 result = 0;
336 if(result == -1)
338 closesocket(netconn->socket);
339 netconn->socket = -1;
341 else {
342 flag = 0;
343 ioctlsocket(netconn->socket, FIONBIO, &flag);
346 if(result == -1)
347 return ERROR_INTERNET_CANNOT_CONNECT;
349 #ifdef TCP_NODELAY
350 flag = 1;
351 result = setsockopt(netconn->socket, IPPROTO_TCP, TCP_NODELAY, (void*)&flag, sizeof(flag));
352 if(result < 0)
353 WARN("setsockopt(TCP_NODELAY) failed\n");
354 #endif
356 return ERROR_SUCCESS;
359 DWORD create_netconn(BOOL useSSL, server_t *server, DWORD security_flags, BOOL mask_errors, DWORD timeout, netconn_t **ret)
361 netconn_t *netconn;
362 int result;
364 netconn = heap_alloc_zero(sizeof(*netconn));
365 if(!netconn)
366 return ERROR_OUTOFMEMORY;
368 netconn->socket = -1;
369 netconn->security_flags = security_flags | server->security_flags;
370 netconn->mask_errors = mask_errors;
371 list_init(&netconn->pool_entry);
372 SecInvalidateHandle(&netconn->ssl_ctx);
374 result = create_netconn_socket(server, netconn, timeout);
375 if (result != ERROR_SUCCESS) {
376 heap_free(netconn);
377 return result;
380 server_addref(server);
381 netconn->server = server;
382 *ret = netconn;
383 return result;
386 BOOL is_valid_netconn(netconn_t *netconn)
388 return netconn && netconn->socket != -1;
391 void close_netconn(netconn_t *netconn)
393 closesocket(netconn->socket);
394 netconn->socket = -1;
397 void free_netconn(netconn_t *netconn)
399 server_release(netconn->server);
401 if (netconn->secure) {
402 heap_free(netconn->peek_msg_mem);
403 netconn->peek_msg_mem = NULL;
404 netconn->peek_msg = NULL;
405 netconn->peek_len = 0;
406 heap_free(netconn->ssl_buf);
407 netconn->ssl_buf = NULL;
408 heap_free(netconn->extra_buf);
409 netconn->extra_buf = NULL;
410 netconn->extra_len = 0;
411 if (SecIsValidHandle(&netconn->ssl_ctx))
412 DeleteSecurityContext(&netconn->ssl_ctx);
415 heap_free(netconn);
418 void NETCON_unload(void)
420 if(cred_handle_initialized)
421 FreeCredentialsHandle(&cred_handle);
422 if(have_compat_cred_handle)
423 FreeCredentialsHandle(&compat_cred_handle);
424 DeleteCriticalSection(&init_sechandle_cs);
427 /* translate a unix error code into a winsock one */
428 int sock_get_error( int err )
430 #if !defined(__MINGW32__) && !defined (_MSC_VER)
431 switch (err)
433 case EINTR: return WSAEINTR;
434 case EBADF: return WSAEBADF;
435 case EPERM:
436 case EACCES: return WSAEACCES;
437 case EFAULT: return WSAEFAULT;
438 case EINVAL: return WSAEINVAL;
439 case EMFILE: return WSAEMFILE;
440 case EWOULDBLOCK: return WSAEWOULDBLOCK;
441 case EINPROGRESS: return WSAEINPROGRESS;
442 case EALREADY: return WSAEALREADY;
443 case ENOTSOCK: return WSAENOTSOCK;
444 case EDESTADDRREQ: return WSAEDESTADDRREQ;
445 case EMSGSIZE: return WSAEMSGSIZE;
446 case EPROTOTYPE: return WSAEPROTOTYPE;
447 case ENOPROTOOPT: return WSAENOPROTOOPT;
448 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
449 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
450 case EOPNOTSUPP: return WSAEOPNOTSUPP;
451 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
452 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
453 case EADDRINUSE: return WSAEADDRINUSE;
454 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
455 case ENETDOWN: return WSAENETDOWN;
456 case ENETUNREACH: return WSAENETUNREACH;
457 case ENETRESET: return WSAENETRESET;
458 case ECONNABORTED: return WSAECONNABORTED;
459 case EPIPE:
460 case ECONNRESET: return WSAECONNRESET;
461 case ENOBUFS: return WSAENOBUFS;
462 case EISCONN: return WSAEISCONN;
463 case ENOTCONN: return WSAENOTCONN;
464 case ESHUTDOWN: return WSAESHUTDOWN;
465 case ETOOMANYREFS: return WSAETOOMANYREFS;
466 case ETIMEDOUT: return WSAETIMEDOUT;
467 case ECONNREFUSED: return WSAECONNREFUSED;
468 case ELOOP: return WSAELOOP;
469 case ENAMETOOLONG: return WSAENAMETOOLONG;
470 case EHOSTDOWN: return WSAEHOSTDOWN;
471 case EHOSTUNREACH: return WSAEHOSTUNREACH;
472 case ENOTEMPTY: return WSAENOTEMPTY;
473 #ifdef EPROCLIM
474 case EPROCLIM: return WSAEPROCLIM;
475 #endif
476 #ifdef EUSERS
477 case EUSERS: return WSAEUSERS;
478 #endif
479 #ifdef EDQUOT
480 case EDQUOT: return WSAEDQUOT;
481 #endif
482 #ifdef ESTALE
483 case ESTALE: return WSAESTALE;
484 #endif
485 #ifdef EREMOTE
486 case EREMOTE: return WSAEREMOTE;
487 #endif
488 default: errno=err; perror("sock_set_error"); return WSAEFAULT;
490 #endif
491 return err;
494 static DWORD netcon_secure_connect_setup(netconn_t *connection, BOOL compat_mode)
496 SecBuffer out_buf = {0, SECBUFFER_TOKEN, NULL}, in_bufs[2] = {{0, SECBUFFER_TOKEN}, {0, SECBUFFER_EMPTY}};
497 SecBufferDesc out_desc = {SECBUFFER_VERSION, 1, &out_buf}, in_desc = {SECBUFFER_VERSION, 2, in_bufs};
498 SecHandle *cred = &cred_handle;
499 BYTE *read_buf;
500 SIZE_T read_buf_size = 2048;
501 ULONG attrs = 0;
502 CtxtHandle ctx;
503 SSIZE_T size;
504 int bits;
505 const CERT_CONTEXT *cert;
506 SECURITY_STATUS status;
507 DWORD res = ERROR_SUCCESS;
509 const DWORD isc_req_flags = ISC_REQ_ALLOCATE_MEMORY|ISC_REQ_USE_SESSION_KEY|ISC_REQ_CONFIDENTIALITY
510 |ISC_REQ_SEQUENCE_DETECT|ISC_REQ_REPLAY_DETECT|ISC_REQ_MANUAL_CRED_VALIDATION;
512 if(!ensure_cred_handle())
513 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
515 if(compat_mode) {
516 if(!have_compat_cred_handle)
517 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
518 cred = &compat_cred_handle;
521 read_buf = heap_alloc(read_buf_size);
522 if(!read_buf)
523 return ERROR_OUTOFMEMORY;
525 status = InitializeSecurityContextW(cred, NULL, connection->server->name, isc_req_flags, 0, 0, NULL, 0,
526 &ctx, &out_desc, &attrs, NULL);
528 assert(status != SEC_E_OK);
530 while(status == SEC_I_CONTINUE_NEEDED || status == SEC_E_INCOMPLETE_MESSAGE) {
531 if(out_buf.cbBuffer) {
532 assert(status == SEC_I_CONTINUE_NEEDED);
534 TRACE("sending %u bytes\n", out_buf.cbBuffer);
536 size = send(connection->socket, out_buf.pvBuffer, out_buf.cbBuffer, 0);
537 if(size != out_buf.cbBuffer) {
538 ERR("send failed\n");
539 status = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
540 break;
543 FreeContextBuffer(out_buf.pvBuffer);
544 out_buf.pvBuffer = NULL;
545 out_buf.cbBuffer = 0;
548 if(status == SEC_I_CONTINUE_NEEDED) {
549 assert(in_bufs[1].cbBuffer < read_buf_size);
551 memmove(read_buf, (BYTE*)in_bufs[0].pvBuffer+in_bufs[0].cbBuffer-in_bufs[1].cbBuffer, in_bufs[1].cbBuffer);
552 in_bufs[0].cbBuffer = in_bufs[1].cbBuffer;
554 in_bufs[1].BufferType = SECBUFFER_EMPTY;
555 in_bufs[1].cbBuffer = 0;
556 in_bufs[1].pvBuffer = NULL;
559 assert(in_bufs[0].BufferType == SECBUFFER_TOKEN);
560 assert(in_bufs[1].BufferType == SECBUFFER_EMPTY);
562 if(in_bufs[0].cbBuffer + 1024 > read_buf_size) {
563 BYTE *new_read_buf;
565 new_read_buf = heap_realloc(read_buf, read_buf_size + 1024);
566 if(!new_read_buf) {
567 status = E_OUTOFMEMORY;
568 break;
571 in_bufs[0].pvBuffer = read_buf = new_read_buf;
572 read_buf_size += 1024;
575 size = recv(connection->socket, read_buf+in_bufs[0].cbBuffer, read_buf_size-in_bufs[0].cbBuffer, 0);
576 if(size < 1) {
577 WARN("recv error\n");
578 res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
579 break;
582 TRACE("recv %lu bytes\n", size);
584 in_bufs[0].cbBuffer += size;
585 in_bufs[0].pvBuffer = read_buf;
586 status = InitializeSecurityContextW(cred, &ctx, connection->server->name, isc_req_flags, 0, 0, &in_desc,
587 0, NULL, &out_desc, &attrs, NULL);
588 TRACE("InitializeSecurityContext ret %08x\n", status);
590 if(status == SEC_E_OK) {
591 if(SecIsValidHandle(&connection->ssl_ctx))
592 DeleteSecurityContext(&connection->ssl_ctx);
593 connection->ssl_ctx = ctx;
595 if(in_bufs[1].BufferType == SECBUFFER_EXTRA)
596 FIXME("SECBUFFER_EXTRA not supported\n");
598 status = QueryContextAttributesW(&ctx, SECPKG_ATTR_STREAM_SIZES, &connection->ssl_sizes);
599 if(status != SEC_E_OK) {
600 WARN("Could not get sizes\n");
601 break;
604 status = QueryContextAttributesW(&ctx, SECPKG_ATTR_REMOTE_CERT_CONTEXT, (void*)&cert);
605 if(status == SEC_E_OK) {
606 res = netconn_verify_cert(connection, cert, cert->hCertStore);
607 CertFreeCertificateContext(cert);
608 if(res != ERROR_SUCCESS) {
609 WARN("cert verify failed: %u\n", res);
610 break;
612 }else {
613 WARN("Could not get cert\n");
614 break;
617 connection->ssl_buf = heap_alloc(connection->ssl_sizes.cbHeader + connection->ssl_sizes.cbMaximumMessage
618 + connection->ssl_sizes.cbTrailer);
619 if(!connection->ssl_buf) {
620 res = GetLastError();
621 break;
626 if(status != SEC_E_OK || res != ERROR_SUCCESS) {
627 WARN("Failed to establish SSL connection: %08x (%u)\n", status, res);
628 heap_free(connection->ssl_buf);
629 connection->ssl_buf = NULL;
630 return res ? res : ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
633 TRACE("established SSL connection\n");
634 connection->secure = TRUE;
635 connection->security_flags |= SECURITY_FLAG_SECURE;
637 bits = NETCON_GetCipherStrength(connection);
638 if (bits >= 128)
639 connection->security_flags |= SECURITY_FLAG_STRENGTH_STRONG;
640 else if (bits >= 56)
641 connection->security_flags |= SECURITY_FLAG_STRENGTH_MEDIUM;
642 else
643 connection->security_flags |= SECURITY_FLAG_STRENGTH_WEAK;
645 if(connection->mask_errors)
646 connection->server->security_flags = connection->security_flags;
647 return ERROR_SUCCESS;
650 /******************************************************************************
651 * NETCON_secure_connect
652 * Initiates a secure connection over an existing plaintext connection.
654 DWORD NETCON_secure_connect(netconn_t *connection, server_t *server)
656 DWORD res;
658 /* can't connect if we are already connected */
659 if(connection->secure) {
660 ERR("already connected\n");
661 return ERROR_INTERNET_CANNOT_CONNECT;
664 if(server != connection->server) {
665 server_release(connection->server);
666 server_addref(server);
667 connection->server = server;
670 /* connect with given TLS options */
671 res = netcon_secure_connect_setup(connection, FALSE);
672 if (res == ERROR_SUCCESS)
673 return res;
675 /* FIXME: when got version alert and FIN from server */
676 /* fallback to connect without TLSv1.1/TLSv1.2 */
677 if (res == ERROR_INTERNET_SECURITY_CHANNEL_ERROR && have_compat_cred_handle)
679 closesocket(connection->socket);
680 res = create_netconn_socket(connection->server, connection, 500);
681 if (res != ERROR_SUCCESS)
682 return res;
683 res = netcon_secure_connect_setup(connection, TRUE);
685 return res;
688 static BOOL send_ssl_chunk(netconn_t *conn, const void *msg, size_t size)
690 SecBuffer bufs[4] = {
691 {conn->ssl_sizes.cbHeader, SECBUFFER_STREAM_HEADER, conn->ssl_buf},
692 {size, SECBUFFER_DATA, conn->ssl_buf+conn->ssl_sizes.cbHeader},
693 {conn->ssl_sizes.cbTrailer, SECBUFFER_STREAM_TRAILER, conn->ssl_buf+conn->ssl_sizes.cbHeader+size},
694 {0, SECBUFFER_EMPTY, NULL}
696 SecBufferDesc buf_desc = {SECBUFFER_VERSION, sizeof(bufs)/sizeof(*bufs), bufs};
697 SECURITY_STATUS res;
699 memcpy(bufs[1].pvBuffer, msg, size);
700 res = EncryptMessage(&conn->ssl_ctx, 0, &buf_desc, 0);
701 if(res != SEC_E_OK) {
702 WARN("EncryptMessage failed\n");
703 return FALSE;
706 if(send(conn->socket, conn->ssl_buf, bufs[0].cbBuffer+bufs[1].cbBuffer+bufs[2].cbBuffer, 0) < 1) {
707 WARN("send failed\n");
708 return FALSE;
711 return TRUE;
714 /******************************************************************************
715 * NETCON_send
716 * Basically calls 'send()' unless we should use SSL
717 * number of chars send is put in *sent
719 DWORD NETCON_send(netconn_t *connection, const void *msg, size_t len, int flags,
720 int *sent /* out */)
722 if(!connection->secure)
724 *sent = send(connection->socket, msg, len, flags);
725 if (*sent == -1)
726 return sock_get_error(errno);
727 return ERROR_SUCCESS;
729 else
731 const BYTE *ptr = msg;
732 size_t chunk_size;
734 *sent = 0;
736 while(len) {
737 chunk_size = min(len, connection->ssl_sizes.cbMaximumMessage);
738 if(!send_ssl_chunk(connection, ptr, chunk_size))
739 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
741 *sent += chunk_size;
742 ptr += chunk_size;
743 len -= chunk_size;
746 return ERROR_SUCCESS;
750 static BOOL read_ssl_chunk(netconn_t *conn, void *buf, SIZE_T buf_size, SIZE_T *ret_size, BOOL *eof)
752 const SIZE_T ssl_buf_size = conn->ssl_sizes.cbHeader+conn->ssl_sizes.cbMaximumMessage+conn->ssl_sizes.cbTrailer;
753 SecBuffer bufs[4];
754 SecBufferDesc buf_desc = {SECBUFFER_VERSION, sizeof(bufs)/sizeof(*bufs), bufs};
755 SSIZE_T size, buf_len;
756 int i;
757 SECURITY_STATUS res;
759 assert(conn->extra_len < ssl_buf_size);
761 if(conn->extra_len) {
762 memcpy(conn->ssl_buf, conn->extra_buf, conn->extra_len);
763 buf_len = conn->extra_len;
764 conn->extra_len = 0;
765 heap_free(conn->extra_buf);
766 conn->extra_buf = NULL;
767 }else {
768 buf_len = recv(conn->socket, conn->ssl_buf+conn->extra_len, ssl_buf_size-conn->extra_len, 0);
769 if(buf_len < 0) {
770 WARN("recv failed\n");
771 return FALSE;
774 if(!buf_len) {
775 *eof = TRUE;
776 return TRUE;
780 *ret_size = 0;
781 *eof = FALSE;
783 do {
784 memset(bufs, 0, sizeof(bufs));
785 bufs[0].BufferType = SECBUFFER_DATA;
786 bufs[0].cbBuffer = buf_len;
787 bufs[0].pvBuffer = conn->ssl_buf;
789 res = DecryptMessage(&conn->ssl_ctx, &buf_desc, 0, NULL);
790 switch(res) {
791 case SEC_E_OK:
792 break;
793 case SEC_I_CONTEXT_EXPIRED:
794 TRACE("context expired\n");
795 *eof = TRUE;
796 return TRUE;
797 case SEC_E_INCOMPLETE_MESSAGE:
798 assert(buf_len < ssl_buf_size);
800 size = recv(conn->socket, conn->ssl_buf+buf_len, ssl_buf_size-buf_len, 0);
801 if(size < 1)
802 return FALSE;
804 buf_len += size;
805 continue;
806 default:
807 WARN("failed: %08x\n", res);
808 return FALSE;
810 } while(res != SEC_E_OK);
812 for(i=0; i < sizeof(bufs)/sizeof(*bufs); i++) {
813 if(bufs[i].BufferType == SECBUFFER_DATA) {
814 size = min(buf_size, bufs[i].cbBuffer);
815 memcpy(buf, bufs[i].pvBuffer, size);
816 if(size < bufs[i].cbBuffer) {
817 assert(!conn->peek_len);
818 conn->peek_msg_mem = conn->peek_msg = heap_alloc(bufs[i].cbBuffer - size);
819 if(!conn->peek_msg)
820 return FALSE;
821 conn->peek_len = bufs[i].cbBuffer-size;
822 memcpy(conn->peek_msg, (char*)bufs[i].pvBuffer+size, conn->peek_len);
825 *ret_size = size;
829 for(i=0; i < sizeof(bufs)/sizeof(*bufs); i++) {
830 if(bufs[i].BufferType == SECBUFFER_EXTRA) {
831 conn->extra_buf = heap_alloc(bufs[i].cbBuffer);
832 if(!conn->extra_buf)
833 return FALSE;
835 conn->extra_len = bufs[i].cbBuffer;
836 memcpy(conn->extra_buf, bufs[i].pvBuffer, conn->extra_len);
840 return TRUE;
843 /******************************************************************************
844 * NETCON_recv
845 * Basically calls 'recv()' unless we should use SSL
846 * number of chars received is put in *recvd
848 DWORD NETCON_recv(netconn_t *connection, void *buf, size_t len, int flags, int *recvd)
850 *recvd = 0;
851 if (!len)
852 return ERROR_SUCCESS;
854 if (!connection->secure)
856 *recvd = recv(connection->socket, buf, len, flags);
857 return *recvd == -1 ? sock_get_error(errno) : ERROR_SUCCESS;
859 else
861 SIZE_T size = 0, cread;
862 BOOL res, eof;
864 if(connection->peek_msg) {
865 size = min(len, connection->peek_len);
866 memcpy(buf, connection->peek_msg, size);
867 connection->peek_len -= size;
868 connection->peek_msg += size;
870 if(!connection->peek_len) {
871 heap_free(connection->peek_msg_mem);
872 connection->peek_msg_mem = connection->peek_msg = NULL;
874 /* check if we have enough data from the peek buffer */
875 if(!(flags & MSG_WAITALL) || size == len) {
876 *recvd = size;
877 return ERROR_SUCCESS;
881 do {
882 res = read_ssl_chunk(connection, (BYTE*)buf+size, len-size, &cread, &eof);
883 if(!res) {
884 WARN("read_ssl_chunk failed\n");
885 if(!size)
886 return ERROR_INTERNET_CONNECTION_ABORTED;
887 break;
890 if(eof) {
891 TRACE("EOF\n");
892 break;
895 size += cread;
896 }while(!size || ((flags & MSG_WAITALL) && size < len));
898 TRACE("received %ld bytes\n", size);
899 *recvd = size;
900 return ERROR_SUCCESS;
904 /******************************************************************************
905 * NETCON_query_data_available
906 * Returns the number of bytes of peeked data plus the number of bytes of
907 * queued, but unread data.
909 BOOL NETCON_query_data_available(netconn_t *connection, DWORD *available)
911 *available = 0;
913 if(!connection->secure)
915 #ifdef FIONREAD
916 ULONG unread;
917 int retval = ioctlsocket(connection->socket, FIONREAD, &unread);
918 if (!retval)
920 TRACE("%d bytes of queued, but unread data\n", unread);
921 *available += unread;
923 #endif
925 else
927 *available = connection->peek_len;
929 return TRUE;
932 BOOL NETCON_is_alive(netconn_t *netconn)
934 #ifdef MSG_DONTWAIT
935 ssize_t len;
936 BYTE b;
938 len = recv(netconn->socket, &b, 1, MSG_PEEK|MSG_DONTWAIT);
939 return len == 1 || (len == -1 && errno == EWOULDBLOCK);
940 #elif defined(__MINGW32__) || defined(_MSC_VER)
941 ULONG mode;
942 int len;
943 char b;
945 mode = 1;
946 if(!ioctlsocket(netconn->socket, FIONBIO, &mode))
947 return FALSE;
949 len = recv(netconn->socket, &b, 1, MSG_PEEK);
951 mode = 0;
952 if(!ioctlsocket(netconn->socket, FIONBIO, &mode))
953 return FALSE;
955 return len == 1 || (len == -1 && errno == WSAEWOULDBLOCK);
956 #else
957 FIXME("not supported on this platform\n");
958 return TRUE;
959 #endif
962 LPCVOID NETCON_GetCert(netconn_t *connection)
964 const CERT_CONTEXT *ret;
965 SECURITY_STATUS res;
967 res = QueryContextAttributesW(&connection->ssl_ctx, SECPKG_ATTR_REMOTE_CERT_CONTEXT, (void*)&ret);
968 return res == SEC_E_OK ? ret : NULL;
971 int NETCON_GetCipherStrength(netconn_t *connection)
973 SecPkgContext_ConnectionInfo conn_info;
974 SECURITY_STATUS res;
976 if (!connection->secure)
977 return 0;
979 res = QueryContextAttributesW(&connection->ssl_ctx, SECPKG_ATTR_CONNECTION_INFO, (void*)&conn_info);
980 if(res != SEC_E_OK)
981 WARN("QueryContextAttributesW failed: %08x\n", res);
982 return res == SEC_E_OK ? conn_info.dwCipherStrength : 0;
985 DWORD NETCON_set_timeout(netconn_t *connection, BOOL send, DWORD value)
987 int result;
988 struct timeval tv;
990 /* value is in milliseconds, convert to struct timeval */
991 if (value == INFINITE)
993 tv.tv_sec = 0;
994 tv.tv_usec = 0;
996 else
998 tv.tv_sec = value / 1000;
999 tv.tv_usec = (value % 1000) * 1000;
1001 result = setsockopt(connection->socket, SOL_SOCKET,
1002 send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv,
1003 sizeof(tv));
1004 if (result == -1)
1006 WARN("setsockopt failed (%s)\n", strerror(errno));
1007 return sock_get_error(errno);
1009 return ERROR_SUCCESS;