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