kernel32: Make GetModuleHandleA hotpatchable.
[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, DWORD timeout, 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         flag = 1;
530         ioctlsocket(netconn->socketFD, FIONBIO, &flag);
531         result = connect(netconn->socketFD, (struct sockaddr*)&server->addr, server->addr_len);
532         if(result == -1)
533         {
534             if (sock_get_error(errno) == WSAEINPROGRESS) {
535                 struct pollfd pfd;
536                 int res;
537
538                 pfd.fd = netconn->socketFD;
539                 pfd.events = POLLOUT;
540                 res = poll(&pfd, 1, timeout);
541                 if (!res)
542                 {
543                     closesocket(netconn->socketFD);
544                     heap_free(netconn);
545                     return ERROR_INTERNET_CANNOT_CONNECT;
546                 }
547                 else if (res > 0)
548                 {
549                     int err;
550                     socklen_t len = sizeof(err);
551                     if (!getsockopt(netconn->socketFD, SOL_SOCKET, SO_ERROR, &err, &len) && !err)
552                         result = 0;
553                 }
554             }
555         }
556         if(result == -1)
557             closesocket(netconn->socketFD);
558         else {
559             flag = 0;
560             ioctlsocket(netconn->socketFD, FIONBIO, &flag);
561         }
562     }
563     if(result == -1) {
564         heap_free(netconn);
565         return sock_get_error(errno);
566     }
567
568 #ifdef TCP_NODELAY
569     flag = 1;
570     result = setsockopt(netconn->socketFD, IPPROTO_TCP, TCP_NODELAY, (void*)&flag, sizeof(flag));
571     if(result < 0)
572         WARN("setsockopt(TCP_NODELAY) failed\n");
573 #endif
574
575     server_addref(server);
576     netconn->server = server;
577
578     *ret = netconn;
579     return ERROR_SUCCESS;
580 }
581
582 void free_netconn(netconn_t *netconn)
583 {
584     server_release(netconn->server);
585
586 #ifdef SONAME_LIBSSL
587     if (netconn->ssl_s) {
588         pSSL_shutdown(netconn->ssl_s);
589         pSSL_free(netconn->ssl_s);
590     }
591 #endif
592
593     closesocket(netconn->socketFD);
594     heap_free(netconn);
595 }
596
597 void NETCON_unload(void)
598 {
599 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
600     if (OpenSSL_crypto_handle)
601     {
602         pERR_free_strings();
603         wine_dlclose(OpenSSL_crypto_handle, NULL, 0);
604     }
605     if (OpenSSL_ssl_handle)
606     {
607         if (ctx)
608             pSSL_CTX_free(ctx);
609         wine_dlclose(OpenSSL_ssl_handle, NULL, 0);
610     }
611     if (ssl_locks)
612     {
613         int i;
614         for (i = 0; i < num_ssl_locks; i++)
615         {
616             ssl_locks[i].DebugInfo->Spare[0] = 0;
617             DeleteCriticalSection(&ssl_locks[i]);
618         }
619         heap_free(ssl_locks);
620     }
621 #endif
622 }
623
624 /* translate a unix error code into a winsock one */
625 int sock_get_error( int err )
626 {
627 #if !defined(__MINGW32__) && !defined (_MSC_VER)
628     switch (err)
629     {
630         case EINTR:             return WSAEINTR;
631         case EBADF:             return WSAEBADF;
632         case EPERM:
633         case EACCES:            return WSAEACCES;
634         case EFAULT:            return WSAEFAULT;
635         case EINVAL:            return WSAEINVAL;
636         case EMFILE:            return WSAEMFILE;
637         case EWOULDBLOCK:       return WSAEWOULDBLOCK;
638         case EINPROGRESS:       return WSAEINPROGRESS;
639         case EALREADY:          return WSAEALREADY;
640         case ENOTSOCK:          return WSAENOTSOCK;
641         case EDESTADDRREQ:      return WSAEDESTADDRREQ;
642         case EMSGSIZE:          return WSAEMSGSIZE;
643         case EPROTOTYPE:        return WSAEPROTOTYPE;
644         case ENOPROTOOPT:       return WSAENOPROTOOPT;
645         case EPROTONOSUPPORT:   return WSAEPROTONOSUPPORT;
646         case ESOCKTNOSUPPORT:   return WSAESOCKTNOSUPPORT;
647         case EOPNOTSUPP:        return WSAEOPNOTSUPP;
648         case EPFNOSUPPORT:      return WSAEPFNOSUPPORT;
649         case EAFNOSUPPORT:      return WSAEAFNOSUPPORT;
650         case EADDRINUSE:        return WSAEADDRINUSE;
651         case EADDRNOTAVAIL:     return WSAEADDRNOTAVAIL;
652         case ENETDOWN:          return WSAENETDOWN;
653         case ENETUNREACH:       return WSAENETUNREACH;
654         case ENETRESET:         return WSAENETRESET;
655         case ECONNABORTED:      return WSAECONNABORTED;
656         case EPIPE:
657         case ECONNRESET:        return WSAECONNRESET;
658         case ENOBUFS:           return WSAENOBUFS;
659         case EISCONN:           return WSAEISCONN;
660         case ENOTCONN:          return WSAENOTCONN;
661         case ESHUTDOWN:         return WSAESHUTDOWN;
662         case ETOOMANYREFS:      return WSAETOOMANYREFS;
663         case ETIMEDOUT:         return WSAETIMEDOUT;
664         case ECONNREFUSED:      return WSAECONNREFUSED;
665         case ELOOP:             return WSAELOOP;
666         case ENAMETOOLONG:      return WSAENAMETOOLONG;
667         case EHOSTDOWN:         return WSAEHOSTDOWN;
668         case EHOSTUNREACH:      return WSAEHOSTUNREACH;
669         case ENOTEMPTY:         return WSAENOTEMPTY;
670 #ifdef EPROCLIM
671         case EPROCLIM:          return WSAEPROCLIM;
672 #endif
673 #ifdef EUSERS
674         case EUSERS:            return WSAEUSERS;
675 #endif
676 #ifdef EDQUOT
677         case EDQUOT:            return WSAEDQUOT;
678 #endif
679 #ifdef ESTALE
680         case ESTALE:            return WSAESTALE;
681 #endif
682 #ifdef EREMOTE
683         case EREMOTE:           return WSAEREMOTE;
684 #endif
685     default: errno=err; perror("sock_set_error"); return WSAEFAULT;
686     }
687 #endif
688     return err;
689 }
690
691 /******************************************************************************
692  * NETCON_secure_connect
693  * Initiates a secure connection over an existing plaintext connection.
694  */
695 DWORD NETCON_secure_connect(netconn_t *connection, LPWSTR hostname)
696 {
697     DWORD res = ERROR_NOT_SUPPORTED;
698 #ifdef SONAME_LIBSSL
699     void *ssl_s;
700
701     /* can't connect if we are already connected */
702     if (connection->ssl_s)
703     {
704         ERR("already connected\n");
705         return ERROR_INTERNET_CANNOT_CONNECT;
706     }
707
708     ssl_s = pSSL_new(ctx);
709     if (!ssl_s)
710     {
711         ERR("SSL_new failed: %s\n",
712             pERR_error_string(pERR_get_error(), 0));
713         return ERROR_OUTOFMEMORY;
714     }
715
716     if (!pSSL_set_fd(ssl_s, connection->socketFD))
717     {
718         ERR("SSL_set_fd failed: %s\n",
719             pERR_error_string(pERR_get_error(), 0));
720         res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
721         goto fail;
722     }
723
724     if (!pSSL_set_ex_data(ssl_s, hostname_idx, hostname))
725     {
726         ERR("SSL_set_ex_data failed: %s\n",
727             pERR_error_string(pERR_get_error(), 0));
728         res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
729         goto fail;
730     }
731     if (!pSSL_set_ex_data(ssl_s, conn_idx, connection))
732     {
733         ERR("SSL_set_ex_data failed: %s\n",
734             pERR_error_string(pERR_get_error(), 0));
735         res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
736         goto fail;
737     }
738     if (pSSL_connect(ssl_s) <= 0)
739     {
740         res = (DWORD_PTR)pSSL_get_ex_data(ssl_s, error_idx);
741         if (!res)
742             res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
743         ERR("SSL_connect failed: %d\n", res);
744         goto fail;
745     }
746
747     connection->ssl_s = ssl_s;
748     return ERROR_SUCCESS;
749
750 fail:
751     if (ssl_s)
752     {
753         pSSL_shutdown(ssl_s);
754         pSSL_free(ssl_s);
755     }
756 #endif
757     return res;
758 }
759
760 /******************************************************************************
761  * NETCON_send
762  * Basically calls 'send()' unless we should use SSL
763  * number of chars send is put in *sent
764  */
765 DWORD NETCON_send(netconn_t *connection, const void *msg, size_t len, int flags,
766                 int *sent /* out */)
767 {
768     if (!connection->useSSL)
769     {
770         *sent = send(connection->socketFD, msg, len, flags);
771         if (*sent == -1)
772             return sock_get_error(errno);
773         return ERROR_SUCCESS;
774     }
775     else
776     {
777 #ifdef SONAME_LIBSSL
778         if(!connection->ssl_s) {
779             FIXME("not connected\n");
780             return ERROR_NOT_SUPPORTED;
781         }
782         if (flags)
783             FIXME("SSL_write doesn't support any flags (%08x)\n", flags);
784         *sent = pSSL_write(connection->ssl_s, msg, len);
785         if (*sent < 1 && len)
786             return ERROR_INTERNET_CONNECTION_ABORTED;
787         return ERROR_SUCCESS;
788 #else
789         return ERROR_NOT_SUPPORTED;
790 #endif
791     }
792 }
793
794 /******************************************************************************
795  * NETCON_recv
796  * Basically calls 'recv()' unless we should use SSL
797  * number of chars received is put in *recvd
798  */
799 DWORD NETCON_recv(netconn_t *connection, void *buf, size_t len, int flags,
800                 int *recvd /* out */)
801 {
802     *recvd = 0;
803     if (!len)
804         return ERROR_SUCCESS;
805     if (!connection->useSSL)
806     {
807         *recvd = recv(connection->socketFD, buf, len, flags);
808         return *recvd == -1 ? sock_get_error(errno) :  ERROR_SUCCESS;
809     }
810     else
811     {
812 #ifdef SONAME_LIBSSL
813         if(!connection->ssl_s) {
814             FIXME("not connected\n");
815             return ERROR_NOT_SUPPORTED;
816         }
817         *recvd = pSSL_read(connection->ssl_s, buf, len);
818
819         /* Check if EOF was received */
820         if(!*recvd && (pSSL_get_error(connection->ssl_s, *recvd)==SSL_ERROR_ZERO_RETURN
821                     || pSSL_get_error(connection->ssl_s, *recvd)==SSL_ERROR_SYSCALL))
822             return ERROR_SUCCESS;
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(netconn_t *connection, DWORD *available)
837 {
838     *available = 0;
839
840     if (!connection->useSSL)
841     {
842 #ifdef FIONREAD
843         int unread;
844         int retval = ioctlsocket(connection->socketFD, FIONREAD, &unread);
845         if (!retval)
846         {
847             TRACE("%d bytes of queued, but unread data\n", unread);
848             *available += unread;
849         }
850 #endif
851     }
852     else
853     {
854 #ifdef SONAME_LIBSSL
855         *available = connection->ssl_s ? pSSL_pending(connection->ssl_s) : 0;
856 #endif
857     }
858     return TRUE;
859 }
860
861 BOOL NETCON_is_alive(netconn_t *netconn)
862 {
863 #ifdef MSG_DONTWAIT
864     ssize_t len;
865     BYTE b;
866
867     len = recv(netconn->socketFD, &b, 1, MSG_PEEK|MSG_DONTWAIT);
868     return len == 1 || (len == -1 && errno == EWOULDBLOCK);
869 #elif defined(__MINGW32__) || defined(_MSC_VER)
870     ULONG mode;
871     int len;
872     char b;
873
874     mode = 1;
875     if(!ioctlsocket(netconn->socketFD, FIONBIO, &mode))
876         return FALSE;
877
878     len = recv(netconn->socketFD, &b, 1, MSG_PEEK);
879
880     mode = 0;
881     if(!ioctlsocket(netconn->socketFD, FIONBIO, &mode))
882         return FALSE;
883
884     return len == 1 || (len == -1 && errno == WSAEWOULDBLOCK);
885 #else
886     FIXME("not supported on this platform\n");
887     return TRUE;
888 #endif
889 }
890
891 LPCVOID NETCON_GetCert(netconn_t *connection)
892 {
893 #ifdef SONAME_LIBSSL
894     X509* cert;
895     LPCVOID r = NULL;
896
897     if (!connection->ssl_s)
898         return NULL;
899
900     cert = pSSL_get_peer_certificate(connection->ssl_s);
901     r = X509_to_cert_context(cert);
902     return r;
903 #else
904     return NULL;
905 #endif
906 }
907
908 int NETCON_GetCipherStrength(netconn_t *connection)
909 {
910 #ifdef SONAME_LIBSSL
911 #if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER >= 0x0090707f)
912     const SSL_CIPHER *cipher;
913 #else
914     SSL_CIPHER *cipher;
915 #endif
916     int bits = 0;
917
918     if (!connection->ssl_s)
919         return 0;
920     cipher = pSSL_get_current_cipher(connection->ssl_s);
921     if (!cipher)
922         return 0;
923     pSSL_CIPHER_get_bits(cipher, &bits);
924     return bits;
925 #else
926     return 0;
927 #endif
928 }
929
930 DWORD NETCON_set_timeout(netconn_t *connection, BOOL send, DWORD value)
931 {
932     int result;
933     struct timeval tv;
934
935     /* value is in milliseconds, convert to struct timeval */
936     if (value == INFINITE)
937     {
938         tv.tv_sec = 0;
939         tv.tv_usec = 0;
940     }
941     else
942     {
943         tv.tv_sec = value / 1000;
944         tv.tv_usec = (value % 1000) * 1000;
945     }
946     result = setsockopt(connection->socketFD, SOL_SOCKET,
947                         send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv,
948                         sizeof(tv));
949     if (result == -1)
950     {
951         WARN("setsockopt failed (%s)\n", strerror(errno));
952         return sock_get_error(errno);
953     }
954     return ERROR_SUCCESS;
955 }