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