wininet: Remove a no-op trinary expression.
[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, chainFlags = 0;
232
233     TRACE("verifying %s\n", debugstr_w(server));
234     chainPara.RequestedUsage.Usage.cUsageIdentifier = 1;
235     chainPara.RequestedUsage.Usage.rgpszUsageIdentifier = server_auth;
236     if (!(security_flags & SECURITY_FLAG_IGNORE_REVOCATION))
237         chainFlags |= CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT;
238     if ((ret = CertGetCertificateChain(NULL, cert, NULL, store, &chainPara,
239         chainFlags, NULL, &chain)))
240     {
241         if (chain->TrustStatus.dwErrorStatus)
242         {
243             static const DWORD supportedErrors =
244                 CERT_TRUST_IS_NOT_TIME_VALID |
245                 CERT_TRUST_IS_UNTRUSTED_ROOT |
246                 CERT_TRUST_IS_OFFLINE_REVOCATION |
247                 CERT_TRUST_REVOCATION_STATUS_UNKNOWN |
248                 CERT_TRUST_IS_REVOKED |
249                 CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
250
251             if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_NOT_TIME_VALID &&
252                 !(security_flags & SECURITY_FLAG_IGNORE_CERT_DATE_INVALID))
253                 err = ERROR_INTERNET_SEC_CERT_DATE_INVALID;
254             else if (chain->TrustStatus.dwErrorStatus &
255                      CERT_TRUST_IS_UNTRUSTED_ROOT &&
256                      !(security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA))
257                 err = ERROR_INTERNET_INVALID_CA;
258             else if (!(security_flags & SECURITY_FLAG_IGNORE_REVOCATION) &&
259                      ((chain->TrustStatus.dwErrorStatus &
260                       CERT_TRUST_IS_OFFLINE_REVOCATION) ||
261                       (chain->TrustStatus.dwErrorStatus &
262                        CERT_TRUST_REVOCATION_STATUS_UNKNOWN)))
263                 err = ERROR_INTERNET_SEC_CERT_NO_REV;
264             else if (!(security_flags & SECURITY_FLAG_IGNORE_REVOCATION) &&
265                      (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_REVOKED))
266                 err = ERROR_INTERNET_SEC_CERT_REVOKED;
267             else if (!(security_flags & SECURITY_FLAG_IGNORE_WRONG_USAGE) &&
268                      (chain->TrustStatus.dwErrorStatus &
269                       CERT_TRUST_IS_NOT_VALID_FOR_USAGE))
270                 err = ERROR_INTERNET_SEC_INVALID_CERT;
271             else if (chain->TrustStatus.dwErrorStatus & ~supportedErrors)
272                 err = ERROR_INTERNET_SEC_INVALID_CERT;
273         }
274         if (!err)
275         {
276             CERT_CHAIN_POLICY_PARA policyPara;
277             SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslExtraPolicyPara;
278             CERT_CHAIN_POLICY_STATUS policyStatus;
279             CERT_CHAIN_CONTEXT chainCopy;
280
281             /* Clear chain->TrustStatus.dwErrorStatus so
282              * CertVerifyCertificateChainPolicy will verify additional checks
283              * rather than stopping with an existing, ignored error.
284              */
285             memcpy(&chainCopy, chain, sizeof(chainCopy));
286             chainCopy.TrustStatus.dwErrorStatus = 0;
287             sslExtraPolicyPara.u.cbSize = sizeof(sslExtraPolicyPara);
288             sslExtraPolicyPara.dwAuthType = AUTHTYPE_SERVER;
289             sslExtraPolicyPara.pwszServerName = server;
290             sslExtraPolicyPara.fdwChecks = security_flags;
291             policyPara.cbSize = sizeof(policyPara);
292             policyPara.dwFlags = 0;
293             policyPara.pvExtraPolicyPara = &sslExtraPolicyPara;
294             ret = CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL,
295                 &chainCopy, &policyPara, &policyStatus);
296             /* Any error in the policy status indicates that the
297              * policy couldn't be verified.
298              */
299             if (ret && policyStatus.dwError)
300             {
301                 if (policyStatus.dwError == CERT_E_CN_NO_MATCH)
302                     err = ERROR_INTERNET_SEC_CERT_CN_INVALID;
303                 else
304                     err = ERROR_INTERNET_SEC_INVALID_CERT;
305             }
306         }
307         CertFreeCertificateChain(chain);
308     }
309     TRACE("returning %08x\n", err);
310     return err;
311 }
312
313 static int netconn_secure_verify(int preverify_ok, X509_STORE_CTX *ctx)
314 {
315     SSL *ssl;
316     WCHAR *server;
317     BOOL ret = FALSE;
318     HCERTSTORE store = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
319         CERT_STORE_CREATE_NEW_FLAG, NULL);
320     WININET_NETCONNECTION *conn;
321
322     ssl = pX509_STORE_CTX_get_ex_data(ctx,
323         pSSL_get_ex_data_X509_STORE_CTX_idx());
324     server = pSSL_get_ex_data(ssl, hostname_idx);
325     conn = pSSL_get_ex_data(ssl, conn_idx);
326     if (store)
327     {
328         X509 *cert;
329         int i;
330         PCCERT_CONTEXT endCert = NULL;
331
332         ret = TRUE;
333         for (i = 0; ret && i < psk_num((struct stack_st *)ctx->chain); i++)
334         {
335             PCCERT_CONTEXT context;
336
337             cert = (X509 *)psk_value((struct stack_st *)ctx->chain, i);
338             if ((context = X509_to_cert_context(cert)))
339             {
340                 if (i == 0)
341                     ret = CertAddCertificateContextToStore(store, context,
342                         CERT_STORE_ADD_ALWAYS, &endCert);
343                 else
344                     ret = CertAddCertificateContextToStore(store, context,
345                         CERT_STORE_ADD_ALWAYS, NULL);
346                 CertFreeCertificateContext(context);
347             }
348         }
349         if (!endCert) ret = FALSE;
350         if (ret)
351         {
352             DWORD_PTR err = netconn_verify_cert(endCert, store, server,
353                                                 conn->security_flags);
354
355             if (err)
356             {
357                 pSSL_set_ex_data(ssl, error_idx, (void *)err);
358                 ret = FALSE;
359             }
360         }
361         CertFreeCertificateContext(endCert);
362         CertCloseStore(store, 0);
363     }
364     return ret;
365 }
366
367 #endif
368
369 DWORD NETCON_init(WININET_NETCONNECTION *connection, BOOL useSSL)
370 {
371     connection->useSSL = useSSL;
372     connection->socketFD = -1;
373     if (useSSL)
374     {
375 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
376         int i;
377
378         TRACE("using SSL connection\n");
379         EnterCriticalSection(&init_ssl_cs);
380         if (OpenSSL_ssl_handle) /* already initialized everything */
381         {
382             LeaveCriticalSection(&init_ssl_cs);
383             return ERROR_SUCCESS;
384         }
385         OpenSSL_ssl_handle = wine_dlopen(SONAME_LIBSSL, RTLD_NOW, NULL, 0);
386         if (!OpenSSL_ssl_handle)
387         {
388             ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n",
389                 SONAME_LIBSSL);
390             LeaveCriticalSection(&init_ssl_cs);
391             return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
392         }
393         OpenSSL_crypto_handle = wine_dlopen(SONAME_LIBCRYPTO, RTLD_NOW, NULL, 0);
394         if (!OpenSSL_crypto_handle)
395         {
396             ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n",
397                 SONAME_LIBCRYPTO);
398             LeaveCriticalSection(&init_ssl_cs);
399             return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
400         }
401
402         /* mmm nice ugly macroness */
403 #define DYNSSL(x) \
404     p##x = wine_dlsym(OpenSSL_ssl_handle, #x, NULL, 0); \
405     if (!p##x) \
406     { \
407         ERR("failed to load symbol %s\n", #x); \
408         LeaveCriticalSection(&init_ssl_cs); \
409         return ERROR_INTERNET_SECURITY_CHANNEL_ERROR; \
410     }
411
412         DYNSSL(SSL_library_init);
413         DYNSSL(SSL_load_error_strings);
414         DYNSSL(SSLv23_method);
415         DYNSSL(SSL_CTX_free);
416         DYNSSL(SSL_CTX_new);
417         DYNSSL(SSL_new);
418         DYNSSL(SSL_free);
419         DYNSSL(SSL_set_fd);
420         DYNSSL(SSL_connect);
421         DYNSSL(SSL_shutdown);
422         DYNSSL(SSL_write);
423         DYNSSL(SSL_read);
424         DYNSSL(SSL_pending);
425         DYNSSL(SSL_get_error);
426         DYNSSL(SSL_get_ex_new_index);
427         DYNSSL(SSL_get_ex_data);
428         DYNSSL(SSL_set_ex_data);
429         DYNSSL(SSL_get_ex_data_X509_STORE_CTX_idx);
430         DYNSSL(SSL_get_peer_certificate);
431         DYNSSL(SSL_CTX_get_timeout);
432         DYNSSL(SSL_CTX_set_timeout);
433         DYNSSL(SSL_CTX_set_default_verify_paths);
434         DYNSSL(SSL_CTX_set_verify);
435         DYNSSL(SSL_get_current_cipher);
436         DYNSSL(SSL_CIPHER_get_bits);
437 #undef DYNSSL
438
439 #define DYNCRYPTO(x) \
440     p##x = wine_dlsym(OpenSSL_crypto_handle, #x, NULL, 0); \
441     if (!p##x) \
442     { \
443         ERR("failed to load symbol %s\n", #x); \
444         LeaveCriticalSection(&init_ssl_cs); \
445         return ERROR_INTERNET_SECURITY_CHANNEL_ERROR; \
446     }
447         DYNCRYPTO(BIO_new_fp);
448         DYNCRYPTO(CRYPTO_num_locks);
449         DYNCRYPTO(CRYPTO_set_id_callback);
450         DYNCRYPTO(CRYPTO_set_locking_callback);
451         DYNCRYPTO(ERR_free_strings);
452         DYNCRYPTO(ERR_get_error);
453         DYNCRYPTO(ERR_error_string);
454         DYNCRYPTO(X509_STORE_CTX_get_ex_data);
455         DYNCRYPTO(i2d_X509);
456         DYNCRYPTO(sk_num);
457         DYNCRYPTO(sk_value);
458 #undef DYNCRYPTO
459
460         pSSL_library_init();
461         pSSL_load_error_strings();
462         pBIO_new_fp(stderr, BIO_NOCLOSE); /* FIXME: should use winedebug stuff */
463
464         meth = pSSLv23_method();
465         ctx = pSSL_CTX_new(meth);
466         if (!pSSL_CTX_set_default_verify_paths(ctx))
467         {
468             ERR("SSL_CTX_set_default_verify_paths failed: %s\n",
469                 pERR_error_string(pERR_get_error(), 0));
470             LeaveCriticalSection(&init_ssl_cs);
471             return ERROR_OUTOFMEMORY;
472         }
473         hostname_idx = pSSL_get_ex_new_index(0, (void *)"hostname index",
474                 NULL, NULL, NULL);
475         if (hostname_idx == -1)
476         {
477             ERR("SSL_get_ex_new_index failed; %s\n",
478                 pERR_error_string(pERR_get_error(), 0));
479             LeaveCriticalSection(&init_ssl_cs);
480             return ERROR_OUTOFMEMORY;
481         }
482         error_idx = pSSL_get_ex_new_index(0, (void *)"error index",
483                 NULL, NULL, NULL);
484         if (error_idx == -1)
485         {
486             ERR("SSL_get_ex_new_index failed; %s\n",
487                 pERR_error_string(pERR_get_error(), 0));
488             LeaveCriticalSection(&init_ssl_cs);
489             return ERROR_OUTOFMEMORY;
490         }
491         conn_idx = pSSL_get_ex_new_index(0, (void *)"netconn index",
492                 NULL, NULL, NULL);
493         if (conn_idx == -1)
494         {
495             ERR("SSL_get_ex_new_index failed; %s\n",
496                 pERR_error_string(pERR_get_error(), 0));
497             LeaveCriticalSection(&init_ssl_cs);
498             return ERROR_OUTOFMEMORY;
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 = HeapAlloc(GetProcessHeap(), 0, num_ssl_locks * sizeof(CRITICAL_SECTION));
505         if (!ssl_locks)
506         {
507             LeaveCriticalSection(&init_ssl_cs);
508             return ERROR_OUTOFMEMORY;
509         }
510         for (i = 0; i < num_ssl_locks; i++)
511             InitializeCriticalSection(&ssl_locks[i]);
512         pCRYPTO_set_locking_callback(ssl_lock_callback);
513         LeaveCriticalSection(&init_ssl_cs);
514 #else
515         FIXME("can't use SSL, not compiled in.\n");
516         return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
517 #endif
518     }
519     return ERROR_SUCCESS;
520 }
521
522 void NETCON_unload(void)
523 {
524 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
525     if (OpenSSL_crypto_handle)
526     {
527         pERR_free_strings();
528         wine_dlclose(OpenSSL_crypto_handle, NULL, 0);
529     }
530     if (OpenSSL_ssl_handle)
531     {
532         if (ctx)
533             pSSL_CTX_free(ctx);
534         wine_dlclose(OpenSSL_ssl_handle, NULL, 0);
535     }
536     if (ssl_locks)
537     {
538         int i;
539         for (i = 0; i < num_ssl_locks; i++) DeleteCriticalSection(&ssl_locks[i]);
540         HeapFree(GetProcessHeap(), 0, ssl_locks);
541     }
542 #endif
543 }
544
545 BOOL NETCON_connected(WININET_NETCONNECTION *connection)
546 {
547     return connection->socketFD != -1;
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->ssl_s)
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->ssl_s)
648     {
649         pSSL_shutdown(connection->ssl_s);
650         pSSL_free(connection->ssl_s);
651         connection->ssl_s = NULL;
652     }
653 #endif
654
655     result = closesocket(connection->socketFD);
656     connection->socketFD = -1;
657
658     if (result == -1)
659         return sock_get_error(errno);
660     return ERROR_SUCCESS;
661 }
662
663 /******************************************************************************
664  * NETCON_secure_connect
665  * Initiates a secure connection over an existing plaintext connection.
666  */
667 DWORD NETCON_secure_connect(WININET_NETCONNECTION *connection, LPWSTR hostname)
668 {
669     void *ssl_s;
670     DWORD res = ERROR_NOT_SUPPORTED;
671
672 #ifdef SONAME_LIBSSL
673     /* can't connect if we are already connected */
674     if (connection->ssl_s)
675     {
676         ERR("already connected\n");
677         return ERROR_INTERNET_CANNOT_CONNECT;
678     }
679
680     ssl_s = pSSL_new(ctx);
681     if (!ssl_s)
682     {
683         ERR("SSL_new failed: %s\n",
684             pERR_error_string(pERR_get_error(), 0));
685         return ERROR_OUTOFMEMORY;
686     }
687
688     if (!pSSL_set_fd(ssl_s, connection->socketFD))
689     {
690         ERR("SSL_set_fd failed: %s\n",
691             pERR_error_string(pERR_get_error(), 0));
692         res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
693         goto fail;
694     }
695
696     if (!pSSL_set_ex_data(ssl_s, hostname_idx, hostname))
697     {
698         ERR("SSL_set_ex_data failed: %s\n",
699             pERR_error_string(pERR_get_error(), 0));
700         res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
701         goto fail;
702     }
703     if (!pSSL_set_ex_data(ssl_s, conn_idx, connection))
704     {
705         ERR("SSL_set_ex_data failed: %s\n",
706             pERR_error_string(pERR_get_error(), 0));
707         res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
708         goto fail;
709     }
710     if (pSSL_connect(ssl_s) <= 0)
711     {
712         res = (DWORD_PTR)pSSL_get_ex_data(ssl_s, error_idx);
713         if (!res)
714             res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
715         ERR("SSL_connect failed: %d\n", res);
716         goto fail;
717     }
718
719     connection->ssl_s = ssl_s;
720     return ERROR_SUCCESS;
721
722 fail:
723     if (ssl_s)
724     {
725         pSSL_shutdown(ssl_s);
726         pSSL_free(ssl_s);
727     }
728 #endif
729     return res;
730 }
731
732 /******************************************************************************
733  * NETCON_connect
734  * Connects to the specified address.
735  */
736 DWORD NETCON_connect(WININET_NETCONNECTION *connection, const struct sockaddr *serv_addr,
737                     unsigned int addrlen)
738 {
739     int result;
740
741     result = connect(connection->socketFD, serv_addr, addrlen);
742     if (result == -1)
743     {
744         WARN("Unable to connect to host (%s)\n", strerror(errno));
745
746         closesocket(connection->socketFD);
747         connection->socketFD = -1;
748         return sock_get_error(errno);
749     }
750
751     return ERROR_SUCCESS;
752 }
753
754 /******************************************************************************
755  * NETCON_send
756  * Basically calls 'send()' unless we should use SSL
757  * number of chars send is put in *sent
758  */
759 DWORD NETCON_send(WININET_NETCONNECTION *connection, const void *msg, size_t len, int flags,
760                 int *sent /* out */)
761 {
762     if (!NETCON_connected(connection)) return ERROR_INTERNET_CONNECTION_ABORTED;
763     if (!connection->useSSL)
764     {
765         *sent = send(connection->socketFD, msg, len, flags);
766         if (*sent == -1)
767             return sock_get_error(errno);
768         return ERROR_SUCCESS;
769     }
770     else
771     {
772 #ifdef SONAME_LIBSSL
773         if(!connection->ssl_s) {
774             FIXME("not connected\n");
775             return ERROR_NOT_SUPPORTED;
776         }
777         if (flags)
778             FIXME("SSL_write doesn't support any flags (%08x)\n", flags);
779         *sent = pSSL_write(connection->ssl_s, msg, len);
780         if (*sent < 1 && len)
781             return ERROR_INTERNET_CONNECTION_ABORTED;
782         return ERROR_SUCCESS;
783 #else
784         return ERROR_NOT_SUPPORTED;
785 #endif
786     }
787 }
788
789 /******************************************************************************
790  * NETCON_recv
791  * Basically calls 'recv()' unless we should use SSL
792  * number of chars received is put in *recvd
793  */
794 DWORD NETCON_recv(WININET_NETCONNECTION *connection, void *buf, size_t len, int flags,
795                 int *recvd /* out */)
796 {
797     *recvd = 0;
798     if (!NETCON_connected(connection)) return ERROR_INTERNET_CONNECTION_ABORTED;
799     if (!len)
800         return ERROR_SUCCESS;
801     if (!connection->useSSL)
802     {
803         *recvd = recv(connection->socketFD, buf, len, flags);
804         if(!*recvd)
805             NETCON_close(connection);
806         return *recvd == -1 ? sock_get_error(errno) :  ERROR_SUCCESS;
807     }
808     else
809     {
810 #ifdef SONAME_LIBSSL
811         if(!connection->ssl_s) {
812             FIXME("not connected\n");
813             return ERROR_NOT_SUPPORTED;
814         }
815         *recvd = pSSL_read(connection->ssl_s, buf, len);
816
817         /* Check if EOF was received */
818         if(!*recvd && (pSSL_get_error(connection->ssl_s, *recvd)==SSL_ERROR_ZERO_RETURN
819                     || pSSL_get_error(connection->ssl_s, *recvd)==SSL_ERROR_SYSCALL)) {
820             NETCON_close(connection);
821             return ERROR_SUCCESS;
822         }
823
824         return *recvd > 0 ? ERROR_SUCCESS : ERROR_INTERNET_CONNECTION_ABORTED;
825 #else
826         return ERROR_NOT_SUPPORTED;
827 #endif
828     }
829 }
830
831 /******************************************************************************
832  * NETCON_query_data_available
833  * Returns the number of bytes of peeked data plus the number of bytes of
834  * queued, but unread data.
835  */
836 BOOL NETCON_query_data_available(WININET_NETCONNECTION *connection, DWORD *available)
837 {
838     *available = 0;
839     if (!NETCON_connected(connection))
840         return FALSE;
841
842     if (!connection->useSSL)
843     {
844 #ifdef FIONREAD
845         int unread;
846         int retval = ioctlsocket(connection->socketFD, FIONREAD, &unread);
847         if (!retval)
848         {
849             TRACE("%d bytes of queued, but unread data\n", unread);
850             *available += unread;
851         }
852 #endif
853     }
854     else
855     {
856 #ifdef SONAME_LIBSSL
857         *available = connection->ssl_s ? pSSL_pending(connection->ssl_s) : 0;
858 #endif
859     }
860     return TRUE;
861 }
862
863 LPCVOID NETCON_GetCert(WININET_NETCONNECTION *connection)
864 {
865 #ifdef SONAME_LIBSSL
866     X509* cert;
867     LPCVOID r = NULL;
868
869     if (!connection->ssl_s)
870         return NULL;
871
872     cert = pSSL_get_peer_certificate(connection->ssl_s);
873     r = X509_to_cert_context(cert);
874     return r;
875 #else
876     return NULL;
877 #endif
878 }
879
880 int NETCON_GetCipherStrength(WININET_NETCONNECTION *connection)
881 {
882 #ifdef SONAME_LIBSSL
883 #if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER >= 0x0090707f)
884     const SSL_CIPHER *cipher;
885 #else
886     SSL_CIPHER *cipher;
887 #endif
888     int bits = 0;
889
890     if (!connection->ssl_s)
891         return 0;
892     cipher = pSSL_get_current_cipher(connection->ssl_s);
893     if (!cipher)
894         return 0;
895     pSSL_CIPHER_get_bits(cipher, &bits);
896     return bits;
897 #else
898     return 0;
899 #endif
900 }
901
902 DWORD NETCON_set_timeout(WININET_NETCONNECTION *connection, BOOL send, int value)
903 {
904     int result;
905     struct timeval tv;
906
907     /* FIXME: we should probably store the timeout in the connection to set
908      * when we do connect */
909     if (!NETCON_connected(connection))
910         return ERROR_SUCCESS;
911
912     /* value is in milliseconds, convert to struct timeval */
913     tv.tv_sec = value / 1000;
914     tv.tv_usec = (value % 1000) * 1000;
915
916     result = setsockopt(connection->socketFD, SOL_SOCKET,
917                         send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv,
918                         sizeof(tv));
919
920     if (result == -1)
921     {
922         WARN("setsockopt failed (%s)\n", strerror(errno));
923         return sock_get_error(errno);
924     }
925
926     return ERROR_SUCCESS;
927 }