jscript: Return buffer pointer separately from jsstr_t from jsstr_alloc_len.
[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
467 static CRITICAL_SECTION init_ssl_cs;
468 static CRITICAL_SECTION_DEBUG init_ssl_cs_debug =
469 {
470     0, 0, &init_ssl_cs,
471     { &init_ssl_cs_debug.ProcessLocksList,
472       &init_ssl_cs_debug.ProcessLocksList },
473     0, 0, { (DWORD_PTR)(__FILE__ ": init_ssl_cs") }
474 };
475 static CRITICAL_SECTION init_ssl_cs = { &init_ssl_cs_debug, -1, 0, 0, 0, 0 };
476
477 static DWORD init_openssl(void)
478 {
479 #ifdef SONAME_LIBCRYPTO
480     unsigned int i;
481
482     if(OpenSSL_ssl_handle)
483         return ERROR_SUCCESS;
484
485     OpenSSL_ssl_handle = wine_dlopen(SONAME_LIBSSL, RTLD_NOW, NULL, 0);
486     if(!OpenSSL_ssl_handle) {
487         ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n", SONAME_LIBSSL);
488         return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
489     }
490
491     OpenSSL_crypto_handle = wine_dlopen(SONAME_LIBCRYPTO, RTLD_NOW, NULL, 0);
492     if(!OpenSSL_crypto_handle) {
493         ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n", SONAME_LIBCRYPTO);
494         return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
495     }
496
497     /* mmm nice ugly macroness */
498 #define DYNSSL(x) \
499     p##x = wine_dlsym(OpenSSL_ssl_handle, #x, NULL, 0); \
500     if (!p##x) { \
501         ERR("failed to load symbol %s\n", #x); \
502         return ERROR_INTERNET_SECURITY_CHANNEL_ERROR; \
503     }
504
505     DYNSSL(SSL_library_init);
506     DYNSSL(SSL_load_error_strings);
507     DYNSSL(SSLv23_method);
508     DYNSSL(SSL_CTX_free);
509     DYNSSL(SSL_CTX_new);
510     DYNSSL(SSL_CTX_ctrl);
511     DYNSSL(SSL_new);
512     DYNSSL(SSL_free);
513     DYNSSL(SSL_ctrl);
514     DYNSSL(SSL_set_fd);
515     DYNSSL(SSL_connect);
516     DYNSSL(SSL_shutdown);
517     DYNSSL(SSL_write);
518     DYNSSL(SSL_read);
519     DYNSSL(SSL_pending);
520     DYNSSL(SSL_get_error);
521     DYNSSL(SSL_get_ex_new_index);
522     DYNSSL(SSL_get_ex_data);
523     DYNSSL(SSL_set_ex_data);
524     DYNSSL(SSL_get_ex_data_X509_STORE_CTX_idx);
525     DYNSSL(SSL_get_peer_certificate);
526     DYNSSL(SSL_CTX_get_timeout);
527     DYNSSL(SSL_CTX_set_timeout);
528     DYNSSL(SSL_CTX_set_default_verify_paths);
529     DYNSSL(SSL_CTX_set_verify);
530     DYNSSL(SSL_get_current_cipher);
531     DYNSSL(SSL_CIPHER_get_bits);
532 #undef DYNSSL
533
534 #define DYNCRYPTO(x) \
535     p##x = wine_dlsym(OpenSSL_crypto_handle, #x, NULL, 0); \
536     if (!p##x) { \
537         ERR("failed to load symbol %s\n", #x); \
538         return ERROR_INTERNET_SECURITY_CHANNEL_ERROR; \
539     }
540
541     DYNCRYPTO(BIO_new_fp);
542     DYNCRYPTO(CRYPTO_num_locks);
543     DYNCRYPTO(CRYPTO_set_id_callback);
544     DYNCRYPTO(CRYPTO_set_locking_callback);
545     DYNCRYPTO(ERR_free_strings);
546     DYNCRYPTO(ERR_get_error);
547     DYNCRYPTO(ERR_error_string);
548     DYNCRYPTO(X509_STORE_CTX_get_ex_data);
549     DYNCRYPTO(X509_STORE_CTX_get_chain);
550     DYNCRYPTO(i2d_X509);
551     DYNCRYPTO(sk_num);
552     DYNCRYPTO(sk_value);
553 #undef DYNCRYPTO
554
555 #define pSSL_CTX_set_options(ctx,op) \
556        pSSL_CTX_ctrl((ctx),SSL_CTRL_OPTIONS,(op),NULL)
557 #define pSSL_set_options(ssl,op) \
558        pSSL_ctrl((ssl),SSL_CTRL_OPTIONS,(op),NULL)
559
560     pSSL_library_init();
561     pSSL_load_error_strings();
562     pBIO_new_fp(stderr, BIO_NOCLOSE); /* FIXME: should use winedebug stuff */
563
564     meth = pSSLv23_method();
565     ctx = pSSL_CTX_new(meth);
566     pSSL_CTX_set_options(ctx, get_tls_option());
567     if(!pSSL_CTX_set_default_verify_paths(ctx)) {
568         ERR("SSL_CTX_set_default_verify_paths failed: %s\n",
569             pERR_error_string(pERR_get_error(), 0));
570         return ERROR_OUTOFMEMORY;
571     }
572
573     error_idx = pSSL_get_ex_new_index(0, (void *)"error index", NULL, NULL, NULL);
574     if(error_idx == -1) {
575         ERR("SSL_get_ex_new_index failed; %s\n", pERR_error_string(pERR_get_error(), 0));
576         return ERROR_OUTOFMEMORY;
577     }
578
579     conn_idx = pSSL_get_ex_new_index(0, (void *)"netconn index", NULL, NULL, NULL);
580     if(conn_idx == -1) {
581         ERR("SSL_get_ex_new_index failed; %s\n", pERR_error_string(pERR_get_error(), 0));
582         return ERROR_OUTOFMEMORY;
583     }
584
585     pSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, netconn_secure_verify);
586
587     pCRYPTO_set_id_callback(ssl_thread_id);
588     num_ssl_locks = pCRYPTO_num_locks();
589     ssl_locks = heap_alloc(num_ssl_locks * sizeof(CRITICAL_SECTION));
590     if(!ssl_locks)
591         return ERROR_OUTOFMEMORY;
592
593     for(i = 0; i < num_ssl_locks; i++)
594     {
595         InitializeCriticalSection(&ssl_locks[i]);
596         ssl_locks[i].DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": ssl_locks");
597     }
598     pCRYPTO_set_locking_callback(ssl_lock_callback);
599
600     return ERROR_SUCCESS;
601 #else
602     FIXME("can't use SSL, libcrypto not compiled in.\n");
603     return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
604 #endif
605 }
606 #endif /* SONAME_LIBSSL */
607
608 static DWORD create_netconn_socket(server_t *server, netconn_t *netconn, DWORD timeout)
609 {
610     int result;
611     ULONG flag;
612
613     assert(server->addr_len);
614     result = netconn->socket = socket(server->addr.ss_family, SOCK_STREAM, 0);
615     if(result != -1) {
616         flag = 1;
617         ioctlsocket(netconn->socket, FIONBIO, &flag);
618         result = connect(netconn->socket, (struct sockaddr*)&server->addr, server->addr_len);
619         if(result == -1)
620         {
621             if (sock_get_error(errno) == WSAEINPROGRESS) {
622                 struct pollfd pfd;
623                 int res;
624
625                 pfd.fd = netconn->socket;
626                 pfd.events = POLLOUT;
627                 res = poll(&pfd, 1, timeout);
628                 if (!res)
629                 {
630                     closesocket(netconn->socket);
631                     return ERROR_INTERNET_CANNOT_CONNECT;
632                 }
633                 else if (res > 0)
634                 {
635                     int err;
636                     socklen_t len = sizeof(err);
637                     if (!getsockopt(netconn->socket, SOL_SOCKET, SO_ERROR, (void *)&err, &len) && !err)
638                         result = 0;
639                 }
640             }
641         }
642         if(result == -1)
643             closesocket(netconn->socket);
644         else {
645             flag = 0;
646             ioctlsocket(netconn->socket, FIONBIO, &flag);
647         }
648     }
649     if(result == -1)
650         return ERROR_INTERNET_CANNOT_CONNECT;
651
652 #ifdef TCP_NODELAY
653     flag = 1;
654     result = setsockopt(netconn->socket, IPPROTO_TCP, TCP_NODELAY, (void*)&flag, sizeof(flag));
655     if(result < 0)
656         WARN("setsockopt(TCP_NODELAY) failed\n");
657 #endif
658
659     return ERROR_SUCCESS;
660 }
661
662 DWORD create_netconn(BOOL useSSL, server_t *server, DWORD security_flags, BOOL mask_errors, DWORD timeout, netconn_t **ret)
663 {
664     netconn_t *netconn;
665     int result;
666
667 #ifdef SONAME_LIBSSL
668     if(useSSL) {
669         DWORD res;
670
671         TRACE("using SSL connection\n");
672
673         EnterCriticalSection(&init_ssl_cs);
674         res = init_openssl();
675         LeaveCriticalSection(&init_ssl_cs);
676         if(res != ERROR_SUCCESS)
677             return res;
678     }
679 #endif
680
681     netconn = heap_alloc_zero(sizeof(*netconn));
682     if(!netconn)
683         return ERROR_OUTOFMEMORY;
684
685     netconn->socket = -1;
686     netconn->security_flags = security_flags | server->security_flags;
687     netconn->mask_errors = mask_errors;
688     list_init(&netconn->pool_entry);
689
690     result = create_netconn_socket(server, netconn, timeout);
691     if (result != ERROR_SUCCESS) {
692         heap_free(netconn);
693         return result;
694     }
695
696     server_addref(server);
697     netconn->server = server;
698     *ret = netconn;
699     return result;
700 }
701
702 void free_netconn(netconn_t *netconn)
703 {
704     server_release(netconn->server);
705
706     if (netconn->secure) {
707 #ifdef SONAME_LIBSSL
708         pSSL_shutdown(netconn->ssl_s);
709         pSSL_free(netconn->ssl_s);
710 #endif
711     }
712
713     closesocket(netconn->socket);
714     heap_free(netconn);
715 }
716
717 void NETCON_unload(void)
718 {
719 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
720     if (OpenSSL_crypto_handle)
721     {
722         pERR_free_strings();
723         wine_dlclose(OpenSSL_crypto_handle, NULL, 0);
724     }
725     if (OpenSSL_ssl_handle)
726     {
727         if (ctx)
728             pSSL_CTX_free(ctx);
729         wine_dlclose(OpenSSL_ssl_handle, NULL, 0);
730     }
731     if (ssl_locks)
732     {
733         unsigned int i;
734         for (i = 0; i < num_ssl_locks; i++)
735         {
736             ssl_locks[i].DebugInfo->Spare[0] = 0;
737             DeleteCriticalSection(&ssl_locks[i]);
738         }
739         heap_free(ssl_locks);
740     }
741 #endif
742 }
743
744 /* translate a unix error code into a winsock one */
745 int sock_get_error( int err )
746 {
747 #if !defined(__MINGW32__) && !defined (_MSC_VER)
748     switch (err)
749     {
750         case EINTR:             return WSAEINTR;
751         case EBADF:             return WSAEBADF;
752         case EPERM:
753         case EACCES:            return WSAEACCES;
754         case EFAULT:            return WSAEFAULT;
755         case EINVAL:            return WSAEINVAL;
756         case EMFILE:            return WSAEMFILE;
757         case EWOULDBLOCK:       return WSAEWOULDBLOCK;
758         case EINPROGRESS:       return WSAEINPROGRESS;
759         case EALREADY:          return WSAEALREADY;
760         case ENOTSOCK:          return WSAENOTSOCK;
761         case EDESTADDRREQ:      return WSAEDESTADDRREQ;
762         case EMSGSIZE:          return WSAEMSGSIZE;
763         case EPROTOTYPE:        return WSAEPROTOTYPE;
764         case ENOPROTOOPT:       return WSAENOPROTOOPT;
765         case EPROTONOSUPPORT:   return WSAEPROTONOSUPPORT;
766         case ESOCKTNOSUPPORT:   return WSAESOCKTNOSUPPORT;
767         case EOPNOTSUPP:        return WSAEOPNOTSUPP;
768         case EPFNOSUPPORT:      return WSAEPFNOSUPPORT;
769         case EAFNOSUPPORT:      return WSAEAFNOSUPPORT;
770         case EADDRINUSE:        return WSAEADDRINUSE;
771         case EADDRNOTAVAIL:     return WSAEADDRNOTAVAIL;
772         case ENETDOWN:          return WSAENETDOWN;
773         case ENETUNREACH:       return WSAENETUNREACH;
774         case ENETRESET:         return WSAENETRESET;
775         case ECONNABORTED:      return WSAECONNABORTED;
776         case EPIPE:
777         case ECONNRESET:        return WSAECONNRESET;
778         case ENOBUFS:           return WSAENOBUFS;
779         case EISCONN:           return WSAEISCONN;
780         case ENOTCONN:          return WSAENOTCONN;
781         case ESHUTDOWN:         return WSAESHUTDOWN;
782         case ETOOMANYREFS:      return WSAETOOMANYREFS;
783         case ETIMEDOUT:         return WSAETIMEDOUT;
784         case ECONNREFUSED:      return WSAECONNREFUSED;
785         case ELOOP:             return WSAELOOP;
786         case ENAMETOOLONG:      return WSAENAMETOOLONG;
787         case EHOSTDOWN:         return WSAEHOSTDOWN;
788         case EHOSTUNREACH:      return WSAEHOSTUNREACH;
789         case ENOTEMPTY:         return WSAENOTEMPTY;
790 #ifdef EPROCLIM
791         case EPROCLIM:          return WSAEPROCLIM;
792 #endif
793 #ifdef EUSERS
794         case EUSERS:            return WSAEUSERS;
795 #endif
796 #ifdef EDQUOT
797         case EDQUOT:            return WSAEDQUOT;
798 #endif
799 #ifdef ESTALE
800         case ESTALE:            return WSAESTALE;
801 #endif
802 #ifdef EREMOTE
803         case EREMOTE:           return WSAEREMOTE;
804 #endif
805     default: errno=err; perror("sock_set_error"); return WSAEFAULT;
806     }
807 #endif
808     return err;
809 }
810
811 #ifdef SONAME_LIBSSL
812 static DWORD netcon_secure_connect_setup(netconn_t *connection, long tls_option)
813 {
814     void *ssl_s;
815     DWORD res;
816     int bits;
817
818     ssl_s = pSSL_new(ctx);
819     if (!ssl_s)
820     {
821         ERR("SSL_new failed: %s\n",
822             pERR_error_string(pERR_get_error(), 0));
823         return ERROR_OUTOFMEMORY;
824     }
825
826     pSSL_set_options(ssl_s, tls_option);
827     if (!pSSL_set_fd(ssl_s, connection->socket))
828     {
829         ERR("SSL_set_fd failed: %s\n",
830             pERR_error_string(pERR_get_error(), 0));
831         res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
832         goto fail;
833     }
834
835     if (!pSSL_set_ex_data(ssl_s, conn_idx, connection))
836     {
837         ERR("SSL_set_ex_data failed: %s\n",
838             pERR_error_string(pERR_get_error(), 0));
839         res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
840         goto fail;
841     }
842     if (pSSL_connect(ssl_s) <= 0)
843     {
844         res = (DWORD_PTR)pSSL_get_ex_data(ssl_s, error_idx);
845         if (!res)
846             res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
847         ERR("SSL_connect failed: %d\n", res);
848         goto fail;
849     }
850
851     connection->ssl_s = ssl_s;
852     connection->secure = TRUE;
853
854     bits = NETCON_GetCipherStrength(connection);
855     if (bits >= 128)
856         connection->security_flags |= SECURITY_FLAG_STRENGTH_STRONG;
857     else if (bits >= 56)
858         connection->security_flags |= SECURITY_FLAG_STRENGTH_MEDIUM;
859     else
860         connection->security_flags |= SECURITY_FLAG_STRENGTH_WEAK;
861     connection->security_flags |= SECURITY_FLAG_SECURE;
862
863     if(connection->mask_errors)
864         connection->server->security_flags = connection->security_flags;
865     return ERROR_SUCCESS;
866
867 fail:
868     if (ssl_s)
869     {
870         pSSL_shutdown(ssl_s);
871         pSSL_free(ssl_s);
872     }
873     return res;
874 }
875 #endif
876
877 /******************************************************************************
878  * NETCON_secure_connect
879  * Initiates a secure connection over an existing plaintext connection.
880  */
881 DWORD NETCON_secure_connect(netconn_t *connection, server_t *server)
882 {
883     DWORD res = ERROR_NOT_SUPPORTED;
884
885     /* can't connect if we are already connected */
886     if(connection->secure) {
887         ERR("already connected\n");
888         return ERROR_INTERNET_CANNOT_CONNECT;
889     }
890
891     if(server != connection->server) {
892         server_release(connection->server);
893         server_addref(server);
894         connection->server = server;
895     }
896
897 #ifdef SONAME_LIBSSL
898     /* connect with given TLS options */
899     res = netcon_secure_connect_setup(connection, get_tls_option());
900     if (res == ERROR_SUCCESS)
901         return res;
902
903 #ifdef SSL_OP_NO_TLSv1_2
904     /* FIXME: when got version alert and FIN from server */
905     /* fallback to connect without TLSv1.1/TLSv1.2        */
906     if (res == ERROR_INTERNET_SECURITY_CHANNEL_ERROR)
907     {
908         closesocket(connection->socket);
909         pSSL_CTX_set_options(ctx,SSL_OP_NO_TLSv1_1|SSL_OP_NO_TLSv1_2);
910         res = create_netconn_socket(connection->server, connection, 500);
911         if (res != ERROR_SUCCESS)
912             return res;
913         res = netcon_secure_connect_setup(connection, get_tls_option()|SSL_OP_NO_TLSv1_1|SSL_OP_NO_TLSv1_2);
914     }
915 #endif
916 #else
917     FIXME("Cannot connect, OpenSSL not available.\n");
918 #endif
919     return res;
920 }
921
922 /******************************************************************************
923  * NETCON_send
924  * Basically calls 'send()' unless we should use SSL
925  * number of chars send is put in *sent
926  */
927 DWORD NETCON_send(netconn_t *connection, const void *msg, size_t len, int flags,
928                 int *sent /* out */)
929 {
930     if(!connection->secure)
931     {
932         *sent = send(connection->socket, msg, len, flags);
933         if (*sent == -1)
934             return sock_get_error(errno);
935         return ERROR_SUCCESS;
936     }
937     else
938     {
939 #ifdef SONAME_LIBSSL
940         if(!connection->secure) {
941             FIXME("not connected\n");
942             return ERROR_NOT_SUPPORTED;
943         }
944         if (flags)
945             FIXME("SSL_write doesn't support any flags (%08x)\n", flags);
946         *sent = pSSL_write(connection->ssl_s, msg, len);
947         if (*sent < 1 && len)
948             return ERROR_INTERNET_CONNECTION_ABORTED;
949         return ERROR_SUCCESS;
950 #else
951         FIXME("not supported on this platform\n");
952         return ERROR_NOT_SUPPORTED;
953 #endif
954     }
955 }
956
957 /******************************************************************************
958  * NETCON_recv
959  * Basically calls 'recv()' unless we should use SSL
960  * number of chars received is put in *recvd
961  */
962 DWORD NETCON_recv(netconn_t *connection, void *buf, size_t len, int flags, int *recvd)
963 {
964     *recvd = 0;
965     if (!len)
966         return ERROR_SUCCESS;
967
968     if (!connection->secure)
969     {
970         *recvd = recv(connection->socket, buf, len, flags);
971         return *recvd == -1 ? sock_get_error(errno) :  ERROR_SUCCESS;
972     }
973     else
974     {
975 #ifdef SONAME_LIBSSL
976         if(!connection->secure) {
977             FIXME("not connected\n");
978             return ERROR_NOT_SUPPORTED;
979         }
980         *recvd = pSSL_read(connection->ssl_s, buf, len);
981
982         /* Check if EOF was received */
983         if(!*recvd && (pSSL_get_error(connection->ssl_s, *recvd)==SSL_ERROR_ZERO_RETURN
984                     || pSSL_get_error(connection->ssl_s, *recvd)==SSL_ERROR_SYSCALL))
985             return ERROR_SUCCESS;
986
987         return *recvd > 0 ? ERROR_SUCCESS : ERROR_INTERNET_CONNECTION_ABORTED;
988 #else
989         FIXME("not supported on this platform\n");
990         return ERROR_NOT_SUPPORTED;
991 #endif
992     }
993 }
994
995 /******************************************************************************
996  * NETCON_query_data_available
997  * Returns the number of bytes of peeked data plus the number of bytes of
998  * queued, but unread data.
999  */
1000 BOOL NETCON_query_data_available(netconn_t *connection, DWORD *available)
1001 {
1002     *available = 0;
1003
1004     if(!connection->secure)
1005     {
1006 #ifdef FIONREAD
1007         ULONG unread;
1008         int retval = ioctlsocket(connection->socket, FIONREAD, &unread);
1009         if (!retval)
1010         {
1011             TRACE("%d bytes of queued, but unread data\n", unread);
1012             *available += unread;
1013         }
1014 #endif
1015     }
1016     else
1017     {
1018 #ifdef SONAME_LIBSSL
1019         *available = pSSL_pending(connection->ssl_s);
1020 #else
1021         FIXME("not supported on this platform\n");
1022         return FALSE;
1023 #endif
1024     }
1025     return TRUE;
1026 }
1027
1028 BOOL NETCON_is_alive(netconn_t *netconn)
1029 {
1030 #ifdef MSG_DONTWAIT
1031     ssize_t len;
1032     BYTE b;
1033
1034     len = recv(netconn->socket, &b, 1, MSG_PEEK|MSG_DONTWAIT);
1035     return len == 1 || (len == -1 && errno == EWOULDBLOCK);
1036 #elif defined(__MINGW32__) || defined(_MSC_VER)
1037     ULONG mode;
1038     int len;
1039     char b;
1040
1041     mode = 1;
1042     if(!ioctlsocket(netconn->socket, FIONBIO, &mode))
1043         return FALSE;
1044
1045     len = recv(netconn->socket, &b, 1, MSG_PEEK);
1046
1047     mode = 0;
1048     if(!ioctlsocket(netconn->socket, FIONBIO, &mode))
1049         return FALSE;
1050
1051     return len == 1 || (len == -1 && errno == WSAEWOULDBLOCK);
1052 #else
1053     FIXME("not supported on this platform\n");
1054     return TRUE;
1055 #endif
1056 }
1057
1058 LPCVOID NETCON_GetCert(netconn_t *connection)
1059 {
1060 #ifdef SONAME_LIBSSL
1061     X509* cert;
1062     LPCVOID r = NULL;
1063
1064     if (!connection->secure)
1065         return NULL;
1066
1067     cert = pSSL_get_peer_certificate(connection->ssl_s);
1068     r = X509_to_cert_context(cert);
1069     return r;
1070 #else
1071     FIXME("not supported on this platform\n");
1072     return NULL;
1073 #endif
1074 }
1075
1076 int NETCON_GetCipherStrength(netconn_t *connection)
1077 {
1078 #ifdef SONAME_LIBSSL
1079 #if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER >= 0x0090707f)
1080     const SSL_CIPHER *cipher;
1081 #else
1082     SSL_CIPHER *cipher;
1083 #endif
1084     int bits = 0;
1085
1086     if (!connection->secure)
1087         return 0;
1088     cipher = pSSL_get_current_cipher(connection->ssl_s);
1089     if (!cipher)
1090         return 0;
1091     pSSL_CIPHER_get_bits(cipher, &bits);
1092     return bits;
1093 #else
1094     FIXME("not supported on this platform\n");
1095     return 0;
1096 #endif
1097 }
1098
1099 DWORD NETCON_set_timeout(netconn_t *connection, BOOL send, DWORD value)
1100 {
1101     int result;
1102     struct timeval tv;
1103
1104     /* value is in milliseconds, convert to struct timeval */
1105     if (value == INFINITE)
1106     {
1107         tv.tv_sec = 0;
1108         tv.tv_usec = 0;
1109     }
1110     else
1111     {
1112         tv.tv_sec = value / 1000;
1113         tv.tv_usec = (value % 1000) * 1000;
1114     }
1115     result = setsockopt(connection->socket, SOL_SOCKET,
1116                         send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv,
1117                         sizeof(tv));
1118     if (result == -1)
1119     {
1120         WARN("setsockopt failed (%s)\n", strerror(errno));
1121         return sock_get_error(errno);
1122     }
1123     return ERROR_SUCCESS;
1124 }