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