wininet: Get rid of the SSL-specific read-ahead buffer.
[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 #if defined(__MINGW32__) || defined (_MSC_VER)
27 #include <ws2tcpip.h>
28 #endif
29
30 #include <sys/types.h>
31 #ifdef HAVE_POLL_H
32 #include <poll.h>
33 #endif
34 #ifdef HAVE_SYS_POLL_H
35 # include <sys/poll.h>
36 #endif
37 #ifdef HAVE_SYS_TIME_H
38 # include <sys/time.h>
39 #endif
40 #ifdef HAVE_SYS_SOCKET_H
41 # include <sys/socket.h>
42 #endif
43 #ifdef HAVE_SYS_FILIO_H
44 # include <sys/filio.h>
45 #endif
46 #ifdef HAVE_UNISTD_H
47 # include <unistd.h>
48 #endif
49 #ifdef HAVE_SYS_IOCTL_H
50 # include <sys/ioctl.h>
51 #endif
52 #include <time.h>
53 #ifdef HAVE_NETDB_H
54 # include <netdb.h>
55 #endif
56 #ifdef HAVE_NETINET_IN_H
57 # include <netinet/in.h>
58 #endif
59 #ifdef HAVE_OPENSSL_SSL_H
60 # include <openssl/ssl.h>
61 #undef FAR
62 #undef DSA
63 #endif
64
65 #include <stdarg.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include <stdio.h>
69 #include <errno.h>
70
71 #include "wine/library.h"
72 #include "windef.h"
73 #include "winbase.h"
74 #include "wininet.h"
75 #include "winerror.h"
76 #include "wincrypt.h"
77
78 #include "wine/debug.h"
79 #include "internet.h"
80
81 /* To avoid conflicts with the Unix socket headers. we only need it for
82  * the error codes anyway. */
83 #define USE_WS_PREFIX
84 #include "winsock2.h"
85
86 #define RESPONSE_TIMEOUT        30            /* FROM internet.c */
87
88
89 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
90
91 /* FIXME!!!!!!
92  *    This should use winsock - To use winsock the functions will have to change a bit
93  *        as they are designed for unix sockets.
94  *    SSL stuff should use crypt32.dll
95  */
96
97 #ifdef SONAME_LIBSSL
98
99 #include <openssl/err.h>
100
101 static void *OpenSSL_ssl_handle;
102 static void *OpenSSL_crypto_handle;
103
104 static SSL_METHOD *meth;
105 static SSL_CTX *ctx;
106
107 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
108
109 /* OpenSSL functions that we use */
110 MAKE_FUNCPTR(SSL_library_init);
111 MAKE_FUNCPTR(SSL_load_error_strings);
112 MAKE_FUNCPTR(SSLv23_method);
113 MAKE_FUNCPTR(SSL_CTX_new);
114 MAKE_FUNCPTR(SSL_new);
115 MAKE_FUNCPTR(SSL_free);
116 MAKE_FUNCPTR(SSL_set_fd);
117 MAKE_FUNCPTR(SSL_connect);
118 MAKE_FUNCPTR(SSL_shutdown);
119 MAKE_FUNCPTR(SSL_write);
120 MAKE_FUNCPTR(SSL_read);
121 MAKE_FUNCPTR(SSL_pending);
122 MAKE_FUNCPTR(SSL_get_verify_result);
123 MAKE_FUNCPTR(SSL_get_peer_certificate);
124 MAKE_FUNCPTR(SSL_CTX_get_timeout);
125 MAKE_FUNCPTR(SSL_CTX_set_timeout);
126 MAKE_FUNCPTR(SSL_CTX_set_default_verify_paths);
127
128 /* OpenSSL's libcrypto functions that we use */
129 MAKE_FUNCPTR(BIO_new_fp);
130 MAKE_FUNCPTR(ERR_get_error);
131 MAKE_FUNCPTR(ERR_error_string);
132 MAKE_FUNCPTR(i2d_X509);
133 #undef MAKE_FUNCPTR
134
135 #endif
136
137 BOOL NETCON_init(WININET_NETCONNECTION *connection, BOOL useSSL)
138 {
139     connection->useSSL = FALSE;
140     connection->socketFD = -1;
141     if (useSSL)
142     {
143 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
144         TRACE("using SSL connection\n");
145         if (OpenSSL_ssl_handle) /* already initialized everything */
146             return TRUE;
147         OpenSSL_ssl_handle = wine_dlopen(SONAME_LIBSSL, RTLD_NOW, NULL, 0);
148         if (!OpenSSL_ssl_handle)
149         {
150             ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n",
151                 SONAME_LIBSSL);
152             INTERNET_SetLastError(ERROR_INTERNET_SECURITY_CHANNEL_ERROR);
153             return FALSE;
154         }
155         OpenSSL_crypto_handle = wine_dlopen(SONAME_LIBCRYPTO, RTLD_NOW, NULL, 0);
156         if (!OpenSSL_crypto_handle)
157         {
158             ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n",
159                 SONAME_LIBCRYPTO);
160             INTERNET_SetLastError(ERROR_INTERNET_SECURITY_CHANNEL_ERROR);
161             return FALSE;
162         }
163
164         /* mmm nice ugly macroness */
165 #define DYNSSL(x) \
166     p##x = wine_dlsym(OpenSSL_ssl_handle, #x, NULL, 0); \
167     if (!p##x) \
168     { \
169         ERR("failed to load symbol %s\n", #x); \
170         INTERNET_SetLastError(ERROR_INTERNET_SECURITY_CHANNEL_ERROR); \
171         return FALSE; \
172     }
173
174         DYNSSL(SSL_library_init);
175         DYNSSL(SSL_load_error_strings);
176         DYNSSL(SSLv23_method);
177         DYNSSL(SSL_CTX_new);
178         DYNSSL(SSL_new);
179         DYNSSL(SSL_free);
180         DYNSSL(SSL_set_fd);
181         DYNSSL(SSL_connect);
182         DYNSSL(SSL_shutdown);
183         DYNSSL(SSL_write);
184         DYNSSL(SSL_read);
185         DYNSSL(SSL_pending);
186         DYNSSL(SSL_get_verify_result);
187         DYNSSL(SSL_get_peer_certificate);
188         DYNSSL(SSL_CTX_get_timeout);
189         DYNSSL(SSL_CTX_set_timeout);
190         DYNSSL(SSL_CTX_set_default_verify_paths);
191 #undef DYNSSL
192
193 #define DYNCRYPTO(x) \
194     p##x = wine_dlsym(OpenSSL_crypto_handle, #x, NULL, 0); \
195     if (!p##x) \
196     { \
197         ERR("failed to load symbol %s\n", #x); \
198         INTERNET_SetLastError(ERROR_INTERNET_SECURITY_CHANNEL_ERROR); \
199         return FALSE; \
200     }
201         DYNCRYPTO(BIO_new_fp);
202         DYNCRYPTO(ERR_get_error);
203         DYNCRYPTO(ERR_error_string);
204         DYNCRYPTO(i2d_X509);
205 #undef DYNCRYPTO
206
207         pSSL_library_init();
208         pSSL_load_error_strings();
209         pBIO_new_fp(stderr, BIO_NOCLOSE); /* FIXME: should use winedebug stuff */
210
211         meth = pSSLv23_method();
212 #else
213         FIXME("can't use SSL, not compiled in.\n");
214         INTERNET_SetLastError(ERROR_INTERNET_SECURITY_CHANNEL_ERROR);
215         return FALSE;
216 #endif
217     }
218     return TRUE;
219 }
220
221 BOOL NETCON_connected(WININET_NETCONNECTION *connection)
222 {
223     if (connection->socketFD == -1)
224         return FALSE;
225     else
226         return TRUE;
227 }
228
229 /* translate a unix error code into a winsock one */
230 static int sock_get_error( int err )
231 {
232 #if !defined(__MINGW32__) && !defined (_MSC_VER)
233     switch (err)
234     {
235         case EINTR:             return WSAEINTR;
236         case EBADF:             return WSAEBADF;
237         case EPERM:
238         case EACCES:            return WSAEACCES;
239         case EFAULT:            return WSAEFAULT;
240         case EINVAL:            return WSAEINVAL;
241         case EMFILE:            return WSAEMFILE;
242         case EWOULDBLOCK:       return WSAEWOULDBLOCK;
243         case EINPROGRESS:       return WSAEINPROGRESS;
244         case EALREADY:          return WSAEALREADY;
245         case ENOTSOCK:          return WSAENOTSOCK;
246         case EDESTADDRREQ:      return WSAEDESTADDRREQ;
247         case EMSGSIZE:          return WSAEMSGSIZE;
248         case EPROTOTYPE:        return WSAEPROTOTYPE;
249         case ENOPROTOOPT:       return WSAENOPROTOOPT;
250         case EPROTONOSUPPORT:   return WSAEPROTONOSUPPORT;
251         case ESOCKTNOSUPPORT:   return WSAESOCKTNOSUPPORT;
252         case EOPNOTSUPP:        return WSAEOPNOTSUPP;
253         case EPFNOSUPPORT:      return WSAEPFNOSUPPORT;
254         case EAFNOSUPPORT:      return WSAEAFNOSUPPORT;
255         case EADDRINUSE:        return WSAEADDRINUSE;
256         case EADDRNOTAVAIL:     return WSAEADDRNOTAVAIL;
257         case ENETDOWN:          return WSAENETDOWN;
258         case ENETUNREACH:       return WSAENETUNREACH;
259         case ENETRESET:         return WSAENETRESET;
260         case ECONNABORTED:      return WSAECONNABORTED;
261         case EPIPE:
262         case ECONNRESET:        return WSAECONNRESET;
263         case ENOBUFS:           return WSAENOBUFS;
264         case EISCONN:           return WSAEISCONN;
265         case ENOTCONN:          return WSAENOTCONN;
266         case ESHUTDOWN:         return WSAESHUTDOWN;
267         case ETOOMANYREFS:      return WSAETOOMANYREFS;
268         case ETIMEDOUT:         return WSAETIMEDOUT;
269         case ECONNREFUSED:      return WSAECONNREFUSED;
270         case ELOOP:             return WSAELOOP;
271         case ENAMETOOLONG:      return WSAENAMETOOLONG;
272         case EHOSTDOWN:         return WSAEHOSTDOWN;
273         case EHOSTUNREACH:      return WSAEHOSTUNREACH;
274         case ENOTEMPTY:         return WSAENOTEMPTY;
275 #ifdef EPROCLIM
276         case EPROCLIM:          return WSAEPROCLIM;
277 #endif
278 #ifdef EUSERS
279         case EUSERS:            return WSAEUSERS;
280 #endif
281 #ifdef EDQUOT
282         case EDQUOT:            return WSAEDQUOT;
283 #endif
284 #ifdef ESTALE
285         case ESTALE:            return WSAESTALE;
286 #endif
287 #ifdef EREMOTE
288         case EREMOTE:           return WSAEREMOTE;
289 #endif
290     default: errno=err; perror("sock_set_error"); return WSAEFAULT;
291     }
292 #endif
293     return err;
294 }
295
296 /******************************************************************************
297  * NETCON_create
298  * Basically calls 'socket()'
299  */
300 BOOL NETCON_create(WININET_NETCONNECTION *connection, int domain,
301               int type, int protocol)
302 {
303 #ifdef SONAME_LIBSSL
304     if (connection->useSSL)
305         return FALSE;
306 #endif
307
308     connection->socketFD = socket(domain, type, protocol);
309     if (connection->socketFD == -1)
310     {
311         INTERNET_SetLastError(sock_get_error(errno));
312         return FALSE;
313     }
314     return TRUE;
315 }
316
317 /******************************************************************************
318  * NETCON_close
319  * Basically calls 'close()' unless we should use SSL
320  */
321 BOOL NETCON_close(WININET_NETCONNECTION *connection)
322 {
323     int result;
324
325     if (!NETCON_connected(connection)) return FALSE;
326
327 #ifdef SONAME_LIBSSL
328     if (connection->useSSL)
329     {
330         pSSL_shutdown(connection->ssl_s);
331         pSSL_free(connection->ssl_s);
332         connection->ssl_s = NULL;
333
334         connection->useSSL = FALSE;
335     }
336 #endif
337
338     result = closesocket(connection->socketFD);
339     connection->socketFD = -1;
340
341     if (result == -1)
342     {
343         INTERNET_SetLastError(sock_get_error(errno));
344         return FALSE;
345     }
346     return TRUE;
347 }
348 #ifdef SONAME_LIBSSL
349 static BOOL check_hostname(X509 *cert, char *hostname)
350 {
351     /* FIXME: implement */
352     return TRUE;
353 }
354 #endif
355 /******************************************************************************
356  * NETCON_secure_connect
357  * Initiates a secure connection over an existing plaintext connection.
358  */
359 BOOL NETCON_secure_connect(WININET_NETCONNECTION *connection, LPCWSTR hostname)
360 {
361 #ifdef SONAME_LIBSSL
362     long verify_res;
363     X509 *cert;
364     int len;
365     char *hostname_unix;
366
367     /* can't connect if we are already connected */
368     if (connection->useSSL)
369     {
370         ERR("already connected\n");
371         return FALSE;
372     }
373
374     ctx = pSSL_CTX_new(meth);
375     if (!pSSL_CTX_set_default_verify_paths(ctx))
376     {
377         ERR("SSL_CTX_set_default_verify_paths failed: %s\n",
378             pERR_error_string(pERR_get_error(), 0));
379         INTERNET_SetLastError(ERROR_OUTOFMEMORY);
380         return FALSE;
381     }
382     connection->ssl_s = pSSL_new(ctx);
383     if (!connection->ssl_s)
384     {
385         ERR("SSL_new failed: %s\n",
386             pERR_error_string(pERR_get_error(), 0));
387         INTERNET_SetLastError(ERROR_OUTOFMEMORY);
388         goto fail;
389     }
390
391     if (!pSSL_set_fd(connection->ssl_s, connection->socketFD))
392     {
393         ERR("SSL_set_fd failed: %s\n",
394             pERR_error_string(pERR_get_error(), 0));
395         INTERNET_SetLastError(ERROR_INTERNET_SECURITY_CHANNEL_ERROR);
396         goto fail;
397     }
398
399     if (pSSL_connect(connection->ssl_s) <= 0)
400     {
401         ERR("SSL_connect failed: %s\n",
402             pERR_error_string(pERR_get_error(), 0));
403         INTERNET_SetLastError(ERROR_INTERNET_SECURITY_CHANNEL_ERROR);
404         goto fail;
405     }
406     cert = pSSL_get_peer_certificate(connection->ssl_s);
407     if (!cert)
408     {
409         ERR("no certificate for server %s\n", debugstr_w(hostname));
410         /* FIXME: is this the best error? */
411         INTERNET_SetLastError(ERROR_INTERNET_INVALID_CA);
412         goto fail;
413     }
414     verify_res = pSSL_get_verify_result(connection->ssl_s);
415     if (verify_res != X509_V_OK)
416     {
417         ERR("couldn't verify the security of the connection, %ld\n", verify_res);
418         /* FIXME: we should set an error and return, but we only warn at
419          * the moment */
420     }
421
422     len = WideCharToMultiByte(CP_UNIXCP, 0, hostname, -1, NULL, 0, NULL, NULL);
423     hostname_unix = HeapAlloc(GetProcessHeap(), 0, len);
424     if (!hostname_unix)
425     {
426         INTERNET_SetLastError(ERROR_OUTOFMEMORY);
427         goto fail;
428     }
429     WideCharToMultiByte(CP_UNIXCP, 0, hostname, -1, hostname_unix, len, NULL, NULL);
430
431     if (!check_hostname(cert, hostname_unix))
432     {
433         HeapFree(GetProcessHeap(), 0, hostname_unix);
434         INTERNET_SetLastError(ERROR_INTERNET_SEC_CERT_CN_INVALID);
435         goto fail;
436     }
437
438     HeapFree(GetProcessHeap(), 0, hostname_unix);
439     connection->useSSL = TRUE;
440     return TRUE;
441
442 fail:
443     if (connection->ssl_s)
444     {
445         pSSL_shutdown(connection->ssl_s);
446         pSSL_free(connection->ssl_s);
447         connection->ssl_s = NULL;
448     }
449 #endif
450     return FALSE;
451 }
452
453 /******************************************************************************
454  * NETCON_connect
455  * Connects to the specified address.
456  */
457 BOOL NETCON_connect(WININET_NETCONNECTION *connection, const struct sockaddr *serv_addr,
458                     unsigned int addrlen)
459 {
460     int result;
461
462     if (!NETCON_connected(connection)) return FALSE;
463
464     result = connect(connection->socketFD, serv_addr, addrlen);
465     if (result == -1)
466     {
467         WARN("Unable to connect to host (%s)\n", strerror(errno));
468         INTERNET_SetLastError(sock_get_error(errno));
469
470         closesocket(connection->socketFD);
471         connection->socketFD = -1;
472         return FALSE;
473     }
474
475     return TRUE;
476 }
477
478 /******************************************************************************
479  * NETCON_send
480  * Basically calls 'send()' unless we should use SSL
481  * number of chars send is put in *sent
482  */
483 BOOL NETCON_send(WININET_NETCONNECTION *connection, const void *msg, size_t len, int flags,
484                 int *sent /* out */)
485 {
486     if (!NETCON_connected(connection)) return FALSE;
487     if (!connection->useSSL)
488     {
489         *sent = send(connection->socketFD, msg, len, flags);
490         if (*sent == -1)
491         {
492             INTERNET_SetLastError(sock_get_error(errno));
493             return FALSE;
494         }
495         return TRUE;
496     }
497     else
498     {
499 #ifdef SONAME_LIBSSL
500         if (flags)
501             FIXME("SSL_write doesn't support any flags (%08x)\n", flags);
502         *sent = pSSL_write(connection->ssl_s, msg, len);
503         if (*sent < 1 && len)
504             return FALSE;
505         return TRUE;
506 #else
507         return FALSE;
508 #endif
509     }
510 }
511
512 /******************************************************************************
513  * NETCON_recv
514  * Basically calls 'recv()' unless we should use SSL
515  * number of chars received is put in *recvd
516  */
517 BOOL NETCON_recv(WININET_NETCONNECTION *connection, void *buf, size_t len, int flags,
518                 int *recvd /* out */)
519 {
520     *recvd = 0;
521     if (!NETCON_connected(connection)) return FALSE;
522     if (!len)
523         return TRUE;
524     if (!connection->useSSL)
525     {
526         *recvd = recv(connection->socketFD, buf, len, flags);
527         if (*recvd == -1)
528         {
529             INTERNET_SetLastError(sock_get_error(errno));
530             return FALSE;
531         }
532         return TRUE;
533     }
534     else
535     {
536 #ifdef SONAME_LIBSSL
537         *recvd = pSSL_read(connection->ssl_s, buf, len);
538         return *recvd > 0 || !len;
539 #else
540         return FALSE;
541 #endif
542     }
543 }
544
545 /******************************************************************************
546  * NETCON_query_data_available
547  * Returns the number of bytes of peeked data plus the number of bytes of
548  * queued, but unread data.
549  */
550 BOOL NETCON_query_data_available(WININET_NETCONNECTION *connection, DWORD *available)
551 {
552     *available = 0;
553     if (!NETCON_connected(connection))
554         return FALSE;
555
556     if (!connection->useSSL)
557     {
558 #ifdef FIONREAD
559         int unread;
560         int retval = ioctlsocket(connection->socketFD, FIONREAD, &unread);
561         if (!retval)
562         {
563             TRACE("%d bytes of queued, but unread data\n", unread);
564             *available += unread;
565         }
566 #endif
567     }
568     else
569     {
570 #ifdef SONAME_LIBSSL
571         *available = pSSL_pending(connection->ssl_s);
572 #endif
573     }
574     return TRUE;
575 }
576
577 LPCVOID NETCON_GetCert(WININET_NETCONNECTION *connection)
578 {
579 #ifdef SONAME_LIBSSL
580     X509* cert;
581     unsigned char* buffer,*p;
582     INT len;
583     BOOL malloced = FALSE;
584     LPCVOID r = NULL;
585
586     if (!connection->useSSL)
587         return NULL;
588
589     cert = pSSL_get_peer_certificate(connection->ssl_s);
590     p = NULL;
591     len = pi2d_X509(cert,&p);
592     /*
593      * SSL 0.9.7 and above malloc the buffer if it is null. 
594      * however earlier version do not and so we would need to alloc the buffer.
595      *
596      * see the i2d_X509 man page for more details.
597      */
598     if (!p)
599     {
600         buffer = HeapAlloc(GetProcessHeap(),0,len);
601         p = buffer;
602         len = pi2d_X509(cert,&p);
603     }
604     else
605     {
606         buffer = p;
607         malloced = TRUE;
608     }
609
610     r = CertCreateCertificateContext(X509_ASN_ENCODING,buffer,len);
611
612     if (malloced)
613         free(buffer);
614     else
615         HeapFree(GetProcessHeap(),0,buffer);
616
617     return r;
618 #else
619     return NULL;
620 #endif
621 }
622
623 DWORD NETCON_set_timeout(WININET_NETCONNECTION *connection, BOOL send, int value)
624 {
625     int result;
626     struct timeval tv;
627
628     /* FIXME: we should probably store the timeout in the connection to set
629      * when we do connect */
630     if (!NETCON_connected(connection))
631         return ERROR_SUCCESS;
632
633     /* value is in milliseconds, convert to struct timeval */
634     tv.tv_sec = value / 1000;
635     tv.tv_usec = (value % 1000) * 1000;
636
637     result = setsockopt(connection->socketFD, SOL_SOCKET,
638                         send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv,
639                         sizeof(tv));
640
641     if (result == -1)
642     {
643         WARN("setsockopt failed (%s)\n", strerror(errno));
644         return sock_get_error(errno);
645     }
646
647     return ERROR_SUCCESS;
648 }