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