wininet: Use the correct struct in a sizeof.
[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_new);
128 MAKE_FUNCPTR(SSL_free);
129 MAKE_FUNCPTR(SSL_set_fd);
130 MAKE_FUNCPTR(SSL_connect);
131 MAKE_FUNCPTR(SSL_shutdown);
132 MAKE_FUNCPTR(SSL_write);
133 MAKE_FUNCPTR(SSL_read);
134 MAKE_FUNCPTR(SSL_pending);
135 MAKE_FUNCPTR(SSL_get_error);
136 MAKE_FUNCPTR(SSL_get_ex_new_index);
137 MAKE_FUNCPTR(SSL_get_ex_data);
138 MAKE_FUNCPTR(SSL_set_ex_data);
139 MAKE_FUNCPTR(SSL_get_ex_data_X509_STORE_CTX_idx);
140 MAKE_FUNCPTR(SSL_get_peer_certificate);
141 MAKE_FUNCPTR(SSL_CTX_get_timeout);
142 MAKE_FUNCPTR(SSL_CTX_set_timeout);
143 MAKE_FUNCPTR(SSL_CTX_set_default_verify_paths);
144 MAKE_FUNCPTR(SSL_CTX_set_verify);
145 MAKE_FUNCPTR(SSL_get_current_cipher);
146 MAKE_FUNCPTR(SSL_CIPHER_get_bits);
147
148 /* OpenSSL's libcrypto functions that we use */
149 MAKE_FUNCPTR(BIO_new_fp);
150 MAKE_FUNCPTR(CRYPTO_num_locks);
151 MAKE_FUNCPTR(CRYPTO_set_id_callback);
152 MAKE_FUNCPTR(CRYPTO_set_locking_callback);
153 MAKE_FUNCPTR(ERR_free_strings);
154 MAKE_FUNCPTR(ERR_get_error);
155 MAKE_FUNCPTR(ERR_error_string);
156 MAKE_FUNCPTR(X509_STORE_CTX_get_ex_data);
157 MAKE_FUNCPTR(X509_STORE_CTX_get_chain);
158 MAKE_FUNCPTR(i2d_X509);
159 MAKE_FUNCPTR(sk_num);
160 MAKE_FUNCPTR(sk_value);
161 #undef MAKE_FUNCPTR
162
163 static CRITICAL_SECTION *ssl_locks;
164 static unsigned int num_ssl_locks;
165
166 static unsigned long ssl_thread_id(void)
167 {
168     return GetCurrentThreadId();
169 }
170
171 static void ssl_lock_callback(int mode, int type, const char *file, int line)
172 {
173     if (mode & CRYPTO_LOCK)
174         EnterCriticalSection(&ssl_locks[type]);
175     else
176         LeaveCriticalSection(&ssl_locks[type]);
177 }
178
179 static PCCERT_CONTEXT X509_to_cert_context(X509 *cert)
180 {
181     unsigned char* buffer,*p;
182     INT len;
183     BOOL malloced = FALSE;
184     PCCERT_CONTEXT ret;
185
186     p = NULL;
187     len = pi2d_X509(cert,&p);
188     /*
189      * SSL 0.9.7 and above malloc the buffer if it is null.
190      * however earlier version do not and so we would need to alloc the buffer.
191      *
192      * see the i2d_X509 man page for more details.
193      */
194     if (!p)
195     {
196         buffer = heap_alloc(len);
197         p = buffer;
198         len = pi2d_X509(cert,&p);
199     }
200     else
201     {
202         buffer = p;
203         malloced = TRUE;
204     }
205
206     ret = CertCreateCertificateContext(X509_ASN_ENCODING,buffer,len);
207
208     if (malloced)
209         free(buffer);
210     else
211         heap_free(buffer);
212
213     return ret;
214 }
215
216 static DWORD netconn_verify_cert(netconn_t *conn, PCCERT_CONTEXT cert, HCERTSTORE store)
217 {
218     BOOL ret;
219     CERT_CHAIN_PARA chainPara = { sizeof(chainPara), { 0 } };
220     PCCERT_CHAIN_CONTEXT chain;
221     char oid_server_auth[] = szOID_PKIX_KP_SERVER_AUTH;
222     char *server_auth[] = { oid_server_auth };
223     DWORD err = ERROR_SUCCESS, chainFlags = 0, errors;
224
225     static const DWORD supportedErrors =
226         CERT_TRUST_IS_NOT_TIME_VALID |
227         CERT_TRUST_IS_UNTRUSTED_ROOT |
228         CERT_TRUST_IS_PARTIAL_CHAIN |
229         CERT_TRUST_IS_OFFLINE_REVOCATION |
230         CERT_TRUST_REVOCATION_STATUS_UNKNOWN |
231         CERT_TRUST_IS_REVOKED |
232         CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
233
234     TRACE("verifying %s\n", debugstr_w(conn->server->name));
235
236     chainPara.RequestedUsage.Usage.cUsageIdentifier = 1;
237     chainPara.RequestedUsage.Usage.rgpszUsageIdentifier = server_auth;
238     if (!(conn->security_flags & SECURITY_FLAG_IGNORE_REVOCATION))
239         chainFlags |= CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT;
240
241     if (!(ret = CertGetCertificateChain(NULL, cert, NULL, store, &chainPara, chainFlags, NULL, &chain))) {
242         TRACE("failed\n");
243         return GetLastError();
244     }
245
246     errors = chain->TrustStatus.dwErrorStatus;
247
248     if (chain->TrustStatus.dwErrorStatus & ~supportedErrors) {
249         WARN("error status %x\n", chain->TrustStatus.dwErrorStatus & ~supportedErrors);
250         if(conn->mask_errors)
251             WARN("CERT_TRUST_IS_NOT_TIME_VALID, unknown error flags\n");
252         err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_INVALID_CERT;
253         errors &= supportedErrors;
254     }
255
256     if(errors & CERT_TRUST_IS_NOT_TIME_VALID) {
257         WARN("CERT_TRUST_IS_NOT_TIME_VALID\n");
258         if(conn->mask_errors)
259             conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_DATE;
260         if(!(conn->security_flags & SECURITY_FLAG_IGNORE_CERT_DATE_INVALID))
261             err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_CERT_DATE_INVALID;
262         errors &= ~CERT_TRUST_IS_NOT_TIME_VALID;
263     }
264
265     if(errors & CERT_TRUST_IS_UNTRUSTED_ROOT) {
266         WARN("CERT_TRUST_IS_UNTRUSTED_ROOT\n");
267         if(conn->mask_errors)
268             WARN("CERT_TRUST_IS_UNTRUSTED_ROOT, unknown flags\n");
269         if(!(conn->security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA))
270             err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_INVALID_CA;
271         errors &= ~CERT_TRUST_IS_UNTRUSTED_ROOT;
272     }
273
274     /* This seems strange, but that's what tests show */
275     if(errors & CERT_TRUST_IS_PARTIAL_CHAIN) {
276         WARN("CERT_TRUST_IS_PARTIAL_CHAIN\n");
277         if(!(conn->security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA)) {
278             if(!(conn->security_flags & _SECURITY_FLAG_CERT_REV_FAILED))
279                 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_CERT_REV_FAILED;
280             else
281                 err = conn->mask_errors ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_INVALID_CA;
282         }
283         if(conn->mask_errors) {
284             if(!(conn->security_flags & _SECURITY_FLAG_CERT_REV_FAILED))
285                 conn->security_flags |= _SECURITY_FLAG_CERT_REV_FAILED;
286             else
287                 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CA;
288         }
289         errors &= ~CERT_TRUST_IS_PARTIAL_CHAIN;
290     }
291
292     if(errors & (CERT_TRUST_IS_OFFLINE_REVOCATION | CERT_TRUST_REVOCATION_STATUS_UNKNOWN)) {
293         WARN("CERT_TRUST_IS_OFFLINE_REVOCATION | CERT_TRUST_REVOCATION_STATUS_UNKNOWN\n");
294         if(conn->mask_errors)
295             WARN("TRUST_IS_OFFLINE_REVOCATION | CERT_TRUST_REVOCATION_STATUS_UNKNOWN, unknown error flags\n");
296         if(!(conn->security_flags & SECURITY_FLAG_IGNORE_REVOCATION))
297             err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_CERT_NO_REV;
298         errors &= ~(CERT_TRUST_IS_OFFLINE_REVOCATION | CERT_TRUST_REVOCATION_STATUS_UNKNOWN);
299     }
300
301     if(errors & CERT_TRUST_IS_REVOKED) {
302         WARN("CERT_TRUST_IS_REVOKED\n");
303         if(conn->mask_errors)
304             WARN("TRUST_IS_OFFLINE_REVOCATION | CERT_TRUST_REVOCATION_STATUS_UNKNOWN, unknown error flags\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_REVOKED;
307         errors &= ~CERT_TRUST_IS_REVOKED;
308     }
309
310     if(errors & CERT_TRUST_IS_NOT_VALID_FOR_USAGE) {
311         WARN("CERT_TRUST_IS_NOT_VALID_FOR_USAGE\n");
312         if(conn->mask_errors)
313             WARN("CERT_TRUST_IS_NOT_VALID_FOR_USAGE, unknown error flags\n");
314         if(!(conn->security_flags & SECURITY_FLAG_IGNORE_WRONG_USAGE))
315             err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_INVALID_CERT;
316         errors &= ~CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
317     }
318
319     if(!err || conn->mask_errors) {
320         CERT_CHAIN_POLICY_PARA policyPara;
321         SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslExtraPolicyPara;
322         CERT_CHAIN_POLICY_STATUS policyStatus;
323         CERT_CHAIN_CONTEXT chainCopy;
324
325         /* Clear chain->TrustStatus.dwErrorStatus so
326          * CertVerifyCertificateChainPolicy will verify additional checks
327          * rather than stopping with an existing, ignored error.
328          */
329         memcpy(&chainCopy, chain, sizeof(chainCopy));
330         chainCopy.TrustStatus.dwErrorStatus = 0;
331         sslExtraPolicyPara.u.cbSize = sizeof(sslExtraPolicyPara);
332         sslExtraPolicyPara.dwAuthType = AUTHTYPE_SERVER;
333         sslExtraPolicyPara.pwszServerName = conn->server->name;
334         sslExtraPolicyPara.fdwChecks = conn->security_flags;
335         policyPara.cbSize = sizeof(policyPara);
336         policyPara.dwFlags = 0;
337         policyPara.pvExtraPolicyPara = &sslExtraPolicyPara;
338         ret = CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL,
339                 &chainCopy, &policyPara, &policyStatus);
340         /* Any error in the policy status indicates that the
341          * policy couldn't be verified.
342          */
343         if(ret) {
344             if(policyStatus.dwError == CERT_E_CN_NO_MATCH) {
345                 WARN("CERT_E_CN_NO_MATCH\n");
346                 if(conn->mask_errors)
347                     conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CN;
348                 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_CERT_CN_INVALID;
349             }else if(policyStatus.dwError) {
350                 WARN("policyStatus.dwError %x\n", policyStatus.dwError);
351                 if(conn->mask_errors)
352                     WARN("unknown error flags for policy status %x\n", policyStatus.dwError);
353                 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_INVALID_CERT;
354             }
355         }else {
356             err = GetLastError();
357         }
358     }
359
360     if(err) {
361         WARN("failed %u\n", err);
362         CertFreeCertificateChain(chain);
363         if(conn->server->cert_chain) {
364             CertFreeCertificateChain(conn->server->cert_chain);
365             conn->server->cert_chain = NULL;
366         }
367         if(conn->mask_errors)
368             conn->server->security_flags |= conn->security_flags & _SECURITY_ERROR_FLAGS_MASK;
369         return err;
370     }
371
372     /* FIXME: Reuse cached chain */
373     if(conn->server->cert_chain)
374         CertFreeCertificateChain(chain);
375     else
376         conn->server->cert_chain = chain;
377     return ERROR_SUCCESS;
378 }
379
380 static int netconn_secure_verify(int preverify_ok, X509_STORE_CTX *ctx)
381 {
382     SSL *ssl;
383     BOOL ret = FALSE;
384     HCERTSTORE store = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
385         CERT_STORE_CREATE_NEW_FLAG, NULL);
386     netconn_t *conn;
387
388     ssl = pX509_STORE_CTX_get_ex_data(ctx,
389         pSSL_get_ex_data_X509_STORE_CTX_idx());
390     conn = pSSL_get_ex_data(ssl, conn_idx);
391     if (store)
392     {
393         X509 *cert;
394         int i;
395         PCCERT_CONTEXT endCert = NULL;
396         struct stack_st *chain = (struct stack_st *)pX509_STORE_CTX_get_chain( ctx );
397
398         ret = TRUE;
399         for (i = 0; ret && i < psk_num(chain); i++)
400         {
401             PCCERT_CONTEXT context;
402
403             cert = (X509 *)psk_value(chain, i);
404             if ((context = X509_to_cert_context(cert)))
405             {
406                 ret = CertAddCertificateContextToStore(store, context,
407                         CERT_STORE_ADD_ALWAYS, i ? NULL : &endCert);
408                 CertFreeCertificateContext(context);
409             }
410         }
411         if (!endCert) ret = FALSE;
412         if (ret)
413         {
414             DWORD_PTR err = netconn_verify_cert(conn, endCert, store);
415
416             if (err)
417             {
418                 pSSL_set_ex_data(ssl, error_idx, (void *)err);
419                 ret = FALSE;
420             }
421         }
422         CertFreeCertificateContext(endCert);
423         CertCloseStore(store, 0);
424     }
425     return ret;
426 }
427
428 #endif
429
430 static CRITICAL_SECTION init_ssl_cs;
431 static CRITICAL_SECTION_DEBUG init_ssl_cs_debug =
432 {
433     0, 0, &init_ssl_cs,
434     { &init_ssl_cs_debug.ProcessLocksList,
435       &init_ssl_cs_debug.ProcessLocksList },
436     0, 0, { (DWORD_PTR)(__FILE__ ": init_ssl_cs") }
437 };
438 static CRITICAL_SECTION init_ssl_cs = { &init_ssl_cs_debug, -1, 0, 0, 0, 0 };
439
440 static DWORD init_openssl(void)
441 {
442 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
443     int i;
444
445     if(OpenSSL_ssl_handle)
446         return ERROR_SUCCESS;
447
448     OpenSSL_ssl_handle = wine_dlopen(SONAME_LIBSSL, RTLD_NOW, NULL, 0);
449     if(!OpenSSL_ssl_handle) {
450         ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n", SONAME_LIBSSL);
451         return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
452     }
453
454     OpenSSL_crypto_handle = wine_dlopen(SONAME_LIBCRYPTO, RTLD_NOW, NULL, 0);
455     if(!OpenSSL_crypto_handle) {
456         ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n", SONAME_LIBCRYPTO);
457         return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
458     }
459
460     /* mmm nice ugly macroness */
461 #define DYNSSL(x) \
462     p##x = wine_dlsym(OpenSSL_ssl_handle, #x, NULL, 0); \
463     if (!p##x) { \
464         ERR("failed to load symbol %s\n", #x); \
465         return ERROR_INTERNET_SECURITY_CHANNEL_ERROR; \
466     }
467
468     DYNSSL(SSL_library_init);
469     DYNSSL(SSL_load_error_strings);
470     DYNSSL(SSLv23_method);
471     DYNSSL(SSL_CTX_free);
472     DYNSSL(SSL_CTX_new);
473     DYNSSL(SSL_new);
474     DYNSSL(SSL_free);
475     DYNSSL(SSL_set_fd);
476     DYNSSL(SSL_connect);
477     DYNSSL(SSL_shutdown);
478     DYNSSL(SSL_write);
479     DYNSSL(SSL_read);
480     DYNSSL(SSL_pending);
481     DYNSSL(SSL_get_error);
482     DYNSSL(SSL_get_ex_new_index);
483     DYNSSL(SSL_get_ex_data);
484     DYNSSL(SSL_set_ex_data);
485     DYNSSL(SSL_get_ex_data_X509_STORE_CTX_idx);
486     DYNSSL(SSL_get_peer_certificate);
487     DYNSSL(SSL_CTX_get_timeout);
488     DYNSSL(SSL_CTX_set_timeout);
489     DYNSSL(SSL_CTX_set_default_verify_paths);
490     DYNSSL(SSL_CTX_set_verify);
491     DYNSSL(SSL_get_current_cipher);
492     DYNSSL(SSL_CIPHER_get_bits);
493 #undef DYNSSL
494
495 #define DYNCRYPTO(x) \
496     p##x = wine_dlsym(OpenSSL_crypto_handle, #x, NULL, 0); \
497     if (!p##x) { \
498         ERR("failed to load symbol %s\n", #x); \
499         return ERROR_INTERNET_SECURITY_CHANNEL_ERROR; \
500     }
501
502     DYNCRYPTO(BIO_new_fp);
503     DYNCRYPTO(CRYPTO_num_locks);
504     DYNCRYPTO(CRYPTO_set_id_callback);
505     DYNCRYPTO(CRYPTO_set_locking_callback);
506     DYNCRYPTO(ERR_free_strings);
507     DYNCRYPTO(ERR_get_error);
508     DYNCRYPTO(ERR_error_string);
509     DYNCRYPTO(X509_STORE_CTX_get_ex_data);
510     DYNCRYPTO(X509_STORE_CTX_get_chain);
511     DYNCRYPTO(i2d_X509);
512     DYNCRYPTO(sk_num);
513     DYNCRYPTO(sk_value);
514 #undef DYNCRYPTO
515
516     pSSL_library_init();
517     pSSL_load_error_strings();
518     pBIO_new_fp(stderr, BIO_NOCLOSE); /* FIXME: should use winedebug stuff */
519
520     meth = pSSLv23_method();
521     ctx = pSSL_CTX_new(meth);
522     if(!pSSL_CTX_set_default_verify_paths(ctx)) {
523         ERR("SSL_CTX_set_default_verify_paths failed: %s\n",
524             pERR_error_string(pERR_get_error(), 0));
525         return ERROR_OUTOFMEMORY;
526     }
527
528     error_idx = pSSL_get_ex_new_index(0, (void *)"error index", NULL, NULL, NULL);
529     if(error_idx == -1) {
530         ERR("SSL_get_ex_new_index failed; %s\n", pERR_error_string(pERR_get_error(), 0));
531         return ERROR_OUTOFMEMORY;
532     }
533
534     conn_idx = pSSL_get_ex_new_index(0, (void *)"netconn index", NULL, NULL, NULL);
535     if(conn_idx == -1) {
536         ERR("SSL_get_ex_new_index failed; %s\n", pERR_error_string(pERR_get_error(), 0));
537         return ERROR_OUTOFMEMORY;
538     }
539
540     pSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, netconn_secure_verify);
541
542     pCRYPTO_set_id_callback(ssl_thread_id);
543     num_ssl_locks = pCRYPTO_num_locks();
544     ssl_locks = heap_alloc(num_ssl_locks * sizeof(CRITICAL_SECTION));
545     if(!ssl_locks)
546         return ERROR_OUTOFMEMORY;
547
548     for(i = 0; i < num_ssl_locks; i++)
549     {
550         InitializeCriticalSection(&ssl_locks[i]);
551         ssl_locks[i].DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": ssl_locks");
552     }
553     pCRYPTO_set_locking_callback(ssl_lock_callback);
554
555     return ERROR_SUCCESS;
556 #else
557     FIXME("can't use SSL, not compiled in.\n");
558     return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
559 #endif
560 }
561
562 DWORD create_netconn(BOOL useSSL, server_t *server, DWORD security_flags, BOOL mask_errors, DWORD timeout, netconn_t **ret)
563 {
564     netconn_t *netconn;
565     int result, flag;
566
567     if(useSSL) {
568         DWORD res;
569
570         TRACE("using SSL connection\n");
571
572         EnterCriticalSection(&init_ssl_cs);
573         res = init_openssl();
574         LeaveCriticalSection(&init_ssl_cs);
575         if(res != ERROR_SUCCESS)
576             return res;
577     }
578
579     netconn = heap_alloc_zero(sizeof(*netconn));
580     if(!netconn)
581         return ERROR_OUTOFMEMORY;
582
583     netconn->useSSL = useSSL;
584     netconn->socketFD = -1;
585     netconn->security_flags = security_flags | server->security_flags;
586     netconn->mask_errors = mask_errors;
587     list_init(&netconn->pool_entry);
588
589     assert(server->addr_len);
590     result = netconn->socketFD = socket(server->addr.ss_family, SOCK_STREAM, 0);
591     if(result != -1) {
592         flag = 1;
593         ioctlsocket(netconn->socketFD, FIONBIO, &flag);
594         result = connect(netconn->socketFD, (struct sockaddr*)&server->addr, server->addr_len);
595         if(result == -1)
596         {
597             if (sock_get_error(errno) == WSAEINPROGRESS) {
598                 struct pollfd pfd;
599                 int res;
600
601                 pfd.fd = netconn->socketFD;
602                 pfd.events = POLLOUT;
603                 res = poll(&pfd, 1, timeout);
604                 if (!res)
605                 {
606                     closesocket(netconn->socketFD);
607                     heap_free(netconn);
608                     return ERROR_INTERNET_CANNOT_CONNECT;
609                 }
610                 else if (res > 0)
611                 {
612                     int err;
613                     socklen_t len = sizeof(err);
614                     if (!getsockopt(netconn->socketFD, SOL_SOCKET, SO_ERROR, &err, &len) && !err)
615                         result = 0;
616                 }
617             }
618         }
619         if(result == -1)
620             closesocket(netconn->socketFD);
621         else {
622             flag = 0;
623             ioctlsocket(netconn->socketFD, FIONBIO, &flag);
624         }
625     }
626     if(result == -1) {
627         heap_free(netconn);
628         return sock_get_error(errno);
629     }
630
631 #ifdef TCP_NODELAY
632     flag = 1;
633     result = setsockopt(netconn->socketFD, IPPROTO_TCP, TCP_NODELAY, (void*)&flag, sizeof(flag));
634     if(result < 0)
635         WARN("setsockopt(TCP_NODELAY) failed\n");
636 #endif
637
638     server_addref(server);
639     netconn->server = server;
640
641     *ret = netconn;
642     return ERROR_SUCCESS;
643 }
644
645 void free_netconn(netconn_t *netconn)
646 {
647     server_release(netconn->server);
648
649 #ifdef SONAME_LIBSSL
650     if (netconn->ssl_s) {
651         pSSL_shutdown(netconn->ssl_s);
652         pSSL_free(netconn->ssl_s);
653     }
654 #endif
655
656     closesocket(netconn->socketFD);
657     heap_free(netconn);
658 }
659
660 void NETCON_unload(void)
661 {
662 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
663     if (OpenSSL_crypto_handle)
664     {
665         pERR_free_strings();
666         wine_dlclose(OpenSSL_crypto_handle, NULL, 0);
667     }
668     if (OpenSSL_ssl_handle)
669     {
670         if (ctx)
671             pSSL_CTX_free(ctx);
672         wine_dlclose(OpenSSL_ssl_handle, NULL, 0);
673     }
674     if (ssl_locks)
675     {
676         int i;
677         for (i = 0; i < num_ssl_locks; i++)
678         {
679             ssl_locks[i].DebugInfo->Spare[0] = 0;
680             DeleteCriticalSection(&ssl_locks[i]);
681         }
682         heap_free(ssl_locks);
683     }
684 #endif
685 }
686
687 /* translate a unix error code into a winsock one */
688 int sock_get_error( int err )
689 {
690 #if !defined(__MINGW32__) && !defined (_MSC_VER)
691     switch (err)
692     {
693         case EINTR:             return WSAEINTR;
694         case EBADF:             return WSAEBADF;
695         case EPERM:
696         case EACCES:            return WSAEACCES;
697         case EFAULT:            return WSAEFAULT;
698         case EINVAL:            return WSAEINVAL;
699         case EMFILE:            return WSAEMFILE;
700         case EWOULDBLOCK:       return WSAEWOULDBLOCK;
701         case EINPROGRESS:       return WSAEINPROGRESS;
702         case EALREADY:          return WSAEALREADY;
703         case ENOTSOCK:          return WSAENOTSOCK;
704         case EDESTADDRREQ:      return WSAEDESTADDRREQ;
705         case EMSGSIZE:          return WSAEMSGSIZE;
706         case EPROTOTYPE:        return WSAEPROTOTYPE;
707         case ENOPROTOOPT:       return WSAENOPROTOOPT;
708         case EPROTONOSUPPORT:   return WSAEPROTONOSUPPORT;
709         case ESOCKTNOSUPPORT:   return WSAESOCKTNOSUPPORT;
710         case EOPNOTSUPP:        return WSAEOPNOTSUPP;
711         case EPFNOSUPPORT:      return WSAEPFNOSUPPORT;
712         case EAFNOSUPPORT:      return WSAEAFNOSUPPORT;
713         case EADDRINUSE:        return WSAEADDRINUSE;
714         case EADDRNOTAVAIL:     return WSAEADDRNOTAVAIL;
715         case ENETDOWN:          return WSAENETDOWN;
716         case ENETUNREACH:       return WSAENETUNREACH;
717         case ENETRESET:         return WSAENETRESET;
718         case ECONNABORTED:      return WSAECONNABORTED;
719         case EPIPE:
720         case ECONNRESET:        return WSAECONNRESET;
721         case ENOBUFS:           return WSAENOBUFS;
722         case EISCONN:           return WSAEISCONN;
723         case ENOTCONN:          return WSAENOTCONN;
724         case ESHUTDOWN:         return WSAESHUTDOWN;
725         case ETOOMANYREFS:      return WSAETOOMANYREFS;
726         case ETIMEDOUT:         return WSAETIMEDOUT;
727         case ECONNREFUSED:      return WSAECONNREFUSED;
728         case ELOOP:             return WSAELOOP;
729         case ENAMETOOLONG:      return WSAENAMETOOLONG;
730         case EHOSTDOWN:         return WSAEHOSTDOWN;
731         case EHOSTUNREACH:      return WSAEHOSTUNREACH;
732         case ENOTEMPTY:         return WSAENOTEMPTY;
733 #ifdef EPROCLIM
734         case EPROCLIM:          return WSAEPROCLIM;
735 #endif
736 #ifdef EUSERS
737         case EUSERS:            return WSAEUSERS;
738 #endif
739 #ifdef EDQUOT
740         case EDQUOT:            return WSAEDQUOT;
741 #endif
742 #ifdef ESTALE
743         case ESTALE:            return WSAESTALE;
744 #endif
745 #ifdef EREMOTE
746         case EREMOTE:           return WSAEREMOTE;
747 #endif
748     default: errno=err; perror("sock_set_error"); return WSAEFAULT;
749     }
750 #endif
751     return err;
752 }
753
754 /******************************************************************************
755  * NETCON_secure_connect
756  * Initiates a secure connection over an existing plaintext connection.
757  */
758 DWORD NETCON_secure_connect(netconn_t *connection)
759 {
760     DWORD res = ERROR_NOT_SUPPORTED;
761 #ifdef SONAME_LIBSSL
762     void *ssl_s;
763     int bits;
764
765     /* can't connect if we are already connected */
766     if (connection->ssl_s)
767     {
768         ERR("already connected\n");
769         return ERROR_INTERNET_CANNOT_CONNECT;
770     }
771
772     ssl_s = pSSL_new(ctx);
773     if (!ssl_s)
774     {
775         ERR("SSL_new failed: %s\n",
776             pERR_error_string(pERR_get_error(), 0));
777         return ERROR_OUTOFMEMORY;
778     }
779
780     if (!pSSL_set_fd(ssl_s, connection->socketFD))
781     {
782         ERR("SSL_set_fd failed: %s\n",
783             pERR_error_string(pERR_get_error(), 0));
784         res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
785         goto fail;
786     }
787
788     if (!pSSL_set_ex_data(ssl_s, conn_idx, connection))
789     {
790         ERR("SSL_set_ex_data failed: %s\n",
791             pERR_error_string(pERR_get_error(), 0));
792         res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
793         goto fail;
794     }
795     if (pSSL_connect(ssl_s) <= 0)
796     {
797         res = (DWORD_PTR)pSSL_get_ex_data(ssl_s, error_idx);
798         if (!res)
799             res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
800         ERR("SSL_connect failed: %d\n", res);
801         goto fail;
802     }
803
804     connection->ssl_s = ssl_s;
805
806     bits = NETCON_GetCipherStrength(connection);
807     if (bits >= 128)
808         connection->security_flags |= SECURITY_FLAG_STRENGTH_STRONG;
809     else if (bits >= 56)
810         connection->security_flags |= SECURITY_FLAG_STRENGTH_MEDIUM;
811     else
812         connection->security_flags |= SECURITY_FLAG_STRENGTH_WEAK;
813     connection->security_flags |= SECURITY_FLAG_SECURE;
814
815     if(connection->mask_errors)
816         connection->server->security_flags = connection->security_flags;
817     return ERROR_SUCCESS;
818
819 fail:
820     if (ssl_s)
821     {
822         pSSL_shutdown(ssl_s);
823         pSSL_free(ssl_s);
824     }
825 #endif
826     return res;
827 }
828
829 /******************************************************************************
830  * NETCON_send
831  * Basically calls 'send()' unless we should use SSL
832  * number of chars send is put in *sent
833  */
834 DWORD NETCON_send(netconn_t *connection, const void *msg, size_t len, int flags,
835                 int *sent /* out */)
836 {
837     if (!connection->useSSL)
838     {
839         *sent = send(connection->socketFD, msg, len, flags);
840         if (*sent == -1)
841             return sock_get_error(errno);
842         return ERROR_SUCCESS;
843     }
844     else
845     {
846 #ifdef SONAME_LIBSSL
847         if(!connection->ssl_s) {
848             FIXME("not connected\n");
849             return ERROR_NOT_SUPPORTED;
850         }
851         if (flags)
852             FIXME("SSL_write doesn't support any flags (%08x)\n", flags);
853         *sent = pSSL_write(connection->ssl_s, msg, len);
854         if (*sent < 1 && len)
855             return ERROR_INTERNET_CONNECTION_ABORTED;
856         return ERROR_SUCCESS;
857 #else
858         return ERROR_NOT_SUPPORTED;
859 #endif
860     }
861 }
862
863 /******************************************************************************
864  * NETCON_recv
865  * Basically calls 'recv()' unless we should use SSL
866  * number of chars received is put in *recvd
867  */
868 DWORD NETCON_recv(netconn_t *connection, void *buf, size_t len, int flags,
869                 int *recvd /* out */)
870 {
871     *recvd = 0;
872     if (!len)
873         return ERROR_SUCCESS;
874     if (!connection->useSSL)
875     {
876         *recvd = recv(connection->socketFD, buf, len, flags);
877         return *recvd == -1 ? sock_get_error(errno) :  ERROR_SUCCESS;
878     }
879     else
880     {
881 #ifdef SONAME_LIBSSL
882         if(!connection->ssl_s) {
883             FIXME("not connected\n");
884             return ERROR_NOT_SUPPORTED;
885         }
886         *recvd = pSSL_read(connection->ssl_s, buf, len);
887
888         /* Check if EOF was received */
889         if(!*recvd && (pSSL_get_error(connection->ssl_s, *recvd)==SSL_ERROR_ZERO_RETURN
890                     || pSSL_get_error(connection->ssl_s, *recvd)==SSL_ERROR_SYSCALL))
891             return ERROR_SUCCESS;
892
893         return *recvd > 0 ? ERROR_SUCCESS : ERROR_INTERNET_CONNECTION_ABORTED;
894 #else
895         return ERROR_NOT_SUPPORTED;
896 #endif
897     }
898 }
899
900 /******************************************************************************
901  * NETCON_query_data_available
902  * Returns the number of bytes of peeked data plus the number of bytes of
903  * queued, but unread data.
904  */
905 BOOL NETCON_query_data_available(netconn_t *connection, DWORD *available)
906 {
907     *available = 0;
908
909     if (!connection->useSSL)
910     {
911 #ifdef FIONREAD
912         int unread;
913         int retval = ioctlsocket(connection->socketFD, FIONREAD, &unread);
914         if (!retval)
915         {
916             TRACE("%d bytes of queued, but unread data\n", unread);
917             *available += unread;
918         }
919 #endif
920     }
921     else
922     {
923 #ifdef SONAME_LIBSSL
924         *available = connection->ssl_s ? pSSL_pending(connection->ssl_s) : 0;
925 #endif
926     }
927     return TRUE;
928 }
929
930 BOOL NETCON_is_alive(netconn_t *netconn)
931 {
932 #ifdef MSG_DONTWAIT
933     ssize_t len;
934     BYTE b;
935
936     len = recv(netconn->socketFD, &b, 1, MSG_PEEK|MSG_DONTWAIT);
937     return len == 1 || (len == -1 && errno == EWOULDBLOCK);
938 #elif defined(__MINGW32__) || defined(_MSC_VER)
939     ULONG mode;
940     int len;
941     char b;
942
943     mode = 1;
944     if(!ioctlsocket(netconn->socketFD, FIONBIO, &mode))
945         return FALSE;
946
947     len = recv(netconn->socketFD, &b, 1, MSG_PEEK);
948
949     mode = 0;
950     if(!ioctlsocket(netconn->socketFD, FIONBIO, &mode))
951         return FALSE;
952
953     return len == 1 || (len == -1 && errno == WSAEWOULDBLOCK);
954 #else
955     FIXME("not supported on this platform\n");
956     return TRUE;
957 #endif
958 }
959
960 LPCVOID NETCON_GetCert(netconn_t *connection)
961 {
962 #ifdef SONAME_LIBSSL
963     X509* cert;
964     LPCVOID r = NULL;
965
966     if (!connection->ssl_s)
967         return NULL;
968
969     cert = pSSL_get_peer_certificate(connection->ssl_s);
970     r = X509_to_cert_context(cert);
971     return r;
972 #else
973     return NULL;
974 #endif
975 }
976
977 int NETCON_GetCipherStrength(netconn_t *connection)
978 {
979 #ifdef SONAME_LIBSSL
980 #if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER >= 0x0090707f)
981     const SSL_CIPHER *cipher;
982 #else
983     SSL_CIPHER *cipher;
984 #endif
985     int bits = 0;
986
987     if (!connection->ssl_s)
988         return 0;
989     cipher = pSSL_get_current_cipher(connection->ssl_s);
990     if (!cipher)
991         return 0;
992     pSSL_CIPHER_get_bits(cipher, &bits);
993     return bits;
994 #else
995     return 0;
996 #endif
997 }
998
999 DWORD NETCON_set_timeout(netconn_t *connection, BOOL send, DWORD value)
1000 {
1001     int result;
1002     struct timeval tv;
1003
1004     /* value is in milliseconds, convert to struct timeval */
1005     if (value == INFINITE)
1006     {
1007         tv.tv_sec = 0;
1008         tv.tv_usec = 0;
1009     }
1010     else
1011     {
1012         tv.tv_sec = value / 1000;
1013         tv.tv_usec = (value % 1000) * 1000;
1014     }
1015     result = setsockopt(connection->socketFD, SOL_SOCKET,
1016                         send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv,
1017                         sizeof(tv));
1018     if (result == -1)
1019     {
1020         WARN("setsockopt failed (%s)\n", strerror(errno));
1021         return sock_get_error(errno);
1022     }
1023     return ERROR_SUCCESS;
1024 }