shlwapi: Beginning implementation of IUnknown_QueryServiceForWebBrowserApp.
[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 CRITICAL_SECTION init_ssl_cs;
102 static CRITICAL_SECTION_DEBUG init_ssl_cs_debug =
103 {
104     0, 0, &init_ssl_cs,
105     { &init_ssl_cs_debug.ProcessLocksList,
106       &init_ssl_cs_debug.ProcessLocksList },
107     0, 0, { (DWORD_PTR)(__FILE__ ": init_ssl_cs") }
108 };
109 static CRITICAL_SECTION init_ssl_cs = { &init_ssl_cs_debug, -1, 0, 0, 0, 0 };
110
111 static void *OpenSSL_ssl_handle;
112 static void *OpenSSL_crypto_handle;
113
114 static SSL_METHOD *meth;
115 static SSL_CTX *ctx;
116
117 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
118
119 /* OpenSSL functions that we use */
120 MAKE_FUNCPTR(SSL_library_init);
121 MAKE_FUNCPTR(SSL_load_error_strings);
122 MAKE_FUNCPTR(SSLv23_method);
123 MAKE_FUNCPTR(SSL_CTX_free);
124 MAKE_FUNCPTR(SSL_CTX_new);
125 MAKE_FUNCPTR(SSL_new);
126 MAKE_FUNCPTR(SSL_free);
127 MAKE_FUNCPTR(SSL_set_fd);
128 MAKE_FUNCPTR(SSL_connect);
129 MAKE_FUNCPTR(SSL_shutdown);
130 MAKE_FUNCPTR(SSL_write);
131 MAKE_FUNCPTR(SSL_read);
132 MAKE_FUNCPTR(SSL_pending);
133 MAKE_FUNCPTR(SSL_get_verify_result);
134 MAKE_FUNCPTR(SSL_get_peer_certificate);
135 MAKE_FUNCPTR(SSL_CTX_get_timeout);
136 MAKE_FUNCPTR(SSL_CTX_set_timeout);
137 MAKE_FUNCPTR(SSL_CTX_set_default_verify_paths);
138
139 /* OpenSSL's libcrypto functions that we use */
140 MAKE_FUNCPTR(BIO_new_fp);
141 MAKE_FUNCPTR(CRYPTO_num_locks);
142 MAKE_FUNCPTR(CRYPTO_set_id_callback);
143 MAKE_FUNCPTR(CRYPTO_set_locking_callback);
144 MAKE_FUNCPTR(ERR_get_error);
145 MAKE_FUNCPTR(ERR_error_string);
146 MAKE_FUNCPTR(i2d_X509);
147 #undef MAKE_FUNCPTR
148
149 static CRITICAL_SECTION *ssl_locks;
150
151 static unsigned long ssl_thread_id(void)
152 {
153     return GetCurrentThreadId();
154 }
155
156 static void ssl_lock_callback(int mode, int type, const char *file, int line)
157 {
158     if (mode & CRYPTO_LOCK)
159         EnterCriticalSection(&ssl_locks[type]);
160     else
161         LeaveCriticalSection(&ssl_locks[type]);
162 }
163
164 #endif
165
166 DWORD NETCON_init(WININET_NETCONNECTION *connection, BOOL useSSL)
167 {
168     connection->useSSL = FALSE;
169     connection->socketFD = -1;
170     if (useSSL)
171     {
172 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
173         int i;
174
175         TRACE("using SSL connection\n");
176         EnterCriticalSection(&init_ssl_cs);
177         if (OpenSSL_ssl_handle) /* already initialized everything */
178         {
179             LeaveCriticalSection(&init_ssl_cs);
180             return ERROR_SUCCESS;
181         }
182         OpenSSL_ssl_handle = wine_dlopen(SONAME_LIBSSL, RTLD_NOW, NULL, 0);
183         if (!OpenSSL_ssl_handle)
184         {
185             ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n",
186                 SONAME_LIBSSL);
187             LeaveCriticalSection(&init_ssl_cs);
188             return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
189         }
190         OpenSSL_crypto_handle = wine_dlopen(SONAME_LIBCRYPTO, RTLD_NOW, NULL, 0);
191         if (!OpenSSL_crypto_handle)
192         {
193             ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n",
194                 SONAME_LIBCRYPTO);
195             LeaveCriticalSection(&init_ssl_cs);
196             return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
197         }
198
199         /* mmm nice ugly macroness */
200 #define DYNSSL(x) \
201     p##x = wine_dlsym(OpenSSL_ssl_handle, #x, NULL, 0); \
202     if (!p##x) \
203     { \
204         ERR("failed to load symbol %s\n", #x); \
205         LeaveCriticalSection(&init_ssl_cs); \
206         return ERROR_INTERNET_SECURITY_CHANNEL_ERROR; \
207     }
208
209         DYNSSL(SSL_library_init);
210         DYNSSL(SSL_load_error_strings);
211         DYNSSL(SSLv23_method);
212         DYNSSL(SSL_CTX_free);
213         DYNSSL(SSL_CTX_new);
214         DYNSSL(SSL_new);
215         DYNSSL(SSL_free);
216         DYNSSL(SSL_set_fd);
217         DYNSSL(SSL_connect);
218         DYNSSL(SSL_shutdown);
219         DYNSSL(SSL_write);
220         DYNSSL(SSL_read);
221         DYNSSL(SSL_pending);
222         DYNSSL(SSL_get_verify_result);
223         DYNSSL(SSL_get_peer_certificate);
224         DYNSSL(SSL_CTX_get_timeout);
225         DYNSSL(SSL_CTX_set_timeout);
226         DYNSSL(SSL_CTX_set_default_verify_paths);
227 #undef DYNSSL
228
229 #define DYNCRYPTO(x) \
230     p##x = wine_dlsym(OpenSSL_crypto_handle, #x, NULL, 0); \
231     if (!p##x) \
232     { \
233         ERR("failed to load symbol %s\n", #x); \
234         LeaveCriticalSection(&init_ssl_cs); \
235         return ERROR_INTERNET_SECURITY_CHANNEL_ERROR; \
236     }
237         DYNCRYPTO(BIO_new_fp);
238         DYNCRYPTO(CRYPTO_num_locks);
239         DYNCRYPTO(CRYPTO_set_id_callback);
240         DYNCRYPTO(CRYPTO_set_locking_callback);
241         DYNCRYPTO(ERR_get_error);
242         DYNCRYPTO(ERR_error_string);
243         DYNCRYPTO(i2d_X509);
244 #undef DYNCRYPTO
245
246         pSSL_library_init();
247         pSSL_load_error_strings();
248         pBIO_new_fp(stderr, BIO_NOCLOSE); /* FIXME: should use winedebug stuff */
249
250         meth = pSSLv23_method();
251         ctx = pSSL_CTX_new(meth);
252         if (!pSSL_CTX_set_default_verify_paths(ctx))
253         {
254             ERR("SSL_CTX_set_default_verify_paths failed: %s\n",
255                 pERR_error_string(pERR_get_error(), 0));
256             LeaveCriticalSection(&init_ssl_cs);
257             return ERROR_OUTOFMEMORY;
258         }
259
260         pCRYPTO_set_id_callback(ssl_thread_id);
261         ssl_locks = HeapAlloc(GetProcessHeap(), 0,
262                 pCRYPTO_num_locks() * sizeof(CRITICAL_SECTION));
263         if (!ssl_locks)
264         {
265             LeaveCriticalSection(&init_ssl_cs);
266             return ERROR_OUTOFMEMORY;
267         }
268         for (i = 0; i < pCRYPTO_num_locks(); i++)
269             InitializeCriticalSection(&ssl_locks[i]);
270         pCRYPTO_set_locking_callback(ssl_lock_callback);
271         LeaveCriticalSection(&init_ssl_cs);
272 #else
273         FIXME("can't use SSL, not compiled in.\n");
274         return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
275 #endif
276     }
277     return ERROR_SUCCESS;
278 }
279
280 void NETCON_unload(void)
281 {
282 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
283     if (OpenSSL_crypto_handle)
284     {
285         wine_dlclose(OpenSSL_crypto_handle, NULL, 0);
286     }
287     if (OpenSSL_ssl_handle)
288     {
289         if (ctx)
290             pSSL_CTX_free(ctx);
291         wine_dlclose(OpenSSL_ssl_handle, NULL, 0);
292     }
293     if (ssl_locks)
294     {
295         int i;
296         for (i = 0; i < pCRYPTO_num_locks(); i++) DeleteCriticalSection(&ssl_locks[i]);
297         HeapFree(GetProcessHeap(), 0, ssl_locks);
298     }
299 #endif
300 }
301
302 BOOL NETCON_connected(WININET_NETCONNECTION *connection)
303 {
304     if (connection->socketFD == -1)
305         return FALSE;
306     else
307         return TRUE;
308 }
309
310 /* translate a unix error code into a winsock one */
311 int sock_get_error( int err )
312 {
313 #if !defined(__MINGW32__) && !defined (_MSC_VER)
314     switch (err)
315     {
316         case EINTR:             return WSAEINTR;
317         case EBADF:             return WSAEBADF;
318         case EPERM:
319         case EACCES:            return WSAEACCES;
320         case EFAULT:            return WSAEFAULT;
321         case EINVAL:            return WSAEINVAL;
322         case EMFILE:            return WSAEMFILE;
323         case EWOULDBLOCK:       return WSAEWOULDBLOCK;
324         case EINPROGRESS:       return WSAEINPROGRESS;
325         case EALREADY:          return WSAEALREADY;
326         case ENOTSOCK:          return WSAENOTSOCK;
327         case EDESTADDRREQ:      return WSAEDESTADDRREQ;
328         case EMSGSIZE:          return WSAEMSGSIZE;
329         case EPROTOTYPE:        return WSAEPROTOTYPE;
330         case ENOPROTOOPT:       return WSAENOPROTOOPT;
331         case EPROTONOSUPPORT:   return WSAEPROTONOSUPPORT;
332         case ESOCKTNOSUPPORT:   return WSAESOCKTNOSUPPORT;
333         case EOPNOTSUPP:        return WSAEOPNOTSUPP;
334         case EPFNOSUPPORT:      return WSAEPFNOSUPPORT;
335         case EAFNOSUPPORT:      return WSAEAFNOSUPPORT;
336         case EADDRINUSE:        return WSAEADDRINUSE;
337         case EADDRNOTAVAIL:     return WSAEADDRNOTAVAIL;
338         case ENETDOWN:          return WSAENETDOWN;
339         case ENETUNREACH:       return WSAENETUNREACH;
340         case ENETRESET:         return WSAENETRESET;
341         case ECONNABORTED:      return WSAECONNABORTED;
342         case EPIPE:
343         case ECONNRESET:        return WSAECONNRESET;
344         case ENOBUFS:           return WSAENOBUFS;
345         case EISCONN:           return WSAEISCONN;
346         case ENOTCONN:          return WSAENOTCONN;
347         case ESHUTDOWN:         return WSAESHUTDOWN;
348         case ETOOMANYREFS:      return WSAETOOMANYREFS;
349         case ETIMEDOUT:         return WSAETIMEDOUT;
350         case ECONNREFUSED:      return WSAECONNREFUSED;
351         case ELOOP:             return WSAELOOP;
352         case ENAMETOOLONG:      return WSAENAMETOOLONG;
353         case EHOSTDOWN:         return WSAEHOSTDOWN;
354         case EHOSTUNREACH:      return WSAEHOSTUNREACH;
355         case ENOTEMPTY:         return WSAENOTEMPTY;
356 #ifdef EPROCLIM
357         case EPROCLIM:          return WSAEPROCLIM;
358 #endif
359 #ifdef EUSERS
360         case EUSERS:            return WSAEUSERS;
361 #endif
362 #ifdef EDQUOT
363         case EDQUOT:            return WSAEDQUOT;
364 #endif
365 #ifdef ESTALE
366         case ESTALE:            return WSAESTALE;
367 #endif
368 #ifdef EREMOTE
369         case EREMOTE:           return WSAEREMOTE;
370 #endif
371     default: errno=err; perror("sock_set_error"); return WSAEFAULT;
372     }
373 #endif
374     return err;
375 }
376
377 /******************************************************************************
378  * NETCON_create
379  * Basically calls 'socket()'
380  */
381 DWORD NETCON_create(WININET_NETCONNECTION *connection, int domain,
382               int type, int protocol)
383 {
384 #ifdef SONAME_LIBSSL
385     if (connection->useSSL)
386         return ERROR_NOT_SUPPORTED;
387 #endif
388
389     connection->socketFD = socket(domain, type, protocol);
390     if (connection->socketFD == -1)
391         return sock_get_error(errno);
392
393     return ERROR_SUCCESS;
394 }
395
396 /******************************************************************************
397  * NETCON_close
398  * Basically calls 'close()' unless we should use SSL
399  */
400 DWORD NETCON_close(WININET_NETCONNECTION *connection)
401 {
402     int result;
403
404     if (!NETCON_connected(connection)) return ERROR_SUCCESS;
405
406 #ifdef SONAME_LIBSSL
407     if (connection->useSSL)
408     {
409         pSSL_shutdown(connection->ssl_s);
410         pSSL_free(connection->ssl_s);
411         connection->ssl_s = NULL;
412
413         connection->useSSL = FALSE;
414     }
415 #endif
416
417     result = closesocket(connection->socketFD);
418     connection->socketFD = -1;
419
420     if (result == -1)
421         return sock_get_error(errno);
422     return ERROR_SUCCESS;
423 }
424 #ifdef SONAME_LIBSSL
425 static BOOL check_hostname(X509 *cert, char *hostname)
426 {
427     /* FIXME: implement */
428     return TRUE;
429 }
430 #endif
431 /******************************************************************************
432  * NETCON_secure_connect
433  * Initiates a secure connection over an existing plaintext connection.
434  */
435 DWORD NETCON_secure_connect(WININET_NETCONNECTION *connection, LPCWSTR hostname)
436 {
437     DWORD res = ERROR_NOT_SUPPORTED;
438 #ifdef SONAME_LIBSSL
439     long verify_res;
440     X509 *cert;
441     int len;
442     char *hostname_unix;
443
444     /* can't connect if we are already connected */
445     if (connection->useSSL)
446     {
447         ERR("already connected\n");
448         return ERROR_INTERNET_CANNOT_CONNECT;
449     }
450
451     connection->ssl_s = pSSL_new(ctx);
452     if (!connection->ssl_s)
453     {
454         ERR("SSL_new failed: %s\n",
455             pERR_error_string(pERR_get_error(), 0));
456         res = ERROR_OUTOFMEMORY;
457         goto fail;
458     }
459
460     if (!pSSL_set_fd(connection->ssl_s, connection->socketFD))
461     {
462         ERR("SSL_set_fd failed: %s\n",
463             pERR_error_string(pERR_get_error(), 0));
464         res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
465         goto fail;
466     }
467
468     if (pSSL_connect(connection->ssl_s) <= 0)
469     {
470         ERR("SSL_connect failed: %s\n",
471             pERR_error_string(pERR_get_error(), 0));
472         res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
473         goto fail;
474     }
475     cert = pSSL_get_peer_certificate(connection->ssl_s);
476     if (!cert)
477     {
478         ERR("no certificate for server %s\n", debugstr_w(hostname));
479         /* FIXME: is this the best error? */
480         res = ERROR_INTERNET_INVALID_CA;
481         goto fail;
482     }
483     verify_res = pSSL_get_verify_result(connection->ssl_s);
484     if (verify_res != X509_V_OK)
485     {
486         ERR("couldn't verify the security of the connection, %ld\n", verify_res);
487         /* FIXME: we should set an error and return, but we only warn at
488          * the moment */
489     }
490
491     len = WideCharToMultiByte(CP_UNIXCP, 0, hostname, -1, NULL, 0, NULL, NULL);
492     hostname_unix = HeapAlloc(GetProcessHeap(), 0, len);
493     if (!hostname_unix)
494     {
495         res = ERROR_OUTOFMEMORY;
496         goto fail;
497     }
498     WideCharToMultiByte(CP_UNIXCP, 0, hostname, -1, hostname_unix, len, NULL, NULL);
499
500     if (!check_hostname(cert, hostname_unix))
501     {
502         HeapFree(GetProcessHeap(), 0, hostname_unix);
503         res = ERROR_INTERNET_SEC_CERT_CN_INVALID;
504         goto fail;
505     }
506
507     HeapFree(GetProcessHeap(), 0, hostname_unix);
508     connection->useSSL = TRUE;
509     return ERROR_SUCCESS;
510
511 fail:
512     if (connection->ssl_s)
513     {
514         pSSL_shutdown(connection->ssl_s);
515         pSSL_free(connection->ssl_s);
516         connection->ssl_s = NULL;
517     }
518 #endif
519     return res;
520 }
521
522 /******************************************************************************
523  * NETCON_connect
524  * Connects to the specified address.
525  */
526 DWORD NETCON_connect(WININET_NETCONNECTION *connection, const struct sockaddr *serv_addr,
527                     unsigned int addrlen)
528 {
529     int result;
530
531     result = connect(connection->socketFD, serv_addr, addrlen);
532     if (result == -1)
533     {
534         WARN("Unable to connect to host (%s)\n", strerror(errno));
535
536         closesocket(connection->socketFD);
537         connection->socketFD = -1;
538         return sock_get_error(errno);
539     }
540
541     return ERROR_SUCCESS;
542 }
543
544 /******************************************************************************
545  * NETCON_send
546  * Basically calls 'send()' unless we should use SSL
547  * number of chars send is put in *sent
548  */
549 DWORD NETCON_send(WININET_NETCONNECTION *connection, const void *msg, size_t len, int flags,
550                 int *sent /* out */)
551 {
552     if (!NETCON_connected(connection)) return ERROR_INTERNET_CONNECTION_ABORTED;
553     if (!connection->useSSL)
554     {
555         *sent = send(connection->socketFD, msg, len, flags);
556         if (*sent == -1)
557             return sock_get_error(errno);
558         return ERROR_SUCCESS;
559     }
560     else
561     {
562 #ifdef SONAME_LIBSSL
563         if (flags)
564             FIXME("SSL_write doesn't support any flags (%08x)\n", flags);
565         *sent = pSSL_write(connection->ssl_s, msg, len);
566         if (*sent < 1 && len)
567             return ERROR_INTERNET_CONNECTION_ABORTED;
568         return ERROR_SUCCESS;
569 #else
570         return ERROR_NOT_SUPPORTED;
571 #endif
572     }
573 }
574
575 /******************************************************************************
576  * NETCON_recv
577  * Basically calls 'recv()' unless we should use SSL
578  * number of chars received is put in *recvd
579  */
580 DWORD NETCON_recv(WININET_NETCONNECTION *connection, void *buf, size_t len, int flags,
581                 int *recvd /* out */)
582 {
583     *recvd = 0;
584     if (!NETCON_connected(connection)) return ERROR_INTERNET_CONNECTION_ABORTED;
585     if (!len)
586         return ERROR_SUCCESS;
587     if (!connection->useSSL)
588     {
589         *recvd = recv(connection->socketFD, buf, len, flags);
590         return *recvd == -1 ? sock_get_error(errno) :  ERROR_SUCCESS;
591     }
592     else
593     {
594 #ifdef SONAME_LIBSSL
595         *recvd = pSSL_read(connection->ssl_s, buf, len);
596         return *recvd > 0 ? ERROR_SUCCESS : ERROR_INTERNET_CONNECTION_ABORTED;
597 #else
598         return ERROR_NOT_SUPPORTED;
599 #endif
600     }
601 }
602
603 /******************************************************************************
604  * NETCON_query_data_available
605  * Returns the number of bytes of peeked data plus the number of bytes of
606  * queued, but unread data.
607  */
608 BOOL NETCON_query_data_available(WININET_NETCONNECTION *connection, DWORD *available)
609 {
610     *available = 0;
611     if (!NETCON_connected(connection))
612         return FALSE;
613
614     if (!connection->useSSL)
615     {
616 #ifdef FIONREAD
617         int unread;
618         int retval = ioctlsocket(connection->socketFD, FIONREAD, &unread);
619         if (!retval)
620         {
621             TRACE("%d bytes of queued, but unread data\n", unread);
622             *available += unread;
623         }
624 #endif
625     }
626     else
627     {
628 #ifdef SONAME_LIBSSL
629         *available = pSSL_pending(connection->ssl_s);
630 #endif
631     }
632     return TRUE;
633 }
634
635 LPCVOID NETCON_GetCert(WININET_NETCONNECTION *connection)
636 {
637 #ifdef SONAME_LIBSSL
638     X509* cert;
639     unsigned char* buffer,*p;
640     INT len;
641     BOOL malloced = FALSE;
642     LPCVOID r = NULL;
643
644     if (!connection->useSSL)
645         return NULL;
646
647     cert = pSSL_get_peer_certificate(connection->ssl_s);
648     p = NULL;
649     len = pi2d_X509(cert,&p);
650     /*
651      * SSL 0.9.7 and above malloc the buffer if it is null. 
652      * however earlier version do not and so we would need to alloc the buffer.
653      *
654      * see the i2d_X509 man page for more details.
655      */
656     if (!p)
657     {
658         buffer = HeapAlloc(GetProcessHeap(),0,len);
659         p = buffer;
660         len = pi2d_X509(cert,&p);
661     }
662     else
663     {
664         buffer = p;
665         malloced = TRUE;
666     }
667
668     r = CertCreateCertificateContext(X509_ASN_ENCODING,buffer,len);
669
670     if (malloced)
671         free(buffer);
672     else
673         HeapFree(GetProcessHeap(),0,buffer);
674
675     return r;
676 #else
677     return NULL;
678 #endif
679 }
680
681 DWORD NETCON_set_timeout(WININET_NETCONNECTION *connection, BOOL send, int value)
682 {
683     int result;
684     struct timeval tv;
685
686     /* FIXME: we should probably store the timeout in the connection to set
687      * when we do connect */
688     if (!NETCON_connected(connection))
689         return ERROR_SUCCESS;
690
691     /* value is in milliseconds, convert to struct timeval */
692     tv.tv_sec = value / 1000;
693     tv.tv_usec = (value % 1000) * 1000;
694
695     result = setsockopt(connection->socketFD, SOL_SOCKET,
696                         send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv,
697                         sizeof(tv));
698
699     if (result == -1)
700     {
701         WARN("setsockopt failed (%s)\n", strerror(errno));
702         return sock_get_error(errno);
703     }
704
705     return ERROR_SUCCESS;
706 }