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