gdi32: Add separate functions for releasing/freeing DCs to replace the standard GDI...
[wine] / dlls / urlmon / umon.c
1 /*
2  * UrlMon
3  *
4  * Copyright 1999 Ulrich Czekalla for Corel Corporation
5  * Copyright 2002 Huw D M Davies for CodeWeavers
6  * Copyright 2005 Jacek Caban for CodeWeavers
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 <stdarg.h>
24 #include <stdio.h>
25
26 #define COBJMACROS
27 #define NONAMELESSUNION
28 #define NONAMELESSSTRUCT
29
30 #include "windef.h"
31 #include "winbase.h"
32 #include "winreg.h"
33 #include "winternl.h"
34 #include "winuser.h"
35 #include "objbase.h"
36 #include "wine/debug.h"
37 #include "wine/unicode.h"
38 #include "ole2.h"
39 #include "urlmon.h"
40 #include "wininet.h"
41 #include "shlwapi.h"
42 #include "urlmon_main.h"
43
44 WINE_DEFAULT_DEBUG_CHANNEL(urlmon);
45
46 /* native urlmon.dll uses this key, too */
47 static WCHAR BSCBHolder[] = { '_','B','S','C','B','_','H','o','l','d','e','r','_',0 };
48
49 /*static BOOL registered_wndclass = FALSE;*/
50
51 typedef struct {
52     const IBindingVtbl *lpVtbl;
53
54     LONG ref;
55
56     LPWSTR URLName;
57
58     HWND hwndCallback;
59     IBindCtx *pBC;
60     HINTERNET hinternet, hconnect, hrequest;
61     HANDLE hCacheFile;
62     IUMCacheStream *pstrCache;
63     IBindStatusCallback *pbscb;
64     DWORD total_read, expected_size;
65 } Binding;
66
67 static HRESULT WINAPI Binding_QueryInterface(IBinding* iface, REFIID riid, void **ppvObject)
68 {
69     Binding *This = (Binding*)iface;
70
71     TRACE("(%p)->(%s,%p)\n", This, debugstr_guid(riid), ppvObject);
72
73     if((This == NULL) || (ppvObject == NULL))
74         return E_INVALIDARG;
75
76     if (IsEqualIID(&IID_IUnknown, riid) || IsEqualIID(&IID_IBinding, riid)) {
77         *ppvObject = iface;
78         IBinding_AddRef(iface);
79         return S_OK;
80     }
81
82     *ppvObject = NULL;
83     return E_NOINTERFACE;
84 }
85
86 static ULONG WINAPI Binding_AddRef(IBinding* iface)
87 {
88     Binding *This = (Binding*)iface;
89     ULONG ref = InterlockedIncrement(&This->ref);
90
91     TRACE("(%p) ref=%d\n", This, ref);
92
93     return ref;
94 }
95
96 static ULONG WINAPI Binding_Release(IBinding* iface)
97 {
98     Binding *This = (Binding*)iface;
99     ULONG ref = InterlockedDecrement(&This->ref);
100
101     TRACE("(%p) ref=%d\n",This, ref);
102
103     if(!ref) {
104         HeapFree(GetProcessHeap(), 0, This->URLName);
105         if (This->hCacheFile)
106             CloseHandle(This->hCacheFile);
107         if (This->pstrCache)
108         {
109             UMCloseCacheFileStream(This->pstrCache);
110             IStream_Release((IStream *)This->pstrCache);
111         }
112         if (This->pbscb)
113             IBindStatusCallback_Release(This->pbscb);
114
115         HeapFree(GetProcessHeap(), 0, This);
116
117         URLMON_UnlockModule();
118     }
119
120     return ref;
121 }
122
123 static HRESULT WINAPI Binding_Abort(IBinding* iface)
124 {
125     Binding *This = (Binding*)iface;
126
127     FIXME("(%p): stub\n", This);
128
129     return E_NOTIMPL;
130 }
131
132 static HRESULT WINAPI Binding_GetBindResult(IBinding* iface, CLSID* pclsidProtocol, DWORD* pdwResult, LPOLESTR* pszResult, DWORD* pdwReserved)
133 {
134     Binding *This = (Binding*)iface;
135
136     FIXME("(%p)->(%p, %p, %p, %p): stub\n", This, pclsidProtocol, pdwResult, pszResult, pdwReserved);
137
138     return E_NOTIMPL;
139 }
140
141 static HRESULT WINAPI Binding_GetPriority(IBinding* iface, LONG* pnPriority)
142 {
143     Binding *This = (Binding*)iface;
144
145     FIXME("(%p)->(%p): stub\n", This, pnPriority);
146
147     return E_NOTIMPL;
148 }
149
150 static HRESULT WINAPI Binding_Resume(IBinding* iface)
151 {
152     Binding *This = (Binding*)iface;
153
154     FIXME("(%p): stub\n", This);
155
156     return E_NOTIMPL;
157 }
158
159 static HRESULT WINAPI Binding_SetPriority(IBinding* iface, LONG nPriority)
160 {
161     Binding *This = (Binding*)iface;
162
163     FIXME("(%p)->(%d): stub\n", This, nPriority);
164
165     return E_NOTIMPL;
166 }
167
168 static HRESULT WINAPI Binding_Suspend(IBinding* iface)
169 {
170     Binding *This = (Binding*)iface;
171
172     FIXME("(%p): stub\n", This);
173
174     return E_NOTIMPL;
175 }
176
177 static void Binding_CloseCacheDownload(Binding *This)
178 {
179     CloseHandle(This->hCacheFile);
180     This->hCacheFile = 0;
181     UMCloseCacheFileStream(This->pstrCache);
182     IStream_Release((IStream *)This->pstrCache);
183     This->pstrCache = 0;
184 }
185
186 static HRESULT Binding_MoreCacheData(Binding *This, char *buf, DWORD dwBytes)
187 {
188     DWORD written;
189
190     if (WriteFile(This->hCacheFile, buf, dwBytes, &written, NULL) && written == dwBytes)
191     {
192         HRESULT hr;
193
194         This->total_read += written;
195         hr = IBindStatusCallback_OnProgress(This->pbscb,
196                                             This->total_read + written,
197                                             This->expected_size,
198                                             (This->total_read == written) ?
199                                                 BINDSTATUS_BEGINDOWNLOADDATA :
200                                                 BINDSTATUS_DOWNLOADINGDATA,
201                                             This->URLName);
202         if (!hr)
203         {
204             STGMEDIUM stg;
205             FORMATETC fmt;
206
207             fmt.cfFormat = 0;
208             fmt.ptd = NULL;
209             fmt.dwAspect = 0;
210             fmt.lindex = -1;
211             fmt.tymed = TYMED_ISTREAM;
212
213             stg.tymed = TYMED_ISTREAM;
214             stg.u.pstm = (IStream *)This->pstrCache;
215             stg.pUnkForRelease = NULL;
216
217             hr = IBindStatusCallback_OnDataAvailable(This->pbscb,
218                                                      (This->total_read == written) ?
219                                                          BSCF_FIRSTDATANOTIFICATION :
220                                                          BSCF_INTERMEDIATEDATANOTIFICATION,
221                                                      This->total_read + written,
222                                                      &fmt,
223                                                      &stg);
224         }
225         if (written < dwBytes)
226             return STG_E_MEDIUMFULL;
227         else
228             return hr;
229     }
230     return HRESULT_FROM_WIN32(GetLastError());
231 }
232
233 static void Binding_FinishedDownload(Binding *This, HRESULT hr)
234 {
235     STGMEDIUM stg;
236     FORMATETC fmt;
237
238     fmt.ptd = NULL;
239     fmt.dwAspect = 0;
240     fmt.lindex = -1;
241     fmt.tymed = TYMED_ISTREAM;
242
243     stg.tymed = TYMED_ISTREAM;
244     stg.u.pstm = (IStream *)This->pstrCache;
245     stg.pUnkForRelease = NULL;
246
247     IBindStatusCallback_OnProgress(This->pbscb, This->total_read, This->expected_size,
248                                    BINDSTATUS_ENDDOWNLOADDATA, This->URLName);
249     IBindStatusCallback_OnDataAvailable(This->pbscb, BSCF_LASTDATANOTIFICATION, This->total_read, &fmt, &stg);
250     if (hr)
251     {
252         WCHAR *pwchError = 0;
253
254         FormatMessageW (FORMAT_MESSAGE_FROM_SYSTEM |
255                          FORMAT_MESSAGE_ALLOCATE_BUFFER,
256                         NULL, (DWORD) hr,
257                         0, (LPWSTR) &pwchError,
258                         0, NULL);
259         if (!pwchError)
260         {
261             static const WCHAR achFormat[] = { '%', '0', '8', 'x', 0 };
262
263             pwchError =(WCHAR *) LocalAlloc(LMEM_FIXED, sizeof(WCHAR) * 9);
264             wsprintfW(pwchError, achFormat, hr);
265         }
266         IBindStatusCallback_OnStopBinding(This->pbscb, hr, pwchError);
267         LocalFree(pwchError);
268     }
269     else
270     {
271         IBindStatusCallback_OnStopBinding(This->pbscb, hr, NULL);
272     }
273     IBindStatusCallback_Release(This->pbscb);
274     This->pbscb = 0;
275 }
276
277 static const IBindingVtbl BindingVtbl =
278 {
279     Binding_QueryInterface,
280     Binding_AddRef,
281     Binding_Release,
282     Binding_Abort,
283     Binding_Suspend,
284     Binding_Resume,
285     Binding_SetPriority,
286     Binding_GetPriority,
287     Binding_GetBindResult
288 };
289
290 /* filemoniker data structure */
291 typedef struct {
292
293     const IMonikerVtbl* lpvtbl;  /* VTable relative to the IMoniker interface.*/
294
295     LONG ref; /* reference counter for this object */
296
297     LPOLESTR URLName; /* URL string identified by this URLmoniker */
298 } URLMonikerImpl;
299
300 /*******************************************************************************
301  *        URLMoniker_QueryInterface
302  *******************************************************************************/
303 static HRESULT WINAPI URLMonikerImpl_QueryInterface(IMoniker* iface,REFIID riid,void** ppvObject)
304 {
305     URLMonikerImpl *This = (URLMonikerImpl *)iface;
306
307     TRACE("(%p)->(%s,%p)\n",This,debugstr_guid(riid),ppvObject);
308
309     /* Perform a sanity check on the parameters.*/
310     if ( (This==0) || (ppvObject==0) )
311         return E_INVALIDARG;
312
313     /* Initialize the return parameter */
314     *ppvObject = 0;
315
316     /* Compare the riid with the interface IDs implemented by this object.*/
317     if (IsEqualIID(&IID_IUnknown, riid)      ||
318         IsEqualIID(&IID_IPersist, riid)      ||
319         IsEqualIID(&IID_IPersistStream,riid) ||
320         IsEqualIID(&IID_IMoniker, riid)
321        )
322         *ppvObject = iface;
323
324     /* Check that we obtained an interface.*/
325     if ((*ppvObject)==0)
326         return E_NOINTERFACE;
327
328     /* Query Interface always increases the reference count by one when it is successful */
329     IMoniker_AddRef(iface);
330
331     return S_OK;
332 }
333
334 /******************************************************************************
335  *        URLMoniker_AddRef
336  ******************************************************************************/
337 static ULONG WINAPI URLMonikerImpl_AddRef(IMoniker* iface)
338 {
339     URLMonikerImpl *This = (URLMonikerImpl *)iface;
340     ULONG refCount = InterlockedIncrement(&This->ref);
341
342     TRACE("(%p) ref=%u\n",This, refCount);
343
344     return refCount;
345 }
346
347 /******************************************************************************
348  *        URLMoniker_Release
349  ******************************************************************************/
350 static ULONG WINAPI URLMonikerImpl_Release(IMoniker* iface)
351 {
352     URLMonikerImpl *This = (URLMonikerImpl *)iface;
353     ULONG refCount = InterlockedDecrement(&This->ref);
354
355     TRACE("(%p) ref=%u\n",This, refCount);
356
357     /* destroy the object if there's no more reference on it */
358     if (!refCount) {
359         HeapFree(GetProcessHeap(),0,This->URLName);
360         HeapFree(GetProcessHeap(),0,This);
361
362         URLMON_UnlockModule();
363     }
364
365     return refCount;
366 }
367
368
369 /******************************************************************************
370  *        URLMoniker_GetClassID
371  ******************************************************************************/
372 static HRESULT WINAPI URLMonikerImpl_GetClassID(IMoniker* iface,
373                                                 CLSID *pClassID)/* Pointer to CLSID of object */
374 {
375     URLMonikerImpl *This = (URLMonikerImpl *)iface;
376
377     TRACE("(%p,%p)\n",This,pClassID);
378
379     if (pClassID==NULL)
380         return E_POINTER;
381     /* Windows always returns CLSID_StdURLMoniker */
382     *pClassID = CLSID_StdURLMoniker;
383     return S_OK;
384 }
385
386 /******************************************************************************
387  *        URLMoniker_IsDirty
388  ******************************************************************************/
389 static HRESULT WINAPI URLMonikerImpl_IsDirty(IMoniker* iface)
390 {
391     URLMonikerImpl *This = (URLMonikerImpl *)iface;
392     /* Note that the OLE-provided implementations of the IPersistStream::IsDirty
393        method in the OLE-provided moniker interfaces always return S_FALSE because
394        their internal state never changes. */
395
396     TRACE("(%p)\n",This);
397
398     return S_FALSE;
399 }
400
401 /******************************************************************************
402  *        URLMoniker_Load
403  *
404  * NOTE
405  *  Writes a ULONG containing length of unicode string, followed
406  *  by that many unicode characters
407  ******************************************************************************/
408 static HRESULT WINAPI URLMonikerImpl_Load(IMoniker* iface,IStream* pStm)
409 {
410     URLMonikerImpl *This = (URLMonikerImpl *)iface;
411     
412     HRESULT res;
413     ULONG size;
414     ULONG got;
415     TRACE("(%p,%p)\n",This,pStm);
416
417     if(!pStm)
418         return E_INVALIDARG;
419
420     res = IStream_Read(pStm, &size, sizeof(ULONG), &got);
421     if(SUCCEEDED(res)) {
422         if(got == sizeof(ULONG)) {
423             HeapFree(GetProcessHeap(), 0, This->URLName);
424             This->URLName=HeapAlloc(GetProcessHeap(),0,size);
425             if(!This->URLName)
426                 res = E_OUTOFMEMORY;
427             else {
428                 res = IStream_Read(pStm, This->URLName, size, NULL);
429                 This->URLName[size/sizeof(WCHAR) - 1] = 0;
430             }
431         }
432         else
433             res = E_FAIL;
434     }
435     return res;
436 }
437
438 /******************************************************************************
439  *        URLMoniker_Save
440  ******************************************************************************/
441 static HRESULT WINAPI URLMonikerImpl_Save(IMoniker* iface,
442                                           IStream* pStm,/* pointer to the stream where the object is to be saved */
443                                           BOOL fClearDirty)/* Specifies whether to clear the dirty flag */
444 {
445     URLMonikerImpl *This = (URLMonikerImpl *)iface;
446
447     HRESULT res;
448     ULONG size;
449     TRACE("(%p,%p,%d)\n",This,pStm,fClearDirty);
450
451     if(!pStm)
452         return E_INVALIDARG;
453
454     size = (strlenW(This->URLName) + 1)*sizeof(WCHAR);
455     res=IStream_Write(pStm,&size,sizeof(ULONG),NULL);
456     if(SUCCEEDED(res))
457         res=IStream_Write(pStm,This->URLName,size,NULL);
458     return res;
459
460 }
461
462 /******************************************************************************
463  *        URLMoniker_GetSizeMax
464  ******************************************************************************/
465 static HRESULT WINAPI URLMonikerImpl_GetSizeMax(IMoniker* iface,
466                                                 ULARGE_INTEGER* pcbSize)/* Pointer to size of stream needed to save object */
467 {
468     URLMonikerImpl *This = (URLMonikerImpl *)iface;
469
470     TRACE("(%p,%p)\n",This,pcbSize);
471
472     if(!pcbSize)
473         return E_INVALIDARG;
474
475     pcbSize->QuadPart = sizeof(ULONG) + ((strlenW(This->URLName)+1) * sizeof(WCHAR));
476     return S_OK;
477 }
478
479 /******************************************************************************
480  *                  URLMoniker_BindToObject
481  ******************************************************************************/
482 static HRESULT WINAPI URLMonikerImpl_BindToObject(IMoniker* iface,
483                                                   IBindCtx* pbc,
484                                                   IMoniker* pmkToLeft,
485                                                   REFIID riid,
486                                                   VOID** ppvResult)
487 {
488     URLMonikerImpl *This = (URLMonikerImpl *)iface;
489
490     *ppvResult=0;
491
492     FIXME("(%p)->(%p,%p,%s,%p): stub\n",This,pbc,pmkToLeft,debugstr_guid(riid),
493           ppvResult);
494
495     return E_NOTIMPL;
496 }
497
498 /******************************************************************************
499  *        URLMoniker_BindToStorage
500  ******************************************************************************/
501 static HRESULT URLMonikerImpl_BindToStorage_hack(LPCWSTR URLName,
502                                                    IBindCtx* pbc,
503                                                    IMoniker* pmkToLeft,
504                                                    REFIID riid,
505                                                    VOID** ppvObject)
506 {
507     HRESULT hres;
508     BINDINFO bi;
509     DWORD bindf;
510     WCHAR szFileName[MAX_PATH + 1];
511     Binding *bind;
512     int len;
513
514     WARN("(%s %p %p %s %p)\n", debugstr_w(URLName), pbc, pmkToLeft, debugstr_guid(riid),
515             ppvObject);
516
517     if(pmkToLeft) {
518         FIXME("pmkToLeft != NULL\n");
519         return E_NOTIMPL;
520     }
521     if(!IsEqualIID(&IID_IStream, riid)) {
522         FIXME("unsupported iid\n");
523         return E_NOTIMPL;
524     }
525
526     bind = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(Binding));
527     bind->lpVtbl = &BindingVtbl;
528     bind->ref = 1;
529     URLMON_LockModule();
530
531     len = lstrlenW(URLName)+1;
532     bind->URLName = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
533     memcpy(bind->URLName, URLName, len*sizeof(WCHAR));
534
535     hres = UMCreateStreamOnCacheFile(bind->URLName, 0, szFileName, &bind->hCacheFile, &bind->pstrCache);
536
537     if(SUCCEEDED(hres)) {
538         TRACE("Created stream...\n");
539
540         *ppvObject = (void *) bind->pstrCache;
541         IStream_AddRef((IStream *) bind->pstrCache);
542
543         hres = IBindCtx_GetObjectParam(pbc, BSCBHolder, (IUnknown**)&bind->pbscb);
544         if(SUCCEEDED(hres)) {
545             TRACE("Got IBindStatusCallback...\n");
546
547             memset(&bi, 0, sizeof(bi));
548             bi.cbSize = sizeof(bi);
549             bindf = 0;
550             hres = IBindStatusCallback_GetBindInfo(bind->pbscb, &bindf, &bi);
551             if(SUCCEEDED(hres)) {
552                 URL_COMPONENTSW url;
553                 WCHAR *host, *path, *user, *pass;
554                 DWORD lensz = sizeof(bind->expected_size);
555                 DWORD dwService = 0;
556                 BOOL bSuccess;
557
558                 TRACE("got bindinfo. bindf = %08x extrainfo = %s bindinfof = %08x bindverb = %08x iid %s\n",
559                       bindf, debugstr_w(bi.szExtraInfo), bi.grfBindInfoF, bi.dwBindVerb, debugstr_guid(&bi.iid));
560                 hres = IBindStatusCallback_OnStartBinding(bind->pbscb, 0, (IBinding*)bind);
561                 TRACE("OnStartBinding rets %08x\n", hres);
562
563                 bind->expected_size = 0;
564                 bind->total_read = 0;
565
566                 memset(&url, 0, sizeof(url));
567                 url.dwStructSize = sizeof(url);
568                 url.dwSchemeLength = url.dwHostNameLength = url.dwUrlPathLength = url.dwUserNameLength = url.dwPasswordLength = 1;
569                 InternetCrackUrlW(URLName, 0, ICU_ESCAPE, &url);
570                 host = HeapAlloc(GetProcessHeap(), 0, (url.dwHostNameLength + 1) * sizeof(WCHAR));
571                 memcpy(host, url.lpszHostName, url.dwHostNameLength * sizeof(WCHAR));
572                 host[url.dwHostNameLength] = '\0';
573                 path = HeapAlloc(GetProcessHeap(), 0, (url.dwUrlPathLength + 1) * sizeof(WCHAR));
574                 memcpy(path, url.lpszUrlPath, url.dwUrlPathLength * sizeof(WCHAR));
575                 path[url.dwUrlPathLength] = '\0';
576                 if (url.dwUserNameLength)
577                 {
578                     user = HeapAlloc(GetProcessHeap(), 0, ((url.dwUserNameLength + 1) * sizeof(WCHAR)));
579                     memcpy(user, url.lpszUserName, url.dwUserNameLength * sizeof(WCHAR));
580                     user[url.dwUserNameLength] = 0;
581                 }
582                 else
583                 {
584                     user = 0;
585                 }
586                 if (url.dwPasswordLength)
587                 {
588                     pass = HeapAlloc(GetProcessHeap(), 0, ((url.dwPasswordLength + 1) * sizeof(WCHAR)));
589                     memcpy(pass, url.lpszPassword, url.dwPasswordLength * sizeof(WCHAR));
590                     pass[url.dwPasswordLength] = 0;
591                 }
592                 else
593                 {
594                     pass = 0;
595                 }
596
597
598                 do {
599                     bind->hinternet = InternetOpenA("User Agent", 0, NULL, NULL, 0);
600                     if (!bind->hinternet)
601                     {
602                             hres = HRESULT_FROM_WIN32(GetLastError());
603                             break;
604                     }
605
606                     switch ((DWORD) url.nScheme)
607                     {
608                     case INTERNET_SCHEME_FTP:
609                         if (!url.nPort)
610                             url.nPort = INTERNET_DEFAULT_FTP_PORT;
611                         dwService = INTERNET_SERVICE_FTP;
612                         break;
613     
614                     case INTERNET_SCHEME_GOPHER:
615                         if (!url.nPort)
616                             url.nPort = INTERNET_DEFAULT_GOPHER_PORT;
617                         dwService = INTERNET_SERVICE_GOPHER;
618                         break;
619
620                     case INTERNET_SCHEME_HTTPS:
621                         if (!url.nPort)
622                             url.nPort = INTERNET_DEFAULT_HTTPS_PORT;
623                         dwService = INTERNET_SERVICE_HTTP;
624                         break;
625                     }
626
627                     bind->hconnect = InternetConnectW(bind->hinternet, host, url.nPort, user, pass,
628                                                       dwService, 0, (DWORD)bind);
629                     if (!bind->hconnect)
630                     {
631                             hres = HRESULT_FROM_WIN32(GetLastError());
632                             CloseHandle(bind->hinternet);
633                             break;
634                     }
635
636                     hres = IBindStatusCallback_OnProgress(bind->pbscb, 0, 0, 0x22, NULL);
637                     hres = IBindStatusCallback_OnProgress(bind->pbscb, 0, 0, BINDSTATUS_FINDINGRESOURCE, NULL);
638                     hres = IBindStatusCallback_OnProgress(bind->pbscb, 0, 0, BINDSTATUS_CONNECTING, NULL);
639                     hres = IBindStatusCallback_OnProgress(bind->pbscb, 0, 0, BINDSTATUS_SENDINGREQUEST, NULL);
640
641                     bSuccess = FALSE;
642
643                     switch (dwService)
644                     {
645                     case INTERNET_SERVICE_GOPHER:
646                         bind->hrequest = GopherOpenFileW(bind->hconnect,
647                                                          path,
648                                                          0,
649                                                          INTERNET_FLAG_RELOAD,
650                                                          0);
651                         if (bind->hrequest)
652                                 bSuccess = TRUE;
653                         else
654                                 hres = HRESULT_FROM_WIN32(GetLastError());
655                         break;
656
657                     case INTERNET_SERVICE_FTP:
658                         bind->hrequest = FtpOpenFileW(bind->hconnect,
659                                                       path,
660                                                       GENERIC_READ,
661                                                       FTP_TRANSFER_TYPE_BINARY |
662                                                        INTERNET_FLAG_TRANSFER_BINARY |
663                                                        INTERNET_FLAG_RELOAD,
664                                                       0);
665                         if (bind->hrequest)
666                                 bSuccess = TRUE;
667                         else
668                                 hres = HRESULT_FROM_WIN32(GetLastError());
669                         break;
670
671                     case INTERNET_SERVICE_HTTP:
672                         bind->hrequest = HttpOpenRequestW(bind->hconnect, NULL, path, NULL, NULL, NULL, 0, (DWORD)bind);
673                         if (!bind->hrequest)
674                         {
675                                 hres = HRESULT_FROM_WIN32(GetLastError());
676                         }
677                         else if (!HttpSendRequestW(bind->hrequest, NULL, 0, NULL, 0))
678                         {
679                                 hres = HRESULT_FROM_WIN32(GetLastError());
680                                 InternetCloseHandle(bind->hrequest);
681                         }
682                         else
683                         {
684                                 HttpQueryInfoW(bind->hrequest,
685                                                HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER,
686                                                &bind->expected_size,
687                                                &lensz,
688                                                NULL);
689                                 bSuccess = TRUE;
690                         }
691                         break;
692                     }
693                     if(bSuccess)
694                     {
695                         TRACE("res = %d gle = %u url len = %d\n", hres, GetLastError(), bind->expected_size);
696
697                         IBindStatusCallback_OnProgress(bind->pbscb, 0, 0, BINDSTATUS_CACHEFILENAMEAVAILABLE, szFileName);
698
699                         while(1) {
700                             char buf[4096];
701                             DWORD bufread;
702                             if(InternetReadFile(bind->hrequest, buf, sizeof(buf), &bufread)) {
703                                 TRACE("read %d bytes %s...\n", bufread, debugstr_an(buf, 10));
704                                 if(bufread == 0) break;
705                                 hres = Binding_MoreCacheData(bind, buf, bufread);
706                             } else
707                                 break;
708                         }
709                         InternetCloseHandle(bind->hrequest);
710                             hres = S_OK;
711                     }
712             
713                     InternetCloseHandle(bind->hconnect);
714                     InternetCloseHandle(bind->hinternet);
715                 } while(0);
716
717                 Binding_FinishedDownload(bind, hres);
718                 Binding_CloseCacheDownload(bind);
719
720                 HeapFree(GetProcessHeap(), 0, user);
721                 HeapFree(GetProcessHeap(), 0, pass);
722                 HeapFree(GetProcessHeap(), 0, path);
723                 HeapFree(GetProcessHeap(), 0, host);
724             }
725         }
726     }
727
728     IBinding_Release((IBinding*)bind);
729
730     return hres;
731 }
732
733 static HRESULT WINAPI URLMonikerImpl_BindToStorage(IMoniker* iface,
734                                                    IBindCtx* pbc,
735                                                    IMoniker* pmkToLeft,
736                                                    REFIID riid,
737                                                    VOID** ppvObject)
738 {
739     URLMonikerImpl *This = (URLMonikerImpl*)iface;
740     WCHAR schema[64];
741     BOOL bret;
742
743     URL_COMPONENTSW url = {sizeof(URL_COMPONENTSW), schema,
744         sizeof(schema)/sizeof(WCHAR), 0, NULL, 0, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0};
745
746     bret = InternetCrackUrlW(This->URLName, 0, ICU_ESCAPE, &url);
747     if(!bret) {
748         ERR("InternetCrackUrl failed: %u\n", GetLastError());
749         return E_FAIL;
750     }
751
752     if(url.nScheme== INTERNET_SCHEME_HTTPS
753        || url.nScheme== INTERNET_SCHEME_FTP
754        || url.nScheme == INTERNET_SCHEME_GOPHER)
755         return URLMonikerImpl_BindToStorage_hack(This->URLName, pbc, pmkToLeft, riid, ppvObject);
756
757     TRACE("(%p)->(%p %p %s %p)\n", This, pbc, pmkToLeft, debugstr_guid(riid), ppvObject);
758
759     return start_binding(This->URLName, pbc, riid, ppvObject);
760 }
761
762 /******************************************************************************
763  *        URLMoniker_Reduce
764  ******************************************************************************/
765 static HRESULT WINAPI URLMonikerImpl_Reduce(IMoniker* iface,
766                                             IBindCtx* pbc,
767                                             DWORD dwReduceHowFar,
768                                             IMoniker** ppmkToLeft,
769                                             IMoniker** ppmkReduced)
770 {
771     URLMonikerImpl *This = (URLMonikerImpl *)iface;
772     
773     TRACE("(%p,%p,%d,%p,%p)\n",This,pbc,dwReduceHowFar,ppmkToLeft,ppmkReduced);
774
775     if(!ppmkReduced)
776         return E_INVALIDARG;
777
778     URLMonikerImpl_AddRef(iface);
779     *ppmkReduced = iface;
780     return MK_S_REDUCED_TO_SELF;
781 }
782
783 /******************************************************************************
784  *        URLMoniker_ComposeWith
785  ******************************************************************************/
786 static HRESULT WINAPI URLMonikerImpl_ComposeWith(IMoniker* iface,
787                                                  IMoniker* pmkRight,
788                                                  BOOL fOnlyIfNotGeneric,
789                                                  IMoniker** ppmkComposite)
790 {
791     URLMonikerImpl *This = (URLMonikerImpl *)iface;
792     FIXME("(%p)->(%p,%d,%p): stub\n",This,pmkRight,fOnlyIfNotGeneric,ppmkComposite);
793
794     return E_NOTIMPL;
795 }
796
797 /******************************************************************************
798  *        URLMoniker_Enum
799  ******************************************************************************/
800 static HRESULT WINAPI URLMonikerImpl_Enum(IMoniker* iface,BOOL fForward, IEnumMoniker** ppenumMoniker)
801 {
802     URLMonikerImpl *This = (URLMonikerImpl *)iface;
803     TRACE("(%p,%d,%p)\n",This,fForward,ppenumMoniker);
804
805     if(!ppenumMoniker)
806         return E_INVALIDARG;
807
808     /* Does not support sub-monikers */
809     *ppenumMoniker = NULL;
810     return S_OK;
811 }
812
813 /******************************************************************************
814  *        URLMoniker_IsEqual
815  ******************************************************************************/
816 static HRESULT WINAPI URLMonikerImpl_IsEqual(IMoniker* iface,IMoniker* pmkOtherMoniker)
817 {
818     URLMonikerImpl *This = (URLMonikerImpl *)iface;
819     CLSID clsid;
820     LPOLESTR urlPath;
821     IBindCtx* bind;
822     HRESULT res;
823
824     TRACE("(%p,%p)\n",This,pmkOtherMoniker);
825
826     if(pmkOtherMoniker==NULL)
827         return E_INVALIDARG;
828
829     IMoniker_GetClassID(pmkOtherMoniker,&clsid);
830
831     if(!IsEqualCLSID(&clsid,&CLSID_StdURLMoniker))
832         return S_FALSE;
833
834     res = CreateBindCtx(0,&bind);
835     if(FAILED(res))
836         return res;
837
838     res = S_FALSE;
839     if(SUCCEEDED(IMoniker_GetDisplayName(pmkOtherMoniker,bind,NULL,&urlPath))) {
840         int result = lstrcmpiW(urlPath, This->URLName);
841         CoTaskMemFree(urlPath);
842         if(result == 0)
843             res = S_OK;
844     }
845     IUnknown_Release(bind);
846     return res;
847 }
848
849
850 /******************************************************************************
851  *        URLMoniker_Hash
852  ******************************************************************************/
853 static HRESULT WINAPI URLMonikerImpl_Hash(IMoniker* iface,DWORD* pdwHash)
854 {
855     URLMonikerImpl *This = (URLMonikerImpl *)iface;
856     
857     int  h = 0,i,skip,len;
858     int  off = 0;
859     LPOLESTR val;
860
861     TRACE("(%p,%p)\n",This,pdwHash);
862
863     if(!pdwHash)
864         return E_INVALIDARG;
865
866     val = This->URLName;
867     len = lstrlenW(val);
868
869     if(len < 16) {
870         for(i = len ; i > 0; i--) {
871             h = (h * 37) + val[off++];
872         }
873     }
874     else {
875         /* only sample some characters */
876         skip = len / 8;
877         for(i = len; i > 0; i -= skip, off += skip) {
878             h = (h * 39) + val[off];
879         }
880     }
881     *pdwHash = h;
882     return S_OK;
883 }
884
885 /******************************************************************************
886  *        URLMoniker_IsRunning
887  ******************************************************************************/
888 static HRESULT WINAPI URLMonikerImpl_IsRunning(IMoniker* iface,
889                                                IBindCtx* pbc,
890                                                IMoniker* pmkToLeft,
891                                                IMoniker* pmkNewlyRunning)
892 {
893     URLMonikerImpl *This = (URLMonikerImpl *)iface;
894     FIXME("(%p)->(%p,%p,%p): stub\n",This,pbc,pmkToLeft,pmkNewlyRunning);
895
896     return E_NOTIMPL;
897 }
898
899 /******************************************************************************
900  *        URLMoniker_GetTimeOfLastChange
901  ******************************************************************************/
902 static HRESULT WINAPI URLMonikerImpl_GetTimeOfLastChange(IMoniker* iface,
903                                                          IBindCtx* pbc,
904                                                          IMoniker* pmkToLeft,
905                                                          FILETIME* pFileTime)
906 {
907     URLMonikerImpl *This = (URLMonikerImpl *)iface;
908     FIXME("(%p)->(%p,%p,%p): stub\n",This,pbc,pmkToLeft,pFileTime);
909
910     return E_NOTIMPL;
911 }
912
913 /******************************************************************************
914  *        URLMoniker_Inverse
915  ******************************************************************************/
916 static HRESULT WINAPI URLMonikerImpl_Inverse(IMoniker* iface,IMoniker** ppmk)
917 {
918     URLMonikerImpl *This = (URLMonikerImpl *)iface;
919     TRACE("(%p,%p)\n",This,ppmk);
920
921     return MK_E_NOINVERSE;
922 }
923
924 /******************************************************************************
925  *        URLMoniker_CommonPrefixWith
926  ******************************************************************************/
927 static HRESULT WINAPI URLMonikerImpl_CommonPrefixWith(IMoniker* iface,IMoniker* pmkOther,IMoniker** ppmkPrefix)
928 {
929     URLMonikerImpl *This = (URLMonikerImpl *)iface;
930     FIXME("(%p)->(%p,%p): stub\n",This,pmkOther,ppmkPrefix);
931
932     return E_NOTIMPL;
933 }
934
935 /******************************************************************************
936  *        URLMoniker_RelativePathTo
937  ******************************************************************************/
938 static HRESULT WINAPI URLMonikerImpl_RelativePathTo(IMoniker* iface,IMoniker* pmOther, IMoniker** ppmkRelPath)
939 {
940     URLMonikerImpl *This = (URLMonikerImpl *)iface;
941     FIXME("(%p)->(%p,%p): stub\n",This,pmOther,ppmkRelPath);
942
943     return E_NOTIMPL;
944 }
945
946 /******************************************************************************
947  *        URLMoniker_GetDisplayName
948  ******************************************************************************/
949 static HRESULT WINAPI URLMonikerImpl_GetDisplayName(IMoniker* iface,
950                                                     IBindCtx* pbc,
951                                                     IMoniker* pmkToLeft,
952                                                     LPOLESTR *ppszDisplayName)
953 {
954     URLMonikerImpl *This = (URLMonikerImpl *)iface;
955     
956     int len;
957     
958     TRACE("(%p,%p,%p,%p)\n",This,pbc,pmkToLeft,ppszDisplayName);
959     
960     if(!ppszDisplayName)
961         return E_INVALIDARG;
962     
963     /* FIXME: If this is a partial URL, try and get a URL moniker from SZ_URLCONTEXT in the bind context,
964         then look at pmkToLeft to try and complete the URL
965     */
966     len = lstrlenW(This->URLName)+1;
967     *ppszDisplayName = CoTaskMemAlloc(len*sizeof(WCHAR));
968     if(!*ppszDisplayName)
969         return E_OUTOFMEMORY;
970     lstrcpyW(*ppszDisplayName, This->URLName);
971     return S_OK;
972 }
973
974 /******************************************************************************
975  *        URLMoniker_ParseDisplayName
976  ******************************************************************************/
977 static HRESULT WINAPI URLMonikerImpl_ParseDisplayName(IMoniker* iface,
978                                                       IBindCtx* pbc,
979                                                       IMoniker* pmkToLeft,
980                                                       LPOLESTR pszDisplayName,
981                                                       ULONG* pchEaten,
982                                                       IMoniker** ppmkOut)
983 {
984     URLMonikerImpl *This = (URLMonikerImpl *)iface;
985     FIXME("(%p)->(%p,%p,%p,%p,%p): stub\n",This,pbc,pmkToLeft,pszDisplayName,pchEaten,ppmkOut);
986
987     return E_NOTIMPL;
988 }
989
990 /******************************************************************************
991  *        URLMoniker_IsSystemMoniker
992  ******************************************************************************/
993 static HRESULT WINAPI URLMonikerImpl_IsSystemMoniker(IMoniker* iface,DWORD* pwdMksys)
994 {
995     URLMonikerImpl *This = (URLMonikerImpl *)iface;
996     TRACE("(%p,%p)\n",This,pwdMksys);
997
998     if(!pwdMksys)
999         return E_INVALIDARG;
1000
1001     *pwdMksys = MKSYS_URLMONIKER;
1002     return S_OK;
1003 }
1004
1005 /********************************************************************************/
1006 /* Virtual function table for the URLMonikerImpl class which  include IPersist,*/
1007 /* IPersistStream and IMoniker functions.                                       */
1008 static const IMonikerVtbl VT_URLMonikerImpl =
1009 {
1010     URLMonikerImpl_QueryInterface,
1011     URLMonikerImpl_AddRef,
1012     URLMonikerImpl_Release,
1013     URLMonikerImpl_GetClassID,
1014     URLMonikerImpl_IsDirty,
1015     URLMonikerImpl_Load,
1016     URLMonikerImpl_Save,
1017     URLMonikerImpl_GetSizeMax,
1018     URLMonikerImpl_BindToObject,
1019     URLMonikerImpl_BindToStorage,
1020     URLMonikerImpl_Reduce,
1021     URLMonikerImpl_ComposeWith,
1022     URLMonikerImpl_Enum,
1023     URLMonikerImpl_IsEqual,
1024     URLMonikerImpl_Hash,
1025     URLMonikerImpl_IsRunning,
1026     URLMonikerImpl_GetTimeOfLastChange,
1027     URLMonikerImpl_Inverse,
1028     URLMonikerImpl_CommonPrefixWith,
1029     URLMonikerImpl_RelativePathTo,
1030     URLMonikerImpl_GetDisplayName,
1031     URLMonikerImpl_ParseDisplayName,
1032     URLMonikerImpl_IsSystemMoniker
1033 };
1034
1035 /******************************************************************************
1036  *         URLMoniker_Construct (local function)
1037  *******************************************************************************/
1038 static HRESULT URLMonikerImpl_Construct(URLMonikerImpl* This, LPCOLESTR lpszLeftURLName, LPCOLESTR lpszURLName)
1039 {
1040     HRESULT hres;
1041     DWORD sizeStr = 0;
1042
1043     TRACE("(%p,%s,%s)\n",This,debugstr_w(lpszLeftURLName),debugstr_w(lpszURLName));
1044
1045     This->lpvtbl = &VT_URLMonikerImpl;
1046     This->ref = 0;
1047
1048     This->URLName = HeapAlloc(GetProcessHeap(), 0, INTERNET_MAX_URL_LENGTH*sizeof(WCHAR));
1049
1050     if(lpszLeftURLName)
1051         hres = CoInternetCombineUrl(lpszLeftURLName, lpszURLName, URL_FILE_USE_PATHURL,
1052                 This->URLName, INTERNET_MAX_URL_LENGTH, &sizeStr, 0);
1053     else
1054         hres = CoInternetParseUrl(lpszURLName, PARSE_CANONICALIZE, URL_FILE_USE_PATHURL,
1055                 This->URLName, INTERNET_MAX_URL_LENGTH, &sizeStr, 0);
1056
1057     if(FAILED(hres)) {
1058         HeapFree(GetProcessHeap(), 0, This->URLName);
1059         return hres;
1060     }
1061
1062     URLMON_LockModule();
1063
1064     if(sizeStr != INTERNET_MAX_URL_LENGTH)
1065         This->URLName = HeapReAlloc(GetProcessHeap(), 0, This->URLName, (sizeStr+1)*sizeof(WCHAR));
1066
1067     TRACE("URLName = %s\n", debugstr_w(This->URLName));
1068
1069     return S_OK;
1070 }
1071
1072 /***********************************************************************
1073  *           CreateURLMonikerEx (URLMON.@)
1074  *
1075  * Create a url moniker.
1076  *
1077  * PARAMS
1078  *    pmkContext [I] Context
1079  *    szURL      [I] Url to create the moniker for
1080  *    ppmk       [O] Destination for created moniker.
1081  *    dwFlags    [I] Flags.
1082  *
1083  * RETURNS
1084  *    Success: S_OK. ppmk contains the created IMoniker object.
1085  *    Failure: MK_E_SYNTAX if szURL is not a valid url, or
1086  *             E_OUTOFMEMORY if memory allocation fails.
1087  */
1088 HRESULT WINAPI CreateURLMonikerEx(IMoniker *pmkContext, LPCWSTR szURL, IMoniker **ppmk, DWORD dwFlags)
1089 {
1090     URLMonikerImpl *obj;
1091     HRESULT hres;
1092     LPOLESTR lefturl = NULL;
1093
1094     TRACE("(%p, %s, %p, %08x)\n", pmkContext, debugstr_w(szURL), ppmk, dwFlags);
1095
1096     if (dwFlags & URL_MK_UNIFORM) FIXME("ignoring flag URL_MK_UNIFORM\n");
1097
1098     if(!(obj = HeapAlloc(GetProcessHeap(), 0, sizeof(*obj))))
1099         return E_OUTOFMEMORY;
1100
1101     if(pmkContext) {
1102         IBindCtx* bind;
1103         DWORD dwMksys = 0;
1104         IMoniker_IsSystemMoniker(pmkContext, &dwMksys);
1105         if(dwMksys == MKSYS_URLMONIKER && SUCCEEDED(CreateBindCtx(0, &bind))) {
1106             IMoniker_GetDisplayName(pmkContext, bind, NULL, &lefturl);
1107             TRACE("lefturl = %s\n", debugstr_w(lefturl));
1108             IBindCtx_Release(bind);
1109         }
1110     }
1111         
1112     hres = URLMonikerImpl_Construct(obj, lefturl, szURL);
1113     CoTaskMemFree(lefturl);
1114     if(SUCCEEDED(hres))
1115         hres = URLMonikerImpl_QueryInterface((IMoniker*)obj, &IID_IMoniker, (void**)ppmk);
1116     else
1117         HeapFree(GetProcessHeap(), 0, obj);
1118     return hres;
1119 }
1120
1121 /**********************************************************************
1122  *           CreateURLMoniker (URLMON.@)
1123  *
1124  * Create a url moniker.
1125  *
1126  * PARAMS
1127  *    pmkContext [I] Context
1128  *    szURL      [I] Url to create the moniker for
1129  *    ppmk       [O] Destination for created moniker.
1130  *
1131  * RETURNS
1132  *    Success: S_OK. ppmk contains the created IMoniker object.
1133  *    Failure: MK_E_SYNTAX if szURL is not a valid url, or
1134  *             E_OUTOFMEMORY if memory allocation fails.
1135  */
1136 HRESULT WINAPI CreateURLMoniker(IMoniker *pmkContext, LPCWSTR szURL, IMoniker **ppmk)
1137 {
1138     return CreateURLMonikerEx(pmkContext, szURL, ppmk, URL_MK_LEGACY);
1139 }
1140
1141 /***********************************************************************
1142  *           CoInternetQueryInfo (URLMON.@)
1143  *
1144  * Retrieves information relevant to a specified URL
1145  *
1146  * RETURNS
1147  *    S_OK                      success
1148  *    S_FALSE                   buffer too small
1149  *    INET_E_QUERYOPTIONUNKNOWN invalid option
1150  *
1151  */
1152 HRESULT WINAPI CoInternetQueryInfo(LPCWSTR pwzUrl, QUERYOPTION QueryOption,
1153   DWORD dwQueryFlags, LPVOID pvBuffer, DWORD cbBuffer, DWORD * pcbBuffer,
1154   DWORD dwReserved)
1155 {
1156   FIXME("(%s, %x, %x, %p, %x, %p, %x): stub\n", debugstr_w(pwzUrl),
1157     QueryOption, dwQueryFlags, pvBuffer, cbBuffer, pcbBuffer, dwReserved);
1158   return S_OK;
1159 }
1160
1161 /***********************************************************************
1162  *           IsAsyncMoniker (URLMON.@)
1163  */
1164 HRESULT WINAPI IsAsyncMoniker(IMoniker *pmk)
1165 {
1166     IUnknown *am;
1167     
1168     TRACE("(%p)\n", pmk);
1169     if(!pmk)
1170         return E_INVALIDARG;
1171     if(SUCCEEDED(IMoniker_QueryInterface(pmk, &IID_IAsyncMoniker, (void**)&am))) {
1172         IUnknown_Release(am);
1173         return S_OK;
1174     }
1175     return S_FALSE;
1176 }
1177
1178 /***********************************************************************
1179  *           BindAsyncMoniker (URLMON.@)
1180  *
1181  * Bind a bind status callback to an asynchronous URL Moniker.
1182  *
1183  * PARAMS
1184  *  pmk           [I] Moniker object to bind status callback to
1185  *  grfOpt        [I] Options, seems not used
1186  *  pbsc          [I] Status callback to bind
1187  *  iidResult     [I] Interface to return
1188  *  ppvResult     [O] Resulting asynchronous moniker object
1189  *
1190  * RETURNS
1191  *    Success: S_OK.
1192  *    Failure: E_INVALIDARG, if any argument is invalid, or
1193  *             E_OUTOFMEMORY if memory allocation fails.
1194  */
1195 HRESULT WINAPI BindAsyncMoniker(IMoniker *pmk, DWORD grfOpt, IBindStatusCallback *pbsc, REFIID iidResult, LPVOID *ppvResult)
1196 {
1197     LPBC pbc = NULL;
1198     HRESULT hr = E_INVALIDARG;
1199
1200     if (pmk && ppvResult)
1201     {
1202         *ppvResult = NULL;
1203
1204         hr = CreateAsyncBindCtx(0, pbsc, NULL, &pbc);
1205         if (hr == NOERROR)
1206         {
1207             hr = IMoniker_BindToObject(pmk, pbc, NULL, iidResult, ppvResult);
1208             IBindCtx_Release(pbc);
1209         }
1210     }
1211     return hr;
1212 }
1213
1214 /***********************************************************************
1215  *           RegisterBindStatusCallback (URLMON.@)
1216  *
1217  * Register a bind status callback.
1218  *
1219  * PARAMS
1220  *  pbc           [I] Binding context
1221  *  pbsc          [I] Callback to register
1222  *  ppbscPrevious [O] Destination for previous callback
1223  *  dwReserved    [I] Reserved, must be 0.
1224  *
1225  * RETURNS
1226  *    Success: S_OK.
1227  *    Failure: E_INVALIDARG, if any argument is invalid, or
1228  *             E_OUTOFMEMORY if memory allocation fails.
1229  */
1230 HRESULT WINAPI RegisterBindStatusCallback(
1231     IBindCtx *pbc,
1232     IBindStatusCallback *pbsc,
1233     IBindStatusCallback **ppbscPrevious,
1234     DWORD dwReserved)
1235 {
1236     IBindStatusCallback *prev;
1237
1238     TRACE("(%p,%p,%p,%u)\n", pbc, pbsc, ppbscPrevious, dwReserved);
1239
1240     if (pbc == NULL || pbsc == NULL)
1241         return E_INVALIDARG;
1242
1243     if (SUCCEEDED(IBindCtx_GetObjectParam(pbc, BSCBHolder, (IUnknown **)&prev)))
1244     {
1245         IBindCtx_RevokeObjectParam(pbc, BSCBHolder);
1246         if (ppbscPrevious)
1247             *ppbscPrevious = prev;
1248         else
1249             IBindStatusCallback_Release(prev);
1250     }
1251
1252     return IBindCtx_RegisterObjectParam(pbc, BSCBHolder, (IUnknown *)pbsc);
1253 }
1254
1255 /***********************************************************************
1256  *           RevokeBindStatusCallback (URLMON.@)
1257  *
1258  * Unregister a bind status callback.
1259  *
1260  *  pbc           [I] Binding context
1261  *  pbsc          [I] Callback to unregister
1262  *
1263  * RETURNS
1264  *    Success: S_OK.
1265  *    Failure: E_INVALIDARG, if any argument is invalid, or
1266  *             E_FAIL if pbsc wasn't registered with pbc.
1267  */
1268 HRESULT WINAPI RevokeBindStatusCallback(
1269     IBindCtx *pbc,
1270     IBindStatusCallback *pbsc)
1271 {
1272     IBindStatusCallback *callback;
1273     HRESULT hr = E_FAIL;
1274
1275         TRACE("(%p,%p)\n", pbc, pbsc);
1276
1277     if (pbc == NULL || pbsc == NULL)
1278         return E_INVALIDARG;
1279
1280     if (SUCCEEDED(IBindCtx_GetObjectParam(pbc, BSCBHolder, (IUnknown **)&callback)))
1281     {
1282         if (callback == pbsc)
1283         {
1284             IBindCtx_RevokeObjectParam(pbc, BSCBHolder);
1285             hr = S_OK;
1286         }
1287         IBindStatusCallback_Release(pbsc);
1288     }
1289
1290     return hr;
1291 }
1292
1293 /***********************************************************************
1294  *           URLDownloadToFileA (URLMON.@)
1295  *
1296  * Downloads URL szURL to rile szFileName and call lpfnCB callback to
1297  * report progress.
1298  *
1299  * PARAMS
1300  *  pCaller    [I] controlling IUnknown interface.
1301  *  szURL      [I] URL of the file to download
1302  *  szFileName [I] file name to store the content of the URL
1303  *  dwReserved [I] reserved - set to 0
1304  *  lpfnCB     [I] callback for progress report
1305  *
1306  * RETURNS
1307  *  S_OK on success
1308  *  E_OUTOFMEMORY when going out of memory
1309  */
1310 HRESULT WINAPI URLDownloadToFileA(LPUNKNOWN pCaller,
1311                                   LPCSTR szURL,
1312                                   LPCSTR szFileName,
1313                                   DWORD dwReserved,
1314                                   LPBINDSTATUSCALLBACK lpfnCB)
1315 {
1316     UNICODE_STRING szURL_w, szFileName_w;
1317
1318     if ((szURL == NULL) || (szFileName == NULL)) {
1319         FIXME("(%p,%s,%s,%08x,%p) cannot accept NULL strings !\n", pCaller, debugstr_a(szURL), debugstr_a(szFileName), dwReserved, lpfnCB);
1320         return E_INVALIDARG; /* The error code is not specified in this case... */
1321     }
1322     
1323     if (RtlCreateUnicodeStringFromAsciiz(&szURL_w, szURL)) {
1324         if (RtlCreateUnicodeStringFromAsciiz(&szFileName_w, szFileName)) {
1325             HRESULT ret = URLDownloadToFileW(pCaller, szURL_w.Buffer, szFileName_w.Buffer, dwReserved, lpfnCB);
1326
1327             RtlFreeUnicodeString(&szURL_w);
1328             RtlFreeUnicodeString(&szFileName_w);
1329             
1330             return ret;
1331         } else {
1332             RtlFreeUnicodeString(&szURL_w);
1333         }
1334     }
1335     
1336     FIXME("(%p,%s,%s,%08x,%p) could not allocate W strings !\n", pCaller, szURL, szFileName, dwReserved, lpfnCB);
1337     return E_OUTOFMEMORY;
1338 }
1339
1340 /***********************************************************************
1341  *           URLDownloadToFileW (URLMON.@)
1342  *
1343  * Downloads URL szURL to rile szFileName and call lpfnCB callback to
1344  * report progress.
1345  *
1346  * PARAMS
1347  *  pCaller    [I] controlling IUnknown interface.
1348  *  szURL      [I] URL of the file to download
1349  *  szFileName [I] file name to store the content of the URL
1350  *  dwReserved [I] reserved - set to 0
1351  *  lpfnCB     [I] callback for progress report
1352  *
1353  * RETURNS
1354  *  S_OK on success
1355  *  E_OUTOFMEMORY when going out of memory
1356  */
1357 HRESULT WINAPI URLDownloadToFileW(LPUNKNOWN pCaller,
1358                                   LPCWSTR szURL,
1359                                   LPCWSTR szFileName,
1360                                   DWORD dwReserved,
1361                                   LPBINDSTATUSCALLBACK lpfnCB)
1362 {
1363     HINTERNET hinternet, hcon, hreq;
1364     BOOL r;
1365     CHAR buffer[0x1000];
1366     DWORD sz, total, written;
1367     DWORD total_size = 0xFFFFFFFF, arg_size = sizeof(total_size);
1368     URL_COMPONENTSW url;
1369     WCHAR host[0x80], path[0x100];
1370     HANDLE hfile;
1371     static const WCHAR wszAppName[]={'u','r','l','m','o','n','.','d','l','l',0};
1372
1373     /* Note: all error codes would need to be checked agains real Windows behaviour... */
1374     TRACE("(%p,%s,%s,%08x,%p) stub!\n", pCaller, debugstr_w(szURL), debugstr_w(szFileName), dwReserved, lpfnCB);
1375
1376     if ((szURL == NULL) || (szFileName == NULL)) {
1377         FIXME(" cannot accept NULL strings !\n");
1378         return E_INVALIDARG;
1379     }
1380
1381     /* Would be better to use the application name here rather than 'urlmon' :-/ */
1382     hinternet = InternetOpenW(wszAppName, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
1383     if (hinternet == NULL) {
1384         return E_OUTOFMEMORY;
1385     }                                                                                                                             
1386
1387     memset(&url, 0, sizeof(url));
1388     url.dwStructSize = sizeof(url);
1389     url.lpszHostName = host;
1390     url.dwHostNameLength = sizeof(host);
1391     url.lpszUrlPath = path;
1392     url.dwUrlPathLength = sizeof(path);
1393
1394     if (!InternetCrackUrlW(szURL, 0, 0, &url)) {
1395         InternetCloseHandle(hinternet);
1396         return E_OUTOFMEMORY;
1397     }
1398
1399     if (lpfnCB) {
1400         if (IBindStatusCallback_OnProgress(lpfnCB, 0, 0, BINDSTATUS_CONNECTING, url.lpszHostName) == E_ABORT) {
1401             InternetCloseHandle(hinternet);
1402             return S_OK;
1403         }
1404     }
1405     
1406     hcon = InternetConnectW(hinternet, url.lpszHostName, url.nPort,
1407                             url.lpszUserName, url.lpszPassword,
1408                             INTERNET_SERVICE_HTTP, 0, 0);
1409     if (!hcon) {
1410         InternetCloseHandle(hinternet);
1411         return E_OUTOFMEMORY;
1412     }
1413     
1414     hreq = HttpOpenRequestW(hcon, NULL, url.lpszUrlPath, NULL, NULL, NULL, 0, 0);
1415     if (!hreq) {
1416         InternetCloseHandle(hinternet);
1417         InternetCloseHandle(hcon);
1418         return E_OUTOFMEMORY;
1419     }                                                                                                                             
1420
1421     if (!HttpSendRequestW(hreq, NULL, 0, NULL, 0)) {
1422         InternetCloseHandle(hinternet);
1423         InternetCloseHandle(hcon);
1424         InternetCloseHandle(hreq);
1425         return E_OUTOFMEMORY;
1426     }
1427     
1428     if (HttpQueryInfoW(hreq, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER,
1429                        &total_size, &arg_size, NULL)) {
1430         TRACE(" total size : %d\n", total_size);
1431     }
1432     
1433     hfile = CreateFileW(szFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
1434                         FILE_ATTRIBUTE_NORMAL, NULL );
1435     if (hfile == INVALID_HANDLE_VALUE) {
1436         return E_ACCESSDENIED;
1437     }
1438     
1439     if (lpfnCB) {
1440         if (IBindStatusCallback_OnProgress(lpfnCB, 0, total_size != 0xFFFFFFFF ? total_size : 0,
1441                                            BINDSTATUS_BEGINDOWNLOADDATA, szURL) == E_ABORT) {
1442             InternetCloseHandle(hreq);
1443             InternetCloseHandle(hcon);
1444             InternetCloseHandle(hinternet);
1445             CloseHandle(hfile);
1446             return S_OK;
1447         }
1448     }
1449     
1450     total = 0;
1451     while (1) {
1452         r = InternetReadFile(hreq, buffer, sizeof(buffer), &sz);
1453         if (!r) {
1454             InternetCloseHandle(hreq);
1455             InternetCloseHandle(hcon);
1456             InternetCloseHandle(hinternet);
1457             
1458             CloseHandle(hfile);
1459             return E_OUTOFMEMORY;           
1460         }
1461         if (!sz)
1462             break;
1463         
1464         total += sz;
1465
1466         if (lpfnCB) {
1467             if (IBindStatusCallback_OnProgress(lpfnCB, total, total_size != 0xFFFFFFFF ? total_size : 0,
1468                                                BINDSTATUS_DOWNLOADINGDATA, szURL) == E_ABORT) {
1469                 InternetCloseHandle(hreq);
1470                 InternetCloseHandle(hcon);
1471                 InternetCloseHandle(hinternet);
1472                 CloseHandle(hfile);
1473                 return S_OK;
1474             }
1475         }
1476         
1477         if (!WriteFile(hfile, buffer, sz, &written, NULL)) {
1478             InternetCloseHandle(hreq);
1479             InternetCloseHandle(hcon);
1480             InternetCloseHandle(hinternet);
1481             
1482             CloseHandle(hfile);
1483             return E_OUTOFMEMORY;
1484         }
1485     }
1486
1487     if (lpfnCB) {
1488         if (IBindStatusCallback_OnProgress(lpfnCB, total, total_size != 0xFFFFFFFF ? total_size : 0,
1489                                            BINDSTATUS_ENDDOWNLOADDATA, szURL) == E_ABORT) {
1490             InternetCloseHandle(hreq);
1491             InternetCloseHandle(hcon);
1492             InternetCloseHandle(hinternet);
1493             CloseHandle(hfile);
1494             return S_OK;
1495         }
1496     }
1497     
1498     InternetCloseHandle(hreq);
1499     InternetCloseHandle(hcon);
1500     InternetCloseHandle(hinternet);
1501     
1502     CloseHandle(hfile);
1503
1504     return S_OK;
1505 }
1506
1507 /***********************************************************************
1508  *           URLDownloadToCacheFileA (URLMON.@)
1509  */
1510 HRESULT WINAPI URLDownloadToCacheFileA(LPUNKNOWN lpUnkCaller, LPCSTR szURL, LPSTR szFileName,
1511         DWORD dwBufLength, DWORD dwReserved, LPBINDSTATUSCALLBACK pBSC)
1512 {
1513     LPWSTR url = NULL, file_name = NULL;
1514     int len;
1515     HRESULT hres;
1516
1517     TRACE("(%p %s %p %d %d %p)\n", lpUnkCaller, debugstr_a(szURL), szFileName,
1518             dwBufLength, dwReserved, pBSC);
1519
1520     if(szURL) {
1521         len = MultiByteToWideChar(CP_ACP, 0, szURL, -1, NULL, 0);
1522         url = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1523         MultiByteToWideChar(CP_ACP, 0, szURL, -1, url, -1);
1524     }
1525
1526     if(szFileName)
1527         file_name = HeapAlloc(GetProcessHeap(), 0, dwBufLength*sizeof(WCHAR));
1528
1529     hres = URLDownloadToCacheFileW(lpUnkCaller, url, file_name, dwBufLength*sizeof(WCHAR),
1530             dwReserved, pBSC);
1531
1532     if(SUCCEEDED(hres) && file_name)
1533         WideCharToMultiByte(CP_ACP, 0, file_name, -1, szFileName, dwBufLength, NULL, NULL);
1534
1535     HeapFree(GetProcessHeap(), 0, url);
1536     HeapFree(GetProcessHeap(), 0, file_name);
1537
1538     return hres;
1539 }
1540
1541 /***********************************************************************
1542  *           URLDownloadToCacheFileW (URLMON.@)
1543  */
1544 HRESULT WINAPI URLDownloadToCacheFileW(LPUNKNOWN lpUnkCaller, LPCWSTR szURL, LPWSTR szFileName,
1545                 DWORD dwBufLength, DWORD dwReserved, LPBINDSTATUSCALLBACK pBSC)
1546 {
1547     WCHAR cache_path[MAX_PATH + 1];
1548     FILETIME expire, modified;
1549     HRESULT hr;
1550     LPWSTR ext;
1551
1552     static WCHAR header[] = {
1553         'H','T','T','P','/','1','.','0',' ','2','0','0',' ',
1554         'O','K','\\','r','\\','n','\\','r','\\','n',0
1555     };
1556
1557     TRACE("(%p, %s, %p, %d, %d, %p)\n", lpUnkCaller, debugstr_w(szURL),
1558           szFileName, dwBufLength, dwReserved, pBSC);
1559
1560     if (!szURL || !szFileName)
1561         return E_INVALIDARG;
1562
1563     ext = PathFindExtensionW(szURL);
1564
1565     if (!CreateUrlCacheEntryW(szURL, 0, ext, cache_path, 0))
1566         return E_FAIL;
1567
1568     hr = URLDownloadToFileW(lpUnkCaller, szURL, cache_path, 0, pBSC);
1569     if (FAILED(hr))
1570         return hr;
1571
1572     expire.dwHighDateTime = 0;
1573     expire.dwLowDateTime = 0;
1574     modified.dwHighDateTime = 0;
1575     modified.dwLowDateTime = 0;
1576
1577     if (!CommitUrlCacheEntryW(szURL, cache_path, expire, modified, NORMAL_CACHE_ENTRY,
1578                               header, sizeof(header), NULL, NULL))
1579         return E_FAIL;
1580
1581     if (lstrlenW(cache_path) > dwBufLength)
1582         return E_OUTOFMEMORY;
1583
1584     lstrcpyW(szFileName, cache_path);
1585
1586     return S_OK;
1587 }
1588
1589 /***********************************************************************
1590  *           HlinkSimpleNavigateToString (URLMON.@)
1591  */
1592 HRESULT WINAPI HlinkSimpleNavigateToString( LPCWSTR szTarget,
1593     LPCWSTR szLocation, LPCWSTR szTargetFrameName, IUnknown *pUnk,
1594     IBindCtx *pbc, IBindStatusCallback *pbsc, DWORD grfHLNF, DWORD dwReserved)
1595 {
1596     FIXME("%s\n", debugstr_w( szTarget ) );
1597     return E_NOTIMPL;
1598 }
1599
1600 /***********************************************************************
1601  *           HlinkNavigateString (URLMON.@)
1602  */
1603 HRESULT WINAPI HlinkNavigateString( IUnknown *pUnk, LPCWSTR szTarget )
1604 {
1605     TRACE("%p %s\n", pUnk, debugstr_w( szTarget ) );
1606     return HlinkSimpleNavigateToString( 
1607                szTarget, NULL, NULL, pUnk, NULL, NULL, 0, 0 );
1608 }
1609
1610 /***********************************************************************
1611  *           GetSoftwareUpdateInfo (URLMON.@)
1612  */
1613 HRESULT WINAPI GetSoftwareUpdateInfo( LPCWSTR szDistUnit, LPSOFTDISTINFO psdi )
1614 {
1615     FIXME("%s %p\n", debugstr_w(szDistUnit), psdi );
1616     return E_FAIL;
1617 }