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