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