2 * Copyright 2008 Hans Leidekker for CodeWeavers
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 #include "wine/port.h"
26 #include <sys/types.h>
27 #ifdef HAVE_SYS_SOCKET_H
28 # include <sys/socket.h>
30 #ifdef HAVE_SYS_IOCTL_H
31 # include <sys/ioctl.h>
33 #ifdef HAVE_SYS_FILIO_H
34 # include <sys/filio.h>
39 #ifdef HAVE_OPENSSL_SSL_H
40 # include <openssl/ssl.h>
41 # include <openssl/opensslv.h>
46 #define NONAMELESSUNION
48 #include "wine/debug.h"
49 #include "wine/library.h"
56 #include "winhttp_private.h"
58 /* to avoid conflicts with the Unix socket headers */
62 WINE_DEFAULT_DEBUG_CHANNEL(winhttp
);
64 #ifndef HAVE_GETADDRINFO
66 /* critical section to protect non-reentrant gethostbyname() */
67 static CRITICAL_SECTION cs_gethostbyname
;
68 static CRITICAL_SECTION_DEBUG critsect_debug
=
70 0, 0, &cs_gethostbyname
,
71 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
72 0, 0, { (DWORD_PTR
)(__FILE__
": cs_gethostbyname") }
74 static CRITICAL_SECTION cs_gethostbyname
= { &critsect_debug
, -1, 0, 0, 0, 0 };
80 #include <openssl/err.h>
82 static CRITICAL_SECTION init_ssl_cs
;
83 static CRITICAL_SECTION_DEBUG init_ssl_cs_debug
=
86 { &init_ssl_cs_debug
.ProcessLocksList
,
87 &init_ssl_cs_debug
.ProcessLocksList
},
88 0, 0, { (DWORD_PTR
)(__FILE__
": init_ssl_cs") }
90 static CRITICAL_SECTION init_ssl_cs
= { &init_ssl_cs_debug
, -1, 0, 0, 0, 0 };
92 static void *libssl_handle
;
93 static void *libcrypto_handle
;
95 #if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER > 0x10000000)
96 static const SSL_METHOD
*method
;
98 static SSL_METHOD
*method
;
101 static int hostname_idx
;
102 static int error_idx
;
105 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
107 MAKE_FUNCPTR( SSL_library_init
);
108 MAKE_FUNCPTR( SSL_load_error_strings
);
109 MAKE_FUNCPTR( SSLv23_method
);
110 MAKE_FUNCPTR( SSL_CTX_free
);
111 MAKE_FUNCPTR( SSL_CTX_new
);
112 MAKE_FUNCPTR( SSL_new
);
113 MAKE_FUNCPTR( SSL_free
);
114 MAKE_FUNCPTR( SSL_set_fd
);
115 MAKE_FUNCPTR( SSL_connect
);
116 MAKE_FUNCPTR( SSL_shutdown
);
117 MAKE_FUNCPTR( SSL_write
);
118 MAKE_FUNCPTR( SSL_read
);
119 MAKE_FUNCPTR( SSL_get_error
);
120 MAKE_FUNCPTR( SSL_get_ex_new_index
);
121 MAKE_FUNCPTR( SSL_get_ex_data
);
122 MAKE_FUNCPTR( SSL_set_ex_data
);
123 MAKE_FUNCPTR( SSL_get_ex_data_X509_STORE_CTX_idx
);
124 MAKE_FUNCPTR( SSL_get_peer_certificate
);
125 MAKE_FUNCPTR( SSL_CTX_set_default_verify_paths
);
126 MAKE_FUNCPTR( SSL_CTX_set_verify
);
127 MAKE_FUNCPTR( SSL_get_current_cipher
);
128 MAKE_FUNCPTR( SSL_CIPHER_get_bits
);
130 MAKE_FUNCPTR( CRYPTO_num_locks
);
131 MAKE_FUNCPTR( CRYPTO_set_id_callback
);
132 MAKE_FUNCPTR( CRYPTO_set_locking_callback
);
133 MAKE_FUNCPTR( ERR_free_strings
);
134 MAKE_FUNCPTR( ERR_get_error
);
135 MAKE_FUNCPTR( ERR_error_string
);
136 MAKE_FUNCPTR( X509_STORE_CTX_get_ex_data
);
137 MAKE_FUNCPTR( i2d_X509
);
138 MAKE_FUNCPTR( sk_value
);
139 MAKE_FUNCPTR( sk_num
);
142 static CRITICAL_SECTION
*ssl_locks
;
143 static unsigned int num_ssl_locks
;
145 static unsigned long ssl_thread_id(void)
147 return GetCurrentThreadId();
150 static void ssl_lock_callback(int mode
, int type
, const char *file
, int line
)
152 if (mode
& CRYPTO_LOCK
)
153 EnterCriticalSection( &ssl_locks
[type
] );
155 LeaveCriticalSection( &ssl_locks
[type
] );
160 /* translate a unix error code into a winsock error code */
161 static int sock_get_error( int err
)
163 #if !defined(__MINGW32__) && !defined (_MSC_VER)
166 case EINTR
: return WSAEINTR
;
167 case EBADF
: return WSAEBADF
;
169 case EACCES
: return WSAEACCES
;
170 case EFAULT
: return WSAEFAULT
;
171 case EINVAL
: return WSAEINVAL
;
172 case EMFILE
: return WSAEMFILE
;
173 case EWOULDBLOCK
: return WSAEWOULDBLOCK
;
174 case EINPROGRESS
: return WSAEINPROGRESS
;
175 case EALREADY
: return WSAEALREADY
;
176 case ENOTSOCK
: return WSAENOTSOCK
;
177 case EDESTADDRREQ
: return WSAEDESTADDRREQ
;
178 case EMSGSIZE
: return WSAEMSGSIZE
;
179 case EPROTOTYPE
: return WSAEPROTOTYPE
;
180 case ENOPROTOOPT
: return WSAENOPROTOOPT
;
181 case EPROTONOSUPPORT
: return WSAEPROTONOSUPPORT
;
182 case ESOCKTNOSUPPORT
: return WSAESOCKTNOSUPPORT
;
183 case EOPNOTSUPP
: return WSAEOPNOTSUPP
;
184 case EPFNOSUPPORT
: return WSAEPFNOSUPPORT
;
185 case EAFNOSUPPORT
: return WSAEAFNOSUPPORT
;
186 case EADDRINUSE
: return WSAEADDRINUSE
;
187 case EADDRNOTAVAIL
: return WSAEADDRNOTAVAIL
;
188 case ENETDOWN
: return WSAENETDOWN
;
189 case ENETUNREACH
: return WSAENETUNREACH
;
190 case ENETRESET
: return WSAENETRESET
;
191 case ECONNABORTED
: return WSAECONNABORTED
;
193 case ECONNRESET
: return WSAECONNRESET
;
194 case ENOBUFS
: return WSAENOBUFS
;
195 case EISCONN
: return WSAEISCONN
;
196 case ENOTCONN
: return WSAENOTCONN
;
197 case ESHUTDOWN
: return WSAESHUTDOWN
;
198 case ETOOMANYREFS
: return WSAETOOMANYREFS
;
199 case ETIMEDOUT
: return WSAETIMEDOUT
;
200 case ECONNREFUSED
: return WSAECONNREFUSED
;
201 case ELOOP
: return WSAELOOP
;
202 case ENAMETOOLONG
: return WSAENAMETOOLONG
;
203 case EHOSTDOWN
: return WSAEHOSTDOWN
;
204 case EHOSTUNREACH
: return WSAEHOSTUNREACH
;
205 case ENOTEMPTY
: return WSAENOTEMPTY
;
207 case EPROCLIM
: return WSAEPROCLIM
;
210 case EUSERS
: return WSAEUSERS
;
213 case EDQUOT
: return WSAEDQUOT
;
216 case ESTALE
: return WSAESTALE
;
219 case EREMOTE
: return WSAEREMOTE
;
221 default: errno
= err
; perror( "sock_set_error" ); return WSAEFAULT
;
228 static PCCERT_CONTEXT
X509_to_cert_context(X509
*cert
)
230 unsigned char *buffer
, *p
;
236 if ((len
= pi2d_X509( cert
, &p
)) < 0) return NULL
;
238 * SSL 0.9.7 and above malloc the buffer if it is null.
239 * however earlier version do not and so we would need to alloc the buffer.
241 * see the i2d_X509 man page for more details.
245 if (!(buffer
= heap_alloc( len
))) return NULL
;
247 len
= pi2d_X509( cert
, &p
);
255 ret
= CertCreateCertificateContext( X509_ASN_ENCODING
, buffer
, len
);
257 if (malloc
) free( buffer
);
258 else heap_free( buffer
);
263 static DWORD
netconn_verify_cert( PCCERT_CONTEXT cert
, HCERTSTORE store
,
264 WCHAR
*server
, DWORD security_flags
)
267 CERT_CHAIN_PARA chainPara
= { sizeof(chainPara
), { 0 } };
268 PCCERT_CHAIN_CONTEXT chain
;
269 char oid_server_auth
[] = szOID_PKIX_KP_SERVER_AUTH
;
270 char *server_auth
[] = { oid_server_auth
};
271 DWORD err
= ERROR_SUCCESS
;
273 TRACE("verifying %s\n", debugstr_w( server
));
274 chainPara
.RequestedUsage
.Usage
.cUsageIdentifier
= 1;
275 chainPara
.RequestedUsage
.Usage
.rgpszUsageIdentifier
= server_auth
;
276 if ((ret
= CertGetCertificateChain( NULL
, cert
, NULL
, store
, &chainPara
, 0,
279 if (chain
->TrustStatus
.dwErrorStatus
)
281 static const DWORD supportedErrors
=
282 CERT_TRUST_IS_NOT_TIME_VALID
|
283 CERT_TRUST_IS_UNTRUSTED_ROOT
|
284 CERT_TRUST_IS_NOT_VALID_FOR_USAGE
;
286 if (chain
->TrustStatus
.dwErrorStatus
& CERT_TRUST_IS_NOT_TIME_VALID
)
288 if (!(security_flags
& SECURITY_FLAG_IGNORE_CERT_DATE_INVALID
))
289 err
= ERROR_WINHTTP_SECURE_CERT_DATE_INVALID
;
291 else if (chain
->TrustStatus
.dwErrorStatus
&
292 CERT_TRUST_IS_UNTRUSTED_ROOT
)
294 if (!(security_flags
& SECURITY_FLAG_IGNORE_UNKNOWN_CA
))
295 err
= ERROR_WINHTTP_SECURE_INVALID_CA
;
297 else if ((chain
->TrustStatus
.dwErrorStatus
&
298 CERT_TRUST_IS_OFFLINE_REVOCATION
) ||
299 (chain
->TrustStatus
.dwErrorStatus
&
300 CERT_TRUST_REVOCATION_STATUS_UNKNOWN
))
301 err
= ERROR_WINHTTP_SECURE_CERT_REV_FAILED
;
302 else if (chain
->TrustStatus
.dwErrorStatus
& CERT_TRUST_IS_REVOKED
)
303 err
= ERROR_WINHTTP_SECURE_CERT_REVOKED
;
304 else if (chain
->TrustStatus
.dwErrorStatus
&
305 CERT_TRUST_IS_NOT_VALID_FOR_USAGE
)
307 if (!(security_flags
& SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE
))
308 err
= ERROR_WINHTTP_SECURE_CERT_WRONG_USAGE
;
310 else if (chain
->TrustStatus
.dwErrorStatus
& ~supportedErrors
)
311 err
= ERROR_WINHTTP_SECURE_INVALID_CERT
;
315 CERT_CHAIN_POLICY_PARA policyPara
;
316 SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslExtraPolicyPara
;
317 CERT_CHAIN_POLICY_STATUS policyStatus
;
318 CERT_CHAIN_CONTEXT chainCopy
;
320 /* Clear chain->TrustStatus.dwErrorStatus so
321 * CertVerifyCertificateChainPolicy will verify additional checks
322 * rather than stopping with an existing, ignored error.
324 memcpy(&chainCopy
, chain
, sizeof(chainCopy
));
325 chainCopy
.TrustStatus
.dwErrorStatus
= 0;
326 sslExtraPolicyPara
.u
.cbSize
= sizeof(sslExtraPolicyPara
);
327 sslExtraPolicyPara
.dwAuthType
= AUTHTYPE_SERVER
;
328 sslExtraPolicyPara
.pwszServerName
= server
;
329 sslExtraPolicyPara
.fdwChecks
= security_flags
;
330 policyPara
.cbSize
= sizeof(policyPara
);
331 policyPara
.dwFlags
= 0;
332 policyPara
.pvExtraPolicyPara
= &sslExtraPolicyPara
;
333 ret
= CertVerifyCertificateChainPolicy( CERT_CHAIN_POLICY_SSL
,
334 &chainCopy
, &policyPara
,
336 /* Any error in the policy status indicates that the
337 * policy couldn't be verified.
339 if (ret
&& policyStatus
.dwError
)
341 if (policyStatus
.dwError
== CERT_E_CN_NO_MATCH
)
342 err
= ERROR_WINHTTP_SECURE_CERT_CN_INVALID
;
344 err
= ERROR_WINHTTP_SECURE_INVALID_CERT
;
347 CertFreeCertificateChain( chain
);
350 err
= ERROR_WINHTTP_SECURE_CHANNEL_ERROR
;
351 TRACE("returning %08x\n", err
);
355 static int netconn_secure_verify( int preverify_ok
, X509_STORE_CTX
*ctx
)
361 HCERTSTORE store
= CertOpenStore( CERT_STORE_PROV_MEMORY
, 0, 0,
362 CERT_STORE_CREATE_NEW_FLAG
, NULL
);
364 ssl
= pX509_STORE_CTX_get_ex_data( ctx
, pSSL_get_ex_data_X509_STORE_CTX_idx() );
365 server
= pSSL_get_ex_data( ssl
, hostname_idx
);
366 conn
= pSSL_get_ex_data( ssl
, conn_idx
);
371 PCCERT_CONTEXT endCert
= NULL
;
374 for (i
= 0; ret
&& i
< psk_num((struct stack_st
*)ctx
->chain
); i
++)
376 PCCERT_CONTEXT context
;
378 cert
= (X509
*)psk_value((struct stack_st
*)ctx
->chain
, i
);
379 if ((context
= X509_to_cert_context( cert
)))
382 ret
= CertAddCertificateContextToStore( store
, context
,
383 CERT_STORE_ADD_ALWAYS
, &endCert
);
385 ret
= CertAddCertificateContextToStore( store
, context
,
386 CERT_STORE_ADD_ALWAYS
, NULL
);
387 CertFreeCertificateContext( context
);
390 if (!endCert
) ret
= FALSE
;
393 DWORD_PTR err
= netconn_verify_cert( endCert
, store
, server
,
394 conn
->security_flags
);
398 pSSL_set_ex_data( ssl
, error_idx
, (void *)err
);
402 CertFreeCertificateContext( endCert
);
403 CertCloseStore( store
, 0 );
409 BOOL
netconn_init( netconn_t
*conn
, BOOL secure
)
411 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
416 if (!secure
) return TRUE
;
418 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
419 EnterCriticalSection( &init_ssl_cs
);
422 LeaveCriticalSection( &init_ssl_cs
);
425 if (!(libssl_handle
= wine_dlopen( SONAME_LIBSSL
, RTLD_NOW
, NULL
, 0 )))
427 ERR("Trying to use SSL but couldn't load %s. Expect trouble.\n", SONAME_LIBSSL
);
428 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR
);
429 LeaveCriticalSection( &init_ssl_cs
);
432 if (!(libcrypto_handle
= wine_dlopen( SONAME_LIBCRYPTO
, RTLD_NOW
, NULL
, 0 )))
434 ERR("Trying to use SSL but couldn't load %s. Expect trouble.\n", SONAME_LIBCRYPTO
);
435 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR
);
436 LeaveCriticalSection( &init_ssl_cs
);
439 #define LOAD_FUNCPTR(x) \
440 if (!(p##x = wine_dlsym( libssl_handle, #x, NULL, 0 ))) \
442 ERR("Failed to load symbol %s\n", #x); \
443 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR ); \
444 LeaveCriticalSection( &init_ssl_cs ); \
447 LOAD_FUNCPTR( SSL_library_init
);
448 LOAD_FUNCPTR( SSL_load_error_strings
);
449 LOAD_FUNCPTR( SSLv23_method
);
450 LOAD_FUNCPTR( SSL_CTX_free
);
451 LOAD_FUNCPTR( SSL_CTX_new
);
452 LOAD_FUNCPTR( SSL_new
);
453 LOAD_FUNCPTR( SSL_free
);
454 LOAD_FUNCPTR( SSL_set_fd
);
455 LOAD_FUNCPTR( SSL_connect
);
456 LOAD_FUNCPTR( SSL_shutdown
);
457 LOAD_FUNCPTR( SSL_write
);
458 LOAD_FUNCPTR( SSL_read
);
459 LOAD_FUNCPTR( SSL_get_error
);
460 LOAD_FUNCPTR( SSL_get_ex_new_index
);
461 LOAD_FUNCPTR( SSL_get_ex_data
);
462 LOAD_FUNCPTR( SSL_set_ex_data
);
463 LOAD_FUNCPTR( SSL_get_ex_data_X509_STORE_CTX_idx
);
464 LOAD_FUNCPTR( SSL_get_peer_certificate
);
465 LOAD_FUNCPTR( SSL_CTX_set_default_verify_paths
);
466 LOAD_FUNCPTR( SSL_CTX_set_verify
);
467 LOAD_FUNCPTR( SSL_get_current_cipher
);
468 LOAD_FUNCPTR( SSL_CIPHER_get_bits
);
471 #define LOAD_FUNCPTR(x) \
472 if (!(p##x = wine_dlsym( libcrypto_handle, #x, NULL, 0 ))) \
474 ERR("Failed to load symbol %s\n", #x); \
475 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR ); \
476 LeaveCriticalSection( &init_ssl_cs ); \
479 LOAD_FUNCPTR( CRYPTO_num_locks
);
480 LOAD_FUNCPTR( CRYPTO_set_id_callback
);
481 LOAD_FUNCPTR( CRYPTO_set_locking_callback
);
482 LOAD_FUNCPTR( ERR_free_strings
);
483 LOAD_FUNCPTR( ERR_get_error
);
484 LOAD_FUNCPTR( ERR_error_string
);
485 LOAD_FUNCPTR( X509_STORE_CTX_get_ex_data
);
486 LOAD_FUNCPTR( i2d_X509
);
487 LOAD_FUNCPTR( sk_value
);
488 LOAD_FUNCPTR( sk_num
);
492 pSSL_load_error_strings();
494 method
= pSSLv23_method();
495 ctx
= pSSL_CTX_new( method
);
496 if (!pSSL_CTX_set_default_verify_paths( ctx
))
498 ERR("SSL_CTX_set_default_verify_paths failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
499 set_last_error( ERROR_OUTOFMEMORY
);
500 LeaveCriticalSection( &init_ssl_cs
);
503 hostname_idx
= pSSL_get_ex_new_index( 0, (void *)"hostname index", NULL
, NULL
, NULL
);
504 if (hostname_idx
== -1)
506 ERR("SSL_get_ex_new_index failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
507 set_last_error( ERROR_OUTOFMEMORY
);
508 LeaveCriticalSection( &init_ssl_cs
);
511 error_idx
= pSSL_get_ex_new_index( 0, (void *)"error index", NULL
, NULL
, NULL
);
514 ERR("SSL_get_ex_new_index failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
515 set_last_error( ERROR_OUTOFMEMORY
);
516 LeaveCriticalSection( &init_ssl_cs
);
519 conn_idx
= pSSL_get_ex_new_index( 0, (void *)"netconn index", NULL
, NULL
, NULL
);
522 ERR("SSL_get_ex_new_index failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
523 set_last_error( ERROR_OUTOFMEMORY
);
524 LeaveCriticalSection( &init_ssl_cs
);
527 pSSL_CTX_set_verify( ctx
, SSL_VERIFY_PEER
, netconn_secure_verify
);
529 pCRYPTO_set_id_callback(ssl_thread_id
);
530 num_ssl_locks
= pCRYPTO_num_locks();
531 ssl_locks
= HeapAlloc(GetProcessHeap(), 0, num_ssl_locks
* sizeof(CRITICAL_SECTION
));
534 set_last_error( ERROR_OUTOFMEMORY
);
535 LeaveCriticalSection( &init_ssl_cs
);
538 for (i
= 0; i
< num_ssl_locks
; i
++) InitializeCriticalSection( &ssl_locks
[i
] );
539 pCRYPTO_set_locking_callback(ssl_lock_callback
);
541 LeaveCriticalSection( &init_ssl_cs
);
543 WARN("SSL support not compiled in.\n");
544 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR
);
550 void netconn_unload( void )
552 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
553 if (libcrypto_handle
)
556 wine_dlclose( libcrypto_handle
, NULL
, 0 );
561 pSSL_CTX_free( ctx
);
562 wine_dlclose( libssl_handle
, NULL
, 0 );
567 for (i
= 0; i
< num_ssl_locks
; i
++) DeleteCriticalSection( &ssl_locks
[i
] );
568 HeapFree( GetProcessHeap(), 0, ssl_locks
);
573 BOOL
netconn_connected( netconn_t
*conn
)
575 return (conn
->socket
!= -1);
578 BOOL
netconn_create( netconn_t
*conn
, int domain
, int type
, int protocol
)
580 if ((conn
->socket
= socket( domain
, type
, protocol
)) == -1)
582 WARN("unable to create socket (%s)\n", strerror(errno
));
583 set_last_error( sock_get_error( errno
) );
589 BOOL
netconn_close( netconn_t
*conn
)
596 heap_free( conn
->peek_msg_mem
);
597 conn
->peek_msg_mem
= NULL
;
598 conn
->peek_msg
= NULL
;
601 pSSL_shutdown( conn
->ssl_conn
);
602 pSSL_free( conn
->ssl_conn
);
604 conn
->ssl_conn
= NULL
;
605 conn
->secure
= FALSE
;
608 res
= closesocket( conn
->socket
);
612 set_last_error( sock_get_error( errno
) );
618 BOOL
netconn_connect( netconn_t
*conn
, const struct sockaddr
*sockaddr
, unsigned int addr_len
, int timeout
)
626 ioctlsocket( conn
->socket
, FIONBIO
, &state
);
628 if (connect( conn
->socket
, sockaddr
, addr_len
) < 0)
630 res
= sock_get_error( errno
);
631 if (res
== WSAEWOULDBLOCK
|| res
== WSAEINPROGRESS
)
635 pfd
.fd
= conn
->socket
;
636 pfd
.events
= POLLOUT
;
637 if (poll( &pfd
, 1, timeout
) > 0)
640 res
= sock_get_error( errno
);
648 ioctlsocket( conn
->socket
, FIONBIO
, &state
);
652 WARN("unable to connect to host (%d)\n", res
);
653 set_last_error( res
);
658 BOOL
netconn_secure_connect( netconn_t
*conn
, WCHAR
*hostname
)
661 if (!(conn
->ssl_conn
= pSSL_new( ctx
)))
663 ERR("SSL_new failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
664 set_last_error( ERROR_OUTOFMEMORY
);
667 if (!pSSL_set_ex_data( conn
->ssl_conn
, hostname_idx
, hostname
))
669 ERR("SSL_set_ex_data failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
670 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR
);
673 if (!pSSL_set_ex_data( conn
->ssl_conn
, conn_idx
, conn
))
675 ERR("SSL_set_ex_data failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
676 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR
);
679 if (!pSSL_set_fd( conn
->ssl_conn
, conn
->socket
))
681 ERR("SSL_set_fd failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
682 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR
);
685 if (pSSL_connect( conn
->ssl_conn
) <= 0)
689 err
= (DWORD_PTR
)pSSL_get_ex_data( conn
->ssl_conn
, error_idx
);
690 if (!err
) err
= ERROR_WINHTTP_SECURE_CHANNEL_ERROR
;
691 ERR("couldn't verify server certificate (%d)\n", err
);
692 set_last_error( err
);
695 TRACE("established SSL connection\n");
702 pSSL_shutdown( conn
->ssl_conn
);
703 pSSL_free( conn
->ssl_conn
);
704 conn
->ssl_conn
= NULL
;
710 BOOL
netconn_send( netconn_t
*conn
, const void *msg
, size_t len
, int flags
, int *sent
)
712 if (!netconn_connected( conn
)) return FALSE
;
716 if (flags
) FIXME("SSL_write doesn't support any flags (%08x)\n", flags
);
717 *sent
= pSSL_write( conn
->ssl_conn
, msg
, len
);
718 if (*sent
< 1 && len
) return FALSE
;
724 if ((*sent
= send( conn
->socket
, msg
, len
, flags
)) == -1)
726 set_last_error( sock_get_error( errno
) );
732 BOOL
netconn_recv( netconn_t
*conn
, void *buf
, size_t len
, int flags
, int *recvd
)
737 if (!netconn_connected( conn
)) return FALSE
;
738 if (!len
) return TRUE
;
743 if (flags
& ~(MSG_PEEK
| MSG_WAITALL
))
744 FIXME("SSL_read does not support the following flags: %08x\n", flags
);
746 /* this ugly hack is all for MSG_PEEK */
747 if (flags
& MSG_PEEK
&& !conn
->peek_msg
)
749 if (!(conn
->peek_msg
= conn
->peek_msg_mem
= heap_alloc( len
+ 1 ))) return FALSE
;
751 else if (flags
& MSG_PEEK
&& conn
->peek_msg
)
753 if (len
< conn
->peek_len
) FIXME("buffer isn't big enough, should we wrap?\n");
754 *recvd
= min( len
, conn
->peek_len
);
755 memcpy( buf
, conn
->peek_msg
, *recvd
);
758 else if (conn
->peek_msg
)
760 *recvd
= min( len
, conn
->peek_len
);
761 memcpy( buf
, conn
->peek_msg
, *recvd
);
762 conn
->peek_len
-= *recvd
;
763 conn
->peek_msg
+= *recvd
;
765 if (conn
->peek_len
== 0)
767 heap_free( conn
->peek_msg_mem
);
768 conn
->peek_msg_mem
= NULL
;
769 conn
->peek_msg
= NULL
;
771 /* check if we have enough data from the peek buffer */
772 if (!(flags
& MSG_WAITALL
) || (*recvd
== len
)) return TRUE
;
774 ret
= pSSL_read( conn
->ssl_conn
, (char *)buf
+ *recvd
, len
- *recvd
);
778 /* check if EOF was received */
779 if (!ret
&& (pSSL_get_error( conn
->ssl_conn
, ret
) == SSL_ERROR_ZERO_RETURN
||
780 pSSL_get_error( conn
->ssl_conn
, ret
) == SSL_ERROR_SYSCALL
))
782 netconn_close( conn
);
785 if (flags
& MSG_PEEK
) /* must copy into buffer */
787 conn
->peek_len
= ret
;
790 heap_free( conn
->peek_msg_mem
);
791 conn
->peek_msg_mem
= NULL
;
792 conn
->peek_msg
= NULL
;
794 else memcpy( conn
->peek_msg
, buf
, ret
);
802 if ((*recvd
= recv( conn
->socket
, buf
, len
, flags
)) == -1)
804 set_last_error( sock_get_error( errno
) );
810 BOOL
netconn_query_data_available( netconn_t
*conn
, DWORD
*available
)
816 if (!netconn_connected( conn
)) return FALSE
;
821 if (conn
->peek_msg
) *available
= conn
->peek_len
;
826 if (!(ret
= ioctlsocket( conn
->socket
, FIONREAD
, &unread
))) *available
= unread
;
831 BOOL
netconn_get_next_line( netconn_t
*conn
, char *buffer
, DWORD
*buflen
)
837 if (!netconn_connected( conn
)) return FALSE
;
842 while (recvd
< *buflen
)
845 if (!netconn_recv( conn
, &buffer
[recvd
], 1, 0, &dummy
))
847 set_last_error( ERROR_CONNECTION_ABORTED
);
850 if (buffer
[recvd
] == '\n')
855 if (buffer
[recvd
] != '\r') recvd
++;
861 TRACE("received line %s\n", debugstr_a(buffer
));
869 pfd
.fd
= conn
->socket
;
871 while (recvd
< *buflen
)
875 socklen_t len
= sizeof(tv
);
877 if ((res
= getsockopt( conn
->socket
, SOL_SOCKET
, SO_RCVTIMEO
, (void*)&tv
, &len
) != -1))
878 timeout
= tv
.tv_sec
* 1000 + tv
.tv_usec
/ 1000;
881 if (poll( &pfd
, 1, timeout
) > 0)
883 if ((res
= recv( conn
->socket
, &buffer
[recvd
], 1, 0 )) <= 0)
885 if (res
== -1) set_last_error( sock_get_error( errno
) );
888 if (buffer
[recvd
] == '\n')
893 if (buffer
[recvd
] != '\r') recvd
++;
897 set_last_error( ERROR_WINHTTP_TIMEOUT
);
905 TRACE("received line %s\n", debugstr_a(buffer
));
910 DWORD
netconn_set_timeout( netconn_t
*netconn
, BOOL send
, int value
)
915 /* value is in milliseconds, convert to struct timeval */
916 tv
.tv_sec
= value
/ 1000;
917 tv
.tv_usec
= (value
% 1000) * 1000;
919 if ((res
= setsockopt( netconn
->socket
, SOL_SOCKET
, send
? SO_SNDTIMEO
: SO_RCVTIMEO
, (void*)&tv
, sizeof(tv
) ) == -1))
921 WARN("setsockopt failed (%s)\n", strerror( errno
));
922 return sock_get_error( errno
);
924 return ERROR_SUCCESS
;
927 static DWORD
resolve_hostname( WCHAR
*hostnameW
, INTERNET_PORT port
, struct sockaddr
*sa
, socklen_t
*sa_len
)
930 #ifdef HAVE_GETADDRINFO
931 struct addrinfo
*res
, hints
;
935 struct sockaddr_in
*sin
= (struct sockaddr_in
*)sa
;
938 if (!(hostname
= strdupWA( hostnameW
))) return ERROR_OUTOFMEMORY
;
940 #ifdef HAVE_GETADDRINFO
941 memset( &hints
, 0, sizeof(struct addrinfo
) );
942 /* Prefer IPv4 to IPv6 addresses, since some web servers do not listen on
943 * their IPv6 addresses even though they have IPv6 addresses in the DNS.
945 hints
.ai_family
= AF_INET
;
947 ret
= getaddrinfo( hostname
, NULL
, &hints
, &res
);
950 TRACE("failed to get IPv4 address of %s (%s), retrying with IPv6\n", debugstr_w(hostnameW
), gai_strerror(ret
));
951 hints
.ai_family
= AF_INET6
;
952 ret
= getaddrinfo( hostname
, NULL
, &hints
, &res
);
955 TRACE("failed to get address of %s (%s)\n", debugstr_w(hostnameW
), gai_strerror(ret
));
956 heap_free( hostname
);
957 return ERROR_WINHTTP_NAME_NOT_RESOLVED
;
960 heap_free( hostname
);
961 if (*sa_len
< res
->ai_addrlen
)
963 WARN("address too small\n");
965 return ERROR_WINHTTP_NAME_NOT_RESOLVED
;
967 *sa_len
= res
->ai_addrlen
;
968 memcpy( sa
, res
->ai_addr
, res
->ai_addrlen
);
970 switch (res
->ai_family
)
973 ((struct sockaddr_in
*)sa
)->sin_port
= htons( port
);
976 ((struct sockaddr_in6
*)sa
)->sin6_port
= htons( port
);
981 return ERROR_SUCCESS
;
983 EnterCriticalSection( &cs_gethostbyname
);
985 he
= gethostbyname( hostname
);
986 heap_free( hostname
);
989 TRACE("failed to get address of %s (%d)\n", debugstr_w(hostnameW
), h_errno
);
990 LeaveCriticalSection( &cs_gethostbyname
);
991 return ERROR_WINHTTP_NAME_NOT_RESOLVED
;
993 if (*sa_len
< sizeof(struct sockaddr_in
))
995 WARN("address too small\n");
996 LeaveCriticalSection( &cs_gethostbyname
);
997 return ERROR_WINHTTP_NAME_NOT_RESOLVED
;
999 *sa_len
= sizeof(struct sockaddr_in
);
1000 memset( sa
, 0, sizeof(struct sockaddr_in
) );
1001 memcpy( &sin
->sin_addr
, he
->h_addr
, he
->h_length
);
1002 sin
->sin_family
= he
->h_addrtype
;
1003 sin
->sin_port
= htons( port
);
1005 LeaveCriticalSection( &cs_gethostbyname
);
1006 return ERROR_SUCCESS
;
1014 struct sockaddr
*sa
;
1018 static DWORD CALLBACK
resolve_proc( LPVOID arg
)
1020 struct resolve_args
*ra
= arg
;
1021 return resolve_hostname( ra
->hostname
, ra
->port
, ra
->sa
, ra
->sa_len
);
1024 BOOL
netconn_resolve( WCHAR
*hostname
, INTERNET_PORT port
, struct sockaddr
*sa
, socklen_t
*sa_len
, int timeout
)
1032 struct resolve_args ra
;
1034 ra
.hostname
= hostname
;
1039 thread
= CreateThread( NULL
, 0, resolve_proc
, &ra
, 0, NULL
);
1040 if (!thread
) return FALSE
;
1042 status
= WaitForSingleObject( thread
, timeout
);
1043 if (status
== WAIT_OBJECT_0
) GetExitCodeThread( thread
, &ret
);
1044 else ret
= ERROR_WINHTTP_TIMEOUT
;
1045 CloseHandle( thread
);
1047 else ret
= resolve_hostname( hostname
, port
, sa
, sa_len
);
1051 set_last_error( ret
);
1057 const void *netconn_get_certificate( netconn_t
*conn
)
1059 #ifdef SONAME_LIBSSL
1061 const CERT_CONTEXT
*ret
;
1063 if (!conn
->secure
) return NULL
;
1065 if (!(cert
= pSSL_get_peer_certificate( conn
->ssl_conn
))) return NULL
;
1066 ret
= X509_to_cert_context( cert
);
1073 int netconn_get_cipher_strength( netconn_t
*conn
)
1075 #ifdef SONAME_LIBSSL
1076 #if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER >= 0x0090707f)
1077 const SSL_CIPHER
*cipher
;
1083 if (!conn
->secure
) return 0;
1084 if (!(cipher
= pSSL_get_current_cipher( conn
->ssl_conn
))) return 0;
1085 pSSL_CIPHER_get_bits( cipher
, &bits
);