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