vbscript: Implemented Sgn.
[wine/multimedia.git] / dlls / wininet / netconnection.c
blob483dba45b6c7182e56e6ef7bb1e9d13120ca9210
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 */
89 #ifdef MSG_DONTWAIT
90 #define WINE_MSG_DONTWAIT MSG_DONTWAIT
91 #else
92 #define WINE_MSG_DONTWAIT 0
93 #endif
95 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
97 /* FIXME!!!!!!
98 * This should use winsock - To use winsock the functions will have to change a bit
99 * as they are designed for unix sockets.
102 static DWORD netconn_verify_cert(netconn_t *conn, PCCERT_CONTEXT cert, HCERTSTORE store)
104 BOOL ret;
105 CERT_CHAIN_PARA chainPara = { sizeof(chainPara), { 0 } };
106 PCCERT_CHAIN_CONTEXT chain;
107 char oid_server_auth[] = szOID_PKIX_KP_SERVER_AUTH;
108 char *server_auth[] = { oid_server_auth };
109 DWORD err = ERROR_SUCCESS, errors;
111 static const DWORD supportedErrors =
112 CERT_TRUST_IS_NOT_TIME_VALID |
113 CERT_TRUST_IS_UNTRUSTED_ROOT |
114 CERT_TRUST_IS_PARTIAL_CHAIN |
115 CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
117 TRACE("verifying %s\n", debugstr_w(conn->server->name));
119 chainPara.RequestedUsage.Usage.cUsageIdentifier = 1;
120 chainPara.RequestedUsage.Usage.rgpszUsageIdentifier = server_auth;
121 if (!(ret = CertGetCertificateChain(NULL, cert, NULL, store, &chainPara, 0, NULL, &chain))) {
122 TRACE("failed\n");
123 return GetLastError();
126 errors = chain->TrustStatus.dwErrorStatus;
128 do {
129 /* This seems strange, but that's what tests show */
130 if(errors & CERT_TRUST_IS_PARTIAL_CHAIN) {
131 WARN("ERROR_INTERNET_SEC_CERT_REV_FAILED\n");
132 err = ERROR_INTERNET_SEC_CERT_REV_FAILED;
133 if(conn->mask_errors)
134 conn->security_flags |= _SECURITY_FLAG_CERT_REV_FAILED;
135 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_REVOCATION))
136 break;
139 if (chain->TrustStatus.dwErrorStatus & ~supportedErrors) {
140 WARN("error status %x\n", chain->TrustStatus.dwErrorStatus & ~supportedErrors);
141 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_INVALID_CERT;
142 errors &= supportedErrors;
143 if(!conn->mask_errors)
144 break;
145 WARN("unknown error flags\n");
148 if(errors & CERT_TRUST_IS_NOT_TIME_VALID) {
149 WARN("CERT_TRUST_IS_NOT_TIME_VALID\n");
150 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_CERT_DATE_INVALID)) {
151 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_CERT_DATE_INVALID;
152 if(!conn->mask_errors)
153 break;
154 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_DATE;
156 errors &= ~CERT_TRUST_IS_NOT_TIME_VALID;
159 if(errors & CERT_TRUST_IS_UNTRUSTED_ROOT) {
160 WARN("CERT_TRUST_IS_UNTRUSTED_ROOT\n");
161 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA)) {
162 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_INVALID_CA;
163 if(!conn->mask_errors)
164 break;
165 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CA;
167 errors &= ~CERT_TRUST_IS_UNTRUSTED_ROOT;
170 if(errors & CERT_TRUST_IS_PARTIAL_CHAIN) {
171 WARN("CERT_TRUST_IS_PARTIAL_CHAIN\n");
172 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA)) {
173 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_INVALID_CA;
174 if(!conn->mask_errors)
175 break;
176 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CA;
178 errors &= ~CERT_TRUST_IS_PARTIAL_CHAIN;
181 if(errors & CERT_TRUST_IS_NOT_VALID_FOR_USAGE) {
182 WARN("CERT_TRUST_IS_NOT_VALID_FOR_USAGE\n");
183 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_WRONG_USAGE)) {
184 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_INVALID_CERT;
185 if(!conn->mask_errors)
186 break;
187 WARN("CERT_TRUST_IS_NOT_VALID_FOR_USAGE, unknown error flags\n");
189 errors &= ~CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
192 if(err == ERROR_INTERNET_SEC_CERT_REV_FAILED) {
193 assert(conn->security_flags & SECURITY_FLAG_IGNORE_REVOCATION);
194 err = ERROR_SUCCESS;
196 }while(0);
198 if(!err || conn->mask_errors) {
199 CERT_CHAIN_POLICY_PARA policyPara;
200 SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslExtraPolicyPara;
201 CERT_CHAIN_POLICY_STATUS policyStatus;
202 CERT_CHAIN_CONTEXT chainCopy;
204 /* Clear chain->TrustStatus.dwErrorStatus so
205 * CertVerifyCertificateChainPolicy will verify additional checks
206 * rather than stopping with an existing, ignored error.
208 memcpy(&chainCopy, chain, sizeof(chainCopy));
209 chainCopy.TrustStatus.dwErrorStatus = 0;
210 sslExtraPolicyPara.u.cbSize = sizeof(sslExtraPolicyPara);
211 sslExtraPolicyPara.dwAuthType = AUTHTYPE_SERVER;
212 sslExtraPolicyPara.pwszServerName = conn->server->name;
213 sslExtraPolicyPara.fdwChecks = conn->security_flags;
214 policyPara.cbSize = sizeof(policyPara);
215 policyPara.dwFlags = 0;
216 policyPara.pvExtraPolicyPara = &sslExtraPolicyPara;
217 ret = CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL,
218 &chainCopy, &policyPara, &policyStatus);
219 /* Any error in the policy status indicates that the
220 * policy couldn't be verified.
222 if(ret) {
223 if(policyStatus.dwError == CERT_E_CN_NO_MATCH) {
224 WARN("CERT_E_CN_NO_MATCH\n");
225 if(conn->mask_errors)
226 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CN;
227 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_CERT_CN_INVALID;
228 }else if(policyStatus.dwError) {
229 WARN("policyStatus.dwError %x\n", policyStatus.dwError);
230 if(conn->mask_errors)
231 WARN("unknown error flags for policy status %x\n", policyStatus.dwError);
232 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_INVALID_CERT;
234 }else {
235 err = GetLastError();
239 if(err) {
240 WARN("failed %u\n", err);
241 CertFreeCertificateChain(chain);
242 if(conn->server->cert_chain) {
243 CertFreeCertificateChain(conn->server->cert_chain);
244 conn->server->cert_chain = NULL;
246 if(conn->mask_errors)
247 conn->server->security_flags |= conn->security_flags & _SECURITY_ERROR_FLAGS_MASK;
248 return err;
251 /* FIXME: Reuse cached chain */
252 if(conn->server->cert_chain)
253 CertFreeCertificateChain(chain);
254 else
255 conn->server->cert_chain = chain;
256 return ERROR_SUCCESS;
259 static SecHandle cred_handle, compat_cred_handle;
260 static BOOL cred_handle_initialized, have_compat_cred_handle;
262 static CRITICAL_SECTION init_sechandle_cs;
263 static CRITICAL_SECTION_DEBUG init_sechandle_cs_debug = {
264 0, 0, &init_sechandle_cs,
265 { &init_sechandle_cs_debug.ProcessLocksList,
266 &init_sechandle_cs_debug.ProcessLocksList },
267 0, 0, { (DWORD_PTR)(__FILE__ ": init_sechandle_cs") }
269 static CRITICAL_SECTION init_sechandle_cs = { &init_sechandle_cs_debug, -1, 0, 0, 0, 0 };
271 static BOOL ensure_cred_handle(void)
273 SECURITY_STATUS res = SEC_E_OK;
275 EnterCriticalSection(&init_sechandle_cs);
277 if(!cred_handle_initialized) {
278 SCHANNEL_CRED cred = {SCHANNEL_CRED_VERSION};
279 SecPkgCred_SupportedProtocols prots;
281 res = AcquireCredentialsHandleW(NULL, (WCHAR*)UNISP_NAME_W, SECPKG_CRED_OUTBOUND, NULL, &cred,
282 NULL, NULL, &cred_handle, NULL);
283 if(res == SEC_E_OK) {
284 res = QueryCredentialsAttributesA(&cred_handle, SECPKG_ATTR_SUPPORTED_PROTOCOLS, &prots);
285 if(res != SEC_E_OK || (prots.grbitProtocol & SP_PROT_TLS1_1PLUS_CLIENT)) {
286 cred.grbitEnabledProtocols = prots.grbitProtocol & ~SP_PROT_TLS1_1PLUS_CLIENT;
287 res = AcquireCredentialsHandleW(NULL, (WCHAR*)UNISP_NAME_W, SECPKG_CRED_OUTBOUND, NULL, &cred,
288 NULL, NULL, &compat_cred_handle, NULL);
289 have_compat_cred_handle = res == SEC_E_OK;
293 cred_handle_initialized = res == SEC_E_OK;
296 LeaveCriticalSection(&init_sechandle_cs);
298 if(res != SEC_E_OK) {
299 WARN("Failed: %08x\n", res);
300 return FALSE;
303 return TRUE;
306 static DWORD create_netconn_socket(server_t *server, netconn_t *netconn, DWORD timeout)
308 int result;
309 ULONG flag;
311 assert(server->addr_len);
312 result = netconn->socket = socket(server->addr.ss_family, SOCK_STREAM, 0);
313 if(result != -1) {
314 flag = 1;
315 ioctlsocket(netconn->socket, FIONBIO, &flag);
316 result = connect(netconn->socket, (struct sockaddr*)&server->addr, server->addr_len);
317 if(result == -1)
319 if (sock_get_error(errno) == WSAEINPROGRESS) {
320 struct pollfd pfd;
321 int res;
323 pfd.fd = netconn->socket;
324 pfd.events = POLLOUT;
325 res = poll(&pfd, 1, timeout);
326 if (!res)
328 closesocket(netconn->socket);
329 netconn->socket = -1;
330 return ERROR_INTERNET_CANNOT_CONNECT;
332 else if (res > 0)
334 int err;
335 socklen_t len = sizeof(err);
336 if (!getsockopt(netconn->socket, SOL_SOCKET, SO_ERROR, (void *)&err, &len) && !err)
337 result = 0;
341 if(result == -1)
343 closesocket(netconn->socket);
344 netconn->socket = -1;
346 else {
347 flag = 0;
348 ioctlsocket(netconn->socket, FIONBIO, &flag);
351 if(result == -1)
352 return ERROR_INTERNET_CANNOT_CONNECT;
354 #ifdef TCP_NODELAY
355 flag = 1;
356 result = setsockopt(netconn->socket, IPPROTO_TCP, TCP_NODELAY, (void*)&flag, sizeof(flag));
357 if(result < 0)
358 WARN("setsockopt(TCP_NODELAY) failed\n");
359 #endif
361 return ERROR_SUCCESS;
364 DWORD create_netconn(BOOL useSSL, server_t *server, DWORD security_flags, BOOL mask_errors, DWORD timeout, netconn_t **ret)
366 netconn_t *netconn;
367 int result;
369 netconn = heap_alloc_zero(sizeof(*netconn));
370 if(!netconn)
371 return ERROR_OUTOFMEMORY;
373 netconn->socket = -1;
374 netconn->security_flags = security_flags | server->security_flags;
375 netconn->mask_errors = mask_errors;
376 list_init(&netconn->pool_entry);
377 SecInvalidateHandle(&netconn->ssl_ctx);
379 result = create_netconn_socket(server, netconn, timeout);
380 if (result != ERROR_SUCCESS) {
381 heap_free(netconn);
382 return result;
385 server_addref(server);
386 netconn->server = server;
387 *ret = netconn;
388 return result;
391 BOOL is_valid_netconn(netconn_t *netconn)
393 return netconn && netconn->socket != -1;
396 void close_netconn(netconn_t *netconn)
398 closesocket(netconn->socket);
399 netconn->socket = -1;
402 void free_netconn(netconn_t *netconn)
404 server_release(netconn->server);
406 if (netconn->secure) {
407 heap_free(netconn->peek_msg_mem);
408 netconn->peek_msg_mem = NULL;
409 netconn->peek_msg = NULL;
410 netconn->peek_len = 0;
411 heap_free(netconn->ssl_buf);
412 netconn->ssl_buf = NULL;
413 heap_free(netconn->extra_buf);
414 netconn->extra_buf = NULL;
415 netconn->extra_len = 0;
416 if (SecIsValidHandle(&netconn->ssl_ctx))
417 DeleteSecurityContext(&netconn->ssl_ctx);
420 heap_free(netconn);
423 void NETCON_unload(void)
425 if(cred_handle_initialized)
426 FreeCredentialsHandle(&cred_handle);
427 if(have_compat_cred_handle)
428 FreeCredentialsHandle(&compat_cred_handle);
429 DeleteCriticalSection(&init_sechandle_cs);
432 /* translate a unix error code into a winsock one */
433 int sock_get_error( int err )
435 #if !defined(__MINGW32__) && !defined (_MSC_VER)
436 switch (err)
438 case EINTR: return WSAEINTR;
439 case EBADF: return WSAEBADF;
440 case EPERM:
441 case EACCES: return WSAEACCES;
442 case EFAULT: return WSAEFAULT;
443 case EINVAL: return WSAEINVAL;
444 case EMFILE: return WSAEMFILE;
445 case EWOULDBLOCK: return WSAEWOULDBLOCK;
446 case EINPROGRESS: return WSAEINPROGRESS;
447 case EALREADY: return WSAEALREADY;
448 case ENOTSOCK: return WSAENOTSOCK;
449 case EDESTADDRREQ: return WSAEDESTADDRREQ;
450 case EMSGSIZE: return WSAEMSGSIZE;
451 case EPROTOTYPE: return WSAEPROTOTYPE;
452 case ENOPROTOOPT: return WSAENOPROTOOPT;
453 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
454 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
455 case EOPNOTSUPP: return WSAEOPNOTSUPP;
456 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
457 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
458 case EADDRINUSE: return WSAEADDRINUSE;
459 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
460 case ENETDOWN: return WSAENETDOWN;
461 case ENETUNREACH: return WSAENETUNREACH;
462 case ENETRESET: return WSAENETRESET;
463 case ECONNABORTED: return WSAECONNABORTED;
464 case EPIPE:
465 case ECONNRESET: return WSAECONNRESET;
466 case ENOBUFS: return WSAENOBUFS;
467 case EISCONN: return WSAEISCONN;
468 case ENOTCONN: return WSAENOTCONN;
469 case ESHUTDOWN: return WSAESHUTDOWN;
470 case ETOOMANYREFS: return WSAETOOMANYREFS;
471 case ETIMEDOUT: return WSAETIMEDOUT;
472 case ECONNREFUSED: return WSAECONNREFUSED;
473 case ELOOP: return WSAELOOP;
474 case ENAMETOOLONG: return WSAENAMETOOLONG;
475 case EHOSTDOWN: return WSAEHOSTDOWN;
476 case EHOSTUNREACH: return WSAEHOSTUNREACH;
477 case ENOTEMPTY: return WSAENOTEMPTY;
478 #ifdef EPROCLIM
479 case EPROCLIM: return WSAEPROCLIM;
480 #endif
481 #ifdef EUSERS
482 case EUSERS: return WSAEUSERS;
483 #endif
484 #ifdef EDQUOT
485 case EDQUOT: return WSAEDQUOT;
486 #endif
487 #ifdef ESTALE
488 case ESTALE: return WSAESTALE;
489 #endif
490 #ifdef EREMOTE
491 case EREMOTE: return WSAEREMOTE;
492 #endif
493 default: errno=err; perror("sock_set_error"); return WSAEFAULT;
495 #endif
496 return err;
499 int sock_send(int fd, const void *msg, size_t len, int flags)
501 int ret;
504 ret = send(fd, msg, len, flags);
506 while(ret == -1 && errno == EINTR);
507 return ret;
510 int sock_recv(int fd, void *msg, size_t len, int flags)
512 int ret;
515 ret = recv(fd, msg, len, flags);
517 while(ret == -1 && errno == EINTR);
518 return ret;
521 static void set_socket_blocking(int socket, blocking_mode_t mode)
523 #if defined(__MINGW32__) || defined (_MSC_VER)
524 ULONG arg = mode == BLOCKING_DISALLOW;
525 ioctlsocket(socket, FIONBIO, &arg);
526 #endif
529 static DWORD netcon_secure_connect_setup(netconn_t *connection, BOOL compat_mode)
531 SecBuffer out_buf = {0, SECBUFFER_TOKEN, NULL}, in_bufs[2] = {{0, SECBUFFER_TOKEN}, {0, SECBUFFER_EMPTY}};
532 SecBufferDesc out_desc = {SECBUFFER_VERSION, 1, &out_buf}, in_desc = {SECBUFFER_VERSION, 2, in_bufs};
533 SecHandle *cred = &cred_handle;
534 BYTE *read_buf;
535 SIZE_T read_buf_size = 2048;
536 ULONG attrs = 0;
537 CtxtHandle ctx;
538 SSIZE_T size;
539 int bits;
540 const CERT_CONTEXT *cert;
541 SECURITY_STATUS status;
542 DWORD res = ERROR_SUCCESS;
544 const DWORD isc_req_flags = ISC_REQ_ALLOCATE_MEMORY|ISC_REQ_USE_SESSION_KEY|ISC_REQ_CONFIDENTIALITY
545 |ISC_REQ_SEQUENCE_DETECT|ISC_REQ_REPLAY_DETECT|ISC_REQ_MANUAL_CRED_VALIDATION;
547 if(!ensure_cred_handle())
548 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
550 if(compat_mode) {
551 if(!have_compat_cred_handle)
552 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
553 cred = &compat_cred_handle;
556 read_buf = heap_alloc(read_buf_size);
557 if(!read_buf)
558 return ERROR_OUTOFMEMORY;
560 status = InitializeSecurityContextW(cred, NULL, connection->server->name, isc_req_flags, 0, 0, NULL, 0,
561 &ctx, &out_desc, &attrs, NULL);
563 assert(status != SEC_E_OK);
565 while(status == SEC_I_CONTINUE_NEEDED || status == SEC_E_INCOMPLETE_MESSAGE) {
566 if(out_buf.cbBuffer) {
567 assert(status == SEC_I_CONTINUE_NEEDED);
569 TRACE("sending %u bytes\n", out_buf.cbBuffer);
571 size = sock_send(connection->socket, out_buf.pvBuffer, out_buf.cbBuffer, 0);
572 if(size != out_buf.cbBuffer) {
573 ERR("send failed\n");
574 status = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
575 break;
578 FreeContextBuffer(out_buf.pvBuffer);
579 out_buf.pvBuffer = NULL;
580 out_buf.cbBuffer = 0;
583 if(status == SEC_I_CONTINUE_NEEDED) {
584 assert(in_bufs[1].cbBuffer < read_buf_size);
586 memmove(read_buf, (BYTE*)in_bufs[0].pvBuffer+in_bufs[0].cbBuffer-in_bufs[1].cbBuffer, in_bufs[1].cbBuffer);
587 in_bufs[0].cbBuffer = in_bufs[1].cbBuffer;
589 in_bufs[1].BufferType = SECBUFFER_EMPTY;
590 in_bufs[1].cbBuffer = 0;
591 in_bufs[1].pvBuffer = NULL;
594 assert(in_bufs[0].BufferType == SECBUFFER_TOKEN);
595 assert(in_bufs[1].BufferType == SECBUFFER_EMPTY);
597 if(in_bufs[0].cbBuffer + 1024 > read_buf_size) {
598 BYTE *new_read_buf;
600 new_read_buf = heap_realloc(read_buf, read_buf_size + 1024);
601 if(!new_read_buf) {
602 status = E_OUTOFMEMORY;
603 break;
606 in_bufs[0].pvBuffer = read_buf = new_read_buf;
607 read_buf_size += 1024;
610 size = sock_recv(connection->socket, read_buf+in_bufs[0].cbBuffer, read_buf_size-in_bufs[0].cbBuffer, 0);
611 if(size < 1) {
612 WARN("recv error\n");
613 res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
614 break;
617 TRACE("recv %lu bytes\n", size);
619 in_bufs[0].cbBuffer += size;
620 in_bufs[0].pvBuffer = read_buf;
621 status = InitializeSecurityContextW(cred, &ctx, connection->server->name, isc_req_flags, 0, 0, &in_desc,
622 0, NULL, &out_desc, &attrs, NULL);
623 TRACE("InitializeSecurityContext ret %08x\n", status);
625 if(status == SEC_E_OK) {
626 if(SecIsValidHandle(&connection->ssl_ctx))
627 DeleteSecurityContext(&connection->ssl_ctx);
628 connection->ssl_ctx = ctx;
630 if(in_bufs[1].BufferType == SECBUFFER_EXTRA)
631 FIXME("SECBUFFER_EXTRA not supported\n");
633 status = QueryContextAttributesW(&ctx, SECPKG_ATTR_STREAM_SIZES, &connection->ssl_sizes);
634 if(status != SEC_E_OK) {
635 WARN("Could not get sizes\n");
636 break;
639 status = QueryContextAttributesW(&ctx, SECPKG_ATTR_REMOTE_CERT_CONTEXT, (void*)&cert);
640 if(status == SEC_E_OK) {
641 res = netconn_verify_cert(connection, cert, cert->hCertStore);
642 CertFreeCertificateContext(cert);
643 if(res != ERROR_SUCCESS) {
644 WARN("cert verify failed: %u\n", res);
645 break;
647 }else {
648 WARN("Could not get cert\n");
649 break;
652 connection->ssl_buf = heap_alloc(connection->ssl_sizes.cbHeader + connection->ssl_sizes.cbMaximumMessage
653 + connection->ssl_sizes.cbTrailer);
654 if(!connection->ssl_buf) {
655 res = GetLastError();
656 break;
661 heap_free(read_buf);
663 if(status != SEC_E_OK || res != ERROR_SUCCESS) {
664 WARN("Failed to establish SSL connection: %08x (%u)\n", status, res);
665 heap_free(connection->ssl_buf);
666 connection->ssl_buf = NULL;
667 return res ? res : ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
670 TRACE("established SSL connection\n");
671 connection->secure = TRUE;
672 connection->security_flags |= SECURITY_FLAG_SECURE;
674 bits = NETCON_GetCipherStrength(connection);
675 if (bits >= 128)
676 connection->security_flags |= SECURITY_FLAG_STRENGTH_STRONG;
677 else if (bits >= 56)
678 connection->security_flags |= SECURITY_FLAG_STRENGTH_MEDIUM;
679 else
680 connection->security_flags |= SECURITY_FLAG_STRENGTH_WEAK;
682 if(connection->mask_errors)
683 connection->server->security_flags = connection->security_flags;
684 return ERROR_SUCCESS;
687 /******************************************************************************
688 * NETCON_secure_connect
689 * Initiates a secure connection over an existing plaintext connection.
691 DWORD NETCON_secure_connect(netconn_t *connection, server_t *server)
693 DWORD res;
695 /* can't connect if we are already connected */
696 if(connection->secure) {
697 ERR("already connected\n");
698 return ERROR_INTERNET_CANNOT_CONNECT;
701 if(server != connection->server) {
702 server_release(connection->server);
703 server_addref(server);
704 connection->server = server;
707 /* connect with given TLS options */
708 res = netcon_secure_connect_setup(connection, FALSE);
709 if (res == ERROR_SUCCESS)
710 return res;
712 /* FIXME: when got version alert and FIN from server */
713 /* fallback to connect without TLSv1.1/TLSv1.2 */
714 if (res == ERROR_INTERNET_SECURITY_CHANNEL_ERROR && have_compat_cred_handle)
716 closesocket(connection->socket);
717 res = create_netconn_socket(connection->server, connection, 500);
718 if (res != ERROR_SUCCESS)
719 return res;
720 res = netcon_secure_connect_setup(connection, TRUE);
722 return res;
725 static BOOL send_ssl_chunk(netconn_t *conn, const void *msg, size_t size)
727 SecBuffer bufs[4] = {
728 {conn->ssl_sizes.cbHeader, SECBUFFER_STREAM_HEADER, conn->ssl_buf},
729 {size, SECBUFFER_DATA, conn->ssl_buf+conn->ssl_sizes.cbHeader},
730 {conn->ssl_sizes.cbTrailer, SECBUFFER_STREAM_TRAILER, conn->ssl_buf+conn->ssl_sizes.cbHeader+size},
731 {0, SECBUFFER_EMPTY, NULL}
733 SecBufferDesc buf_desc = {SECBUFFER_VERSION, sizeof(bufs)/sizeof(*bufs), bufs};
734 SECURITY_STATUS res;
736 memcpy(bufs[1].pvBuffer, msg, size);
737 res = EncryptMessage(&conn->ssl_ctx, 0, &buf_desc, 0);
738 if(res != SEC_E_OK) {
739 WARN("EncryptMessage failed\n");
740 return FALSE;
743 if(sock_send(conn->socket, conn->ssl_buf, bufs[0].cbBuffer+bufs[1].cbBuffer+bufs[2].cbBuffer, 0) < 1) {
744 WARN("send failed\n");
745 return FALSE;
748 return TRUE;
751 /******************************************************************************
752 * NETCON_send
753 * Basically calls 'send()' unless we should use SSL
754 * number of chars send is put in *sent
756 DWORD NETCON_send(netconn_t *connection, const void *msg, size_t len, int flags,
757 int *sent /* out */)
759 if(!connection->secure)
761 *sent = sock_send(connection->socket, msg, len, flags);
762 if (*sent == -1)
763 return sock_get_error(errno);
764 return ERROR_SUCCESS;
766 else
768 const BYTE *ptr = msg;
769 size_t chunk_size;
771 *sent = 0;
773 while(len) {
774 chunk_size = min(len, connection->ssl_sizes.cbMaximumMessage);
775 if(!send_ssl_chunk(connection, ptr, chunk_size))
776 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
778 *sent += chunk_size;
779 ptr += chunk_size;
780 len -= chunk_size;
783 return ERROR_SUCCESS;
787 static BOOL read_ssl_chunk(netconn_t *conn, void *buf, SIZE_T buf_size, blocking_mode_t mode, SIZE_T *ret_size, BOOL *eof)
789 const SIZE_T ssl_buf_size = conn->ssl_sizes.cbHeader+conn->ssl_sizes.cbMaximumMessage+conn->ssl_sizes.cbTrailer;
790 SecBuffer bufs[4];
791 SecBufferDesc buf_desc = {SECBUFFER_VERSION, sizeof(bufs)/sizeof(*bufs), bufs};
792 SSIZE_T size, buf_len = 0;
793 blocking_mode_t tmp_mode;
794 int i;
795 SECURITY_STATUS res;
797 assert(conn->extra_len < ssl_buf_size);
799 /* BLOCKING_WAITALL is handled by caller */
800 if(mode == BLOCKING_WAITALL)
801 mode = BLOCKING_ALLOW;
803 if(conn->extra_len) {
804 memcpy(conn->ssl_buf, conn->extra_buf, conn->extra_len);
805 buf_len = conn->extra_len;
806 conn->extra_len = 0;
807 heap_free(conn->extra_buf);
808 conn->extra_buf = NULL;
811 tmp_mode = buf_len ? BLOCKING_DISALLOW : mode;
812 set_socket_blocking(conn->socket, tmp_mode);
813 size = sock_recv(conn->socket, conn->ssl_buf+buf_len, ssl_buf_size-buf_len, tmp_mode == BLOCKING_ALLOW ? 0 : WINE_MSG_DONTWAIT);
814 if(size < 0) {
815 if(!buf_len) {
816 if(errno == EAGAIN || errno == EWOULDBLOCK) {
817 TRACE("would block\n");
818 return WSAEWOULDBLOCK;
820 WARN("recv failed\n");
821 return ERROR_INTERNET_CONNECTION_ABORTED;
823 }else {
824 buf_len += size;
827 *ret_size = buf_len;
829 if(!buf_len) {
830 *eof = TRUE;
831 return ERROR_SUCCESS;
834 *eof = FALSE;
836 do {
837 memset(bufs, 0, sizeof(bufs));
838 bufs[0].BufferType = SECBUFFER_DATA;
839 bufs[0].cbBuffer = buf_len;
840 bufs[0].pvBuffer = conn->ssl_buf;
842 res = DecryptMessage(&conn->ssl_ctx, &buf_desc, 0, NULL);
843 switch(res) {
844 case SEC_E_OK:
845 break;
846 case SEC_I_CONTEXT_EXPIRED:
847 TRACE("context expired\n");
848 *eof = TRUE;
849 return ERROR_SUCCESS;
850 case SEC_E_INCOMPLETE_MESSAGE:
851 assert(buf_len < ssl_buf_size);
853 set_socket_blocking(conn->socket, mode);
854 size = sock_recv(conn->socket, conn->ssl_buf+buf_len, ssl_buf_size-buf_len, mode == BLOCKING_ALLOW ? 0 : WINE_MSG_DONTWAIT);
855 if(size < 1) {
856 if(size < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
857 TRACE("would block\n");
859 /* FIXME: Optimize extra_buf usage. */
860 conn->extra_buf = heap_alloc(buf_len);
861 if(!conn->extra_buf)
862 return ERROR_NOT_ENOUGH_MEMORY;
864 conn->extra_len = buf_len;
865 memcpy(conn->extra_buf, conn->ssl_buf, conn->extra_len);
866 return WSAEWOULDBLOCK;
869 return ERROR_INTERNET_CONNECTION_ABORTED;
872 buf_len += size;
873 continue;
874 default:
875 WARN("failed: %08x\n", res);
876 return ERROR_INTERNET_CONNECTION_ABORTED;
878 } while(res != SEC_E_OK);
880 for(i=0; i < sizeof(bufs)/sizeof(*bufs); i++) {
881 if(bufs[i].BufferType == SECBUFFER_DATA) {
882 size = min(buf_size, bufs[i].cbBuffer);
883 memcpy(buf, bufs[i].pvBuffer, size);
884 if(size < bufs[i].cbBuffer) {
885 assert(!conn->peek_len);
886 conn->peek_msg_mem = conn->peek_msg = heap_alloc(bufs[i].cbBuffer - size);
887 if(!conn->peek_msg)
888 return ERROR_NOT_ENOUGH_MEMORY;
889 conn->peek_len = bufs[i].cbBuffer-size;
890 memcpy(conn->peek_msg, (char*)bufs[i].pvBuffer+size, conn->peek_len);
893 *ret_size = size;
897 for(i=0; i < sizeof(bufs)/sizeof(*bufs); i++) {
898 if(bufs[i].BufferType == SECBUFFER_EXTRA) {
899 conn->extra_buf = heap_alloc(bufs[i].cbBuffer);
900 if(!conn->extra_buf)
901 return ERROR_NOT_ENOUGH_MEMORY;
903 conn->extra_len = bufs[i].cbBuffer;
904 memcpy(conn->extra_buf, bufs[i].pvBuffer, conn->extra_len);
908 return ERROR_SUCCESS;
911 /******************************************************************************
912 * NETCON_recv
913 * Basically calls 'recv()' unless we should use SSL
914 * number of chars received is put in *recvd
916 DWORD NETCON_recv(netconn_t *connection, void *buf, size_t len, blocking_mode_t mode, int *recvd)
918 *recvd = 0;
919 if (!len)
920 return ERROR_SUCCESS;
922 if (!connection->secure)
924 int flags = 0;
926 switch(mode) {
927 case BLOCKING_ALLOW:
928 break;
929 case BLOCKING_DISALLOW:
930 flags = WINE_MSG_DONTWAIT;
931 break;
932 case BLOCKING_WAITALL:
933 flags = MSG_WAITALL;
934 break;
937 set_socket_blocking(connection->socket, mode);
938 *recvd = sock_recv(connection->socket, buf, len, flags);
939 return *recvd == -1 ? sock_get_error(errno) : ERROR_SUCCESS;
941 else
943 SIZE_T size = 0, cread;
944 BOOL eof;
945 DWORD res;
947 if(connection->peek_msg) {
948 size = min(len, connection->peek_len);
949 memcpy(buf, connection->peek_msg, size);
950 connection->peek_len -= size;
951 connection->peek_msg += size;
953 if(!connection->peek_len) {
954 heap_free(connection->peek_msg_mem);
955 connection->peek_msg_mem = connection->peek_msg = NULL;
957 /* check if we have enough data from the peek buffer */
958 if(mode != BLOCKING_WAITALL || size == len) {
959 *recvd = size;
960 return ERROR_SUCCESS;
963 mode = BLOCKING_DISALLOW;
966 do {
967 res = read_ssl_chunk(connection, (BYTE*)buf+size, len-size, mode, &cread, &eof);
968 if(res != ERROR_SUCCESS) {
969 if(res == WSAEWOULDBLOCK) {
970 if(size)
971 res = ERROR_SUCCESS;
972 }else {
973 WARN("read_ssl_chunk failed\n");
975 break;
978 if(eof) {
979 TRACE("EOF\n");
980 break;
983 size += cread;
984 }while(!size || (mode == BLOCKING_WAITALL && size < len));
986 TRACE("received %ld bytes\n", size);
987 *recvd = size;
988 return res;
992 /******************************************************************************
993 * NETCON_query_data_available
994 * Returns the number of bytes of peeked data plus the number of bytes of
995 * queued, but unread data.
997 BOOL NETCON_query_data_available(netconn_t *connection, DWORD *available)
999 *available = 0;
1001 if(!connection->secure)
1003 #ifdef FIONREAD
1004 ULONG unread;
1005 int retval = ioctlsocket(connection->socket, FIONREAD, &unread);
1006 if (!retval)
1008 TRACE("%d bytes of queued, but unread data\n", unread);
1009 *available += unread;
1011 #endif
1013 else
1015 *available = connection->peek_len;
1017 return TRUE;
1020 BOOL NETCON_is_alive(netconn_t *netconn)
1022 #ifdef MSG_DONTWAIT
1023 ssize_t len;
1024 BYTE b;
1026 len = sock_recv(netconn->socket, &b, 1, MSG_PEEK|MSG_DONTWAIT);
1027 return len == 1 || (len == -1 && errno == EWOULDBLOCK);
1028 #elif defined(__MINGW32__) || defined(_MSC_VER)
1029 ULONG mode;
1030 int len;
1031 char b;
1033 mode = 1;
1034 if(!ioctlsocket(netconn->socket, FIONBIO, &mode))
1035 return FALSE;
1037 len = sock_recv(netconn->socket, &b, 1, MSG_PEEK);
1039 mode = 0;
1040 if(!ioctlsocket(netconn->socket, FIONBIO, &mode))
1041 return FALSE;
1043 return len == 1 || (len == -1 && errno == WSAEWOULDBLOCK);
1044 #else
1045 FIXME("not supported on this platform\n");
1046 return TRUE;
1047 #endif
1050 LPCVOID NETCON_GetCert(netconn_t *connection)
1052 const CERT_CONTEXT *ret;
1053 SECURITY_STATUS res;
1055 res = QueryContextAttributesW(&connection->ssl_ctx, SECPKG_ATTR_REMOTE_CERT_CONTEXT, (void*)&ret);
1056 return res == SEC_E_OK ? ret : NULL;
1059 int NETCON_GetCipherStrength(netconn_t *connection)
1061 SecPkgContext_ConnectionInfo conn_info;
1062 SECURITY_STATUS res;
1064 if (!connection->secure)
1065 return 0;
1067 res = QueryContextAttributesW(&connection->ssl_ctx, SECPKG_ATTR_CONNECTION_INFO, (void*)&conn_info);
1068 if(res != SEC_E_OK)
1069 WARN("QueryContextAttributesW failed: %08x\n", res);
1070 return res == SEC_E_OK ? conn_info.dwCipherStrength : 0;
1073 DWORD NETCON_set_timeout(netconn_t *connection, BOOL send, DWORD value)
1075 int result;
1076 struct timeval tv;
1078 /* value is in milliseconds, convert to struct timeval */
1079 if (value == INFINITE)
1081 tv.tv_sec = 0;
1082 tv.tv_usec = 0;
1084 else
1086 tv.tv_sec = value / 1000;
1087 tv.tv_usec = (value % 1000) * 1000;
1089 result = setsockopt(connection->socket, SOL_SOCKET,
1090 send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv,
1091 sizeof(tv));
1092 if (result == -1)
1094 WARN("setsockopt failed (%s)\n", strerror(errno));
1095 return sock_get_error(errno);
1097 return ERROR_SUCCESS;