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