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