winhttp: Implement WinHttpQueryHeaders(WINHTTP_QUERY_RAW_HEADERS).
[wine] / dlls / winhttp / net.c
1 /*
2  * Copyright 2008 Hans Leidekker for CodeWeavers
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
17  */
18
19 #include "config.h"
20 #include "wine/port.h"
21
22 #include <stdarg.h>
23 #include <stdio.h>
24 #include <errno.h>
25
26 #include <sys/types.h>
27 #ifdef HAVE_SYS_SOCKET_H
28 # include <sys/socket.h>
29 #endif
30 #ifdef HAVE_SYS_IOCTL_H
31 # include <sys/ioctl.h>
32 #endif
33 #ifdef HAVE_SYS_FILIO_H
34 # include <sys/filio.h>
35 #endif
36 #ifdef HAVE_POLL_H
37 # include <poll.h>
38 #endif
39 #ifdef HAVE_OPENSSL_SSL_H
40 # include <openssl/ssl.h>
41 #undef FAR
42 #undef DSA
43 #endif
44
45 #include "wine/debug.h"
46 #include "wine/library.h"
47
48 #include "windef.h"
49 #include "winbase.h"
50 #include "winhttp.h"
51
52 /* to avoid conflicts with the Unix socket headers */
53 #define USE_WS_PREFIX
54 #include "winsock2.h"
55
56 #include "winhttp_private.h"
57
58 WINE_DEFAULT_DEBUG_CHANNEL(winhttp);
59
60 #define DEFAULT_SEND_TIMEOUT        30
61 #define DEFAULT_RECEIVE_TIMEOUT     30
62
63 #ifndef HAVE_GETADDRINFO
64
65 /* critical section to protect non-reentrant gethostbyname() */
66 static CRITICAL_SECTION cs_gethostbyname;
67 static CRITICAL_SECTION_DEBUG critsect_debug =
68 {
69     0, 0, &cs_gethostbyname,
70     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
71       0, 0, { (DWORD_PTR)(__FILE__ ": cs_gethostbyname") }
72 };
73 static CRITICAL_SECTION cs_gethostbyname = { &critsect_debug, -1, 0, 0, 0, 0 };
74
75 #endif
76
77 #ifdef SONAME_LIBSSL
78
79 #include <openssl/err.h>
80
81 static void *libssl_handle;
82 static void *libcrypto_handle;
83
84 static SSL_METHOD *method;
85
86 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
87
88 MAKE_FUNCPTR( SSL_library_init );
89 MAKE_FUNCPTR( SSL_load_error_strings );
90 MAKE_FUNCPTR( SSLv23_method );
91 MAKE_FUNCPTR( SSL_CTX_new );
92 MAKE_FUNCPTR( SSL_CTX_free );
93 MAKE_FUNCPTR( SSL_new );
94 MAKE_FUNCPTR( SSL_free );
95 MAKE_FUNCPTR( SSL_set_fd );
96 MAKE_FUNCPTR( SSL_connect );
97 MAKE_FUNCPTR( SSL_shutdown );
98 MAKE_FUNCPTR( SSL_write );
99 MAKE_FUNCPTR( SSL_read );
100 MAKE_FUNCPTR( SSL_get_verify_result );
101 MAKE_FUNCPTR( SSL_get_peer_certificate );
102 MAKE_FUNCPTR( SSL_CTX_get_timeout );
103 MAKE_FUNCPTR( SSL_CTX_set_timeout );
104 MAKE_FUNCPTR( SSL_CTX_set_default_verify_paths );
105
106 MAKE_FUNCPTR( BIO_new_fp );
107 MAKE_FUNCPTR( ERR_get_error );
108 MAKE_FUNCPTR( ERR_error_string );
109 #undef MAKE_FUNCPTR
110
111 #endif
112
113 /* translate a unix error code into a winsock error code */
114 static int sock_get_error( int err )
115 {
116     switch (err)
117     {
118         case EINTR:             return WSAEINTR;
119         case EBADF:             return WSAEBADF;
120         case EPERM:
121         case EACCES:            return WSAEACCES;
122         case EFAULT:            return WSAEFAULT;
123         case EINVAL:            return WSAEINVAL;
124         case EMFILE:            return WSAEMFILE;
125         case EWOULDBLOCK:       return WSAEWOULDBLOCK;
126         case EINPROGRESS:       return WSAEINPROGRESS;
127         case EALREADY:          return WSAEALREADY;
128         case ENOTSOCK:          return WSAENOTSOCK;
129         case EDESTADDRREQ:      return WSAEDESTADDRREQ;
130         case EMSGSIZE:          return WSAEMSGSIZE;
131         case EPROTOTYPE:        return WSAEPROTOTYPE;
132         case ENOPROTOOPT:       return WSAENOPROTOOPT;
133         case EPROTONOSUPPORT:   return WSAEPROTONOSUPPORT;
134         case ESOCKTNOSUPPORT:   return WSAESOCKTNOSUPPORT;
135         case EOPNOTSUPP:        return WSAEOPNOTSUPP;
136         case EPFNOSUPPORT:      return WSAEPFNOSUPPORT;
137         case EAFNOSUPPORT:      return WSAEAFNOSUPPORT;
138         case EADDRINUSE:        return WSAEADDRINUSE;
139         case EADDRNOTAVAIL:     return WSAEADDRNOTAVAIL;
140         case ENETDOWN:          return WSAENETDOWN;
141         case ENETUNREACH:       return WSAENETUNREACH;
142         case ENETRESET:         return WSAENETRESET;
143         case ECONNABORTED:      return WSAECONNABORTED;
144         case EPIPE:
145         case ECONNRESET:        return WSAECONNRESET;
146         case ENOBUFS:           return WSAENOBUFS;
147         case EISCONN:           return WSAEISCONN;
148         case ENOTCONN:          return WSAENOTCONN;
149         case ESHUTDOWN:         return WSAESHUTDOWN;
150         case ETOOMANYREFS:      return WSAETOOMANYREFS;
151         case ETIMEDOUT:         return WSAETIMEDOUT;
152         case ECONNREFUSED:      return WSAECONNREFUSED;
153         case ELOOP:             return WSAELOOP;
154         case ENAMETOOLONG:      return WSAENAMETOOLONG;
155         case EHOSTDOWN:         return WSAEHOSTDOWN;
156         case EHOSTUNREACH:      return WSAEHOSTUNREACH;
157         case ENOTEMPTY:         return WSAENOTEMPTY;
158 #ifdef EPROCLIM
159         case EPROCLIM:          return WSAEPROCLIM;
160 #endif
161 #ifdef EUSERS
162         case EUSERS:            return WSAEUSERS;
163 #endif
164 #ifdef EDQUOT
165         case EDQUOT:            return WSAEDQUOT;
166 #endif
167 #ifdef ESTALE
168         case ESTALE:            return WSAESTALE;
169 #endif
170 #ifdef EREMOTE
171         case EREMOTE:           return WSAEREMOTE;
172 #endif
173     default: errno = err; perror( "sock_set_error" ); return WSAEFAULT;
174     }
175     return err;
176 }
177
178 BOOL netconn_init( netconn_t *conn, BOOL secure )
179 {
180     conn->socket = -1;
181     if (!secure) return TRUE;
182
183 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
184     if (libssl_handle) return TRUE;
185     if (!(libssl_handle = wine_dlopen( SONAME_LIBSSL, RTLD_NOW, NULL, 0 )))
186     {
187         ERR("Trying to use SSL but couldn't load %s. Expect trouble.\n", SONAME_LIBSSL);
188         set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
189         return FALSE;
190     }
191     if (!(libcrypto_handle = wine_dlopen( SONAME_LIBCRYPTO, RTLD_NOW, NULL, 0 )))
192     {
193         ERR("Trying to use SSL but couldn't load %s. Expect trouble.\n", SONAME_LIBCRYPTO);
194         set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
195         return FALSE;
196     }
197 #define LOAD_FUNCPTR(x) \
198     if (!(p##x = wine_dlsym( libssl_handle, #x, NULL, 0 ))) \
199     { \
200         ERR("Failed to load symbol %s\n", #x); \
201         set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR ); \
202         return FALSE; \
203     }
204     LOAD_FUNCPTR( SSL_library_init );
205     LOAD_FUNCPTR( SSL_load_error_strings );
206     LOAD_FUNCPTR( SSLv23_method );
207     LOAD_FUNCPTR( SSL_CTX_new );
208     LOAD_FUNCPTR( SSL_CTX_free );
209     LOAD_FUNCPTR( SSL_new );
210     LOAD_FUNCPTR( SSL_free );
211     LOAD_FUNCPTR( SSL_set_fd );
212     LOAD_FUNCPTR( SSL_connect );
213     LOAD_FUNCPTR( SSL_shutdown );
214     LOAD_FUNCPTR( SSL_write );
215     LOAD_FUNCPTR( SSL_read );
216     LOAD_FUNCPTR( SSL_get_verify_result );
217     LOAD_FUNCPTR( SSL_get_peer_certificate );
218     LOAD_FUNCPTR( SSL_CTX_get_timeout );
219     LOAD_FUNCPTR( SSL_CTX_set_timeout );
220     LOAD_FUNCPTR( SSL_CTX_set_default_verify_paths );
221 #undef LOAD_FUNCPTR
222
223 #define LOAD_FUNCPTR(x) \
224     if (!(p##x = wine_dlsym( libcrypto_handle, #x, NULL, 0 ))) \
225     { \
226         ERR("Failed to load symbol %s\n", #x); \
227         set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR ); \
228         return FALSE; \
229     }
230     LOAD_FUNCPTR( BIO_new_fp );
231     LOAD_FUNCPTR( ERR_get_error );
232     LOAD_FUNCPTR( ERR_error_string );
233 #undef LOAD_FUNCPTR
234
235     pSSL_library_init();
236     pSSL_load_error_strings();
237     pBIO_new_fp( stderr, BIO_NOCLOSE );
238
239     method = pSSLv23_method();
240     conn->ssl_ctx = pSSL_CTX_new( method );
241
242 #else
243     WARN("SSL support not compiled in.\n");
244     set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
245     return FALSE;
246 #endif
247     return TRUE;
248 }
249
250 BOOL netconn_connected( netconn_t *conn )
251 {
252     return (conn->socket != -1);
253 }
254
255 BOOL netconn_create( netconn_t *conn, int domain, int type, int protocol )
256 {
257     if ((conn->socket = socket( domain, type, protocol )) == -1)
258     {
259         WARN("unable to create socket (%s)\n", strerror(errno));
260         set_last_error( sock_get_error( errno ) );
261         return FALSE;
262     }
263     return TRUE;
264 }
265
266 BOOL netconn_close( netconn_t *conn )
267 {
268     int res;
269
270 #ifdef SONAME_LIBSSL
271     if (conn->secure)
272     {
273         heap_free( conn->peek_msg_mem );
274         conn->peek_msg_mem = NULL;
275         conn->peek_msg = NULL;
276         conn->peek_len = 0;
277
278         pSSL_shutdown( conn->ssl_conn );
279         pSSL_free( conn->ssl_conn );
280
281         conn->ssl_conn = NULL;
282         conn->secure = FALSE;
283     }
284 #endif
285     res = close( conn->socket );
286     conn->socket = -1;
287     if (res == -1)
288     {
289         set_last_error( sock_get_error( errno ) );
290         return FALSE;
291     }
292     return TRUE;
293 }
294
295 BOOL netconn_connect( netconn_t *conn, const struct sockaddr *sockaddr, unsigned int addr_len )
296 {
297     if (connect( conn->socket, sockaddr, addr_len ) == -1)
298     {
299         WARN("unable to connect to host (%s)\n", strerror(errno));
300         set_last_error( sock_get_error( errno ) );
301         return FALSE;
302     }
303     return TRUE;
304 }
305
306 BOOL netconn_secure_connect( netconn_t *conn )
307 {
308 #ifdef SONAME_LIBSSL
309     X509 *cert;
310     long res;
311
312     if (!pSSL_CTX_set_default_verify_paths( conn->ssl_ctx ))
313     {
314         ERR("SSL_CTX_set_default_verify_paths failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
315         set_last_error( ERROR_OUTOFMEMORY );
316         return FALSE;
317     }
318     if (!(conn->ssl_conn = pSSL_new( conn->ssl_ctx )))
319     {
320         ERR("SSL_new failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
321         set_last_error( ERROR_OUTOFMEMORY );
322         goto fail;
323     }
324     if (!pSSL_set_fd( conn->ssl_conn, conn->socket ))
325     {
326         ERR("SSL_set_fd failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
327         set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
328         goto fail;
329     }
330     if (pSSL_connect( conn->ssl_conn ) <= 0)
331     {
332         ERR("SSL_connect failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
333         set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
334         goto fail;
335     }
336     if (!(cert = pSSL_get_peer_certificate( conn->ssl_conn )))
337     {
338         ERR("No certificate for server: %s\n", pERR_error_string( pERR_get_error(), 0 ));
339         set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
340         goto fail;
341     }
342     if ((res = pSSL_get_verify_result( conn->ssl_conn )) != X509_V_OK)
343     {
344         /* FIXME: we should set an error and return, but we only print an error at the moment */
345         ERR("couldn't verify server certificate (%ld)\n", res);
346     }
347     TRACE("established SSL connection\n");
348     conn->secure = TRUE;
349     return TRUE;
350
351 fail:
352     if (conn->ssl_conn)
353     {
354         pSSL_shutdown( conn->ssl_conn );
355         pSSL_free( conn->ssl_conn );
356         conn->ssl_conn = NULL;
357     }
358 #endif
359     return FALSE;
360 }
361
362 BOOL netconn_send( netconn_t *conn, const void *msg, size_t len, int flags, int *sent )
363 {
364     if (!netconn_connected( conn )) return FALSE;
365     if (conn->secure)
366     {
367 #ifdef SONAME_LIBSSL
368         if (flags) FIXME("SSL_write doesn't support any flags (%08x)\n", flags);
369         *sent = pSSL_write( conn->ssl_conn, msg, len );
370         if (*sent < 1 && len) return FALSE;
371         return TRUE;
372 #else
373         return FALSE;
374 #endif
375     }
376     if ((*sent = send( conn->socket, msg, len, flags )) == -1)
377     {
378         set_last_error( sock_get_error( errno ) );
379         return FALSE;
380     }
381     return TRUE;
382 }
383
384 BOOL netconn_recv( netconn_t *conn, void *buf, size_t len, int flags, int *recvd )
385 {
386     *recvd = 0;
387     if (!netconn_connected( conn )) return FALSE;
388     if (!len) return TRUE;
389
390     if (conn->secure)
391     {
392 #ifdef SONAME_LIBSSL
393         if (flags & ~(MSG_PEEK | MSG_WAITALL))
394             FIXME("SSL_read does not support the following flags: %08x\n", flags);
395
396         /* this ugly hack is all for MSG_PEEK */
397         if (flags & MSG_PEEK && !conn->peek_msg)
398         {
399             if (!(conn->peek_msg = conn->peek_msg_mem = heap_alloc( len + 1 ))) return FALSE;
400         }
401         else if (flags & MSG_PEEK && conn->peek_msg)
402         {
403             if (len < conn->peek_len) FIXME("buffer isn't big enough, should we wrap?\n");
404             *recvd = min( len, conn->peek_len );
405             memcpy( buf, conn->peek_msg, *recvd );
406             return TRUE;
407         }
408         else if (conn->peek_msg)
409         {
410             *recvd = min( len, conn->peek_len );
411             memcpy( buf, conn->peek_msg, *recvd );
412             conn->peek_len -= *recvd;
413             conn->peek_msg += *recvd;
414
415             if (conn->peek_len == 0)
416             {
417                 heap_free( conn->peek_msg_mem );
418                 conn->peek_msg_mem = NULL;
419                 conn->peek_msg = NULL;
420             }
421             /* check if we have enough data from the peek buffer */
422             if (!(flags & MSG_WAITALL) || (*recvd == len)) return TRUE;
423         }
424         *recvd += pSSL_read( conn->ssl_conn, (char *)buf + *recvd, len - *recvd );
425         if (flags & MSG_PEEK) /* must copy into buffer */
426         {
427             conn->peek_len = *recvd;
428             if (!*recvd)
429             {
430                 heap_free( conn->peek_msg_mem );
431                 conn->peek_msg_mem = NULL;
432                 conn->peek_msg = NULL;
433             }
434             else memcpy( conn->peek_msg, buf, *recvd );
435         }
436         if (*recvd < 1 && len) return FALSE;
437         return TRUE;
438 #else
439         return FALSE;
440 #endif
441     }
442     if ((*recvd = recv( conn->socket, buf, len, flags )) == -1)
443     {
444         set_last_error( sock_get_error( errno ) );
445         return FALSE;
446     }
447     return TRUE;
448 }
449
450 BOOL netconn_query_data_available( netconn_t *conn, DWORD *available )
451 {
452 #ifdef FIONREAD
453     int ret, unread;
454 #endif
455     *available = 0;
456     if (!netconn_connected( conn )) return FALSE;
457
458     if (conn->secure)
459     {
460 #ifdef SONAME_LIBSSL
461         if (conn->peek_msg) *available = conn->peek_len;
462 #endif
463         return TRUE;
464     }
465 #ifdef FIONREAD
466     if (!(ret = ioctl( conn->socket, FIONREAD, &unread )))
467     {
468         TRACE("%d bytes of queued, but unread data\n", unread);
469         *available += unread;
470     }
471 #endif
472     return TRUE;
473 }
474
475 BOOL netconn_get_next_line( netconn_t *conn, char *buffer, DWORD *buflen )
476 {
477     struct pollfd pfd;
478     BOOL ret = FALSE;
479     DWORD recvd = 0;
480
481     if (!netconn_connected( conn )) return FALSE;
482
483     if (conn->secure)
484     {
485 #ifdef SONAME_LIBSSL
486         long timeout;
487
488         timeout = pSSL_CTX_get_timeout( conn->ssl_ctx );
489         pSSL_CTX_set_timeout( conn->ssl_ctx, DEFAULT_RECEIVE_TIMEOUT );
490
491         while (recvd < *buflen)
492         {
493             int dummy;
494             if (!netconn_recv( conn, &buffer[recvd], 1, 0, &dummy ))
495             {
496                 set_last_error( ERROR_CONNECTION_ABORTED );
497                 break;
498             }
499             if (buffer[recvd] == '\n')
500             {
501                 ret = TRUE;
502                 break;
503             }
504             if (buffer[recvd] != '\r') recvd++;
505         }
506         pSSL_CTX_set_timeout( conn->ssl_ctx, timeout );
507         if (ret)
508         {
509             buffer[recvd++] = 0;
510             *buflen = recvd;
511             TRACE("received line %s\n", debugstr_a(buffer));
512         }
513         return ret;
514 #else
515         return FALSE;
516 #endif
517     }
518
519     pfd.fd = conn->socket;
520     pfd.events = POLLIN;
521     while (recvd < *buflen)
522     {
523         if (poll( &pfd, 1, DEFAULT_RECEIVE_TIMEOUT * 1000 ) > 0)
524         {
525             int res;
526             if ((res = recv( conn->socket, &buffer[recvd], 1, 0 )) <= 0)
527             {
528                 if (res == -1) set_last_error( sock_get_error( errno ) );
529                 break;
530             }
531             if (buffer[recvd] == '\n')
532             {
533                 ret = TRUE;
534                 break;
535             }
536             if (buffer[recvd] != '\r') recvd++;
537         }
538         else
539         {
540             set_last_error( ERROR_WINHTTP_TIMEOUT );
541             break;
542         }
543     }
544     if (ret)
545     {
546         buffer[recvd++] = 0;
547         *buflen = recvd;
548         TRACE("received line %s\n", debugstr_a(buffer));
549     }
550     return ret;
551 }
552
553 DWORD netconn_set_timeout( netconn_t *netconn, BOOL send, int value )
554 {
555     int res;
556     struct timeval tv;
557
558     /* value is in milliseconds, convert to struct timeval */
559     tv.tv_sec = value / 1000;
560     tv.tv_usec = (value % 1000) * 1000;
561
562     if ((res = setsockopt( netconn->socket, SOL_SOCKET, send ? SO_SNDTIMEO : SO_RCVTIMEO, &tv, sizeof(tv) ) == -1))
563     {
564         WARN("setsockopt failed (%s)\n", strerror( errno ));
565         return sock_get_error( errno );
566     }
567     return ERROR_SUCCESS;
568 }
569
570 BOOL netconn_resolve( WCHAR *hostnameW, INTERNET_PORT port, struct sockaddr_in *sa )
571 {
572     char *hostname;
573 #ifdef HAVE_GETADDRINFO
574     struct addrinfo *res, hints;
575     int ret;
576 #else
577     struct hostent *he;
578 #endif
579
580     if (!(hostname = strdupWA( hostnameW ))) return FALSE;
581
582 #ifdef HAVE_GETADDRINFO
583     memset( &hints, 0, sizeof(struct addrinfo) );
584     hints.ai_family = AF_INET;
585
586     ret = getaddrinfo( hostname, NULL, &hints, &res );
587     heap_free( hostname );
588     if (ret != 0)
589     {
590         TRACE("failed to get address of %s (%s)\n", debugstr_a(hostname), gai_strerror(ret));
591         return FALSE;
592     }
593     memset( sa, 0, sizeof(struct sockaddr_in) );
594     memcpy( &sa->sin_addr, &((struct sockaddr_in *)res->ai_addr)->sin_addr, sizeof(struct in_addr) );
595     sa->sin_family = res->ai_family;
596     sa->sin_port = htons( port );
597
598     freeaddrinfo( res );
599 #else
600     EnterCriticalSection( &cs_gethostbyname );
601
602     he = gethostbyname( hostname );
603     heap_free( hostname );
604     if (!he)
605     {
606         TRACE("failed to get address of %s (%d)\n", debugstr_a(hostname), h_errno);
607         LeaveCriticalSection( &cs_gethostbyname );
608         return FALSE;
609     }
610     memset( sa, 0, sizeof(struct sockaddr_in) );
611     memcpy( (char *)&sa->sin_addr, he->h_addr, he->h_length );
612     sa->sin_family = he->h_addrtype;
613     sa->sin_port = htons( port );
614
615     LeaveCriticalSection( &cs_gethostbyname );
616 #endif
617     return TRUE;
618 }