uxtheme: Remove unused variable.
[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, chainFlags = 0, 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_OFFLINE_REVOCATION |
232         CERT_TRUST_REVOCATION_STATUS_UNKNOWN |
233         CERT_TRUST_IS_REVOKED |
234         CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
235
236     TRACE("verifying %s\n", debugstr_w(conn->server->name));
237
238     chainPara.RequestedUsage.Usage.cUsageIdentifier = 1;
239     chainPara.RequestedUsage.Usage.rgpszUsageIdentifier = server_auth;
240     if (!(conn->security_flags & SECURITY_FLAG_IGNORE_REVOCATION))
241         chainFlags |= CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT;
242
243     if (!(ret = CertGetCertificateChain(NULL, cert, NULL, store, &chainPara, chainFlags, NULL, &chain))) {
244         TRACE("failed\n");
245         return GetLastError();
246     }
247
248     errors = chain->TrustStatus.dwErrorStatus;
249
250     do {
251         /* This seems strange, but that's what tests show */
252         if(errors & (CERT_TRUST_IS_PARTIAL_CHAIN|CERT_TRUST_IS_OFFLINE_REVOCATION)) {
253             WARN("ERROR_INTERNET_SEC_CERT_REV_FAILED\n");
254             err = ERROR_INTERNET_SEC_CERT_REV_FAILED;
255             if(conn->mask_errors)
256                 conn->security_flags |= _SECURITY_FLAG_CERT_REV_FAILED;
257             if(!(conn->security_flags & SECURITY_FLAG_IGNORE_REVOCATION))
258                 break;
259         }
260
261         if (chain->TrustStatus.dwErrorStatus & ~supportedErrors) {
262             WARN("error status %x\n", chain->TrustStatus.dwErrorStatus & ~supportedErrors);
263             err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_INVALID_CERT;
264             errors &= supportedErrors;
265             if(!conn->mask_errors)
266                 break;
267             WARN("unknown error flags\n");
268         }
269
270         if(errors & CERT_TRUST_IS_NOT_TIME_VALID) {
271             WARN("CERT_TRUST_IS_NOT_TIME_VALID\n");
272             if(!(conn->security_flags & SECURITY_FLAG_IGNORE_CERT_DATE_INVALID)) {
273                 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_CERT_DATE_INVALID;
274                 if(!conn->mask_errors)
275                     break;
276                 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_DATE;
277             }
278             errors &= ~CERT_TRUST_IS_NOT_TIME_VALID;
279         }
280
281         if(errors & CERT_TRUST_IS_UNTRUSTED_ROOT) {
282             WARN("CERT_TRUST_IS_UNTRUSTED_ROOT\n");
283             if(!(conn->security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA)) {
284                 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_INVALID_CA;
285                 if(!conn->mask_errors)
286                     break;
287                 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CA;
288             }
289             errors &= ~CERT_TRUST_IS_UNTRUSTED_ROOT;
290         }
291
292         if(errors & CERT_TRUST_IS_PARTIAL_CHAIN) {
293             WARN("CERT_TRUST_IS_PARTIAL_CHAIN\n");
294             if(!(conn->security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA)) {
295                 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_INVALID_CA;
296                 if(!conn->mask_errors)
297                     break;
298                 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CA;
299             }
300             errors &= ~CERT_TRUST_IS_PARTIAL_CHAIN;
301         }
302
303         if(errors & (CERT_TRUST_IS_OFFLINE_REVOCATION | CERT_TRUST_REVOCATION_STATUS_UNKNOWN)) {
304             WARN("CERT_TRUST_IS_OFFLINE_REVOCATION | CERT_TRUST_REVOCATION_STATUS_UNKNOWN\n");
305             if(!(conn->security_flags & SECURITY_FLAG_IGNORE_REVOCATION)) {
306                 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_CERT_NO_REV;
307                 if(!conn->mask_errors)
308                     break;
309                 conn->security_flags |= _SECURITY_FLAG_CERT_REV_FAILED;
310             }
311             errors &= ~(CERT_TRUST_IS_OFFLINE_REVOCATION | CERT_TRUST_REVOCATION_STATUS_UNKNOWN);
312         }
313
314         if(errors & CERT_TRUST_IS_REVOKED) {
315             WARN("CERT_TRUST_IS_REVOKED\n");
316             if(!(conn->security_flags & SECURITY_FLAG_IGNORE_REVOCATION)) {
317                 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_CERT_REVOKED;
318                 if(!conn->mask_errors)
319                     break;
320                 WARN("TRUST_IS_OFFLINE_REVOCATION | CERT_TRUST_REVOCATION_STATUS_UNKNOWN, unknown error flags\n");
321             }
322             errors &= ~CERT_TRUST_IS_REVOKED;
323         }
324
325         if(errors & CERT_TRUST_IS_NOT_VALID_FOR_USAGE) {
326             WARN("CERT_TRUST_IS_NOT_VALID_FOR_USAGE\n");
327             if(!(conn->security_flags & SECURITY_FLAG_IGNORE_WRONG_USAGE)) {
328                 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_INVALID_CERT;
329                 if(!conn->mask_errors)
330                     break;
331                 WARN("CERT_TRUST_IS_NOT_VALID_FOR_USAGE, unknown error flags\n");
332             }
333             errors &= ~CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
334         }
335
336         if(err == ERROR_INTERNET_SEC_CERT_REV_FAILED) {
337             assert(conn->security_flags & SECURITY_FLAG_IGNORE_REVOCATION);
338             err = ERROR_SUCCESS;
339         }
340     }while(0);
341
342     if(!err || conn->mask_errors) {
343         CERT_CHAIN_POLICY_PARA policyPara;
344         SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslExtraPolicyPara;
345         CERT_CHAIN_POLICY_STATUS policyStatus;
346         CERT_CHAIN_CONTEXT chainCopy;
347
348         /* Clear chain->TrustStatus.dwErrorStatus so
349          * CertVerifyCertificateChainPolicy will verify additional checks
350          * rather than stopping with an existing, ignored error.
351          */
352         memcpy(&chainCopy, chain, sizeof(chainCopy));
353         chainCopy.TrustStatus.dwErrorStatus = 0;
354         sslExtraPolicyPara.u.cbSize = sizeof(sslExtraPolicyPara);
355         sslExtraPolicyPara.dwAuthType = AUTHTYPE_SERVER;
356         sslExtraPolicyPara.pwszServerName = conn->server->name;
357         sslExtraPolicyPara.fdwChecks = conn->security_flags;
358         policyPara.cbSize = sizeof(policyPara);
359         policyPara.dwFlags = 0;
360         policyPara.pvExtraPolicyPara = &sslExtraPolicyPara;
361         ret = CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL,
362                 &chainCopy, &policyPara, &policyStatus);
363         /* Any error in the policy status indicates that the
364          * policy couldn't be verified.
365          */
366         if(ret) {
367             if(policyStatus.dwError == CERT_E_CN_NO_MATCH) {
368                 WARN("CERT_E_CN_NO_MATCH\n");
369                 if(conn->mask_errors)
370                     conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CN;
371                 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_CERT_CN_INVALID;
372             }else if(policyStatus.dwError) {
373                 WARN("policyStatus.dwError %x\n", policyStatus.dwError);
374                 if(conn->mask_errors)
375                     WARN("unknown error flags for policy status %x\n", policyStatus.dwError);
376                 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_INVALID_CERT;
377             }
378         }else {
379             err = GetLastError();
380         }
381     }
382
383     if(err) {
384         WARN("failed %u\n", err);
385         CertFreeCertificateChain(chain);
386         if(conn->server->cert_chain) {
387             CertFreeCertificateChain(conn->server->cert_chain);
388             conn->server->cert_chain = NULL;
389         }
390         if(conn->mask_errors)
391             conn->server->security_flags |= conn->security_flags & _SECURITY_ERROR_FLAGS_MASK;
392         return err;
393     }
394
395     /* FIXME: Reuse cached chain */
396     if(conn->server->cert_chain)
397         CertFreeCertificateChain(chain);
398     else
399         conn->server->cert_chain = chain;
400     return ERROR_SUCCESS;
401 }
402
403 static int netconn_secure_verify(int preverify_ok, X509_STORE_CTX *ctx)
404 {
405     SSL *ssl;
406     BOOL ret = FALSE;
407     HCERTSTORE store = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
408         CERT_STORE_CREATE_NEW_FLAG, NULL);
409     netconn_t *conn;
410
411     ssl = pX509_STORE_CTX_get_ex_data(ctx,
412         pSSL_get_ex_data_X509_STORE_CTX_idx());
413     conn = pSSL_get_ex_data(ssl, conn_idx);
414     if (store)
415     {
416         X509 *cert;
417         int i;
418         PCCERT_CONTEXT endCert = NULL;
419         struct stack_st *chain = (struct stack_st *)pX509_STORE_CTX_get_chain( ctx );
420
421         ret = TRUE;
422         for (i = 0; ret && i < psk_num(chain); i++)
423         {
424             PCCERT_CONTEXT context;
425
426             cert = (X509 *)psk_value(chain, i);
427             if ((context = X509_to_cert_context(cert)))
428             {
429                 ret = CertAddCertificateContextToStore(store, context,
430                         CERT_STORE_ADD_ALWAYS, i ? NULL : &endCert);
431                 CertFreeCertificateContext(context);
432             }
433         }
434         if (!endCert) ret = FALSE;
435         if (ret)
436         {
437             DWORD_PTR err = netconn_verify_cert(conn, endCert, store);
438
439             if (err)
440             {
441                 pSSL_set_ex_data(ssl, error_idx, (void *)err);
442                 ret = FALSE;
443             }
444         }
445         CertFreeCertificateContext(endCert);
446         CertCloseStore(store, 0);
447     }
448     return ret;
449 }
450
451 static long get_tls_option(void) {
452     long tls_option = SSL_OP_NO_SSLv2; /* disable SSLv2 for security reason, secur32/Schannel(GnuTLS) don't support it */
453 #ifdef SSL_OP_NO_TLSv1_2
454     DWORD type, val, size;
455     HKEY hkey,tls12_client,tls11_client;
456     LONG res;
457     const WCHAR Schannel_Prot[] = {  /* SYSTEM\\CurrentControlSet\\Control\\SecurityProviders\\SCANNEL\\Protocols */
458               'S','Y','S','T','E','M','\\',
459               'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
460               'C','o','n','t','r','o','l','\\',
461               'S','e','c','u','r','i','t','y','P','r','o','v','i','d','e','r','s','\\',
462               'S','C','H','A','N','N','E','L','\\',
463               'P','r','o','t','o','c','o','l','s',0 };
464      const WCHAR TLS12_Client[] = {'T','L','S',' ','1','.','2','\\','C','l','i','e','n','t',0};
465      const WCHAR TLS11_Client[] = {'T','L','S',' ','1','.','1','\\','C','l','i','e','n','t',0};
466      const WCHAR DisabledByDefault[] = {'D','i','s','a','b','l','e','d','B','y','D','e','f','a','u','l','t',0};
467
468     res = RegOpenKeyExW(HKEY_LOCAL_MACHINE,
469           Schannel_Prot,
470           0, KEY_READ, &hkey);
471     if (res != ERROR_SUCCESS) { /* enabled TLSv1.1/1.2 when no registry entry */
472         return tls_option;
473     }
474     if (RegOpenKeyExW(hkey, TLS12_Client, 0, KEY_READ, &tls12_client) == ERROR_SUCCESS) {
475         size = sizeof(DWORD);
476         if (RegQueryValueExW(tls12_client, DisabledByDefault, NULL, &type,  (LPBYTE) &val, &size) == ERROR_SUCCESS
477             && type == REG_DWORD) {
478             tls_option |= val?SSL_OP_NO_TLSv1_2:0;
479         }
480         RegCloseKey(tls12_client);
481     }
482     if (RegOpenKeyExW(hkey, TLS11_Client, 0, KEY_READ, &tls11_client) == ERROR_SUCCESS) {
483         size = sizeof(DWORD);
484         if (RegQueryValueExW(tls11_client, DisabledByDefault, NULL, &type,  (LPBYTE) &val, &size) == ERROR_SUCCESS
485             && type == REG_DWORD) {
486             tls_option |= val?SSL_OP_NO_TLSv1_1:0;
487         }
488         RegCloseKey(tls11_client);
489     }
490     RegCloseKey(hkey);
491 #endif
492     return tls_option;
493 }
494 #endif /* SONAME_LIBSSL */
495
496 static CRITICAL_SECTION init_ssl_cs;
497 static CRITICAL_SECTION_DEBUG init_ssl_cs_debug =
498 {
499     0, 0, &init_ssl_cs,
500     { &init_ssl_cs_debug.ProcessLocksList,
501       &init_ssl_cs_debug.ProcessLocksList },
502     0, 0, { (DWORD_PTR)(__FILE__ ": init_ssl_cs") }
503 };
504 static CRITICAL_SECTION init_ssl_cs = { &init_ssl_cs_debug, -1, 0, 0, 0, 0 };
505
506 static DWORD init_openssl(void)
507 {
508 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
509     int i;
510
511     if(OpenSSL_ssl_handle)
512         return ERROR_SUCCESS;
513
514     OpenSSL_ssl_handle = wine_dlopen(SONAME_LIBSSL, RTLD_NOW, NULL, 0);
515     if(!OpenSSL_ssl_handle) {
516         ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n", SONAME_LIBSSL);
517         return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
518     }
519
520     OpenSSL_crypto_handle = wine_dlopen(SONAME_LIBCRYPTO, RTLD_NOW, NULL, 0);
521     if(!OpenSSL_crypto_handle) {
522         ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n", SONAME_LIBCRYPTO);
523         return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
524     }
525
526     /* mmm nice ugly macroness */
527 #define DYNSSL(x) \
528     p##x = wine_dlsym(OpenSSL_ssl_handle, #x, NULL, 0); \
529     if (!p##x) { \
530         ERR("failed to load symbol %s\n", #x); \
531         return ERROR_INTERNET_SECURITY_CHANNEL_ERROR; \
532     }
533
534     DYNSSL(SSL_library_init);
535     DYNSSL(SSL_load_error_strings);
536     DYNSSL(SSLv23_method);
537     DYNSSL(SSL_CTX_free);
538     DYNSSL(SSL_CTX_new);
539     DYNSSL(SSL_CTX_ctrl);
540     DYNSSL(SSL_new);
541     DYNSSL(SSL_free);
542     DYNSSL(SSL_ctrl);
543     DYNSSL(SSL_set_fd);
544     DYNSSL(SSL_connect);
545     DYNSSL(SSL_shutdown);
546     DYNSSL(SSL_write);
547     DYNSSL(SSL_read);
548     DYNSSL(SSL_pending);
549     DYNSSL(SSL_get_error);
550     DYNSSL(SSL_get_ex_new_index);
551     DYNSSL(SSL_get_ex_data);
552     DYNSSL(SSL_set_ex_data);
553     DYNSSL(SSL_get_ex_data_X509_STORE_CTX_idx);
554     DYNSSL(SSL_get_peer_certificate);
555     DYNSSL(SSL_CTX_get_timeout);
556     DYNSSL(SSL_CTX_set_timeout);
557     DYNSSL(SSL_CTX_set_default_verify_paths);
558     DYNSSL(SSL_CTX_set_verify);
559     DYNSSL(SSL_get_current_cipher);
560     DYNSSL(SSL_CIPHER_get_bits);
561 #undef DYNSSL
562
563 #define DYNCRYPTO(x) \
564     p##x = wine_dlsym(OpenSSL_crypto_handle, #x, NULL, 0); \
565     if (!p##x) { \
566         ERR("failed to load symbol %s\n", #x); \
567         return ERROR_INTERNET_SECURITY_CHANNEL_ERROR; \
568     }
569
570     DYNCRYPTO(BIO_new_fp);
571     DYNCRYPTO(CRYPTO_num_locks);
572     DYNCRYPTO(CRYPTO_set_id_callback);
573     DYNCRYPTO(CRYPTO_set_locking_callback);
574     DYNCRYPTO(ERR_free_strings);
575     DYNCRYPTO(ERR_get_error);
576     DYNCRYPTO(ERR_error_string);
577     DYNCRYPTO(X509_STORE_CTX_get_ex_data);
578     DYNCRYPTO(X509_STORE_CTX_get_chain);
579     DYNCRYPTO(i2d_X509);
580     DYNCRYPTO(sk_num);
581     DYNCRYPTO(sk_value);
582 #undef DYNCRYPTO
583
584 #define pSSL_CTX_set_options(ctx,op) \
585        pSSL_CTX_ctrl((ctx),SSL_CTRL_OPTIONS,(op),NULL)
586 #define pSSL_set_options(ssl,op) \
587        pSSL_ctrl((ssl),SSL_CTRL_OPTIONS,(op),NULL)
588
589     pSSL_library_init();
590     pSSL_load_error_strings();
591     pBIO_new_fp(stderr, BIO_NOCLOSE); /* FIXME: should use winedebug stuff */
592
593     meth = pSSLv23_method();
594     ctx = pSSL_CTX_new(meth);
595     pSSL_CTX_set_options(ctx, get_tls_option());
596     if(!pSSL_CTX_set_default_verify_paths(ctx)) {
597         ERR("SSL_CTX_set_default_verify_paths failed: %s\n",
598             pERR_error_string(pERR_get_error(), 0));
599         return ERROR_OUTOFMEMORY;
600     }
601
602     error_idx = pSSL_get_ex_new_index(0, (void *)"error index", NULL, NULL, NULL);
603     if(error_idx == -1) {
604         ERR("SSL_get_ex_new_index failed; %s\n", pERR_error_string(pERR_get_error(), 0));
605         return ERROR_OUTOFMEMORY;
606     }
607
608     conn_idx = pSSL_get_ex_new_index(0, (void *)"netconn index", NULL, NULL, NULL);
609     if(conn_idx == -1) {
610         ERR("SSL_get_ex_new_index failed; %s\n", pERR_error_string(pERR_get_error(), 0));
611         return ERROR_OUTOFMEMORY;
612     }
613
614     pSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, netconn_secure_verify);
615
616     pCRYPTO_set_id_callback(ssl_thread_id);
617     num_ssl_locks = pCRYPTO_num_locks();
618     ssl_locks = heap_alloc(num_ssl_locks * sizeof(CRITICAL_SECTION));
619     if(!ssl_locks)
620         return ERROR_OUTOFMEMORY;
621
622     for(i = 0; i < num_ssl_locks; i++)
623     {
624         InitializeCriticalSection(&ssl_locks[i]);
625         ssl_locks[i].DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": ssl_locks");
626     }
627     pCRYPTO_set_locking_callback(ssl_lock_callback);
628
629     return ERROR_SUCCESS;
630 #else
631     FIXME("can't use SSL, not compiled in.\n");
632     return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
633 #endif
634 }
635
636 static DWORD create_netconn_socket(server_t *server, netconn_t *netconn, DWORD timeout)
637 {
638     int result, flag;
639
640     assert(server->addr_len);
641     result = netconn->socketFD = socket(server->addr.ss_family, SOCK_STREAM, 0);
642     if(result != -1) {
643         flag = 1;
644         ioctlsocket(netconn->socketFD, FIONBIO, &flag);
645         result = connect(netconn->socketFD, (struct sockaddr*)&server->addr, server->addr_len);
646         if(result == -1)
647         {
648             if (sock_get_error(errno) == WSAEINPROGRESS) {
649                 struct pollfd pfd;
650                 int res;
651
652                 pfd.fd = netconn->socketFD;
653                 pfd.events = POLLOUT;
654                 res = poll(&pfd, 1, timeout);
655                 if (!res)
656                 {
657                     closesocket(netconn->socketFD);
658                     return ERROR_INTERNET_CANNOT_CONNECT;
659                 }
660                 else if (res > 0)
661                 {
662                     int err;
663                     socklen_t len = sizeof(err);
664                     if (!getsockopt(netconn->socketFD, SOL_SOCKET, SO_ERROR, &err, &len) && !err)
665                         result = 0;
666                 }
667             }
668         }
669         if(result == -1)
670             closesocket(netconn->socketFD);
671         else {
672             flag = 0;
673             ioctlsocket(netconn->socketFD, FIONBIO, &flag);
674         }
675     }
676     if(result == -1)
677         return sock_get_error(errno);
678
679 #ifdef TCP_NODELAY
680     flag = 1;
681     result = setsockopt(netconn->socketFD, IPPROTO_TCP, TCP_NODELAY, (void*)&flag, sizeof(flag));
682     if(result < 0)
683         WARN("setsockopt(TCP_NODELAY) failed\n");
684 #endif
685
686     return ERROR_SUCCESS;
687 }
688
689 DWORD create_netconn(BOOL useSSL, server_t *server, DWORD security_flags, BOOL mask_errors, DWORD timeout, netconn_t **ret)
690 {
691     netconn_t *netconn;
692     int result;
693
694     if(useSSL) {
695         DWORD res;
696
697         TRACE("using SSL connection\n");
698
699         EnterCriticalSection(&init_ssl_cs);
700         res = init_openssl();
701         LeaveCriticalSection(&init_ssl_cs);
702         if(res != ERROR_SUCCESS)
703             return res;
704     }
705
706     netconn = heap_alloc_zero(sizeof(*netconn));
707     if(!netconn)
708         return ERROR_OUTOFMEMORY;
709
710     netconn->socketFD = -1;
711     netconn->security_flags = security_flags | server->security_flags;
712     netconn->mask_errors = mask_errors;
713     list_init(&netconn->pool_entry);
714
715     result = create_netconn_socket(server, netconn, timeout);
716     if (result != ERROR_SUCCESS) {
717         heap_free(netconn);
718         return result;
719     }
720
721     server_addref(server);
722     netconn->server = server;
723     *ret = netconn;
724     return result;
725 }
726
727 void free_netconn(netconn_t *netconn)
728 {
729     server_release(netconn->server);
730
731 #ifdef SONAME_LIBSSL
732     if (netconn->ssl_s) {
733         pSSL_shutdown(netconn->ssl_s);
734         pSSL_free(netconn->ssl_s);
735     }
736 #endif
737
738     closesocket(netconn->socketFD);
739     heap_free(netconn);
740 }
741
742 void NETCON_unload(void)
743 {
744 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
745     if (OpenSSL_crypto_handle)
746     {
747         pERR_free_strings();
748         wine_dlclose(OpenSSL_crypto_handle, NULL, 0);
749     }
750     if (OpenSSL_ssl_handle)
751     {
752         if (ctx)
753             pSSL_CTX_free(ctx);
754         wine_dlclose(OpenSSL_ssl_handle, NULL, 0);
755     }
756     if (ssl_locks)
757     {
758         int i;
759         for (i = 0; i < num_ssl_locks; i++)
760         {
761             ssl_locks[i].DebugInfo->Spare[0] = 0;
762             DeleteCriticalSection(&ssl_locks[i]);
763         }
764         heap_free(ssl_locks);
765     }
766 #endif
767 }
768
769 /* translate a unix error code into a winsock one */
770 int sock_get_error( int err )
771 {
772 #if !defined(__MINGW32__) && !defined (_MSC_VER)
773     switch (err)
774     {
775         case EINTR:             return WSAEINTR;
776         case EBADF:             return WSAEBADF;
777         case EPERM:
778         case EACCES:            return WSAEACCES;
779         case EFAULT:            return WSAEFAULT;
780         case EINVAL:            return WSAEINVAL;
781         case EMFILE:            return WSAEMFILE;
782         case EWOULDBLOCK:       return WSAEWOULDBLOCK;
783         case EINPROGRESS:       return WSAEINPROGRESS;
784         case EALREADY:          return WSAEALREADY;
785         case ENOTSOCK:          return WSAENOTSOCK;
786         case EDESTADDRREQ:      return WSAEDESTADDRREQ;
787         case EMSGSIZE:          return WSAEMSGSIZE;
788         case EPROTOTYPE:        return WSAEPROTOTYPE;
789         case ENOPROTOOPT:       return WSAENOPROTOOPT;
790         case EPROTONOSUPPORT:   return WSAEPROTONOSUPPORT;
791         case ESOCKTNOSUPPORT:   return WSAESOCKTNOSUPPORT;
792         case EOPNOTSUPP:        return WSAEOPNOTSUPP;
793         case EPFNOSUPPORT:      return WSAEPFNOSUPPORT;
794         case EAFNOSUPPORT:      return WSAEAFNOSUPPORT;
795         case EADDRINUSE:        return WSAEADDRINUSE;
796         case EADDRNOTAVAIL:     return WSAEADDRNOTAVAIL;
797         case ENETDOWN:          return WSAENETDOWN;
798         case ENETUNREACH:       return WSAENETUNREACH;
799         case ENETRESET:         return WSAENETRESET;
800         case ECONNABORTED:      return WSAECONNABORTED;
801         case EPIPE:
802         case ECONNRESET:        return WSAECONNRESET;
803         case ENOBUFS:           return WSAENOBUFS;
804         case EISCONN:           return WSAEISCONN;
805         case ENOTCONN:          return WSAENOTCONN;
806         case ESHUTDOWN:         return WSAESHUTDOWN;
807         case ETOOMANYREFS:      return WSAETOOMANYREFS;
808         case ETIMEDOUT:         return WSAETIMEDOUT;
809         case ECONNREFUSED:      return WSAECONNREFUSED;
810         case ELOOP:             return WSAELOOP;
811         case ENAMETOOLONG:      return WSAENAMETOOLONG;
812         case EHOSTDOWN:         return WSAEHOSTDOWN;
813         case EHOSTUNREACH:      return WSAEHOSTUNREACH;
814         case ENOTEMPTY:         return WSAENOTEMPTY;
815 #ifdef EPROCLIM
816         case EPROCLIM:          return WSAEPROCLIM;
817 #endif
818 #ifdef EUSERS
819         case EUSERS:            return WSAEUSERS;
820 #endif
821 #ifdef EDQUOT
822         case EDQUOT:            return WSAEDQUOT;
823 #endif
824 #ifdef ESTALE
825         case ESTALE:            return WSAESTALE;
826 #endif
827 #ifdef EREMOTE
828         case EREMOTE:           return WSAEREMOTE;
829 #endif
830     default: errno=err; perror("sock_set_error"); return WSAEFAULT;
831     }
832 #endif
833     return err;
834 }
835
836 #ifdef SONAME_LIBSSL
837 static DWORD netcon_secure_connect_setup(netconn_t *connection, long tls_option)
838 {
839     void *ssl_s;
840     DWORD res;
841     int bits;
842
843     ssl_s = pSSL_new(ctx);
844     if (!ssl_s)
845     {
846         ERR("SSL_new failed: %s\n",
847             pERR_error_string(pERR_get_error(), 0));
848         return ERROR_OUTOFMEMORY;
849     }
850
851     pSSL_set_options(ssl_s, tls_option);
852     if (!pSSL_set_fd(ssl_s, connection->socketFD))
853     {
854         ERR("SSL_set_fd failed: %s\n",
855             pERR_error_string(pERR_get_error(), 0));
856         res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
857         goto fail;
858     }
859
860     if (!pSSL_set_ex_data(ssl_s, conn_idx, connection))
861     {
862         ERR("SSL_set_ex_data failed: %s\n",
863             pERR_error_string(pERR_get_error(), 0));
864         res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
865         goto fail;
866     }
867     if (pSSL_connect(ssl_s) <= 0)
868     {
869         res = (DWORD_PTR)pSSL_get_ex_data(ssl_s, error_idx);
870         if (!res)
871             res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
872         ERR("SSL_connect failed: %d\n", res);
873         goto fail;
874     }
875
876     connection->ssl_s = ssl_s;
877
878     bits = NETCON_GetCipherStrength(connection);
879     if (bits >= 128)
880         connection->security_flags |= SECURITY_FLAG_STRENGTH_STRONG;
881     else if (bits >= 56)
882         connection->security_flags |= SECURITY_FLAG_STRENGTH_MEDIUM;
883     else
884         connection->security_flags |= SECURITY_FLAG_STRENGTH_WEAK;
885     connection->security_flags |= SECURITY_FLAG_SECURE;
886
887     if(connection->mask_errors)
888         connection->server->security_flags = connection->security_flags;
889     return ERROR_SUCCESS;
890
891 fail:
892     if (ssl_s)
893     {
894         pSSL_shutdown(ssl_s);
895         pSSL_free(ssl_s);
896     }
897     return res;
898 }
899 #endif
900
901 /******************************************************************************
902  * NETCON_secure_connect
903  * Initiates a secure connection over an existing plaintext connection.
904  */
905 DWORD NETCON_secure_connect(netconn_t *connection, server_t *server)
906 {
907     DWORD res = ERROR_NOT_SUPPORTED;
908 #ifdef SONAME_LIBSSL
909     /* can't connect if we are already connected */
910     if (connection->ssl_s)
911     {
912         ERR("already connected\n");
913         return ERROR_INTERNET_CANNOT_CONNECT;
914     }
915
916     connection->useSSL = TRUE;
917     if(server != connection->server) {
918         server_release(connection->server);
919         server_addref(server);
920         connection->server = server;
921     }
922
923     /* connect with given TLS options */
924     res = netcon_secure_connect_setup(connection, get_tls_option());
925     if (res == ERROR_SUCCESS)
926         return res;
927
928 #ifdef SSL_OP_NO_TLSv1_2
929     /* FIXME: when got version alert and FIN from server */
930     /* fallback to connect without TLSv1.1/TLSv1.2        */
931     if (res == ERROR_INTERNET_SECURITY_CHANNEL_ERROR)
932     {
933         closesocket(connection->socketFD);
934         pSSL_CTX_set_options(ctx,SSL_OP_NO_TLSv1_1|SSL_OP_NO_TLSv1_2);
935         res = create_netconn_socket(connection->server, connection, 500);
936         if (res != ERROR_SUCCESS)
937             return res;
938         res = netcon_secure_connect_setup(connection, get_tls_option()|SSL_OP_NO_TLSv1_1|SSL_OP_NO_TLSv1_2);
939     }
940 #endif
941 #endif
942     return res;
943 }
944
945 /******************************************************************************
946  * NETCON_send
947  * Basically calls 'send()' unless we should use SSL
948  * number of chars send is put in *sent
949  */
950 DWORD NETCON_send(netconn_t *connection, const void *msg, size_t len, int flags,
951                 int *sent /* out */)
952 {
953     if (!connection->useSSL)
954     {
955         *sent = send(connection->socketFD, msg, len, flags);
956         if (*sent == -1)
957             return sock_get_error(errno);
958         return ERROR_SUCCESS;
959     }
960     else
961     {
962 #ifdef SONAME_LIBSSL
963         if(!connection->ssl_s) {
964             FIXME("not connected\n");
965             return ERROR_NOT_SUPPORTED;
966         }
967         if (flags)
968             FIXME("SSL_write doesn't support any flags (%08x)\n", flags);
969         *sent = pSSL_write(connection->ssl_s, msg, len);
970         if (*sent < 1 && len)
971             return ERROR_INTERNET_CONNECTION_ABORTED;
972         return ERROR_SUCCESS;
973 #else
974         return ERROR_NOT_SUPPORTED;
975 #endif
976     }
977 }
978
979 /******************************************************************************
980  * NETCON_recv
981  * Basically calls 'recv()' unless we should use SSL
982  * number of chars received is put in *recvd
983  */
984 DWORD NETCON_recv(netconn_t *connection, void *buf, size_t len, int flags,
985                 int *recvd /* out */)
986 {
987     *recvd = 0;
988     if (!len)
989         return ERROR_SUCCESS;
990     if (!connection->useSSL)
991     {
992         *recvd = recv(connection->socketFD, buf, len, flags);
993         return *recvd == -1 ? sock_get_error(errno) :  ERROR_SUCCESS;
994     }
995     else
996     {
997 #ifdef SONAME_LIBSSL
998         if(!connection->ssl_s) {
999             FIXME("not connected\n");
1000             return ERROR_NOT_SUPPORTED;
1001         }
1002         *recvd = pSSL_read(connection->ssl_s, buf, len);
1003
1004         /* Check if EOF was received */
1005         if(!*recvd && (pSSL_get_error(connection->ssl_s, *recvd)==SSL_ERROR_ZERO_RETURN
1006                     || pSSL_get_error(connection->ssl_s, *recvd)==SSL_ERROR_SYSCALL))
1007             return ERROR_SUCCESS;
1008
1009         return *recvd > 0 ? ERROR_SUCCESS : ERROR_INTERNET_CONNECTION_ABORTED;
1010 #else
1011         return ERROR_NOT_SUPPORTED;
1012 #endif
1013     }
1014 }
1015
1016 /******************************************************************************
1017  * NETCON_query_data_available
1018  * Returns the number of bytes of peeked data plus the number of bytes of
1019  * queued, but unread data.
1020  */
1021 BOOL NETCON_query_data_available(netconn_t *connection, DWORD *available)
1022 {
1023     *available = 0;
1024
1025     if (!connection->useSSL)
1026     {
1027 #ifdef FIONREAD
1028         int unread;
1029         int retval = ioctlsocket(connection->socketFD, FIONREAD, &unread);
1030         if (!retval)
1031         {
1032             TRACE("%d bytes of queued, but unread data\n", unread);
1033             *available += unread;
1034         }
1035 #endif
1036     }
1037     else
1038     {
1039 #ifdef SONAME_LIBSSL
1040         *available = connection->ssl_s ? pSSL_pending(connection->ssl_s) : 0;
1041 #endif
1042     }
1043     return TRUE;
1044 }
1045
1046 BOOL NETCON_is_alive(netconn_t *netconn)
1047 {
1048 #ifdef MSG_DONTWAIT
1049     ssize_t len;
1050     BYTE b;
1051
1052     len = recv(netconn->socketFD, &b, 1, MSG_PEEK|MSG_DONTWAIT);
1053     return len == 1 || (len == -1 && errno == EWOULDBLOCK);
1054 #elif defined(__MINGW32__) || defined(_MSC_VER)
1055     ULONG mode;
1056     int len;
1057     char b;
1058
1059     mode = 1;
1060     if(!ioctlsocket(netconn->socketFD, FIONBIO, &mode))
1061         return FALSE;
1062
1063     len = recv(netconn->socketFD, &b, 1, MSG_PEEK);
1064
1065     mode = 0;
1066     if(!ioctlsocket(netconn->socketFD, FIONBIO, &mode))
1067         return FALSE;
1068
1069     return len == 1 || (len == -1 && errno == WSAEWOULDBLOCK);
1070 #else
1071     FIXME("not supported on this platform\n");
1072     return TRUE;
1073 #endif
1074 }
1075
1076 LPCVOID NETCON_GetCert(netconn_t *connection)
1077 {
1078 #ifdef SONAME_LIBSSL
1079     X509* cert;
1080     LPCVOID r = NULL;
1081
1082     if (!connection->ssl_s)
1083         return NULL;
1084
1085     cert = pSSL_get_peer_certificate(connection->ssl_s);
1086     r = X509_to_cert_context(cert);
1087     return r;
1088 #else
1089     return NULL;
1090 #endif
1091 }
1092
1093 int NETCON_GetCipherStrength(netconn_t *connection)
1094 {
1095 #ifdef SONAME_LIBSSL
1096 #if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER >= 0x0090707f)
1097     const SSL_CIPHER *cipher;
1098 #else
1099     SSL_CIPHER *cipher;
1100 #endif
1101     int bits = 0;
1102
1103     if (!connection->ssl_s)
1104         return 0;
1105     cipher = pSSL_get_current_cipher(connection->ssl_s);
1106     if (!cipher)
1107         return 0;
1108     pSSL_CIPHER_get_bits(cipher, &bits);
1109     return bits;
1110 #else
1111     return 0;
1112 #endif
1113 }
1114
1115 DWORD NETCON_set_timeout(netconn_t *connection, BOOL send, DWORD value)
1116 {
1117     int result;
1118     struct timeval tv;
1119
1120     /* value is in milliseconds, convert to struct timeval */
1121     if (value == INFINITE)
1122     {
1123         tv.tv_sec = 0;
1124         tv.tv_usec = 0;
1125     }
1126     else
1127     {
1128         tv.tv_sec = value / 1000;
1129         tv.tv_usec = (value % 1000) * 1000;
1130     }
1131     result = setsockopt(connection->socketFD, SOL_SOCKET,
1132                         send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv,
1133                         sizeof(tv));
1134     if (result == -1)
1135     {
1136         WARN("setsockopt failed (%s)\n", strerror(errno));
1137         return sock_get_error(errno);
1138     }
1139     return ERROR_SUCCESS;
1140 }