2 * Wininet - networking layer. Uses unix sockets.
4 * Copyright 2002 TransGaming Technologies Inc.
5 * Copyright 2013 Jacek Caban for CodeWeavers
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
25 #include "wine/port.h"
27 #define NONAMELESSUNION
29 #if defined(__MINGW32__) || defined (_MSC_VER)
37 #include <sys/types.h>
41 #ifdef HAVE_SYS_POLL_H
42 # include <sys/poll.h>
44 #ifdef HAVE_SYS_TIME_H
45 # include <sys/time.h>
47 #ifdef HAVE_SYS_SOCKET_H
48 # include <sys/socket.h>
50 #ifdef HAVE_SYS_FILIO_H
51 # include <sys/filio.h>
56 #ifdef HAVE_SYS_IOCTL_H
57 # include <sys/ioctl.h>
63 #ifdef HAVE_NETINET_IN_H
64 # include <netinet/in.h>
66 #ifdef HAVE_NETINET_TCP_H
67 # include <netinet/tcp.h>
79 #include "wine/library.h"
85 #include "wine/debug.h"
88 /* To avoid conflicts with the Unix socket headers. we only need it for
89 * the error codes anyway. */
93 #define RESPONSE_TIMEOUT 30 /* FROM internet.c */
96 #define WINE_MSG_DONTWAIT MSG_DONTWAIT
98 #define WINE_MSG_DONTWAIT 0
101 WINE_DEFAULT_DEBUG_CHANNEL(wininet
);
104 * This should use winsock - To use winsock the functions will have to change a bit
105 * as they are designed for unix sockets.
108 static DWORD
netconn_verify_cert(netconn_t
*conn
, PCCERT_CONTEXT cert
, HCERTSTORE store
)
111 CERT_CHAIN_PARA chainPara
= { sizeof(chainPara
), { 0 } };
112 PCCERT_CHAIN_CONTEXT chain
;
113 char oid_server_auth
[] = szOID_PKIX_KP_SERVER_AUTH
;
114 char *server_auth
[] = { oid_server_auth
};
115 DWORD err
= ERROR_SUCCESS
, errors
;
117 static const DWORD supportedErrors
=
118 CERT_TRUST_IS_NOT_TIME_VALID
|
119 CERT_TRUST_IS_UNTRUSTED_ROOT
|
120 CERT_TRUST_IS_PARTIAL_CHAIN
|
121 CERT_TRUST_IS_NOT_SIGNATURE_VALID
|
122 CERT_TRUST_IS_NOT_VALID_FOR_USAGE
;
124 TRACE("verifying %s\n", debugstr_w(conn
->server
->name
));
126 chainPara
.RequestedUsage
.Usage
.cUsageIdentifier
= 1;
127 chainPara
.RequestedUsage
.Usage
.rgpszUsageIdentifier
= server_auth
;
128 if (!(ret
= CertGetCertificateChain(NULL
, cert
, NULL
, store
, &chainPara
, 0, NULL
, &chain
))) {
130 return GetLastError();
133 errors
= chain
->TrustStatus
.dwErrorStatus
;
136 /* This seems strange, but that's what tests show */
137 if(errors
& CERT_TRUST_IS_PARTIAL_CHAIN
) {
138 WARN("ERROR_INTERNET_SEC_CERT_REV_FAILED\n");
139 err
= ERROR_INTERNET_SEC_CERT_REV_FAILED
;
140 if(conn
->mask_errors
)
141 conn
->security_flags
|= _SECURITY_FLAG_CERT_REV_FAILED
;
142 if(!(conn
->security_flags
& SECURITY_FLAG_IGNORE_REVOCATION
))
146 if (chain
->TrustStatus
.dwErrorStatus
& ~supportedErrors
) {
147 WARN("error status %x\n", chain
->TrustStatus
.dwErrorStatus
& ~supportedErrors
);
148 err
= conn
->mask_errors
&& err
? ERROR_INTERNET_SEC_CERT_ERRORS
: ERROR_INTERNET_SEC_INVALID_CERT
;
149 errors
&= supportedErrors
;
150 if(!conn
->mask_errors
)
152 WARN("unknown error flags\n");
155 if(errors
& CERT_TRUST_IS_NOT_TIME_VALID
) {
156 WARN("CERT_TRUST_IS_NOT_TIME_VALID\n");
157 if(!(conn
->security_flags
& SECURITY_FLAG_IGNORE_CERT_DATE_INVALID
)) {
158 err
= conn
->mask_errors
&& err
? ERROR_INTERNET_SEC_CERT_ERRORS
: ERROR_INTERNET_SEC_CERT_DATE_INVALID
;
159 if(!conn
->mask_errors
)
161 conn
->security_flags
|= _SECURITY_FLAG_CERT_INVALID_DATE
;
163 errors
&= ~CERT_TRUST_IS_NOT_TIME_VALID
;
166 if(errors
& CERT_TRUST_IS_UNTRUSTED_ROOT
) {
167 WARN("CERT_TRUST_IS_UNTRUSTED_ROOT\n");
168 if(!(conn
->security_flags
& SECURITY_FLAG_IGNORE_UNKNOWN_CA
)) {
169 err
= conn
->mask_errors
&& err
? ERROR_INTERNET_SEC_CERT_ERRORS
: ERROR_INTERNET_INVALID_CA
;
170 if(!conn
->mask_errors
)
172 conn
->security_flags
|= _SECURITY_FLAG_CERT_INVALID_CA
;
174 errors
&= ~CERT_TRUST_IS_UNTRUSTED_ROOT
;
177 if(errors
& CERT_TRUST_IS_PARTIAL_CHAIN
) {
178 WARN("CERT_TRUST_IS_PARTIAL_CHAIN\n");
179 if(!(conn
->security_flags
& SECURITY_FLAG_IGNORE_UNKNOWN_CA
)) {
180 err
= conn
->mask_errors
&& err
? ERROR_INTERNET_SEC_CERT_ERRORS
: ERROR_INTERNET_INVALID_CA
;
181 if(!conn
->mask_errors
)
183 conn
->security_flags
|= _SECURITY_FLAG_CERT_INVALID_CA
;
185 errors
&= ~CERT_TRUST_IS_PARTIAL_CHAIN
;
188 if(errors
& CERT_TRUST_IS_NOT_SIGNATURE_VALID
) {
189 WARN("CERT_TRUST_IS_NOT_SIGNATURE_VALID\n");
190 if(!(conn
->security_flags
& SECURITY_FLAG_IGNORE_UNKNOWN_CA
)) {
191 err
= conn
->mask_errors
&& err
? ERROR_INTERNET_SEC_CERT_ERRORS
: ERROR_INTERNET_INVALID_CA
;
192 if(!conn
->mask_errors
)
194 conn
->security_flags
|= _SECURITY_FLAG_CERT_INVALID_CA
;
196 errors
&= ~CERT_TRUST_IS_NOT_SIGNATURE_VALID
;
199 if(errors
& CERT_TRUST_IS_NOT_VALID_FOR_USAGE
) {
200 WARN("CERT_TRUST_IS_NOT_VALID_FOR_USAGE\n");
201 if(!(conn
->security_flags
& SECURITY_FLAG_IGNORE_WRONG_USAGE
)) {
202 err
= conn
->mask_errors
&& err
? ERROR_INTERNET_SEC_CERT_ERRORS
: ERROR_INTERNET_SEC_INVALID_CERT
;
203 if(!conn
->mask_errors
)
205 WARN("CERT_TRUST_IS_NOT_VALID_FOR_USAGE, unknown error flags\n");
207 errors
&= ~CERT_TRUST_IS_NOT_VALID_FOR_USAGE
;
210 if(err
== ERROR_INTERNET_SEC_CERT_REV_FAILED
) {
211 assert(conn
->security_flags
& SECURITY_FLAG_IGNORE_REVOCATION
);
216 if(!err
|| conn
->mask_errors
) {
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
= conn
->server
->name
;
231 sslExtraPolicyPara
.fdwChecks
= conn
->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
, &policyStatus
);
237 /* Any error in the policy status indicates that the
238 * policy couldn't be verified.
241 if(policyStatus
.dwError
== CERT_E_CN_NO_MATCH
) {
242 WARN("CERT_E_CN_NO_MATCH\n");
243 if(conn
->mask_errors
)
244 conn
->security_flags
|= _SECURITY_FLAG_CERT_INVALID_CN
;
245 err
= conn
->mask_errors
&& err
? ERROR_INTERNET_SEC_CERT_ERRORS
: ERROR_INTERNET_SEC_CERT_CN_INVALID
;
246 }else if(policyStatus
.dwError
) {
247 WARN("policyStatus.dwError %x\n", policyStatus
.dwError
);
248 if(conn
->mask_errors
)
249 WARN("unknown error flags for policy status %x\n", policyStatus
.dwError
);
250 err
= conn
->mask_errors
&& err
? ERROR_INTERNET_SEC_CERT_ERRORS
: ERROR_INTERNET_SEC_INVALID_CERT
;
253 err
= GetLastError();
258 WARN("failed %u\n", err
);
259 CertFreeCertificateChain(chain
);
260 if(conn
->server
->cert_chain
) {
261 CertFreeCertificateChain(conn
->server
->cert_chain
);
262 conn
->server
->cert_chain
= NULL
;
264 if(conn
->mask_errors
)
265 conn
->server
->security_flags
|= conn
->security_flags
& _SECURITY_ERROR_FLAGS_MASK
;
269 /* FIXME: Reuse cached chain */
270 if(conn
->server
->cert_chain
)
271 CertFreeCertificateChain(chain
);
273 conn
->server
->cert_chain
= chain
;
274 return ERROR_SUCCESS
;
277 static SecHandle cred_handle
, compat_cred_handle
;
278 static BOOL cred_handle_initialized
, have_compat_cred_handle
;
280 static CRITICAL_SECTION init_sechandle_cs
;
281 static CRITICAL_SECTION_DEBUG init_sechandle_cs_debug
= {
282 0, 0, &init_sechandle_cs
,
283 { &init_sechandle_cs_debug
.ProcessLocksList
,
284 &init_sechandle_cs_debug
.ProcessLocksList
},
285 0, 0, { (DWORD_PTR
)(__FILE__
": init_sechandle_cs") }
287 static CRITICAL_SECTION init_sechandle_cs
= { &init_sechandle_cs_debug
, -1, 0, 0, 0, 0 };
289 static BOOL
ensure_cred_handle(void)
291 SECURITY_STATUS res
= SEC_E_OK
;
293 EnterCriticalSection(&init_sechandle_cs
);
295 if(!cred_handle_initialized
) {
296 SCHANNEL_CRED cred
= {SCHANNEL_CRED_VERSION
};
297 SecPkgCred_SupportedProtocols prots
;
299 res
= AcquireCredentialsHandleW(NULL
, (WCHAR
*)UNISP_NAME_W
, SECPKG_CRED_OUTBOUND
, NULL
, &cred
,
300 NULL
, NULL
, &cred_handle
, NULL
);
301 if(res
== SEC_E_OK
) {
302 res
= QueryCredentialsAttributesA(&cred_handle
, SECPKG_ATTR_SUPPORTED_PROTOCOLS
, &prots
);
303 if(res
!= SEC_E_OK
|| (prots
.grbitProtocol
& SP_PROT_TLS1_1PLUS_CLIENT
)) {
304 cred
.grbitEnabledProtocols
= prots
.grbitProtocol
& ~SP_PROT_TLS1_1PLUS_CLIENT
;
305 res
= AcquireCredentialsHandleW(NULL
, (WCHAR
*)UNISP_NAME_W
, SECPKG_CRED_OUTBOUND
, NULL
, &cred
,
306 NULL
, NULL
, &compat_cred_handle
, NULL
);
307 have_compat_cred_handle
= res
== SEC_E_OK
;
311 cred_handle_initialized
= res
== SEC_E_OK
;
314 LeaveCriticalSection(&init_sechandle_cs
);
316 if(res
!= SEC_E_OK
) {
317 WARN("Failed: %08x\n", res
);
325 static BOOL winsock_loaded
= FALSE
;
327 static BOOL WINAPI
winsock_startup(INIT_ONCE
*once
, void *param
, void **context
)
332 res
= WSAStartup(MAKEWORD(1,1), &wsa_data
);
333 if(res
== ERROR_SUCCESS
)
334 winsock_loaded
= TRUE
;
336 ERR("WSAStartup failed: %u\n", res
);
341 void init_winsock(void)
344 static INIT_ONCE init_once
= INIT_ONCE_STATIC_INIT
;
345 InitOnceExecuteOnce(&init_once
, winsock_startup
, NULL
, NULL
);
349 static void set_socket_blocking(int socket
, blocking_mode_t mode
)
352 ULONG arg
= mode
== BLOCKING_DISALLOW
;
353 ioctlsocket(socket
, FIONBIO
, &arg
);
357 static DWORD
create_netconn_socket(server_t
*server
, netconn_t
*netconn
, DWORD timeout
)
365 assert(server
->addr_len
);
366 result
= netconn
->socket
= socket(server
->addr
.ss_family
, SOCK_STREAM
, 0);
368 set_socket_blocking(netconn
->socket
, BLOCKING_DISALLOW
);
369 result
= connect(netconn
->socket
, (struct sockaddr
*)&server
->addr
, server
->addr_len
);
372 res
= sock_get_error();
373 if (res
== WSAEINPROGRESS
|| res
== WSAEWOULDBLOCK
) {
377 pfd
.fd
= netconn
->socket
;
378 pfd
.events
= POLLOUT
;
379 res
= poll(&pfd
, 1, timeout
);
382 closesocket(netconn
->socket
);
383 netconn
->socket
= -1;
384 return ERROR_INTERNET_CANNOT_CONNECT
;
389 socklen_t len
= sizeof(err
);
390 if (!getsockopt(netconn
->socket
, SOL_SOCKET
, SO_ERROR
, (void *)&err
, &len
) && !err
)
397 closesocket(netconn
->socket
);
398 netconn
->socket
= -1;
401 set_socket_blocking(netconn
->socket
, BLOCKING_ALLOW
);
405 return ERROR_INTERNET_CANNOT_CONNECT
;
409 result
= setsockopt(netconn
->socket
, IPPROTO_TCP
, TCP_NODELAY
, (void*)&flag
, sizeof(flag
));
411 WARN("setsockopt(TCP_NODELAY) failed\n");
414 return ERROR_SUCCESS
;
417 DWORD
create_netconn(BOOL useSSL
, server_t
*server
, DWORD security_flags
, BOOL mask_errors
, DWORD timeout
, netconn_t
**ret
)
422 netconn
= heap_alloc_zero(sizeof(*netconn
));
424 return ERROR_OUTOFMEMORY
;
426 netconn
->socket
= -1;
427 netconn
->security_flags
= security_flags
| server
->security_flags
;
428 netconn
->mask_errors
= mask_errors
;
429 list_init(&netconn
->pool_entry
);
430 SecInvalidateHandle(&netconn
->ssl_ctx
);
432 result
= create_netconn_socket(server
, netconn
, timeout
);
433 if (result
!= ERROR_SUCCESS
) {
438 server_addref(server
);
439 netconn
->server
= server
;
444 BOOL
is_valid_netconn(netconn_t
*netconn
)
446 return netconn
&& netconn
->socket
!= -1;
449 void close_netconn(netconn_t
*netconn
)
451 closesocket(netconn
->socket
);
452 netconn
->socket
= -1;
455 void free_netconn(netconn_t
*netconn
)
457 server_release(netconn
->server
);
459 if (netconn
->secure
) {
460 heap_free(netconn
->peek_msg_mem
);
461 netconn
->peek_msg_mem
= NULL
;
462 netconn
->peek_msg
= NULL
;
463 netconn
->peek_len
= 0;
464 heap_free(netconn
->ssl_buf
);
465 netconn
->ssl_buf
= NULL
;
466 heap_free(netconn
->extra_buf
);
467 netconn
->extra_buf
= NULL
;
468 netconn
->extra_len
= 0;
469 if (SecIsValidHandle(&netconn
->ssl_ctx
))
470 DeleteSecurityContext(&netconn
->ssl_ctx
);
476 void NETCON_unload(void)
478 if(cred_handle_initialized
)
479 FreeCredentialsHandle(&cred_handle
);
480 if(have_compat_cred_handle
)
481 FreeCredentialsHandle(&compat_cred_handle
);
482 DeleteCriticalSection(&init_sechandle_cs
);
489 /* translate a unix error code into a winsock one */
490 int sock_get_error(void)
493 return WSAGetLastError();
497 case EINTR
: return WSAEINTR
;
498 case EBADF
: return WSAEBADF
;
500 case EACCES
: return WSAEACCES
;
501 case EFAULT
: return WSAEFAULT
;
502 case EINVAL
: return WSAEINVAL
;
503 case EMFILE
: return WSAEMFILE
;
504 #if EAGAIN != EWOULDBLOCK
507 case EWOULDBLOCK
: return WSAEWOULDBLOCK
;
508 case EINPROGRESS
: return WSAEINPROGRESS
;
509 case EALREADY
: return WSAEALREADY
;
510 case ENOTSOCK
: return WSAENOTSOCK
;
511 case EDESTADDRREQ
: return WSAEDESTADDRREQ
;
512 case EMSGSIZE
: return WSAEMSGSIZE
;
513 case EPROTOTYPE
: return WSAEPROTOTYPE
;
514 case ENOPROTOOPT
: return WSAENOPROTOOPT
;
515 case EPROTONOSUPPORT
: return WSAEPROTONOSUPPORT
;
516 case ESOCKTNOSUPPORT
: return WSAESOCKTNOSUPPORT
;
517 case EOPNOTSUPP
: return WSAEOPNOTSUPP
;
518 case EPFNOSUPPORT
: return WSAEPFNOSUPPORT
;
519 case EAFNOSUPPORT
: return WSAEAFNOSUPPORT
;
520 case EADDRINUSE
: return WSAEADDRINUSE
;
521 case EADDRNOTAVAIL
: return WSAEADDRNOTAVAIL
;
522 case ENETDOWN
: return WSAENETDOWN
;
523 case ENETUNREACH
: return WSAENETUNREACH
;
524 case ENETRESET
: return WSAENETRESET
;
525 case ECONNABORTED
: return WSAECONNABORTED
;
527 case ECONNRESET
: return WSAECONNRESET
;
528 case ENOBUFS
: return WSAENOBUFS
;
529 case EISCONN
: return WSAEISCONN
;
530 case ENOTCONN
: return WSAENOTCONN
;
531 case ESHUTDOWN
: return WSAESHUTDOWN
;
532 case ETOOMANYREFS
: return WSAETOOMANYREFS
;
533 case ETIMEDOUT
: return WSAETIMEDOUT
;
534 case ECONNREFUSED
: return WSAECONNREFUSED
;
535 case ELOOP
: return WSAELOOP
;
536 case ENAMETOOLONG
: return WSAENAMETOOLONG
;
537 case EHOSTDOWN
: return WSAEHOSTDOWN
;
538 case EHOSTUNREACH
: return WSAEHOSTUNREACH
;
539 case ENOTEMPTY
: return WSAENOTEMPTY
;
541 case EPROCLIM
: return WSAEPROCLIM
;
544 case EUSERS
: return WSAEUSERS
;
547 case EDQUOT
: return WSAEDQUOT
;
550 case ESTALE
: return WSAESTALE
;
553 case EREMOTE
: return WSAEREMOTE
;
555 default: perror("sock_get_error"); return WSAEFAULT
;
560 int sock_send(int fd
, const void *msg
, size_t len
, int flags
)
565 ret
= send(fd
, msg
, len
, flags
);
567 while(ret
== -1 && sock_get_error() == WSAEINTR
);
571 int sock_recv(int fd
, void *msg
, size_t len
, int flags
)
576 ret
= recv(fd
, msg
, len
, flags
);
578 while(ret
== -1 && sock_get_error() == WSAEINTR
);
582 static DWORD
netcon_secure_connect_setup(netconn_t
*connection
, BOOL compat_mode
)
584 SecBuffer out_buf
= {0, SECBUFFER_TOKEN
, NULL
}, in_bufs
[2] = {{0, SECBUFFER_TOKEN
}, {0, SECBUFFER_EMPTY
}};
585 SecBufferDesc out_desc
= {SECBUFFER_VERSION
, 1, &out_buf
}, in_desc
= {SECBUFFER_VERSION
, 2, in_bufs
};
586 SecHandle
*cred
= &cred_handle
;
588 SIZE_T read_buf_size
= 2048;
593 const CERT_CONTEXT
*cert
;
594 SECURITY_STATUS status
;
595 DWORD res
= ERROR_SUCCESS
;
597 const DWORD isc_req_flags
= ISC_REQ_ALLOCATE_MEMORY
|ISC_REQ_USE_SESSION_KEY
|ISC_REQ_CONFIDENTIALITY
598 |ISC_REQ_SEQUENCE_DETECT
|ISC_REQ_REPLAY_DETECT
|ISC_REQ_MANUAL_CRED_VALIDATION
;
600 if(!ensure_cred_handle())
601 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR
;
604 if(!have_compat_cred_handle
)
605 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR
;
606 cred
= &compat_cred_handle
;
609 read_buf
= heap_alloc(read_buf_size
);
611 return ERROR_OUTOFMEMORY
;
613 status
= InitializeSecurityContextW(cred
, NULL
, connection
->server
->name
, isc_req_flags
, 0, 0, NULL
, 0,
614 &ctx
, &out_desc
, &attrs
, NULL
);
616 assert(status
!= SEC_E_OK
);
618 while(status
== SEC_I_CONTINUE_NEEDED
|| status
== SEC_E_INCOMPLETE_MESSAGE
) {
619 if(out_buf
.cbBuffer
) {
620 assert(status
== SEC_I_CONTINUE_NEEDED
);
622 TRACE("sending %u bytes\n", out_buf
.cbBuffer
);
624 size
= sock_send(connection
->socket
, out_buf
.pvBuffer
, out_buf
.cbBuffer
, 0);
625 if(size
!= out_buf
.cbBuffer
) {
626 ERR("send failed\n");
627 status
= ERROR_INTERNET_SECURITY_CHANNEL_ERROR
;
631 FreeContextBuffer(out_buf
.pvBuffer
);
632 out_buf
.pvBuffer
= NULL
;
633 out_buf
.cbBuffer
= 0;
636 if(status
== SEC_I_CONTINUE_NEEDED
) {
637 assert(in_bufs
[1].cbBuffer
< read_buf_size
);
639 memmove(read_buf
, (BYTE
*)in_bufs
[0].pvBuffer
+in_bufs
[0].cbBuffer
-in_bufs
[1].cbBuffer
, in_bufs
[1].cbBuffer
);
640 in_bufs
[0].cbBuffer
= in_bufs
[1].cbBuffer
;
642 in_bufs
[1].BufferType
= SECBUFFER_EMPTY
;
643 in_bufs
[1].cbBuffer
= 0;
644 in_bufs
[1].pvBuffer
= NULL
;
647 assert(in_bufs
[0].BufferType
== SECBUFFER_TOKEN
);
648 assert(in_bufs
[1].BufferType
== SECBUFFER_EMPTY
);
650 if(in_bufs
[0].cbBuffer
+ 1024 > read_buf_size
) {
653 new_read_buf
= heap_realloc(read_buf
, read_buf_size
+ 1024);
655 status
= E_OUTOFMEMORY
;
659 in_bufs
[0].pvBuffer
= read_buf
= new_read_buf
;
660 read_buf_size
+= 1024;
663 size
= sock_recv(connection
->socket
, read_buf
+in_bufs
[0].cbBuffer
, read_buf_size
-in_bufs
[0].cbBuffer
, 0);
665 WARN("recv error\n");
666 res
= ERROR_INTERNET_SECURITY_CHANNEL_ERROR
;
670 TRACE("recv %lu bytes\n", size
);
672 in_bufs
[0].cbBuffer
+= size
;
673 in_bufs
[0].pvBuffer
= read_buf
;
674 status
= InitializeSecurityContextW(cred
, &ctx
, connection
->server
->name
, isc_req_flags
, 0, 0, &in_desc
,
675 0, NULL
, &out_desc
, &attrs
, NULL
);
676 TRACE("InitializeSecurityContext ret %08x\n", status
);
678 if(status
== SEC_E_OK
) {
679 if(SecIsValidHandle(&connection
->ssl_ctx
))
680 DeleteSecurityContext(&connection
->ssl_ctx
);
681 connection
->ssl_ctx
= ctx
;
683 if(in_bufs
[1].BufferType
== SECBUFFER_EXTRA
)
684 FIXME("SECBUFFER_EXTRA not supported\n");
686 status
= QueryContextAttributesW(&ctx
, SECPKG_ATTR_STREAM_SIZES
, &connection
->ssl_sizes
);
687 if(status
!= SEC_E_OK
) {
688 WARN("Could not get sizes\n");
692 status
= QueryContextAttributesW(&ctx
, SECPKG_ATTR_REMOTE_CERT_CONTEXT
, (void*)&cert
);
693 if(status
== SEC_E_OK
) {
694 res
= netconn_verify_cert(connection
, cert
, cert
->hCertStore
);
695 CertFreeCertificateContext(cert
);
696 if(res
!= ERROR_SUCCESS
) {
697 WARN("cert verify failed: %u\n", res
);
701 WARN("Could not get cert\n");
705 connection
->ssl_buf
= heap_alloc(connection
->ssl_sizes
.cbHeader
+ connection
->ssl_sizes
.cbMaximumMessage
706 + connection
->ssl_sizes
.cbTrailer
);
707 if(!connection
->ssl_buf
) {
708 res
= GetLastError();
716 if(status
!= SEC_E_OK
|| res
!= ERROR_SUCCESS
) {
717 WARN("Failed to establish SSL connection: %08x (%u)\n", status
, res
);
718 heap_free(connection
->ssl_buf
);
719 connection
->ssl_buf
= NULL
;
720 return res
? res
: ERROR_INTERNET_SECURITY_CHANNEL_ERROR
;
723 TRACE("established SSL connection\n");
724 connection
->secure
= TRUE
;
725 connection
->security_flags
|= SECURITY_FLAG_SECURE
;
727 bits
= NETCON_GetCipherStrength(connection
);
729 connection
->security_flags
|= SECURITY_FLAG_STRENGTH_STRONG
;
731 connection
->security_flags
|= SECURITY_FLAG_STRENGTH_MEDIUM
;
733 connection
->security_flags
|= SECURITY_FLAG_STRENGTH_WEAK
;
735 if(connection
->mask_errors
)
736 connection
->server
->security_flags
= connection
->security_flags
;
737 return ERROR_SUCCESS
;
740 /******************************************************************************
741 * NETCON_secure_connect
742 * Initiates a secure connection over an existing plaintext connection.
744 DWORD
NETCON_secure_connect(netconn_t
*connection
, server_t
*server
)
748 /* can't connect if we are already connected */
749 if(connection
->secure
) {
750 ERR("already connected\n");
751 return ERROR_INTERNET_CANNOT_CONNECT
;
754 if(server
!= connection
->server
) {
755 server_release(connection
->server
);
756 server_addref(server
);
757 connection
->server
= server
;
760 /* connect with given TLS options */
761 res
= netcon_secure_connect_setup(connection
, FALSE
);
762 if (res
== ERROR_SUCCESS
)
765 /* FIXME: when got version alert and FIN from server */
766 /* fallback to connect without TLSv1.1/TLSv1.2 */
767 if (res
== ERROR_INTERNET_SECURITY_CHANNEL_ERROR
&& have_compat_cred_handle
)
769 closesocket(connection
->socket
);
770 res
= create_netconn_socket(connection
->server
, connection
, 500);
771 if (res
!= ERROR_SUCCESS
)
773 res
= netcon_secure_connect_setup(connection
, TRUE
);
778 static BOOL
send_ssl_chunk(netconn_t
*conn
, const void *msg
, size_t size
)
780 SecBuffer bufs
[4] = {
781 {conn
->ssl_sizes
.cbHeader
, SECBUFFER_STREAM_HEADER
, conn
->ssl_buf
},
782 {size
, SECBUFFER_DATA
, conn
->ssl_buf
+conn
->ssl_sizes
.cbHeader
},
783 {conn
->ssl_sizes
.cbTrailer
, SECBUFFER_STREAM_TRAILER
, conn
->ssl_buf
+conn
->ssl_sizes
.cbHeader
+size
},
784 {0, SECBUFFER_EMPTY
, NULL
}
786 SecBufferDesc buf_desc
= {SECBUFFER_VERSION
, sizeof(bufs
)/sizeof(*bufs
), bufs
};
789 memcpy(bufs
[1].pvBuffer
, msg
, size
);
790 res
= EncryptMessage(&conn
->ssl_ctx
, 0, &buf_desc
, 0);
791 if(res
!= SEC_E_OK
) {
792 WARN("EncryptMessage failed\n");
796 if(sock_send(conn
->socket
, conn
->ssl_buf
, bufs
[0].cbBuffer
+bufs
[1].cbBuffer
+bufs
[2].cbBuffer
, 0) < 1) {
797 WARN("send failed\n");
804 /******************************************************************************
806 * Basically calls 'send()' unless we should use SSL
807 * number of chars send is put in *sent
809 DWORD
NETCON_send(netconn_t
*connection
, const void *msg
, size_t len
, int flags
,
812 if(!connection
->secure
)
814 *sent
= sock_send(connection
->socket
, msg
, len
, flags
);
815 return *sent
== -1 ? sock_get_error() : ERROR_SUCCESS
;
819 const BYTE
*ptr
= msg
;
825 chunk_size
= min(len
, connection
->ssl_sizes
.cbMaximumMessage
);
826 if(!send_ssl_chunk(connection
, ptr
, chunk_size
))
827 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR
;
834 return ERROR_SUCCESS
;
838 static BOOL
read_ssl_chunk(netconn_t
*conn
, void *buf
, SIZE_T buf_size
, blocking_mode_t mode
, SIZE_T
*ret_size
, BOOL
*eof
)
840 const SIZE_T ssl_buf_size
= conn
->ssl_sizes
.cbHeader
+conn
->ssl_sizes
.cbMaximumMessage
+conn
->ssl_sizes
.cbTrailer
;
842 SecBufferDesc buf_desc
= {SECBUFFER_VERSION
, sizeof(bufs
)/sizeof(*bufs
), bufs
};
843 SSIZE_T size
, buf_len
= 0;
844 blocking_mode_t tmp_mode
;
848 assert(conn
->extra_len
< ssl_buf_size
);
850 /* BLOCKING_WAITALL is handled by caller */
851 if(mode
== BLOCKING_WAITALL
)
852 mode
= BLOCKING_ALLOW
;
854 if(conn
->extra_len
) {
855 memcpy(conn
->ssl_buf
, conn
->extra_buf
, conn
->extra_len
);
856 buf_len
= conn
->extra_len
;
858 heap_free(conn
->extra_buf
);
859 conn
->extra_buf
= NULL
;
862 tmp_mode
= buf_len
? BLOCKING_DISALLOW
: mode
;
863 set_socket_blocking(conn
->socket
, tmp_mode
);
864 size
= sock_recv(conn
->socket
, conn
->ssl_buf
+buf_len
, ssl_buf_size
-buf_len
, tmp_mode
== BLOCKING_ALLOW
? 0 : WINE_MSG_DONTWAIT
);
867 if(sock_get_error() == WSAEWOULDBLOCK
) {
868 TRACE("would block\n");
869 return WSAEWOULDBLOCK
;
871 WARN("recv failed\n");
872 return ERROR_INTERNET_CONNECTION_ABORTED
;
882 return ERROR_SUCCESS
;
888 memset(bufs
, 0, sizeof(bufs
));
889 bufs
[0].BufferType
= SECBUFFER_DATA
;
890 bufs
[0].cbBuffer
= buf_len
;
891 bufs
[0].pvBuffer
= conn
->ssl_buf
;
893 res
= DecryptMessage(&conn
->ssl_ctx
, &buf_desc
, 0, NULL
);
897 case SEC_I_CONTEXT_EXPIRED
:
898 TRACE("context expired\n");
900 return ERROR_SUCCESS
;
901 case SEC_E_INCOMPLETE_MESSAGE
:
902 assert(buf_len
< ssl_buf_size
);
904 set_socket_blocking(conn
->socket
, mode
);
905 size
= sock_recv(conn
->socket
, conn
->ssl_buf
+buf_len
, ssl_buf_size
-buf_len
, mode
== BLOCKING_ALLOW
? 0 : WINE_MSG_DONTWAIT
);
907 if(size
< 0 && sock_get_error() == WSAEWOULDBLOCK
) {
908 TRACE("would block\n");
910 /* FIXME: Optimize extra_buf usage. */
911 conn
->extra_buf
= heap_alloc(buf_len
);
913 return ERROR_NOT_ENOUGH_MEMORY
;
915 conn
->extra_len
= buf_len
;
916 memcpy(conn
->extra_buf
, conn
->ssl_buf
, conn
->extra_len
);
917 return WSAEWOULDBLOCK
;
920 return ERROR_INTERNET_CONNECTION_ABORTED
;
926 WARN("failed: %08x\n", res
);
927 return ERROR_INTERNET_CONNECTION_ABORTED
;
929 } while(res
!= SEC_E_OK
);
931 for(i
=0; i
< sizeof(bufs
)/sizeof(*bufs
); i
++) {
932 if(bufs
[i
].BufferType
== SECBUFFER_DATA
) {
933 size
= min(buf_size
, bufs
[i
].cbBuffer
);
934 memcpy(buf
, bufs
[i
].pvBuffer
, size
);
935 if(size
< bufs
[i
].cbBuffer
) {
936 assert(!conn
->peek_len
);
937 conn
->peek_msg_mem
= conn
->peek_msg
= heap_alloc(bufs
[i
].cbBuffer
- size
);
939 return ERROR_NOT_ENOUGH_MEMORY
;
940 conn
->peek_len
= bufs
[i
].cbBuffer
-size
;
941 memcpy(conn
->peek_msg
, (char*)bufs
[i
].pvBuffer
+size
, conn
->peek_len
);
948 for(i
=0; i
< sizeof(bufs
)/sizeof(*bufs
); i
++) {
949 if(bufs
[i
].BufferType
== SECBUFFER_EXTRA
) {
950 conn
->extra_buf
= heap_alloc(bufs
[i
].cbBuffer
);
952 return ERROR_NOT_ENOUGH_MEMORY
;
954 conn
->extra_len
= bufs
[i
].cbBuffer
;
955 memcpy(conn
->extra_buf
, bufs
[i
].pvBuffer
, conn
->extra_len
);
959 return ERROR_SUCCESS
;
962 /******************************************************************************
964 * Basically calls 'recv()' unless we should use SSL
965 * number of chars received is put in *recvd
967 DWORD
NETCON_recv(netconn_t
*connection
, void *buf
, size_t len
, blocking_mode_t mode
, int *recvd
)
971 return ERROR_SUCCESS
;
973 if (!connection
->secure
)
980 case BLOCKING_DISALLOW
:
981 flags
= WINE_MSG_DONTWAIT
;
983 case BLOCKING_WAITALL
:
988 set_socket_blocking(connection
->socket
, mode
);
989 *recvd
= sock_recv(connection
->socket
, buf
, len
, flags
);
990 return *recvd
== -1 ? sock_get_error() : ERROR_SUCCESS
;
994 SIZE_T size
= 0, cread
;
998 if(connection
->peek_msg
) {
999 size
= min(len
, connection
->peek_len
);
1000 memcpy(buf
, connection
->peek_msg
, size
);
1001 connection
->peek_len
-= size
;
1002 connection
->peek_msg
+= size
;
1004 if(!connection
->peek_len
) {
1005 heap_free(connection
->peek_msg_mem
);
1006 connection
->peek_msg_mem
= connection
->peek_msg
= NULL
;
1008 /* check if we have enough data from the peek buffer */
1009 if(mode
!= BLOCKING_WAITALL
|| size
== len
) {
1011 return ERROR_SUCCESS
;
1014 mode
= BLOCKING_DISALLOW
;
1018 res
= read_ssl_chunk(connection
, (BYTE
*)buf
+size
, len
-size
, mode
, &cread
, &eof
);
1019 if(res
!= ERROR_SUCCESS
) {
1020 if(res
== WSAEWOULDBLOCK
) {
1022 res
= ERROR_SUCCESS
;
1024 WARN("read_ssl_chunk failed\n");
1035 }while(!size
|| (mode
== BLOCKING_WAITALL
&& size
< len
));
1037 TRACE("received %ld bytes\n", size
);
1043 /******************************************************************************
1044 * NETCON_query_data_available
1045 * Returns the number of bytes of peeked data plus the number of bytes of
1046 * queued, but unread data.
1048 BOOL
NETCON_query_data_available(netconn_t
*connection
, DWORD
*available
)
1052 if(!connection
->secure
)
1056 int retval
= ioctlsocket(connection
->socket
, FIONREAD
, &unread
);
1059 TRACE("%d bytes of queued, but unread data\n", unread
);
1060 *available
+= unread
;
1066 *available
= connection
->peek_len
;
1071 BOOL
NETCON_is_alive(netconn_t
*netconn
)
1077 len
= sock_recv(netconn
->socket
, &b
, 1, MSG_PEEK
|MSG_DONTWAIT
);
1078 return len
== 1 || (len
== -1 && sock_get_error() == WSAEWOULDBLOCK
);
1079 #elif defined(USE_WINSOCK)
1083 set_socket_blocking(netconn
->socket
, BLOCKING_DISALLOW
);
1084 len
= sock_recv(netconn
->socket
, &b
, 1, MSG_PEEK
);
1085 set_socket_blocking(netconn
->socket
, BLOCKING_ALLOW
);
1087 return len
== 1 || (len
== -1 && sock_get_error() == WSAEWOULDBLOCK
);
1089 FIXME("not supported on this platform\n");
1094 LPCVOID
NETCON_GetCert(netconn_t
*connection
)
1096 const CERT_CONTEXT
*ret
;
1097 SECURITY_STATUS res
;
1099 res
= QueryContextAttributesW(&connection
->ssl_ctx
, SECPKG_ATTR_REMOTE_CERT_CONTEXT
, (void*)&ret
);
1100 return res
== SEC_E_OK
? ret
: NULL
;
1103 int NETCON_GetCipherStrength(netconn_t
*connection
)
1105 SecPkgContext_ConnectionInfo conn_info
;
1106 SECURITY_STATUS res
;
1108 if (!connection
->secure
)
1111 res
= QueryContextAttributesW(&connection
->ssl_ctx
, SECPKG_ATTR_CONNECTION_INFO
, (void*)&conn_info
);
1113 WARN("QueryContextAttributesW failed: %08x\n", res
);
1114 return res
== SEC_E_OK
? conn_info
.dwCipherStrength
: 0;
1117 DWORD
NETCON_set_timeout(netconn_t
*connection
, BOOL send
, DWORD value
)
1122 /* value is in milliseconds, convert to struct timeval */
1123 if (value
== INFINITE
)
1130 tv
.tv_sec
= value
/ 1000;
1131 tv
.tv_usec
= (value
% 1000) * 1000;
1133 result
= setsockopt(connection
->socket
, SOL_SOCKET
,
1134 send
? SO_SNDTIMEO
: SO_RCVTIMEO
, (void*)&tv
,
1138 WARN("setsockopt failed\n");
1139 return sock_get_error();
1141 return ERROR_SUCCESS
;