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