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