ddraw/tests: Add basic tests for DrawIndexedPrimitiveStrided.
[wine] / dlls / wininet / netconnection.c
1 /*
2  * Wininet - networking layer. Uses unix sockets or OpenSSL.
3  *
4  * Copyright 2002 TransGaming Technologies Inc.
5  *
6  * David Hammerton
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22
23 #include "config.h"
24 #include "wine/port.h"
25
26 #define NONAMELESSUNION
27
28 #if defined(__MINGW32__) || defined (_MSC_VER)
29 #include <ws2tcpip.h>
30 #endif
31
32 #include <sys/types.h>
33 #ifdef HAVE_POLL_H
34 #include <poll.h>
35 #endif
36 #ifdef HAVE_SYS_POLL_H
37 # include <sys/poll.h>
38 #endif
39 #ifdef HAVE_SYS_TIME_H
40 # include <sys/time.h>
41 #endif
42 #ifdef HAVE_SYS_SOCKET_H
43 # include <sys/socket.h>
44 #endif
45 #ifdef HAVE_SYS_FILIO_H
46 # include <sys/filio.h>
47 #endif
48 #ifdef HAVE_UNISTD_H
49 # include <unistd.h>
50 #endif
51 #ifdef HAVE_SYS_IOCTL_H
52 # include <sys/ioctl.h>
53 #endif
54 #include <time.h>
55 #ifdef HAVE_NETDB_H
56 # include <netdb.h>
57 #endif
58 #ifdef HAVE_NETINET_IN_H
59 # include <netinet/in.h>
60 #endif
61 #ifdef HAVE_NETINET_TCP_H
62 # include <netinet/tcp.h>
63 #endif
64 #ifdef HAVE_OPENSSL_SSL_H
65 # include <openssl/ssl.h>
66 # include <openssl/opensslv.h>
67 #undef FAR
68 #undef DSA
69 #endif
70
71 #include <stdarg.h>
72 #include <stdlib.h>
73 #include <string.h>
74 #include <stdio.h>
75 #include <errno.h>
76 #include <assert.h>
77
78 #include "wine/library.h"
79 #include "windef.h"
80 #include "winbase.h"
81 #include "wininet.h"
82 #include "winerror.h"
83
84 #include "wine/debug.h"
85 #include "internet.h"
86
87 /* To avoid conflicts with the Unix socket headers. we only need it for
88  * the error codes anyway. */
89 #define USE_WS_PREFIX
90 #include "winsock2.h"
91
92 #define RESPONSE_TIMEOUT        30            /* FROM internet.c */
93
94
95 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
96
97 /* FIXME!!!!!!
98  *    This should use winsock - To use winsock the functions will have to change a bit
99  *        as they are designed for unix sockets.
100  *    SSL stuff should use crypt32.dll
101  */
102
103 #ifdef SONAME_LIBSSL
104
105 #include <openssl/err.h>
106
107 static void *OpenSSL_ssl_handle;
108 static void *OpenSSL_crypto_handle;
109
110 #if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER > 0x10000000)
111 static const SSL_METHOD *meth;
112 #else
113 static SSL_METHOD *meth;
114 #endif
115 static SSL_CTX *ctx;
116 static int error_idx;
117 static int conn_idx;
118
119 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
120
121 /* OpenSSL functions that we use */
122 MAKE_FUNCPTR(SSL_library_init);
123 MAKE_FUNCPTR(SSL_load_error_strings);
124 MAKE_FUNCPTR(SSLv23_method);
125 MAKE_FUNCPTR(SSL_CTX_free);
126 MAKE_FUNCPTR(SSL_CTX_new);
127 MAKE_FUNCPTR(SSL_CTX_ctrl);
128 MAKE_FUNCPTR(SSL_new);
129 MAKE_FUNCPTR(SSL_free);
130 MAKE_FUNCPTR(SSL_ctrl);
131 MAKE_FUNCPTR(SSL_set_fd);
132 MAKE_FUNCPTR(SSL_connect);
133 MAKE_FUNCPTR(SSL_shutdown);
134 MAKE_FUNCPTR(SSL_write);
135 MAKE_FUNCPTR(SSL_read);
136 MAKE_FUNCPTR(SSL_pending);
137 MAKE_FUNCPTR(SSL_get_error);
138 MAKE_FUNCPTR(SSL_get_ex_new_index);
139 MAKE_FUNCPTR(SSL_get_ex_data);
140 MAKE_FUNCPTR(SSL_set_ex_data);
141 MAKE_FUNCPTR(SSL_get_ex_data_X509_STORE_CTX_idx);
142 MAKE_FUNCPTR(SSL_get_peer_certificate);
143 MAKE_FUNCPTR(SSL_CTX_get_timeout);
144 MAKE_FUNCPTR(SSL_CTX_set_timeout);
145 MAKE_FUNCPTR(SSL_CTX_set_default_verify_paths);
146 MAKE_FUNCPTR(SSL_CTX_set_verify);
147 MAKE_FUNCPTR(SSL_get_current_cipher);
148 MAKE_FUNCPTR(SSL_CIPHER_get_bits);
149
150 /* OpenSSL's libcrypto functions that we use */
151 MAKE_FUNCPTR(BIO_new_fp);
152 MAKE_FUNCPTR(CRYPTO_num_locks);
153 MAKE_FUNCPTR(CRYPTO_set_id_callback);
154 MAKE_FUNCPTR(CRYPTO_set_locking_callback);
155 MAKE_FUNCPTR(ERR_free_strings);
156 MAKE_FUNCPTR(ERR_get_error);
157 MAKE_FUNCPTR(ERR_error_string);
158 MAKE_FUNCPTR(X509_STORE_CTX_get_ex_data);
159 MAKE_FUNCPTR(X509_STORE_CTX_get_chain);
160 MAKE_FUNCPTR(i2d_X509);
161 MAKE_FUNCPTR(sk_num);
162 MAKE_FUNCPTR(sk_value);
163 #undef MAKE_FUNCPTR
164
165 static CRITICAL_SECTION *ssl_locks;
166 static unsigned int num_ssl_locks;
167
168 static unsigned long ssl_thread_id(void)
169 {
170     return GetCurrentThreadId();
171 }
172
173 static void ssl_lock_callback(int mode, int type, const char *file, int line)
174 {
175     if (mode & CRYPTO_LOCK)
176         EnterCriticalSection(&ssl_locks[type]);
177     else
178         LeaveCriticalSection(&ssl_locks[type]);
179 }
180
181 static PCCERT_CONTEXT X509_to_cert_context(X509 *cert)
182 {
183     unsigned char* buffer,*p;
184     INT len;
185     BOOL malloced = FALSE;
186     PCCERT_CONTEXT ret;
187
188     p = NULL;
189     len = pi2d_X509(cert,&p);
190     /*
191      * SSL 0.9.7 and above malloc the buffer if it is null.
192      * however earlier version do not and so we would need to alloc the buffer.
193      *
194      * see the i2d_X509 man page for more details.
195      */
196     if (!p)
197     {
198         buffer = heap_alloc(len);
199         p = buffer;
200         len = pi2d_X509(cert,&p);
201     }
202     else
203     {
204         buffer = p;
205         malloced = TRUE;
206     }
207
208     ret = CertCreateCertificateContext(X509_ASN_ENCODING,buffer,len);
209
210     if (malloced)
211         free(buffer);
212     else
213         heap_free(buffer);
214
215     return ret;
216 }
217
218 static DWORD netconn_verify_cert(netconn_t *conn, PCCERT_CONTEXT cert, HCERTSTORE store)
219 {
220     BOOL ret;
221     CERT_CHAIN_PARA chainPara = { sizeof(chainPara), { 0 } };
222     PCCERT_CHAIN_CONTEXT chain;
223     char oid_server_auth[] = szOID_PKIX_KP_SERVER_AUTH;
224     char *server_auth[] = { oid_server_auth };
225     DWORD err = ERROR_SUCCESS, errors;
226
227     static const DWORD supportedErrors =
228         CERT_TRUST_IS_NOT_TIME_VALID |
229         CERT_TRUST_IS_UNTRUSTED_ROOT |
230         CERT_TRUST_IS_PARTIAL_CHAIN |
231         CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
232
233     TRACE("verifying %s\n", debugstr_w(conn->server->name));
234
235     chainPara.RequestedUsage.Usage.cUsageIdentifier = 1;
236     chainPara.RequestedUsage.Usage.rgpszUsageIdentifier = server_auth;
237     if (!(ret = CertGetCertificateChain(NULL, cert, NULL, store, &chainPara, 0, NULL, &chain))) {
238         TRACE("failed\n");
239         return GetLastError();
240     }
241
242     errors = chain->TrustStatus.dwErrorStatus;
243
244     do {
245         /* This seems strange, but that's what tests show */
246         if(errors & CERT_TRUST_IS_PARTIAL_CHAIN) {
247             WARN("ERROR_INTERNET_SEC_CERT_REV_FAILED\n");
248             err = ERROR_INTERNET_SEC_CERT_REV_FAILED;
249             if(conn->mask_errors)
250                 conn->security_flags |= _SECURITY_FLAG_CERT_REV_FAILED;
251             if(!(conn->security_flags & SECURITY_FLAG_IGNORE_REVOCATION))
252                 break;
253         }
254
255         if (chain->TrustStatus.dwErrorStatus & ~supportedErrors) {
256             WARN("error status %x\n", chain->TrustStatus.dwErrorStatus & ~supportedErrors);
257             err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_INVALID_CERT;
258             errors &= supportedErrors;
259             if(!conn->mask_errors)
260                 break;
261             WARN("unknown error flags\n");
262         }
263
264         if(errors & CERT_TRUST_IS_NOT_TIME_VALID) {
265             WARN("CERT_TRUST_IS_NOT_TIME_VALID\n");
266             if(!(conn->security_flags & SECURITY_FLAG_IGNORE_CERT_DATE_INVALID)) {
267                 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_CERT_DATE_INVALID;
268                 if(!conn->mask_errors)
269                     break;
270                 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_DATE;
271             }
272             errors &= ~CERT_TRUST_IS_NOT_TIME_VALID;
273         }
274
275         if(errors & CERT_TRUST_IS_UNTRUSTED_ROOT) {
276             WARN("CERT_TRUST_IS_UNTRUSTED_ROOT\n");
277             if(!(conn->security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA)) {
278                 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_INVALID_CA;
279                 if(!conn->mask_errors)
280                     break;
281                 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CA;
282             }
283             errors &= ~CERT_TRUST_IS_UNTRUSTED_ROOT;
284         }
285
286         if(errors & CERT_TRUST_IS_PARTIAL_CHAIN) {
287             WARN("CERT_TRUST_IS_PARTIAL_CHAIN\n");
288             if(!(conn->security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA)) {
289                 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_INVALID_CA;
290                 if(!conn->mask_errors)
291                     break;
292                 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CA;
293             }
294             errors &= ~CERT_TRUST_IS_PARTIAL_CHAIN;
295         }
296
297         if(errors & CERT_TRUST_IS_NOT_VALID_FOR_USAGE) {
298             WARN("CERT_TRUST_IS_NOT_VALID_FOR_USAGE\n");
299             if(!(conn->security_flags & SECURITY_FLAG_IGNORE_WRONG_USAGE)) {
300                 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_INVALID_CERT;
301                 if(!conn->mask_errors)
302                     break;
303                 WARN("CERT_TRUST_IS_NOT_VALID_FOR_USAGE, unknown error flags\n");
304             }
305             errors &= ~CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
306         }
307
308         if(err == ERROR_INTERNET_SEC_CERT_REV_FAILED) {
309             assert(conn->security_flags & SECURITY_FLAG_IGNORE_REVOCATION);
310             err = ERROR_SUCCESS;
311         }
312     }while(0);
313
314     if(!err || conn->mask_errors) {
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 = conn->server->name;
329         sslExtraPolicyPara.fdwChecks = conn->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, &policyStatus);
335         /* Any error in the policy status indicates that the
336          * policy couldn't be verified.
337          */
338         if(ret) {
339             if(policyStatus.dwError == CERT_E_CN_NO_MATCH) {
340                 WARN("CERT_E_CN_NO_MATCH\n");
341                 if(conn->mask_errors)
342                     conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CN;
343                 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_CERT_CN_INVALID;
344             }else if(policyStatus.dwError) {
345                 WARN("policyStatus.dwError %x\n", policyStatus.dwError);
346                 if(conn->mask_errors)
347                     WARN("unknown error flags for policy status %x\n", policyStatus.dwError);
348                 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_INVALID_CERT;
349             }
350         }else {
351             err = GetLastError();
352         }
353     }
354
355     if(err) {
356         WARN("failed %u\n", err);
357         CertFreeCertificateChain(chain);
358         if(conn->server->cert_chain) {
359             CertFreeCertificateChain(conn->server->cert_chain);
360             conn->server->cert_chain = NULL;
361         }
362         if(conn->mask_errors)
363             conn->server->security_flags |= conn->security_flags & _SECURITY_ERROR_FLAGS_MASK;
364         return err;
365     }
366
367     /* FIXME: Reuse cached chain */
368     if(conn->server->cert_chain)
369         CertFreeCertificateChain(chain);
370     else
371         conn->server->cert_chain = chain;
372     return ERROR_SUCCESS;
373 }
374
375 static int netconn_secure_verify(int preverify_ok, X509_STORE_CTX *ctx)
376 {
377     SSL *ssl;
378     BOOL ret = FALSE;
379     HCERTSTORE store = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
380         CERT_STORE_CREATE_NEW_FLAG, NULL);
381     netconn_t *conn;
382
383     ssl = pX509_STORE_CTX_get_ex_data(ctx,
384         pSSL_get_ex_data_X509_STORE_CTX_idx());
385     conn = pSSL_get_ex_data(ssl, conn_idx);
386     if (store)
387     {
388         X509 *cert;
389         int i;
390         PCCERT_CONTEXT endCert = NULL;
391         struct stack_st *chain = (struct stack_st *)pX509_STORE_CTX_get_chain( ctx );
392
393         ret = TRUE;
394         for (i = 0; ret && i < psk_num(chain); i++)
395         {
396             PCCERT_CONTEXT context;
397
398             cert = (X509 *)psk_value(chain, i);
399             if ((context = X509_to_cert_context(cert)))
400             {
401                 ret = CertAddCertificateContextToStore(store, context,
402                         CERT_STORE_ADD_ALWAYS, i ? NULL : &endCert);
403                 CertFreeCertificateContext(context);
404             }
405         }
406         if (!endCert) ret = FALSE;
407         if (ret)
408         {
409             DWORD_PTR err = netconn_verify_cert(conn, endCert, store);
410
411             if (err)
412             {
413                 pSSL_set_ex_data(ssl, error_idx, (void *)err);
414                 ret = FALSE;
415             }
416         }
417         CertFreeCertificateContext(endCert);
418         CertCloseStore(store, 0);
419     }
420     return ret;
421 }
422
423 static long get_tls_option(void) {
424     long tls_option = SSL_OP_NO_SSLv2; /* disable SSLv2 for security reason, secur32/Schannel(GnuTLS) don't support it */
425 #ifdef SSL_OP_NO_TLSv1_2
426     DWORD type, val, size;
427     HKEY hkey,tls12_client,tls11_client;
428     LONG res;
429     const WCHAR Schannel_Prot[] = {  /* SYSTEM\\CurrentControlSet\\Control\\SecurityProviders\\SCANNEL\\Protocols */
430               'S','Y','S','T','E','M','\\',
431               'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
432               'C','o','n','t','r','o','l','\\',
433               'S','e','c','u','r','i','t','y','P','r','o','v','i','d','e','r','s','\\',
434               'S','C','H','A','N','N','E','L','\\',
435               'P','r','o','t','o','c','o','l','s',0 };
436      const WCHAR TLS12_Client[] = {'T','L','S',' ','1','.','2','\\','C','l','i','e','n','t',0};
437      const WCHAR TLS11_Client[] = {'T','L','S',' ','1','.','1','\\','C','l','i','e','n','t',0};
438      const WCHAR DisabledByDefault[] = {'D','i','s','a','b','l','e','d','B','y','D','e','f','a','u','l','t',0};
439
440     res = RegOpenKeyExW(HKEY_LOCAL_MACHINE,
441           Schannel_Prot,
442           0, KEY_READ, &hkey);
443     if (res != ERROR_SUCCESS) { /* enabled TLSv1.1/1.2 when no registry entry */
444         return tls_option;
445     }
446     if (RegOpenKeyExW(hkey, TLS12_Client, 0, KEY_READ, &tls12_client) == ERROR_SUCCESS) {
447         size = sizeof(DWORD);
448         if (RegQueryValueExW(tls12_client, DisabledByDefault, NULL, &type,  (LPBYTE) &val, &size) == ERROR_SUCCESS
449             && type == REG_DWORD) {
450             tls_option |= val?SSL_OP_NO_TLSv1_2:0;
451         }
452         RegCloseKey(tls12_client);
453     }
454     if (RegOpenKeyExW(hkey, TLS11_Client, 0, KEY_READ, &tls11_client) == ERROR_SUCCESS) {
455         size = sizeof(DWORD);
456         if (RegQueryValueExW(tls11_client, DisabledByDefault, NULL, &type,  (LPBYTE) &val, &size) == ERROR_SUCCESS
457             && type == REG_DWORD) {
458             tls_option |= val?SSL_OP_NO_TLSv1_1:0;
459         }
460         RegCloseKey(tls11_client);
461     }
462     RegCloseKey(hkey);
463 #endif
464     return tls_option;
465 }
466 #endif /* SONAME_LIBSSL */
467
468 static CRITICAL_SECTION init_ssl_cs;
469 static CRITICAL_SECTION_DEBUG init_ssl_cs_debug =
470 {
471     0, 0, &init_ssl_cs,
472     { &init_ssl_cs_debug.ProcessLocksList,
473       &init_ssl_cs_debug.ProcessLocksList },
474     0, 0, { (DWORD_PTR)(__FILE__ ": init_ssl_cs") }
475 };
476 static CRITICAL_SECTION init_ssl_cs = { &init_ssl_cs_debug, -1, 0, 0, 0, 0 };
477
478 static DWORD init_openssl(void)
479 {
480 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
481     int i;
482
483     if(OpenSSL_ssl_handle)
484         return ERROR_SUCCESS;
485
486     OpenSSL_ssl_handle = wine_dlopen(SONAME_LIBSSL, RTLD_NOW, NULL, 0);
487     if(!OpenSSL_ssl_handle) {
488         ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n", SONAME_LIBSSL);
489         return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
490     }
491
492     OpenSSL_crypto_handle = wine_dlopen(SONAME_LIBCRYPTO, RTLD_NOW, NULL, 0);
493     if(!OpenSSL_crypto_handle) {
494         ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n", SONAME_LIBCRYPTO);
495         return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
496     }
497
498     /* mmm nice ugly macroness */
499 #define DYNSSL(x) \
500     p##x = wine_dlsym(OpenSSL_ssl_handle, #x, NULL, 0); \
501     if (!p##x) { \
502         ERR("failed to load symbol %s\n", #x); \
503         return ERROR_INTERNET_SECURITY_CHANNEL_ERROR; \
504     }
505
506     DYNSSL(SSL_library_init);
507     DYNSSL(SSL_load_error_strings);
508     DYNSSL(SSLv23_method);
509     DYNSSL(SSL_CTX_free);
510     DYNSSL(SSL_CTX_new);
511     DYNSSL(SSL_CTX_ctrl);
512     DYNSSL(SSL_new);
513     DYNSSL(SSL_free);
514     DYNSSL(SSL_ctrl);
515     DYNSSL(SSL_set_fd);
516     DYNSSL(SSL_connect);
517     DYNSSL(SSL_shutdown);
518     DYNSSL(SSL_write);
519     DYNSSL(SSL_read);
520     DYNSSL(SSL_pending);
521     DYNSSL(SSL_get_error);
522     DYNSSL(SSL_get_ex_new_index);
523     DYNSSL(SSL_get_ex_data);
524     DYNSSL(SSL_set_ex_data);
525     DYNSSL(SSL_get_ex_data_X509_STORE_CTX_idx);
526     DYNSSL(SSL_get_peer_certificate);
527     DYNSSL(SSL_CTX_get_timeout);
528     DYNSSL(SSL_CTX_set_timeout);
529     DYNSSL(SSL_CTX_set_default_verify_paths);
530     DYNSSL(SSL_CTX_set_verify);
531     DYNSSL(SSL_get_current_cipher);
532     DYNSSL(SSL_CIPHER_get_bits);
533 #undef DYNSSL
534
535 #define DYNCRYPTO(x) \
536     p##x = wine_dlsym(OpenSSL_crypto_handle, #x, NULL, 0); \
537     if (!p##x) { \
538         ERR("failed to load symbol %s\n", #x); \
539         return ERROR_INTERNET_SECURITY_CHANNEL_ERROR; \
540     }
541
542     DYNCRYPTO(BIO_new_fp);
543     DYNCRYPTO(CRYPTO_num_locks);
544     DYNCRYPTO(CRYPTO_set_id_callback);
545     DYNCRYPTO(CRYPTO_set_locking_callback);
546     DYNCRYPTO(ERR_free_strings);
547     DYNCRYPTO(ERR_get_error);
548     DYNCRYPTO(ERR_error_string);
549     DYNCRYPTO(X509_STORE_CTX_get_ex_data);
550     DYNCRYPTO(X509_STORE_CTX_get_chain);
551     DYNCRYPTO(i2d_X509);
552     DYNCRYPTO(sk_num);
553     DYNCRYPTO(sk_value);
554 #undef DYNCRYPTO
555
556 #define pSSL_CTX_set_options(ctx,op) \
557        pSSL_CTX_ctrl((ctx),SSL_CTRL_OPTIONS,(op),NULL)
558 #define pSSL_set_options(ssl,op) \
559        pSSL_ctrl((ssl),SSL_CTRL_OPTIONS,(op),NULL)
560
561     pSSL_library_init();
562     pSSL_load_error_strings();
563     pBIO_new_fp(stderr, BIO_NOCLOSE); /* FIXME: should use winedebug stuff */
564
565     meth = pSSLv23_method();
566     ctx = pSSL_CTX_new(meth);
567     pSSL_CTX_set_options(ctx, get_tls_option());
568     if(!pSSL_CTX_set_default_verify_paths(ctx)) {
569         ERR("SSL_CTX_set_default_verify_paths failed: %s\n",
570             pERR_error_string(pERR_get_error(), 0));
571         return ERROR_OUTOFMEMORY;
572     }
573
574     error_idx = pSSL_get_ex_new_index(0, (void *)"error index", NULL, NULL, NULL);
575     if(error_idx == -1) {
576         ERR("SSL_get_ex_new_index failed; %s\n", pERR_error_string(pERR_get_error(), 0));
577         return ERROR_OUTOFMEMORY;
578     }
579
580     conn_idx = pSSL_get_ex_new_index(0, (void *)"netconn index", NULL, NULL, NULL);
581     if(conn_idx == -1) {
582         ERR("SSL_get_ex_new_index failed; %s\n", pERR_error_string(pERR_get_error(), 0));
583         return ERROR_OUTOFMEMORY;
584     }
585
586     pSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, netconn_secure_verify);
587
588     pCRYPTO_set_id_callback(ssl_thread_id);
589     num_ssl_locks = pCRYPTO_num_locks();
590     ssl_locks = heap_alloc(num_ssl_locks * sizeof(CRITICAL_SECTION));
591     if(!ssl_locks)
592         return ERROR_OUTOFMEMORY;
593
594     for(i = 0; i < num_ssl_locks; i++)
595     {
596         InitializeCriticalSection(&ssl_locks[i]);
597         ssl_locks[i].DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": ssl_locks");
598     }
599     pCRYPTO_set_locking_callback(ssl_lock_callback);
600
601     return ERROR_SUCCESS;
602 #else
603     FIXME("can't use SSL, not compiled in.\n");
604     return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
605 #endif
606 }
607
608 static DWORD create_netconn_socket(server_t *server, netconn_t *netconn, DWORD timeout)
609 {
610     int result, flag;
611
612     assert(server->addr_len);
613     result = netconn->socketFD = socket(server->addr.ss_family, SOCK_STREAM, 0);
614     if(result != -1) {
615         flag = 1;
616         ioctlsocket(netconn->socketFD, FIONBIO, &flag);
617         result = connect(netconn->socketFD, (struct sockaddr*)&server->addr, server->addr_len);
618         if(result == -1)
619         {
620             if (sock_get_error(errno) == WSAEINPROGRESS) {
621                 struct pollfd pfd;
622                 int res;
623
624                 pfd.fd = netconn->socketFD;
625                 pfd.events = POLLOUT;
626                 res = poll(&pfd, 1, timeout);
627                 if (!res)
628                 {
629                     closesocket(netconn->socketFD);
630                     return ERROR_INTERNET_CANNOT_CONNECT;
631                 }
632                 else if (res > 0)
633                 {
634                     int err;
635                     socklen_t len = sizeof(err);
636                     if (!getsockopt(netconn->socketFD, SOL_SOCKET, SO_ERROR, &err, &len) && !err)
637                         result = 0;
638                 }
639             }
640         }
641         if(result == -1)
642             closesocket(netconn->socketFD);
643         else {
644             flag = 0;
645             ioctlsocket(netconn->socketFD, FIONBIO, &flag);
646         }
647     }
648     if(result == -1)
649         return ERROR_INTERNET_CANNOT_CONNECT;
650
651 #ifdef TCP_NODELAY
652     flag = 1;
653     result = setsockopt(netconn->socketFD, IPPROTO_TCP, TCP_NODELAY, (void*)&flag, sizeof(flag));
654     if(result < 0)
655         WARN("setsockopt(TCP_NODELAY) failed\n");
656 #endif
657
658     return ERROR_SUCCESS;
659 }
660
661 DWORD create_netconn(BOOL useSSL, server_t *server, DWORD security_flags, BOOL mask_errors, DWORD timeout, netconn_t **ret)
662 {
663     netconn_t *netconn;
664     int result;
665
666     if(useSSL) {
667         DWORD res;
668
669         TRACE("using SSL connection\n");
670
671         EnterCriticalSection(&init_ssl_cs);
672         res = init_openssl();
673         LeaveCriticalSection(&init_ssl_cs);
674         if(res != ERROR_SUCCESS)
675             return res;
676     }
677
678     netconn = heap_alloc_zero(sizeof(*netconn));
679     if(!netconn)
680         return ERROR_OUTOFMEMORY;
681
682     netconn->socketFD = -1;
683     netconn->security_flags = security_flags | server->security_flags;
684     netconn->mask_errors = mask_errors;
685     list_init(&netconn->pool_entry);
686
687     result = create_netconn_socket(server, netconn, timeout);
688     if (result != ERROR_SUCCESS) {
689         heap_free(netconn);
690         return result;
691     }
692
693     server_addref(server);
694     netconn->server = server;
695     *ret = netconn;
696     return result;
697 }
698
699 void free_netconn(netconn_t *netconn)
700 {
701     server_release(netconn->server);
702
703 #ifdef SONAME_LIBSSL
704     if (netconn->ssl_s) {
705         pSSL_shutdown(netconn->ssl_s);
706         pSSL_free(netconn->ssl_s);
707     }
708 #endif
709
710     closesocket(netconn->socketFD);
711     heap_free(netconn);
712 }
713
714 void NETCON_unload(void)
715 {
716 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
717     if (OpenSSL_crypto_handle)
718     {
719         pERR_free_strings();
720         wine_dlclose(OpenSSL_crypto_handle, NULL, 0);
721     }
722     if (OpenSSL_ssl_handle)
723     {
724         if (ctx)
725             pSSL_CTX_free(ctx);
726         wine_dlclose(OpenSSL_ssl_handle, NULL, 0);
727     }
728     if (ssl_locks)
729     {
730         int i;
731         for (i = 0; i < num_ssl_locks; i++)
732         {
733             ssl_locks[i].DebugInfo->Spare[0] = 0;
734             DeleteCriticalSection(&ssl_locks[i]);
735         }
736         heap_free(ssl_locks);
737     }
738 #endif
739 }
740
741 /* translate a unix error code into a winsock one */
742 int sock_get_error( int err )
743 {
744 #if !defined(__MINGW32__) && !defined (_MSC_VER)
745     switch (err)
746     {
747         case EINTR:             return WSAEINTR;
748         case EBADF:             return WSAEBADF;
749         case EPERM:
750         case EACCES:            return WSAEACCES;
751         case EFAULT:            return WSAEFAULT;
752         case EINVAL:            return WSAEINVAL;
753         case EMFILE:            return WSAEMFILE;
754         case EWOULDBLOCK:       return WSAEWOULDBLOCK;
755         case EINPROGRESS:       return WSAEINPROGRESS;
756         case EALREADY:          return WSAEALREADY;
757         case ENOTSOCK:          return WSAENOTSOCK;
758         case EDESTADDRREQ:      return WSAEDESTADDRREQ;
759         case EMSGSIZE:          return WSAEMSGSIZE;
760         case EPROTOTYPE:        return WSAEPROTOTYPE;
761         case ENOPROTOOPT:       return WSAENOPROTOOPT;
762         case EPROTONOSUPPORT:   return WSAEPROTONOSUPPORT;
763         case ESOCKTNOSUPPORT:   return WSAESOCKTNOSUPPORT;
764         case EOPNOTSUPP:        return WSAEOPNOTSUPP;
765         case EPFNOSUPPORT:      return WSAEPFNOSUPPORT;
766         case EAFNOSUPPORT:      return WSAEAFNOSUPPORT;
767         case EADDRINUSE:        return WSAEADDRINUSE;
768         case EADDRNOTAVAIL:     return WSAEADDRNOTAVAIL;
769         case ENETDOWN:          return WSAENETDOWN;
770         case ENETUNREACH:       return WSAENETUNREACH;
771         case ENETRESET:         return WSAENETRESET;
772         case ECONNABORTED:      return WSAECONNABORTED;
773         case EPIPE:
774         case ECONNRESET:        return WSAECONNRESET;
775         case ENOBUFS:           return WSAENOBUFS;
776         case EISCONN:           return WSAEISCONN;
777         case ENOTCONN:          return WSAENOTCONN;
778         case ESHUTDOWN:         return WSAESHUTDOWN;
779         case ETOOMANYREFS:      return WSAETOOMANYREFS;
780         case ETIMEDOUT:         return WSAETIMEDOUT;
781         case ECONNREFUSED:      return WSAECONNREFUSED;
782         case ELOOP:             return WSAELOOP;
783         case ENAMETOOLONG:      return WSAENAMETOOLONG;
784         case EHOSTDOWN:         return WSAEHOSTDOWN;
785         case EHOSTUNREACH:      return WSAEHOSTUNREACH;
786         case ENOTEMPTY:         return WSAENOTEMPTY;
787 #ifdef EPROCLIM
788         case EPROCLIM:          return WSAEPROCLIM;
789 #endif
790 #ifdef EUSERS
791         case EUSERS:            return WSAEUSERS;
792 #endif
793 #ifdef EDQUOT
794         case EDQUOT:            return WSAEDQUOT;
795 #endif
796 #ifdef ESTALE
797         case ESTALE:            return WSAESTALE;
798 #endif
799 #ifdef EREMOTE
800         case EREMOTE:           return WSAEREMOTE;
801 #endif
802     default: errno=err; perror("sock_set_error"); return WSAEFAULT;
803     }
804 #endif
805     return err;
806 }
807
808 #ifdef SONAME_LIBSSL
809 static DWORD netcon_secure_connect_setup(netconn_t *connection, long tls_option)
810 {
811     void *ssl_s;
812     DWORD res;
813     int bits;
814
815     ssl_s = pSSL_new(ctx);
816     if (!ssl_s)
817     {
818         ERR("SSL_new failed: %s\n",
819             pERR_error_string(pERR_get_error(), 0));
820         return ERROR_OUTOFMEMORY;
821     }
822
823     pSSL_set_options(ssl_s, tls_option);
824     if (!pSSL_set_fd(ssl_s, connection->socketFD))
825     {
826         ERR("SSL_set_fd failed: %s\n",
827             pERR_error_string(pERR_get_error(), 0));
828         res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
829         goto fail;
830     }
831
832     if (!pSSL_set_ex_data(ssl_s, conn_idx, connection))
833     {
834         ERR("SSL_set_ex_data failed: %s\n",
835             pERR_error_string(pERR_get_error(), 0));
836         res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
837         goto fail;
838     }
839     if (pSSL_connect(ssl_s) <= 0)
840     {
841         res = (DWORD_PTR)pSSL_get_ex_data(ssl_s, error_idx);
842         if (!res)
843             res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
844         ERR("SSL_connect failed: %d\n", res);
845         goto fail;
846     }
847
848     connection->ssl_s = ssl_s;
849
850     bits = NETCON_GetCipherStrength(connection);
851     if (bits >= 128)
852         connection->security_flags |= SECURITY_FLAG_STRENGTH_STRONG;
853     else if (bits >= 56)
854         connection->security_flags |= SECURITY_FLAG_STRENGTH_MEDIUM;
855     else
856         connection->security_flags |= SECURITY_FLAG_STRENGTH_WEAK;
857     connection->security_flags |= SECURITY_FLAG_SECURE;
858
859     if(connection->mask_errors)
860         connection->server->security_flags = connection->security_flags;
861     return ERROR_SUCCESS;
862
863 fail:
864     if (ssl_s)
865     {
866         pSSL_shutdown(ssl_s);
867         pSSL_free(ssl_s);
868     }
869     return res;
870 }
871 #endif
872
873 /******************************************************************************
874  * NETCON_secure_connect
875  * Initiates a secure connection over an existing plaintext connection.
876  */
877 DWORD NETCON_secure_connect(netconn_t *connection, server_t *server)
878 {
879     DWORD res = ERROR_NOT_SUPPORTED;
880 #ifdef SONAME_LIBSSL
881     /* can't connect if we are already connected */
882     if (connection->ssl_s)
883     {
884         ERR("already connected\n");
885         return ERROR_INTERNET_CANNOT_CONNECT;
886     }
887
888     connection->useSSL = TRUE;
889     if(server != connection->server) {
890         server_release(connection->server);
891         server_addref(server);
892         connection->server = server;
893     }
894
895     /* connect with given TLS options */
896     res = netcon_secure_connect_setup(connection, get_tls_option());
897     if (res == ERROR_SUCCESS)
898         return res;
899
900 #ifdef SSL_OP_NO_TLSv1_2
901     /* FIXME: when got version alert and FIN from server */
902     /* fallback to connect without TLSv1.1/TLSv1.2        */
903     if (res == ERROR_INTERNET_SECURITY_CHANNEL_ERROR)
904     {
905         closesocket(connection->socketFD);
906         pSSL_CTX_set_options(ctx,SSL_OP_NO_TLSv1_1|SSL_OP_NO_TLSv1_2);
907         res = create_netconn_socket(connection->server, connection, 500);
908         if (res != ERROR_SUCCESS)
909             return res;
910         res = netcon_secure_connect_setup(connection, get_tls_option()|SSL_OP_NO_TLSv1_1|SSL_OP_NO_TLSv1_2);
911     }
912 #endif
913 #endif
914     return res;
915 }
916
917 /******************************************************************************
918  * NETCON_send
919  * Basically calls 'send()' unless we should use SSL
920  * number of chars send is put in *sent
921  */
922 DWORD NETCON_send(netconn_t *connection, const void *msg, size_t len, int flags,
923                 int *sent /* out */)
924 {
925     if (!connection->useSSL)
926     {
927         *sent = send(connection->socketFD, msg, len, flags);
928         if (*sent == -1)
929             return sock_get_error(errno);
930         return ERROR_SUCCESS;
931     }
932     else
933     {
934 #ifdef SONAME_LIBSSL
935         if(!connection->ssl_s) {
936             FIXME("not connected\n");
937             return ERROR_NOT_SUPPORTED;
938         }
939         if (flags)
940             FIXME("SSL_write doesn't support any flags (%08x)\n", flags);
941         *sent = pSSL_write(connection->ssl_s, msg, len);
942         if (*sent < 1 && len)
943             return ERROR_INTERNET_CONNECTION_ABORTED;
944         return ERROR_SUCCESS;
945 #else
946         return ERROR_NOT_SUPPORTED;
947 #endif
948     }
949 }
950
951 /******************************************************************************
952  * NETCON_recv
953  * Basically calls 'recv()' unless we should use SSL
954  * number of chars received is put in *recvd
955  */
956 DWORD NETCON_recv(netconn_t *connection, void *buf, size_t len, int flags,
957                 int *recvd /* out */)
958 {
959     *recvd = 0;
960     if (!len)
961         return ERROR_SUCCESS;
962     if (!connection->useSSL)
963     {
964         *recvd = recv(connection->socketFD, buf, len, flags);
965         return *recvd == -1 ? sock_get_error(errno) :  ERROR_SUCCESS;
966     }
967     else
968     {
969 #ifdef SONAME_LIBSSL
970         if(!connection->ssl_s) {
971             FIXME("not connected\n");
972             return ERROR_NOT_SUPPORTED;
973         }
974         *recvd = pSSL_read(connection->ssl_s, buf, len);
975
976         /* Check if EOF was received */
977         if(!*recvd && (pSSL_get_error(connection->ssl_s, *recvd)==SSL_ERROR_ZERO_RETURN
978                     || pSSL_get_error(connection->ssl_s, *recvd)==SSL_ERROR_SYSCALL))
979             return ERROR_SUCCESS;
980
981         return *recvd > 0 ? ERROR_SUCCESS : ERROR_INTERNET_CONNECTION_ABORTED;
982 #else
983         return ERROR_NOT_SUPPORTED;
984 #endif
985     }
986 }
987
988 /******************************************************************************
989  * NETCON_query_data_available
990  * Returns the number of bytes of peeked data plus the number of bytes of
991  * queued, but unread data.
992  */
993 BOOL NETCON_query_data_available(netconn_t *connection, DWORD *available)
994 {
995     *available = 0;
996
997     if (!connection->useSSL)
998     {
999 #ifdef FIONREAD
1000         int unread;
1001         int retval = ioctlsocket(connection->socketFD, FIONREAD, &unread);
1002         if (!retval)
1003         {
1004             TRACE("%d bytes of queued, but unread data\n", unread);
1005             *available += unread;
1006         }
1007 #endif
1008     }
1009     else
1010     {
1011 #ifdef SONAME_LIBSSL
1012         *available = connection->ssl_s ? pSSL_pending(connection->ssl_s) : 0;
1013 #endif
1014     }
1015     return TRUE;
1016 }
1017
1018 BOOL NETCON_is_alive(netconn_t *netconn)
1019 {
1020 #ifdef MSG_DONTWAIT
1021     ssize_t len;
1022     BYTE b;
1023
1024     len = recv(netconn->socketFD, &b, 1, MSG_PEEK|MSG_DONTWAIT);
1025     return len == 1 || (len == -1 && errno == EWOULDBLOCK);
1026 #elif defined(__MINGW32__) || defined(_MSC_VER)
1027     ULONG mode;
1028     int len;
1029     char b;
1030
1031     mode = 1;
1032     if(!ioctlsocket(netconn->socketFD, FIONBIO, &mode))
1033         return FALSE;
1034
1035     len = recv(netconn->socketFD, &b, 1, MSG_PEEK);
1036
1037     mode = 0;
1038     if(!ioctlsocket(netconn->socketFD, FIONBIO, &mode))
1039         return FALSE;
1040
1041     return len == 1 || (len == -1 && errno == WSAEWOULDBLOCK);
1042 #else
1043     FIXME("not supported on this platform\n");
1044     return TRUE;
1045 #endif
1046 }
1047
1048 LPCVOID NETCON_GetCert(netconn_t *connection)
1049 {
1050 #ifdef SONAME_LIBSSL
1051     X509* cert;
1052     LPCVOID r = NULL;
1053
1054     if (!connection->ssl_s)
1055         return NULL;
1056
1057     cert = pSSL_get_peer_certificate(connection->ssl_s);
1058     r = X509_to_cert_context(cert);
1059     return r;
1060 #else
1061     return NULL;
1062 #endif
1063 }
1064
1065 int NETCON_GetCipherStrength(netconn_t *connection)
1066 {
1067 #ifdef SONAME_LIBSSL
1068 #if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER >= 0x0090707f)
1069     const SSL_CIPHER *cipher;
1070 #else
1071     SSL_CIPHER *cipher;
1072 #endif
1073     int bits = 0;
1074
1075     if (!connection->ssl_s)
1076         return 0;
1077     cipher = pSSL_get_current_cipher(connection->ssl_s);
1078     if (!cipher)
1079         return 0;
1080     pSSL_CIPHER_get_bits(cipher, &bits);
1081     return bits;
1082 #else
1083     return 0;
1084 #endif
1085 }
1086
1087 DWORD NETCON_set_timeout(netconn_t *connection, BOOL send, DWORD value)
1088 {
1089     int result;
1090     struct timeval tv;
1091
1092     /* value is in milliseconds, convert to struct timeval */
1093     if (value == INFINITE)
1094     {
1095         tv.tv_sec = 0;
1096         tv.tv_usec = 0;
1097     }
1098     else
1099     {
1100         tv.tv_sec = value / 1000;
1101         tv.tv_usec = (value % 1000) * 1000;
1102     }
1103     result = setsockopt(connection->socketFD, SOL_SOCKET,
1104                         send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv,
1105                         sizeof(tv));
1106     if (result == -1)
1107     {
1108         WARN("setsockopt failed (%s)\n", strerror(errno));
1109         return sock_get_error(errno);
1110     }
1111     return ERROR_SUCCESS;
1112 }