d3d9: Partially implement IDirect3D9Ex::CreateDeviceEx().
[wine] / dlls / winhttp / net.c
1 /*
2  * Copyright 2008 Hans Leidekker for CodeWeavers
3  *
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.
8  *
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.
13  *
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
17  */
18
19 #include "config.h"
20 #include "wine/port.h"
21
22 #include <stdarg.h>
23 #include <stdio.h>
24 #include <errno.h>
25
26 #include <sys/types.h>
27 #ifdef HAVE_SYS_SOCKET_H
28 # include <sys/socket.h>
29 #endif
30 #ifdef HAVE_SYS_IOCTL_H
31 # include <sys/ioctl.h>
32 #endif
33 #ifdef HAVE_SYS_FILIO_H
34 # include <sys/filio.h>
35 #endif
36 #ifdef HAVE_POLL_H
37 # include <poll.h>
38 #endif
39 #ifdef HAVE_OPENSSL_SSL_H
40 # include <openssl/ssl.h>
41 # include <openssl/opensslv.h>
42 #undef FAR
43 #undef DSA
44 #endif
45
46 #define NONAMELESSUNION
47
48 #include "wine/debug.h"
49 #include "wine/library.h"
50
51 #include "windef.h"
52 #include "winbase.h"
53 #include "winhttp.h"
54 #include "wincrypt.h"
55
56 #include "winhttp_private.h"
57
58 /* to avoid conflicts with the Unix socket headers */
59 #define USE_WS_PREFIX
60 #include "winsock2.h"
61
62 WINE_DEFAULT_DEBUG_CHANNEL(winhttp);
63
64 #ifndef HAVE_GETADDRINFO
65
66 /* critical section to protect non-reentrant gethostbyname() */
67 static CRITICAL_SECTION cs_gethostbyname;
68 static CRITICAL_SECTION_DEBUG critsect_debug =
69 {
70     0, 0, &cs_gethostbyname,
71     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
72       0, 0, { (DWORD_PTR)(__FILE__ ": cs_gethostbyname") }
73 };
74 static CRITICAL_SECTION cs_gethostbyname = { &critsect_debug, -1, 0, 0, 0, 0 };
75
76 #endif
77
78 #ifdef SONAME_LIBSSL
79
80 #include <openssl/err.h>
81
82 static CRITICAL_SECTION init_ssl_cs;
83 static CRITICAL_SECTION_DEBUG init_ssl_cs_debug =
84 {
85     0, 0, &init_ssl_cs,
86     { &init_ssl_cs_debug.ProcessLocksList,
87       &init_ssl_cs_debug.ProcessLocksList },
88     0, 0, { (DWORD_PTR)(__FILE__ ": init_ssl_cs") }
89 };
90 static CRITICAL_SECTION init_ssl_cs = { &init_ssl_cs_debug, -1, 0, 0, 0, 0 };
91
92 static void *libssl_handle;
93 static void *libcrypto_handle;
94
95 #if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER > 0x10000000)
96 static const SSL_METHOD *method;
97 #else
98 static SSL_METHOD *method;
99 #endif
100 static SSL_CTX *ctx;
101 static int hostname_idx;
102 static int error_idx;
103 static int conn_idx;
104
105 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
106
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 );
129
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 );
140 #undef MAKE_FUNCPTR
141
142 static CRITICAL_SECTION *ssl_locks;
143 static unsigned int num_ssl_locks;
144
145 static unsigned long ssl_thread_id(void)
146 {
147     return GetCurrentThreadId();
148 }
149
150 static void ssl_lock_callback(int mode, int type, const char *file, int line)
151 {
152     if (mode & CRYPTO_LOCK)
153         EnterCriticalSection( &ssl_locks[type] );
154     else
155         LeaveCriticalSection( &ssl_locks[type] );
156 }
157
158 #endif
159
160 /* translate a unix error code into a winsock error code */
161 static int sock_get_error( int err )
162 {
163 #if !defined(__MINGW32__) && !defined (_MSC_VER)
164     switch (err)
165     {
166         case EINTR:             return WSAEINTR;
167         case EBADF:             return WSAEBADF;
168         case EPERM:
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;
192         case EPIPE:
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;
206 #ifdef EPROCLIM
207         case EPROCLIM:          return WSAEPROCLIM;
208 #endif
209 #ifdef EUSERS
210         case EUSERS:            return WSAEUSERS;
211 #endif
212 #ifdef EDQUOT
213         case EDQUOT:            return WSAEDQUOT;
214 #endif
215 #ifdef ESTALE
216         case ESTALE:            return WSAESTALE;
217 #endif
218 #ifdef EREMOTE
219         case EREMOTE:           return WSAEREMOTE;
220 #endif
221     default: errno = err; perror( "sock_set_error" ); return WSAEFAULT;
222     }
223 #endif
224     return err;
225 }
226
227 #ifdef SONAME_LIBSSL
228 static PCCERT_CONTEXT X509_to_cert_context(X509 *cert)
229 {
230     unsigned char *buffer, *p;
231     int len;
232     BOOL malloc = FALSE;
233     PCCERT_CONTEXT ret;
234
235     p = NULL;
236     if ((len = pi2d_X509( cert, &p )) < 0) return NULL;
237     /*
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.
240      *
241      * see the i2d_X509 man page for more details.
242      */
243     if (!p)
244     {
245         if (!(buffer = heap_alloc( len ))) return NULL;
246         p = buffer;
247         len = pi2d_X509( cert, &p );
248     }
249     else
250     {
251         buffer = p;
252         malloc = TRUE;
253     }
254
255     ret = CertCreateCertificateContext( X509_ASN_ENCODING, buffer, len );
256
257     if (malloc) free( buffer );
258     else heap_free( buffer );
259
260     return ret;
261 }
262
263 static DWORD netconn_verify_cert( PCCERT_CONTEXT cert, HCERTSTORE store,
264                                   WCHAR *server, DWORD security_flags )
265 {
266     BOOL ret;
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;
272
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,
277                                         NULL, &chain )))
278     {
279         if (chain->TrustStatus.dwErrorStatus)
280         {
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;
285
286             if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_NOT_TIME_VALID)
287             {
288                 if (!(security_flags & SECURITY_FLAG_IGNORE_CERT_DATE_INVALID))
289                     err = ERROR_WINHTTP_SECURE_CERT_DATE_INVALID;
290             }
291             else if (chain->TrustStatus.dwErrorStatus &
292                      CERT_TRUST_IS_UNTRUSTED_ROOT)
293             {
294                 if (!(security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA))
295                     err = ERROR_WINHTTP_SECURE_INVALID_CA;
296             }
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)
306             {
307                 if (!(security_flags & SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE))
308                     err = ERROR_WINHTTP_SECURE_CERT_WRONG_USAGE;
309             }
310             else if (chain->TrustStatus.dwErrorStatus & ~supportedErrors)
311                 err = ERROR_WINHTTP_SECURE_INVALID_CERT;
312         }
313         if (!err)
314         {
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;
319
320             /* Clear chain->TrustStatus.dwErrorStatus so
321              * CertVerifyCertificateChainPolicy will verify additional checks
322              * rather than stopping with an existing, ignored error.
323              */
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,
335                                                     &policyStatus );
336             /* Any error in the policy status indicates that the
337              * policy couldn't be verified.
338              */
339             if (ret && policyStatus.dwError)
340             {
341                 if (policyStatus.dwError == CERT_E_CN_NO_MATCH)
342                     err = ERROR_WINHTTP_SECURE_CERT_CN_INVALID;
343                 else
344                     err = ERROR_WINHTTP_SECURE_INVALID_CERT;
345             }
346         }
347         CertFreeCertificateChain( chain );
348     }
349     else
350         err = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
351     TRACE("returning %08x\n", err);
352     return err;
353 }
354
355 static int netconn_secure_verify( int preverify_ok, X509_STORE_CTX *ctx )
356 {
357     SSL *ssl;
358     WCHAR *server;
359     BOOL ret = FALSE;
360     netconn_t *conn;
361     HCERTSTORE store = CertOpenStore( CERT_STORE_PROV_MEMORY, 0, 0,
362      CERT_STORE_CREATE_NEW_FLAG, NULL );
363
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 );
367     if (store)
368     {
369         X509 *cert;
370         int i;
371         PCCERT_CONTEXT endCert = NULL;
372
373         ret = TRUE;
374         for (i = 0; ret && i < psk_num((struct stack_st *)ctx->chain); i++)
375         {
376             PCCERT_CONTEXT context;
377
378             cert = (X509 *)psk_value((struct stack_st *)ctx->chain, i);
379             if ((context = X509_to_cert_context( cert )))
380             {
381                 if (i == 0)
382                     ret = CertAddCertificateContextToStore( store, context,
383                         CERT_STORE_ADD_ALWAYS, &endCert );
384                 else
385                     ret = CertAddCertificateContextToStore( store, context,
386                         CERT_STORE_ADD_ALWAYS, NULL );
387                 CertFreeCertificateContext( context );
388             }
389         }
390         if (!endCert) ret = FALSE;
391         if (ret)
392         {
393             DWORD_PTR err = netconn_verify_cert( endCert, store, server,
394                                                  conn->security_flags );
395
396             if (err)
397             {
398                 pSSL_set_ex_data( ssl, error_idx, (void *)err );
399                 ret = FALSE;
400             }
401         }
402         CertFreeCertificateContext( endCert );
403         CertCloseStore( store, 0 );
404     }
405     return ret;
406 }
407 #endif
408
409 BOOL netconn_init( netconn_t *conn, BOOL secure )
410 {
411 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
412     int i;
413 #endif
414
415     conn->socket = -1;
416     if (!secure) return TRUE;
417
418 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
419     EnterCriticalSection( &init_ssl_cs );
420     if (libssl_handle)
421     {
422         LeaveCriticalSection( &init_ssl_cs );
423         return TRUE;
424     }
425     if (!(libssl_handle = wine_dlopen( SONAME_LIBSSL, RTLD_NOW, NULL, 0 )))
426     {
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 );
430         return FALSE;
431     }
432     if (!(libcrypto_handle = wine_dlopen( SONAME_LIBCRYPTO, RTLD_NOW, NULL, 0 )))
433     {
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 );
437         return FALSE;
438     }
439 #define LOAD_FUNCPTR(x) \
440     if (!(p##x = wine_dlsym( libssl_handle, #x, NULL, 0 ))) \
441     { \
442         ERR("Failed to load symbol %s\n", #x); \
443         set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR ); \
444         LeaveCriticalSection( &init_ssl_cs ); \
445         return FALSE; \
446     }
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 );
469 #undef LOAD_FUNCPTR
470
471 #define LOAD_FUNCPTR(x) \
472     if (!(p##x = wine_dlsym( libcrypto_handle, #x, NULL, 0 ))) \
473     { \
474         ERR("Failed to load symbol %s\n", #x); \
475         set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR ); \
476         LeaveCriticalSection( &init_ssl_cs ); \
477         return FALSE; \
478     }
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 );
489 #undef LOAD_FUNCPTR
490
491     pSSL_library_init();
492     pSSL_load_error_strings();
493
494     method = pSSLv23_method();
495     ctx = pSSL_CTX_new( method );
496     if (!pSSL_CTX_set_default_verify_paths( ctx ))
497     {
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 );
501         return FALSE;
502     }
503     hostname_idx = pSSL_get_ex_new_index( 0, (void *)"hostname index", NULL, NULL, NULL );
504     if (hostname_idx == -1)
505     {
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 );
509         return FALSE;
510     }
511     error_idx = pSSL_get_ex_new_index( 0, (void *)"error index", NULL, NULL, NULL );
512     if (error_idx == -1)
513     {
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 );
517         return FALSE;
518     }
519     conn_idx = pSSL_get_ex_new_index( 0, (void *)"netconn index", NULL, NULL, NULL );
520     if (conn_idx == -1)
521     {
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 );
525         return FALSE;
526     }
527     pSSL_CTX_set_verify( ctx, SSL_VERIFY_PEER, netconn_secure_verify );
528
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));
532     if (!ssl_locks)
533     {
534         set_last_error( ERROR_OUTOFMEMORY );
535         LeaveCriticalSection( &init_ssl_cs );
536         return FALSE;
537     }
538     for (i = 0; i < num_ssl_locks; i++) InitializeCriticalSection( &ssl_locks[i] );
539     pCRYPTO_set_locking_callback(ssl_lock_callback);
540
541     LeaveCriticalSection( &init_ssl_cs );
542 #else
543     WARN("SSL support not compiled in.\n");
544     set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
545     return FALSE;
546 #endif
547     return TRUE;
548 }
549
550 void netconn_unload( void )
551 {
552 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
553     if (libcrypto_handle)
554     {
555         pERR_free_strings();
556         wine_dlclose( libcrypto_handle, NULL, 0 );
557     }
558     if (libssl_handle)
559     {
560         if (ctx)
561             pSSL_CTX_free( ctx );
562         wine_dlclose( libssl_handle, NULL, 0 );
563     }
564     if (ssl_locks)
565     {
566         int i;
567         for (i = 0; i < num_ssl_locks; i++) DeleteCriticalSection( &ssl_locks[i] );
568         HeapFree( GetProcessHeap(), 0, ssl_locks );
569     }
570 #endif
571 }
572
573 BOOL netconn_connected( netconn_t *conn )
574 {
575     return (conn->socket != -1);
576 }
577
578 BOOL netconn_create( netconn_t *conn, int domain, int type, int protocol )
579 {
580     if ((conn->socket = socket( domain, type, protocol )) == -1)
581     {
582         WARN("unable to create socket (%s)\n", strerror(errno));
583         set_last_error( sock_get_error( errno ) );
584         return FALSE;
585     }
586     return TRUE;
587 }
588
589 BOOL netconn_close( netconn_t *conn )
590 {
591     int res;
592
593 #ifdef SONAME_LIBSSL
594     if (conn->secure)
595     {
596         heap_free( conn->peek_msg_mem );
597         conn->peek_msg_mem = NULL;
598         conn->peek_msg = NULL;
599         conn->peek_len = 0;
600
601         pSSL_shutdown( conn->ssl_conn );
602         pSSL_free( conn->ssl_conn );
603
604         conn->ssl_conn = NULL;
605         conn->secure = FALSE;
606     }
607 #endif
608     res = closesocket( conn->socket );
609     conn->socket = -1;
610     if (res == -1)
611     {
612         set_last_error( sock_get_error( errno ) );
613         return FALSE;
614     }
615     return TRUE;
616 }
617
618 BOOL netconn_connect( netconn_t *conn, const struct sockaddr *sockaddr, unsigned int addr_len, int timeout )
619 {
620     BOOL ret = FALSE;
621     int res = 0, state;
622
623     if (timeout > 0)
624     {
625         state = 1;
626         ioctlsocket( conn->socket, FIONBIO, &state );
627     }
628     if (connect( conn->socket, sockaddr, addr_len ) < 0)
629     {
630         res = sock_get_error( errno );
631         if (res == WSAEWOULDBLOCK || res == WSAEINPROGRESS)
632         {
633             struct pollfd pfd;
634
635             pfd.fd = conn->socket;
636             pfd.events = POLLOUT;
637             if (poll( &pfd, 1, timeout ) > 0)
638                 ret = TRUE;
639             else
640                 res = sock_get_error( errno );
641         }
642     }
643     else
644         ret = TRUE;
645     if (timeout > 0)
646     {
647         state = 0;
648         ioctlsocket( conn->socket, FIONBIO, &state );
649     }
650     if (!ret)
651     {
652         WARN("unable to connect to host (%d)\n", res);
653         set_last_error( res );
654     }
655     return ret;
656 }
657
658 BOOL netconn_secure_connect( netconn_t *conn, WCHAR *hostname )
659 {
660 #ifdef SONAME_LIBSSL
661     if (!(conn->ssl_conn = pSSL_new( ctx )))
662     {
663         ERR("SSL_new failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
664         set_last_error( ERROR_OUTOFMEMORY );
665         goto fail;
666     }
667     if (!pSSL_set_ex_data( conn->ssl_conn, hostname_idx, hostname ))
668     {
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 );
671         goto fail;
672     }
673     if (!pSSL_set_ex_data( conn->ssl_conn, conn_idx, conn ))
674     {
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 );
677         return FALSE;
678     }
679     if (!pSSL_set_fd( conn->ssl_conn, conn->socket ))
680     {
681         ERR("SSL_set_fd failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
682         set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
683         goto fail;
684     }
685     if (pSSL_connect( conn->ssl_conn ) <= 0)
686     {
687         DWORD err;
688
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 );
693         goto fail;
694     }
695     TRACE("established SSL connection\n");
696     conn->secure = TRUE;
697     return TRUE;
698
699 fail:
700     if (conn->ssl_conn)
701     {
702         pSSL_shutdown( conn->ssl_conn );
703         pSSL_free( conn->ssl_conn );
704         conn->ssl_conn = NULL;
705     }
706 #endif
707     return FALSE;
708 }
709
710 BOOL netconn_send( netconn_t *conn, const void *msg, size_t len, int flags, int *sent )
711 {
712     if (!netconn_connected( conn )) return FALSE;
713     if (conn->secure)
714     {
715 #ifdef SONAME_LIBSSL
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;
719         return TRUE;
720 #else
721         return FALSE;
722 #endif
723     }
724     if ((*sent = send( conn->socket, msg, len, flags )) == -1)
725     {
726         set_last_error( sock_get_error( errno ) );
727         return FALSE;
728     }
729     return TRUE;
730 }
731
732 BOOL netconn_recv( netconn_t *conn, void *buf, size_t len, int flags, int *recvd )
733 {
734     int ret;
735
736     *recvd = 0;
737     if (!netconn_connected( conn )) return FALSE;
738     if (!len) return TRUE;
739
740     if (conn->secure)
741     {
742 #ifdef SONAME_LIBSSL
743         if (flags & ~(MSG_PEEK | MSG_WAITALL))
744             FIXME("SSL_read does not support the following flags: %08x\n", flags);
745
746         /* this ugly hack is all for MSG_PEEK */
747         if (flags & MSG_PEEK && !conn->peek_msg)
748         {
749             if (!(conn->peek_msg = conn->peek_msg_mem = heap_alloc( len + 1 ))) return FALSE;
750         }
751         else if (flags & MSG_PEEK && conn->peek_msg)
752         {
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 );
756             return TRUE;
757         }
758         else if (conn->peek_msg)
759         {
760             *recvd = min( len, conn->peek_len );
761             memcpy( buf, conn->peek_msg, *recvd );
762             conn->peek_len -= *recvd;
763             conn->peek_msg += *recvd;
764
765             if (conn->peek_len == 0)
766             {
767                 heap_free( conn->peek_msg_mem );
768                 conn->peek_msg_mem = NULL;
769                 conn->peek_msg = NULL;
770             }
771             /* check if we have enough data from the peek buffer */
772             if (!(flags & MSG_WAITALL) || (*recvd == len)) return TRUE;
773         }
774         ret = pSSL_read( conn->ssl_conn, (char *)buf + *recvd, len - *recvd );
775         if (ret < 0)
776             return FALSE;
777
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 ))
781         {
782             netconn_close( conn );
783             return TRUE;
784         }
785         if (flags & MSG_PEEK) /* must copy into buffer */
786         {
787             conn->peek_len = ret;
788             if (!ret)
789             {
790                 heap_free( conn->peek_msg_mem );
791                 conn->peek_msg_mem = NULL;
792                 conn->peek_msg = NULL;
793             }
794             else memcpy( conn->peek_msg, buf, ret );
795         }
796         *recvd = ret;
797         return TRUE;
798 #else
799         return FALSE;
800 #endif
801     }
802     if ((*recvd = recv( conn->socket, buf, len, flags )) == -1)
803     {
804         set_last_error( sock_get_error( errno ) );
805         return FALSE;
806     }
807     return TRUE;
808 }
809
810 BOOL netconn_query_data_available( netconn_t *conn, DWORD *available )
811 {
812 #ifdef FIONREAD
813     int ret, unread;
814 #endif
815     *available = 0;
816     if (!netconn_connected( conn )) return FALSE;
817
818     if (conn->secure)
819     {
820 #ifdef SONAME_LIBSSL
821         if (conn->peek_msg) *available = conn->peek_len;
822 #endif
823         return TRUE;
824     }
825 #ifdef FIONREAD
826     if (!(ret = ioctlsocket( conn->socket, FIONREAD, &unread ))) *available = unread;
827 #endif
828     return TRUE;
829 }
830
831 BOOL netconn_get_next_line( netconn_t *conn, char *buffer, DWORD *buflen )
832 {
833     struct pollfd pfd;
834     BOOL ret = FALSE;
835     DWORD recvd = 0;
836
837     if (!netconn_connected( conn )) return FALSE;
838
839     if (conn->secure)
840     {
841 #ifdef SONAME_LIBSSL
842         while (recvd < *buflen)
843         {
844             int dummy;
845             if (!netconn_recv( conn, &buffer[recvd], 1, 0, &dummy ))
846             {
847                 set_last_error( ERROR_CONNECTION_ABORTED );
848                 break;
849             }
850             if (buffer[recvd] == '\n')
851             {
852                 ret = TRUE;
853                 break;
854             }
855             if (buffer[recvd] != '\r') recvd++;
856         }
857         if (ret)
858         {
859             buffer[recvd++] = 0;
860             *buflen = recvd;
861             TRACE("received line %s\n", debugstr_a(buffer));
862         }
863         return ret;
864 #else
865         return FALSE;
866 #endif
867     }
868
869     pfd.fd = conn->socket;
870     pfd.events = POLLIN;
871     while (recvd < *buflen)
872     {
873         int timeout, res;
874         struct timeval tv;
875         socklen_t len = sizeof(tv);
876
877         if ((res = getsockopt( conn->socket, SOL_SOCKET, SO_RCVTIMEO, (void*)&tv, &len ) != -1))
878             timeout = tv.tv_sec * 1000 + tv.tv_usec / 1000;
879         else
880             timeout = -1;
881         if (poll( &pfd, 1, timeout ) > 0)
882         {
883             if ((res = recv( conn->socket, &buffer[recvd], 1, 0 )) <= 0)
884             {
885                 if (res == -1) set_last_error( sock_get_error( errno ) );
886                 break;
887             }
888             if (buffer[recvd] == '\n')
889             {
890                 ret = TRUE;
891                 break;
892             }
893             if (buffer[recvd] != '\r') recvd++;
894         }
895         else
896         {
897             set_last_error( ERROR_WINHTTP_TIMEOUT );
898             break;
899         }
900     }
901     if (ret)
902     {
903         buffer[recvd++] = 0;
904         *buflen = recvd;
905         TRACE("received line %s\n", debugstr_a(buffer));
906     }
907     return ret;
908 }
909
910 DWORD netconn_set_timeout( netconn_t *netconn, BOOL send, int value )
911 {
912     int res;
913     struct timeval tv;
914
915     /* value is in milliseconds, convert to struct timeval */
916     tv.tv_sec = value / 1000;
917     tv.tv_usec = (value % 1000) * 1000;
918
919     if ((res = setsockopt( netconn->socket, SOL_SOCKET, send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv, sizeof(tv) ) == -1))
920     {
921         WARN("setsockopt failed (%s)\n", strerror( errno ));
922         return sock_get_error( errno );
923     }
924     return ERROR_SUCCESS;
925 }
926
927 static DWORD resolve_hostname( WCHAR *hostnameW, INTERNET_PORT port, struct sockaddr *sa, socklen_t *sa_len )
928 {
929     char *hostname;
930 #ifdef HAVE_GETADDRINFO
931     struct addrinfo *res, hints;
932     int ret;
933 #else
934     struct hostent *he;
935     struct sockaddr_in *sin = (struct sockaddr_in *)sa;
936 #endif
937
938     if (!(hostname = strdupWA( hostnameW ))) return ERROR_OUTOFMEMORY;
939
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.
944      */
945     hints.ai_family = AF_INET;
946
947     ret = getaddrinfo( hostname, NULL, &hints, &res );
948     if (ret != 0)
949     {
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 );
953         if (ret != 0)
954         {
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;
958         }
959     }
960     heap_free( hostname );
961     if (*sa_len < res->ai_addrlen)
962     {
963         WARN("address too small\n");
964         freeaddrinfo( res );
965         return ERROR_WINHTTP_NAME_NOT_RESOLVED;
966     }
967     *sa_len = res->ai_addrlen;
968     memcpy( sa, res->ai_addr, res->ai_addrlen );
969     /* Copy port */
970     switch (res->ai_family)
971     {
972     case AF_INET:
973         ((struct sockaddr_in *)sa)->sin_port = htons( port );
974         break;
975     case AF_INET6:
976         ((struct sockaddr_in6 *)sa)->sin6_port = htons( port );
977         break;
978     }
979
980     freeaddrinfo( res );
981     return ERROR_SUCCESS;
982 #else
983     EnterCriticalSection( &cs_gethostbyname );
984
985     he = gethostbyname( hostname );
986     heap_free( hostname );
987     if (!he)
988     {
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;
992     }
993     if (*sa_len < sizeof(struct sockaddr_in))
994     {
995         WARN("address too small\n");
996         LeaveCriticalSection( &cs_gethostbyname );
997         return ERROR_WINHTTP_NAME_NOT_RESOLVED;
998     }
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 );
1004
1005     LeaveCriticalSection( &cs_gethostbyname );
1006     return ERROR_SUCCESS;
1007 #endif
1008 }
1009
1010 struct resolve_args
1011 {
1012     WCHAR           *hostname;
1013     INTERNET_PORT    port;
1014     struct sockaddr *sa;
1015     socklen_t       *sa_len;
1016 };
1017
1018 static DWORD CALLBACK resolve_proc( LPVOID arg )
1019 {
1020     struct resolve_args *ra = arg;
1021     return resolve_hostname( ra->hostname, ra->port, ra->sa, ra->sa_len );
1022 }
1023
1024 BOOL netconn_resolve( WCHAR *hostname, INTERNET_PORT port, struct sockaddr *sa, socklen_t *sa_len, int timeout )
1025 {
1026     DWORD ret;
1027
1028     if (timeout)
1029     {
1030         DWORD status;
1031         HANDLE thread;
1032         struct resolve_args ra;
1033
1034         ra.hostname = hostname;
1035         ra.port     = port;
1036         ra.sa       = sa;
1037         ra.sa_len   = sa_len;
1038
1039         thread = CreateThread( NULL, 0, resolve_proc, &ra, 0, NULL );
1040         if (!thread) return FALSE;
1041
1042         status = WaitForSingleObject( thread, timeout );
1043         if (status == WAIT_OBJECT_0) GetExitCodeThread( thread, &ret );
1044         else ret = ERROR_WINHTTP_TIMEOUT;
1045         CloseHandle( thread );
1046     }
1047     else ret = resolve_hostname( hostname, port, sa, sa_len );
1048
1049     if (ret)
1050     {
1051         set_last_error( ret );
1052         return FALSE;
1053     }
1054     return TRUE;
1055 }
1056
1057 const void *netconn_get_certificate( netconn_t *conn )
1058 {
1059 #ifdef SONAME_LIBSSL
1060     X509 *cert;
1061     const CERT_CONTEXT *ret;
1062
1063     if (!conn->secure) return NULL;
1064
1065     if (!(cert = pSSL_get_peer_certificate( conn->ssl_conn ))) return NULL;
1066     ret = X509_to_cert_context( cert );
1067     return ret;
1068 #else
1069     return NULL;
1070 #endif
1071 }
1072
1073 int netconn_get_cipher_strength( netconn_t *conn )
1074 {
1075 #ifdef SONAME_LIBSSL
1076 #if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER >= 0x0090707f)
1077     const SSL_CIPHER *cipher;
1078 #else
1079     SSL_CIPHER *cipher;
1080 #endif
1081     int bits = 0;
1082
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 );
1086     return bits;
1087 #else
1088     return 0;
1089 #endif
1090 }