urlmon: Store URI host len in parse_ipv4address before further parsing.
[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_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 &&
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     WCHAR *server;
312     BOOL ret = FALSE;
313     HCERTSTORE store = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
314         CERT_STORE_CREATE_NEW_FLAG, NULL);
315     netconn_t *conn;
316
317     ssl = pX509_STORE_CTX_get_ex_data(ctx,
318         pSSL_get_ex_data_X509_STORE_CTX_idx());
319     server = pSSL_get_ex_data(ssl, hostname_idx);
320     conn = pSSL_get_ex_data(ssl, conn_idx);
321     if (store)
322     {
323         X509 *cert;
324         int i;
325         PCCERT_CONTEXT endCert = NULL;
326         struct stack_st *chain = (struct stack_st *)pX509_STORE_CTX_get_chain( ctx );
327
328         ret = TRUE;
329         for (i = 0; ret && i < psk_num(chain); i++)
330         {
331             PCCERT_CONTEXT context;
332
333             cert = (X509 *)psk_value(chain, i);
334             if ((context = X509_to_cert_context(cert)))
335             {
336                 ret = CertAddCertificateContextToStore(store, context,
337                         CERT_STORE_ADD_ALWAYS, i ? NULL : &endCert);
338                 CertFreeCertificateContext(context);
339             }
340         }
341         if (!endCert) ret = FALSE;
342         if (ret)
343         {
344             DWORD_PTR err = netconn_verify_cert(endCert, store, server,
345                                                 conn->security_flags);
346
347             if (err)
348             {
349                 pSSL_set_ex_data(ssl, error_idx, (void *)err);
350                 ret = FALSE;
351             }
352         }
353         CertFreeCertificateContext(endCert);
354         CertCloseStore(store, 0);
355     }
356     return ret;
357 }
358
359 #endif
360
361 static CRITICAL_SECTION init_ssl_cs;
362 static CRITICAL_SECTION_DEBUG init_ssl_cs_debug =
363 {
364     0, 0, &init_ssl_cs,
365     { &init_ssl_cs_debug.ProcessLocksList,
366       &init_ssl_cs_debug.ProcessLocksList },
367     0, 0, { (DWORD_PTR)(__FILE__ ": init_ssl_cs") }
368 };
369 static CRITICAL_SECTION init_ssl_cs = { &init_ssl_cs_debug, -1, 0, 0, 0, 0 };
370
371 static DWORD init_openssl(void)
372 {
373 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
374     int i;
375
376     if(OpenSSL_ssl_handle)
377         return ERROR_SUCCESS;
378
379     OpenSSL_ssl_handle = wine_dlopen(SONAME_LIBSSL, RTLD_NOW, NULL, 0);
380     if(!OpenSSL_ssl_handle) {
381         ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n", SONAME_LIBSSL);
382         return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
383     }
384
385     OpenSSL_crypto_handle = wine_dlopen(SONAME_LIBCRYPTO, RTLD_NOW, NULL, 0);
386     if(!OpenSSL_crypto_handle) {
387         ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n", SONAME_LIBCRYPTO);
388         return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
389     }
390
391     /* mmm nice ugly macroness */
392 #define DYNSSL(x) \
393     p##x = wine_dlsym(OpenSSL_ssl_handle, #x, NULL, 0); \
394     if (!p##x) { \
395         ERR("failed to load symbol %s\n", #x); \
396         return ERROR_INTERNET_SECURITY_CHANNEL_ERROR; \
397     }
398
399     DYNSSL(SSL_library_init);
400     DYNSSL(SSL_load_error_strings);
401     DYNSSL(SSLv23_method);
402     DYNSSL(SSL_CTX_free);
403     DYNSSL(SSL_CTX_new);
404     DYNSSL(SSL_new);
405     DYNSSL(SSL_free);
406     DYNSSL(SSL_set_fd);
407     DYNSSL(SSL_connect);
408     DYNSSL(SSL_shutdown);
409     DYNSSL(SSL_write);
410     DYNSSL(SSL_read);
411     DYNSSL(SSL_pending);
412     DYNSSL(SSL_get_error);
413     DYNSSL(SSL_get_ex_new_index);
414     DYNSSL(SSL_get_ex_data);
415     DYNSSL(SSL_set_ex_data);
416     DYNSSL(SSL_get_ex_data_X509_STORE_CTX_idx);
417     DYNSSL(SSL_get_peer_certificate);
418     DYNSSL(SSL_CTX_get_timeout);
419     DYNSSL(SSL_CTX_set_timeout);
420     DYNSSL(SSL_CTX_set_default_verify_paths);
421     DYNSSL(SSL_CTX_set_verify);
422     DYNSSL(SSL_get_current_cipher);
423     DYNSSL(SSL_CIPHER_get_bits);
424 #undef DYNSSL
425
426 #define DYNCRYPTO(x) \
427     p##x = wine_dlsym(OpenSSL_crypto_handle, #x, NULL, 0); \
428     if (!p##x) { \
429         ERR("failed to load symbol %s\n", #x); \
430         return ERROR_INTERNET_SECURITY_CHANNEL_ERROR; \
431     }
432
433     DYNCRYPTO(BIO_new_fp);
434     DYNCRYPTO(CRYPTO_num_locks);
435     DYNCRYPTO(CRYPTO_set_id_callback);
436     DYNCRYPTO(CRYPTO_set_locking_callback);
437     DYNCRYPTO(ERR_free_strings);
438     DYNCRYPTO(ERR_get_error);
439     DYNCRYPTO(ERR_error_string);
440     DYNCRYPTO(X509_STORE_CTX_get_ex_data);
441     DYNCRYPTO(X509_STORE_CTX_get_chain);
442     DYNCRYPTO(i2d_X509);
443     DYNCRYPTO(sk_num);
444     DYNCRYPTO(sk_value);
445 #undef DYNCRYPTO
446
447     pSSL_library_init();
448     pSSL_load_error_strings();
449     pBIO_new_fp(stderr, BIO_NOCLOSE); /* FIXME: should use winedebug stuff */
450
451     meth = pSSLv23_method();
452     ctx = pSSL_CTX_new(meth);
453     if(!pSSL_CTX_set_default_verify_paths(ctx)) {
454         ERR("SSL_CTX_set_default_verify_paths failed: %s\n",
455             pERR_error_string(pERR_get_error(), 0));
456         return ERROR_OUTOFMEMORY;
457     }
458
459     hostname_idx = pSSL_get_ex_new_index(0, (void *)"hostname index", NULL, NULL, NULL);
460     if(hostname_idx == -1) {
461         ERR("SSL_get_ex_new_index failed; %s\n", pERR_error_string(pERR_get_error(), 0));
462         return ERROR_OUTOFMEMORY;
463     }
464
465     error_idx = pSSL_get_ex_new_index(0, (void *)"error index", NULL, NULL, NULL);
466     if(error_idx == -1) {
467         ERR("SSL_get_ex_new_index failed; %s\n", pERR_error_string(pERR_get_error(), 0));
468         return ERROR_OUTOFMEMORY;
469     }
470
471     conn_idx = pSSL_get_ex_new_index(0, (void *)"netconn index", NULL, NULL, NULL);
472     if(conn_idx == -1) {
473         ERR("SSL_get_ex_new_index failed; %s\n", pERR_error_string(pERR_get_error(), 0));
474         return ERROR_OUTOFMEMORY;
475     }
476
477     pSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, netconn_secure_verify);
478
479     pCRYPTO_set_id_callback(ssl_thread_id);
480     num_ssl_locks = pCRYPTO_num_locks();
481     ssl_locks = heap_alloc(num_ssl_locks * sizeof(CRITICAL_SECTION));
482     if(!ssl_locks)
483         return ERROR_OUTOFMEMORY;
484
485     for(i = 0; i < num_ssl_locks; i++)
486         InitializeCriticalSection(&ssl_locks[i]);
487     pCRYPTO_set_locking_callback(ssl_lock_callback);
488
489     return ERROR_SUCCESS;
490 #else
491     FIXME("can't use SSL, not compiled in.\n");
492     return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
493 #endif
494 }
495
496 DWORD create_netconn(BOOL useSSL, server_t *server, DWORD security_flags, netconn_t **ret)
497 {
498     netconn_t *netconn;
499     int result, flag;
500
501     if(useSSL) {
502         DWORD res;
503
504         TRACE("using SSL connection\n");
505
506         EnterCriticalSection(&init_ssl_cs);
507         res = init_openssl();
508         LeaveCriticalSection(&init_ssl_cs);
509         if(res != ERROR_SUCCESS)
510             return res;
511     }
512
513     netconn = heap_alloc_zero(sizeof(*netconn));
514     if(!netconn)
515         return ERROR_OUTOFMEMORY;
516
517     netconn->useSSL = useSSL;
518     netconn->socketFD = -1;
519     netconn->security_flags = security_flags;
520     list_init(&netconn->pool_entry);
521
522     assert(server->addr_len);
523     result = netconn->socketFD = socket(server->addr.ss_family, SOCK_STREAM, 0);
524     if(result != -1) {
525         result = connect(netconn->socketFD, (struct sockaddr*)&server->addr, server->addr_len);
526         if(result == -1)
527             closesocket(netconn->socketFD);
528     }
529     if(result == -1) {
530         heap_free(netconn);
531         return sock_get_error(errno);
532     }
533
534 #ifdef TCP_NODELAY
535     flag = 1;
536     result = setsockopt(netconn->socketFD, IPPROTO_TCP, TCP_NODELAY, (void*)&flag, sizeof(flag));
537     if(result < 0)
538         WARN("setsockopt(TCP_NODELAY) failed\n");
539 #endif
540
541     server_addref(server);
542     netconn->server = server;
543
544     *ret = netconn;
545     return ERROR_SUCCESS;
546 }
547
548 void free_netconn(netconn_t *netconn)
549 {
550     server_release(netconn->server);
551
552 #ifdef SONAME_LIBSSL
553     if (netconn->ssl_s) {
554         pSSL_shutdown(netconn->ssl_s);
555         pSSL_free(netconn->ssl_s);
556     }
557 #endif
558
559     closesocket(netconn->socketFD);
560     heap_free(netconn);
561 }
562
563 void NETCON_unload(void)
564 {
565 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
566     if (OpenSSL_crypto_handle)
567     {
568         pERR_free_strings();
569         wine_dlclose(OpenSSL_crypto_handle, NULL, 0);
570     }
571     if (OpenSSL_ssl_handle)
572     {
573         if (ctx)
574             pSSL_CTX_free(ctx);
575         wine_dlclose(OpenSSL_ssl_handle, NULL, 0);
576     }
577     if (ssl_locks)
578     {
579         int i;
580         for (i = 0; i < num_ssl_locks; i++) DeleteCriticalSection(&ssl_locks[i]);
581         heap_free(ssl_locks);
582     }
583 #endif
584 }
585
586 /* translate a unix error code into a winsock one */
587 int sock_get_error( int err )
588 {
589 #if !defined(__MINGW32__) && !defined (_MSC_VER)
590     switch (err)
591     {
592         case EINTR:             return WSAEINTR;
593         case EBADF:             return WSAEBADF;
594         case EPERM:
595         case EACCES:            return WSAEACCES;
596         case EFAULT:            return WSAEFAULT;
597         case EINVAL:            return WSAEINVAL;
598         case EMFILE:            return WSAEMFILE;
599         case EWOULDBLOCK:       return WSAEWOULDBLOCK;
600         case EINPROGRESS:       return WSAEINPROGRESS;
601         case EALREADY:          return WSAEALREADY;
602         case ENOTSOCK:          return WSAENOTSOCK;
603         case EDESTADDRREQ:      return WSAEDESTADDRREQ;
604         case EMSGSIZE:          return WSAEMSGSIZE;
605         case EPROTOTYPE:        return WSAEPROTOTYPE;
606         case ENOPROTOOPT:       return WSAENOPROTOOPT;
607         case EPROTONOSUPPORT:   return WSAEPROTONOSUPPORT;
608         case ESOCKTNOSUPPORT:   return WSAESOCKTNOSUPPORT;
609         case EOPNOTSUPP:        return WSAEOPNOTSUPP;
610         case EPFNOSUPPORT:      return WSAEPFNOSUPPORT;
611         case EAFNOSUPPORT:      return WSAEAFNOSUPPORT;
612         case EADDRINUSE:        return WSAEADDRINUSE;
613         case EADDRNOTAVAIL:     return WSAEADDRNOTAVAIL;
614         case ENETDOWN:          return WSAENETDOWN;
615         case ENETUNREACH:       return WSAENETUNREACH;
616         case ENETRESET:         return WSAENETRESET;
617         case ECONNABORTED:      return WSAECONNABORTED;
618         case EPIPE:
619         case ECONNRESET:        return WSAECONNRESET;
620         case ENOBUFS:           return WSAENOBUFS;
621         case EISCONN:           return WSAEISCONN;
622         case ENOTCONN:          return WSAENOTCONN;
623         case ESHUTDOWN:         return WSAESHUTDOWN;
624         case ETOOMANYREFS:      return WSAETOOMANYREFS;
625         case ETIMEDOUT:         return WSAETIMEDOUT;
626         case ECONNREFUSED:      return WSAECONNREFUSED;
627         case ELOOP:             return WSAELOOP;
628         case ENAMETOOLONG:      return WSAENAMETOOLONG;
629         case EHOSTDOWN:         return WSAEHOSTDOWN;
630         case EHOSTUNREACH:      return WSAEHOSTUNREACH;
631         case ENOTEMPTY:         return WSAENOTEMPTY;
632 #ifdef EPROCLIM
633         case EPROCLIM:          return WSAEPROCLIM;
634 #endif
635 #ifdef EUSERS
636         case EUSERS:            return WSAEUSERS;
637 #endif
638 #ifdef EDQUOT
639         case EDQUOT:            return WSAEDQUOT;
640 #endif
641 #ifdef ESTALE
642         case ESTALE:            return WSAESTALE;
643 #endif
644 #ifdef EREMOTE
645         case EREMOTE:           return WSAEREMOTE;
646 #endif
647     default: errno=err; perror("sock_set_error"); return WSAEFAULT;
648     }
649 #endif
650     return err;
651 }
652
653 /******************************************************************************
654  * NETCON_secure_connect
655  * Initiates a secure connection over an existing plaintext connection.
656  */
657 DWORD NETCON_secure_connect(netconn_t *connection, LPWSTR hostname)
658 {
659     DWORD res = ERROR_NOT_SUPPORTED;
660 #ifdef SONAME_LIBSSL
661     void *ssl_s;
662
663     /* can't connect if we are already connected */
664     if (connection->ssl_s)
665     {
666         ERR("already connected\n");
667         return ERROR_INTERNET_CANNOT_CONNECT;
668     }
669
670     ssl_s = pSSL_new(ctx);
671     if (!ssl_s)
672     {
673         ERR("SSL_new failed: %s\n",
674             pERR_error_string(pERR_get_error(), 0));
675         return ERROR_OUTOFMEMORY;
676     }
677
678     if (!pSSL_set_fd(ssl_s, connection->socketFD))
679     {
680         ERR("SSL_set_fd failed: %s\n",
681             pERR_error_string(pERR_get_error(), 0));
682         res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
683         goto fail;
684     }
685
686     if (!pSSL_set_ex_data(ssl_s, hostname_idx, hostname))
687     {
688         ERR("SSL_set_ex_data failed: %s\n",
689             pERR_error_string(pERR_get_error(), 0));
690         res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
691         goto fail;
692     }
693     if (!pSSL_set_ex_data(ssl_s, conn_idx, connection))
694     {
695         ERR("SSL_set_ex_data failed: %s\n",
696             pERR_error_string(pERR_get_error(), 0));
697         res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
698         goto fail;
699     }
700     if (pSSL_connect(ssl_s) <= 0)
701     {
702         res = (DWORD_PTR)pSSL_get_ex_data(ssl_s, error_idx);
703         if (!res)
704             res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
705         ERR("SSL_connect failed: %d\n", res);
706         goto fail;
707     }
708
709     connection->ssl_s = ssl_s;
710     return ERROR_SUCCESS;
711
712 fail:
713     if (ssl_s)
714     {
715         pSSL_shutdown(ssl_s);
716         pSSL_free(ssl_s);
717     }
718 #endif
719     return res;
720 }
721
722 /******************************************************************************
723  * NETCON_send
724  * Basically calls 'send()' unless we should use SSL
725  * number of chars send is put in *sent
726  */
727 DWORD NETCON_send(netconn_t *connection, const void *msg, size_t len, int flags,
728                 int *sent /* out */)
729 {
730     if (!connection->useSSL)
731     {
732         *sent = send(connection->socketFD, msg, len, flags);
733         if (*sent == -1)
734             return sock_get_error(errno);
735         return ERROR_SUCCESS;
736     }
737     else
738     {
739 #ifdef SONAME_LIBSSL
740         if(!connection->ssl_s) {
741             FIXME("not connected\n");
742             return ERROR_NOT_SUPPORTED;
743         }
744         if (flags)
745             FIXME("SSL_write doesn't support any flags (%08x)\n", flags);
746         *sent = pSSL_write(connection->ssl_s, msg, len);
747         if (*sent < 1 && len)
748             return ERROR_INTERNET_CONNECTION_ABORTED;
749         return ERROR_SUCCESS;
750 #else
751         return ERROR_NOT_SUPPORTED;
752 #endif
753     }
754 }
755
756 /******************************************************************************
757  * NETCON_recv
758  * Basically calls 'recv()' unless we should use SSL
759  * number of chars received is put in *recvd
760  */
761 DWORD NETCON_recv(netconn_t *connection, void *buf, size_t len, int flags,
762                 int *recvd /* out */)
763 {
764     *recvd = 0;
765     if (!len)
766         return ERROR_SUCCESS;
767     if (!connection->useSSL)
768     {
769         *recvd = recv(connection->socketFD, buf, len, flags);
770         return *recvd == -1 ? sock_get_error(errno) :  ERROR_SUCCESS;
771     }
772     else
773     {
774 #ifdef SONAME_LIBSSL
775         if(!connection->ssl_s) {
776             FIXME("not connected\n");
777             return ERROR_NOT_SUPPORTED;
778         }
779         *recvd = pSSL_read(connection->ssl_s, buf, len);
780
781         /* Check if EOF was received */
782         if(!*recvd && (pSSL_get_error(connection->ssl_s, *recvd)==SSL_ERROR_ZERO_RETURN
783                     || pSSL_get_error(connection->ssl_s, *recvd)==SSL_ERROR_SYSCALL))
784             return ERROR_SUCCESS;
785
786         return *recvd > 0 ? ERROR_SUCCESS : ERROR_INTERNET_CONNECTION_ABORTED;
787 #else
788         return ERROR_NOT_SUPPORTED;
789 #endif
790     }
791 }
792
793 /******************************************************************************
794  * NETCON_query_data_available
795  * Returns the number of bytes of peeked data plus the number of bytes of
796  * queued, but unread data.
797  */
798 BOOL NETCON_query_data_available(netconn_t *connection, DWORD *available)
799 {
800     *available = 0;
801
802     if (!connection->useSSL)
803     {
804 #ifdef FIONREAD
805         int unread;
806         int retval = ioctlsocket(connection->socketFD, FIONREAD, &unread);
807         if (!retval)
808         {
809             TRACE("%d bytes of queued, but unread data\n", unread);
810             *available += unread;
811         }
812 #endif
813     }
814     else
815     {
816 #ifdef SONAME_LIBSSL
817         *available = connection->ssl_s ? pSSL_pending(connection->ssl_s) : 0;
818 #endif
819     }
820     return TRUE;
821 }
822
823 BOOL NETCON_is_alive(netconn_t *netconn)
824 {
825 #ifdef MSG_DONTWAIT
826     ssize_t len;
827     BYTE b;
828
829     len = recv(netconn->socketFD, &b, 1, MSG_PEEK|MSG_DONTWAIT);
830     return len == 1 || (len == -1 && errno == EWOULDBLOCK);
831 #elif defined(__MINGW32__) || defined(_MSC_VER)
832     ULONG mode;
833     int len;
834     char b;
835
836     mode = 1;
837     if(!ioctlsocket(netconn->socketFD, FIONBIO, &mode))
838         return FALSE;
839
840     len = recv(netconn->socketFD, &b, 1, MSG_PEEK);
841
842     mode = 0;
843     if(!ioctlsocket(netconn->socketFD, FIONBIO, &mode))
844         return FALSE;
845
846     return len == 1 || (len == -1 && errno == WSAEWOULDBLOCK);
847 #else
848     FIXME("not supported on this platform\n");
849     return TRUE;
850 #endif
851 }
852
853 LPCVOID NETCON_GetCert(netconn_t *connection)
854 {
855 #ifdef SONAME_LIBSSL
856     X509* cert;
857     LPCVOID r = NULL;
858
859     if (!connection->ssl_s)
860         return NULL;
861
862     cert = pSSL_get_peer_certificate(connection->ssl_s);
863     r = X509_to_cert_context(cert);
864     return r;
865 #else
866     return NULL;
867 #endif
868 }
869
870 int NETCON_GetCipherStrength(netconn_t *connection)
871 {
872 #ifdef SONAME_LIBSSL
873 #if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER >= 0x0090707f)
874     const SSL_CIPHER *cipher;
875 #else
876     SSL_CIPHER *cipher;
877 #endif
878     int bits = 0;
879
880     if (!connection->ssl_s)
881         return 0;
882     cipher = pSSL_get_current_cipher(connection->ssl_s);
883     if (!cipher)
884         return 0;
885     pSSL_CIPHER_get_bits(cipher, &bits);
886     return bits;
887 #else
888     return 0;
889 #endif
890 }
891
892 DWORD NETCON_set_timeout(netconn_t *connection, BOOL send, int value)
893 {
894     int result;
895     struct timeval tv;
896
897     /* value is in milliseconds, convert to struct timeval */
898     tv.tv_sec = value / 1000;
899     tv.tv_usec = (value % 1000) * 1000;
900
901     result = setsockopt(connection->socketFD, SOL_SOCKET,
902                         send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv,
903                         sizeof(tv));
904
905     if (result == -1)
906     {
907         WARN("setsockopt failed (%s)\n", strerror(errno));
908         return sock_get_error(errno);
909     }
910
911     return ERROR_SUCCESS;
912 }