urlmon: Rename the wrappers around HeapAlloc() &Co to use the new standard naming.
[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         heap_free(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         heap_free(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, const 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         heap_free(This->URLName);
360         heap_free(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             heap_free(This->URLName);
424             This->URLName = heap_alloc(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                                                    REFIID riid,
504                                                    VOID** ppvObject)
505 {
506     HRESULT hres;
507     BINDINFO bi;
508     DWORD bindf;
509     WCHAR szFileName[MAX_PATH + 1];
510     Binding *bind;
511     int len;
512
513     WARN("(%s %p %s %p)\n", debugstr_w(URLName), pbc, debugstr_guid(riid), ppvObject);
514
515     if(!IsEqualIID(&IID_IStream, riid)) {
516         FIXME("unsupported iid\n");
517         return E_NOTIMPL;
518     }
519
520     bind = heap_alloc_zero(sizeof(Binding));
521     bind->lpVtbl = &BindingVtbl;
522     bind->ref = 1;
523     URLMON_LockModule();
524
525     len = lstrlenW(URLName)+1;
526     bind->URLName = heap_alloc(len*sizeof(WCHAR));
527     memcpy(bind->URLName, URLName, len*sizeof(WCHAR));
528
529     hres = UMCreateStreamOnCacheFile(bind->URLName, 0, szFileName, &bind->hCacheFile, &bind->pstrCache);
530
531     if(SUCCEEDED(hres)) {
532         TRACE("Created stream...\n");
533
534         *ppvObject = (void *) bind->pstrCache;
535         IStream_AddRef((IStream *) bind->pstrCache);
536
537         hres = IBindCtx_GetObjectParam(pbc, BSCBHolder, (IUnknown**)&bind->pbscb);
538         if(SUCCEEDED(hres)) {
539             TRACE("Got IBindStatusCallback...\n");
540
541             memset(&bi, 0, sizeof(bi));
542             bi.cbSize = sizeof(bi);
543             bindf = 0;
544             hres = IBindStatusCallback_GetBindInfo(bind->pbscb, &bindf, &bi);
545             if(SUCCEEDED(hres)) {
546                 URL_COMPONENTSW url;
547                 WCHAR *host, *path, *user, *pass;
548                 DWORD lensz = sizeof(bind->expected_size);
549                 DWORD dwService = 0;
550                 BOOL bSuccess;
551
552                 TRACE("got bindinfo. bindf = %08x extrainfo = %s bindinfof = %08x bindverb = %08x iid %s\n",
553                       bindf, debugstr_w(bi.szExtraInfo), bi.grfBindInfoF, bi.dwBindVerb, debugstr_guid(&bi.iid));
554                 hres = IBindStatusCallback_OnStartBinding(bind->pbscb, 0, (IBinding*)bind);
555                 TRACE("OnStartBinding rets %08x\n", hres);
556
557                 bind->expected_size = 0;
558                 bind->total_read = 0;
559
560                 memset(&url, 0, sizeof(url));
561                 url.dwStructSize = sizeof(url);
562                 url.dwSchemeLength = url.dwHostNameLength = url.dwUrlPathLength = url.dwUserNameLength = url.dwPasswordLength = 1;
563                 InternetCrackUrlW(URLName, 0, ICU_ESCAPE, &url);
564                 host = heap_alloc((url.dwHostNameLength + 1) * sizeof(WCHAR));
565                 memcpy(host, url.lpszHostName, url.dwHostNameLength * sizeof(WCHAR));
566                 host[url.dwHostNameLength] = '\0';
567                 path = heap_alloc((url.dwUrlPathLength + 1) * sizeof(WCHAR));
568                 memcpy(path, url.lpszUrlPath, url.dwUrlPathLength * sizeof(WCHAR));
569                 path[url.dwUrlPathLength] = '\0';
570                 if (url.dwUserNameLength)
571                 {
572                     user = heap_alloc(((url.dwUserNameLength + 1) * sizeof(WCHAR)));
573                     memcpy(user, url.lpszUserName, url.dwUserNameLength * sizeof(WCHAR));
574                     user[url.dwUserNameLength] = 0;
575                 }
576                 else
577                 {
578                     user = 0;
579                 }
580                 if (url.dwPasswordLength)
581                 {
582                     pass = heap_alloc(((url.dwPasswordLength + 1) * sizeof(WCHAR)));
583                     memcpy(pass, url.lpszPassword, url.dwPasswordLength * sizeof(WCHAR));
584                     pass[url.dwPasswordLength] = 0;
585                 }
586                 else
587                 {
588                     pass = 0;
589                 }
590
591
592                 do {
593                     bind->hinternet = InternetOpenA("User Agent", 0, NULL, NULL, 0);
594                     if (!bind->hinternet)
595                     {
596                             hres = HRESULT_FROM_WIN32(GetLastError());
597                             break;
598                     }
599
600                     switch ((DWORD) url.nScheme)
601                     {
602                     case INTERNET_SCHEME_FTP:
603                         if (!url.nPort)
604                             url.nPort = INTERNET_DEFAULT_FTP_PORT;
605                         dwService = INTERNET_SERVICE_FTP;
606                         break;
607     
608                     case INTERNET_SCHEME_GOPHER:
609                         if (!url.nPort)
610                             url.nPort = INTERNET_DEFAULT_GOPHER_PORT;
611                         dwService = INTERNET_SERVICE_GOPHER;
612                         break;
613
614                     case INTERNET_SCHEME_HTTPS:
615                         if (!url.nPort)
616                             url.nPort = INTERNET_DEFAULT_HTTPS_PORT;
617                         dwService = INTERNET_SERVICE_HTTP;
618                         break;
619                     }
620
621                     bind->hconnect = InternetConnectW(bind->hinternet, host, url.nPort, user, pass,
622                                                       dwService, 0, (DWORD)bind);
623                     if (!bind->hconnect)
624                     {
625                             hres = HRESULT_FROM_WIN32(GetLastError());
626                             CloseHandle(bind->hinternet);
627                             break;
628                     }
629
630                     hres = IBindStatusCallback_OnProgress(bind->pbscb, 0, 0, 0x22, NULL);
631                     hres = IBindStatusCallback_OnProgress(bind->pbscb, 0, 0, BINDSTATUS_FINDINGRESOURCE, NULL);
632                     hres = IBindStatusCallback_OnProgress(bind->pbscb, 0, 0, BINDSTATUS_CONNECTING, NULL);
633                     hres = IBindStatusCallback_OnProgress(bind->pbscb, 0, 0, BINDSTATUS_SENDINGREQUEST, NULL);
634
635                     bSuccess = FALSE;
636
637                     switch (dwService)
638                     {
639                     case INTERNET_SERVICE_GOPHER:
640                         bind->hrequest = GopherOpenFileW(bind->hconnect,
641                                                          path,
642                                                          0,
643                                                          INTERNET_FLAG_RELOAD,
644                                                          0);
645                         if (bind->hrequest)
646                                 bSuccess = TRUE;
647                         else
648                                 hres = HRESULT_FROM_WIN32(GetLastError());
649                         break;
650
651                     case INTERNET_SERVICE_FTP:
652                         bind->hrequest = FtpOpenFileW(bind->hconnect,
653                                                       path,
654                                                       GENERIC_READ,
655                                                       FTP_TRANSFER_TYPE_BINARY |
656                                                        INTERNET_FLAG_TRANSFER_BINARY |
657                                                        INTERNET_FLAG_RELOAD,
658                                                       0);
659                         if (bind->hrequest)
660                                 bSuccess = TRUE;
661                         else
662                                 hres = HRESULT_FROM_WIN32(GetLastError());
663                         break;
664
665                     case INTERNET_SERVICE_HTTP:
666                         bind->hrequest = HttpOpenRequestW(bind->hconnect, NULL, path, NULL, NULL, NULL, 0, (DWORD)bind);
667                         if (!bind->hrequest)
668                         {
669                                 hres = HRESULT_FROM_WIN32(GetLastError());
670                         }
671                         else if (!HttpSendRequestW(bind->hrequest, NULL, 0, NULL, 0))
672                         {
673                                 hres = HRESULT_FROM_WIN32(GetLastError());
674                                 InternetCloseHandle(bind->hrequest);
675                         }
676                         else
677                         {
678                                 HttpQueryInfoW(bind->hrequest,
679                                                HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER,
680                                                &bind->expected_size,
681                                                &lensz,
682                                                NULL);
683                                 bSuccess = TRUE;
684                         }
685                         break;
686                     }
687                     if(bSuccess)
688                     {
689                         TRACE("res = %d gle = %u url len = %d\n", hres, GetLastError(), bind->expected_size);
690
691                         IBindStatusCallback_OnProgress(bind->pbscb, 0, 0, BINDSTATUS_CACHEFILENAMEAVAILABLE, szFileName);
692
693                         while(1) {
694                             char buf[4096];
695                             DWORD bufread;
696                             if(InternetReadFile(bind->hrequest, buf, sizeof(buf), &bufread)) {
697                                 TRACE("read %d bytes %s...\n", bufread, debugstr_an(buf, 10));
698                                 if(bufread == 0) break;
699                                 hres = Binding_MoreCacheData(bind, buf, bufread);
700                             } else
701                                 break;
702                         }
703                         InternetCloseHandle(bind->hrequest);
704                             hres = S_OK;
705                     }
706             
707                     InternetCloseHandle(bind->hconnect);
708                     InternetCloseHandle(bind->hinternet);
709                 } while(0);
710
711                 Binding_FinishedDownload(bind, hres);
712                 Binding_CloseCacheDownload(bind);
713
714                 heap_free(user);
715                 heap_free(pass);
716                 heap_free(path);
717                 heap_free(host);
718             }
719         }
720     }
721
722     IBinding_Release((IBinding*)bind);
723
724     return hres;
725 }
726
727 static HRESULT WINAPI URLMonikerImpl_BindToStorage(IMoniker* iface,
728                                                    IBindCtx* pbc,
729                                                    IMoniker* pmkToLeft,
730                                                    REFIID riid,
731                                                    VOID** ppvObject)
732 {
733     URLMonikerImpl *This = (URLMonikerImpl*)iface;
734     WCHAR schema[64];
735     BOOL bret;
736
737     URL_COMPONENTSW url = {sizeof(URL_COMPONENTSW), schema,
738         sizeof(schema)/sizeof(WCHAR), 0, NULL, 0, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0};
739
740     if(pmkToLeft)
741         FIXME("Unsupported pmkToLeft\n");
742
743     bret = InternetCrackUrlW(This->URLName, 0, ICU_ESCAPE, &url);
744     if(!bret) {
745         ERR("InternetCrackUrl failed: %u\n", GetLastError());
746         return E_FAIL;
747     }
748
749     if(url.nScheme== INTERNET_SCHEME_HTTPS
750        || url.nScheme== INTERNET_SCHEME_FTP
751        || url.nScheme == INTERNET_SCHEME_GOPHER)
752         return URLMonikerImpl_BindToStorage_hack(This->URLName, pbc, riid, ppvObject);
753
754     TRACE("(%p)->(%p %p %s %p)\n", This, pbc, pmkToLeft, debugstr_guid(riid), ppvObject);
755
756     return start_binding(This->URLName, pbc, riid, ppvObject);
757 }
758
759 /******************************************************************************
760  *        URLMoniker_Reduce
761  ******************************************************************************/
762 static HRESULT WINAPI URLMonikerImpl_Reduce(IMoniker* iface,
763                                             IBindCtx* pbc,
764                                             DWORD dwReduceHowFar,
765                                             IMoniker** ppmkToLeft,
766                                             IMoniker** ppmkReduced)
767 {
768     URLMonikerImpl *This = (URLMonikerImpl *)iface;
769     
770     TRACE("(%p,%p,%d,%p,%p)\n",This,pbc,dwReduceHowFar,ppmkToLeft,ppmkReduced);
771
772     if(!ppmkReduced)
773         return E_INVALIDARG;
774
775     URLMonikerImpl_AddRef(iface);
776     *ppmkReduced = iface;
777     return MK_S_REDUCED_TO_SELF;
778 }
779
780 /******************************************************************************
781  *        URLMoniker_ComposeWith
782  ******************************************************************************/
783 static HRESULT WINAPI URLMonikerImpl_ComposeWith(IMoniker* iface,
784                                                  IMoniker* pmkRight,
785                                                  BOOL fOnlyIfNotGeneric,
786                                                  IMoniker** ppmkComposite)
787 {
788     URLMonikerImpl *This = (URLMonikerImpl *)iface;
789     FIXME("(%p)->(%p,%d,%p): stub\n",This,pmkRight,fOnlyIfNotGeneric,ppmkComposite);
790
791     return E_NOTIMPL;
792 }
793
794 /******************************************************************************
795  *        URLMoniker_Enum
796  ******************************************************************************/
797 static HRESULT WINAPI URLMonikerImpl_Enum(IMoniker* iface,BOOL fForward, IEnumMoniker** ppenumMoniker)
798 {
799     URLMonikerImpl *This = (URLMonikerImpl *)iface;
800     TRACE("(%p,%d,%p)\n",This,fForward,ppenumMoniker);
801
802     if(!ppenumMoniker)
803         return E_INVALIDARG;
804
805     /* Does not support sub-monikers */
806     *ppenumMoniker = NULL;
807     return S_OK;
808 }
809
810 /******************************************************************************
811  *        URLMoniker_IsEqual
812  ******************************************************************************/
813 static HRESULT WINAPI URLMonikerImpl_IsEqual(IMoniker* iface,IMoniker* pmkOtherMoniker)
814 {
815     URLMonikerImpl *This = (URLMonikerImpl *)iface;
816     CLSID clsid;
817     LPOLESTR urlPath;
818     IBindCtx* bind;
819     HRESULT res;
820
821     TRACE("(%p,%p)\n",This,pmkOtherMoniker);
822
823     if(pmkOtherMoniker==NULL)
824         return E_INVALIDARG;
825
826     IMoniker_GetClassID(pmkOtherMoniker,&clsid);
827
828     if(!IsEqualCLSID(&clsid,&CLSID_StdURLMoniker))
829         return S_FALSE;
830
831     res = CreateBindCtx(0,&bind);
832     if(FAILED(res))
833         return res;
834
835     res = S_FALSE;
836     if(SUCCEEDED(IMoniker_GetDisplayName(pmkOtherMoniker,bind,NULL,&urlPath))) {
837         int result = lstrcmpiW(urlPath, This->URLName);
838         CoTaskMemFree(urlPath);
839         if(result == 0)
840             res = S_OK;
841     }
842     IUnknown_Release(bind);
843     return res;
844 }
845
846
847 /******************************************************************************
848  *        URLMoniker_Hash
849  ******************************************************************************/
850 static HRESULT WINAPI URLMonikerImpl_Hash(IMoniker* iface,DWORD* pdwHash)
851 {
852     URLMonikerImpl *This = (URLMonikerImpl *)iface;
853     
854     int  h = 0,i,skip,len;
855     int  off = 0;
856     LPOLESTR val;
857
858     TRACE("(%p,%p)\n",This,pdwHash);
859
860     if(!pdwHash)
861         return E_INVALIDARG;
862
863     val = This->URLName;
864     len = lstrlenW(val);
865
866     if(len < 16) {
867         for(i = len ; i > 0; i--) {
868             h = (h * 37) + val[off++];
869         }
870     }
871     else {
872         /* only sample some characters */
873         skip = len / 8;
874         for(i = len; i > 0; i -= skip, off += skip) {
875             h = (h * 39) + val[off];
876         }
877     }
878     *pdwHash = h;
879     return S_OK;
880 }
881
882 /******************************************************************************
883  *        URLMoniker_IsRunning
884  ******************************************************************************/
885 static HRESULT WINAPI URLMonikerImpl_IsRunning(IMoniker* iface,
886                                                IBindCtx* pbc,
887                                                IMoniker* pmkToLeft,
888                                                IMoniker* pmkNewlyRunning)
889 {
890     URLMonikerImpl *This = (URLMonikerImpl *)iface;
891     FIXME("(%p)->(%p,%p,%p): stub\n",This,pbc,pmkToLeft,pmkNewlyRunning);
892
893     return E_NOTIMPL;
894 }
895
896 /******************************************************************************
897  *        URLMoniker_GetTimeOfLastChange
898  ******************************************************************************/
899 static HRESULT WINAPI URLMonikerImpl_GetTimeOfLastChange(IMoniker* iface,
900                                                          IBindCtx* pbc,
901                                                          IMoniker* pmkToLeft,
902                                                          FILETIME* pFileTime)
903 {
904     URLMonikerImpl *This = (URLMonikerImpl *)iface;
905     FIXME("(%p)->(%p,%p,%p): stub\n",This,pbc,pmkToLeft,pFileTime);
906
907     return E_NOTIMPL;
908 }
909
910 /******************************************************************************
911  *        URLMoniker_Inverse
912  ******************************************************************************/
913 static HRESULT WINAPI URLMonikerImpl_Inverse(IMoniker* iface,IMoniker** ppmk)
914 {
915     URLMonikerImpl *This = (URLMonikerImpl *)iface;
916     TRACE("(%p,%p)\n",This,ppmk);
917
918     return MK_E_NOINVERSE;
919 }
920
921 /******************************************************************************
922  *        URLMoniker_CommonPrefixWith
923  ******************************************************************************/
924 static HRESULT WINAPI URLMonikerImpl_CommonPrefixWith(IMoniker* iface,IMoniker* pmkOther,IMoniker** ppmkPrefix)
925 {
926     URLMonikerImpl *This = (URLMonikerImpl *)iface;
927     FIXME("(%p)->(%p,%p): stub\n",This,pmkOther,ppmkPrefix);
928
929     return E_NOTIMPL;
930 }
931
932 /******************************************************************************
933  *        URLMoniker_RelativePathTo
934  ******************************************************************************/
935 static HRESULT WINAPI URLMonikerImpl_RelativePathTo(IMoniker* iface,IMoniker* pmOther, IMoniker** ppmkRelPath)
936 {
937     URLMonikerImpl *This = (URLMonikerImpl *)iface;
938     FIXME("(%p)->(%p,%p): stub\n",This,pmOther,ppmkRelPath);
939
940     return E_NOTIMPL;
941 }
942
943 /******************************************************************************
944  *        URLMoniker_GetDisplayName
945  ******************************************************************************/
946 static HRESULT WINAPI URLMonikerImpl_GetDisplayName(IMoniker* iface,
947                                                     IBindCtx* pbc,
948                                                     IMoniker* pmkToLeft,
949                                                     LPOLESTR *ppszDisplayName)
950 {
951     URLMonikerImpl *This = (URLMonikerImpl *)iface;
952     
953     int len;
954     
955     TRACE("(%p,%p,%p,%p)\n",This,pbc,pmkToLeft,ppszDisplayName);
956     
957     if(!ppszDisplayName)
958         return E_INVALIDARG;
959     
960     /* FIXME: If this is a partial URL, try and get a URL moniker from SZ_URLCONTEXT in the bind context,
961         then look at pmkToLeft to try and complete the URL
962     */
963     len = lstrlenW(This->URLName)+1;
964     *ppszDisplayName = CoTaskMemAlloc(len*sizeof(WCHAR));
965     if(!*ppszDisplayName)
966         return E_OUTOFMEMORY;
967     lstrcpyW(*ppszDisplayName, This->URLName);
968     return S_OK;
969 }
970
971 /******************************************************************************
972  *        URLMoniker_ParseDisplayName
973  ******************************************************************************/
974 static HRESULT WINAPI URLMonikerImpl_ParseDisplayName(IMoniker* iface,
975                                                       IBindCtx* pbc,
976                                                       IMoniker* pmkToLeft,
977                                                       LPOLESTR pszDisplayName,
978                                                       ULONG* pchEaten,
979                                                       IMoniker** ppmkOut)
980 {
981     URLMonikerImpl *This = (URLMonikerImpl *)iface;
982     FIXME("(%p)->(%p,%p,%p,%p,%p): stub\n",This,pbc,pmkToLeft,pszDisplayName,pchEaten,ppmkOut);
983
984     return E_NOTIMPL;
985 }
986
987 /******************************************************************************
988  *        URLMoniker_IsSystemMoniker
989  ******************************************************************************/
990 static HRESULT WINAPI URLMonikerImpl_IsSystemMoniker(IMoniker* iface,DWORD* pwdMksys)
991 {
992     URLMonikerImpl *This = (URLMonikerImpl *)iface;
993     TRACE("(%p,%p)\n",This,pwdMksys);
994
995     if(!pwdMksys)
996         return E_INVALIDARG;
997
998     *pwdMksys = MKSYS_URLMONIKER;
999     return S_OK;
1000 }
1001
1002 /********************************************************************************/
1003 /* Virtual function table for the URLMonikerImpl class which  include IPersist,*/
1004 /* IPersistStream and IMoniker functions.                                       */
1005 static const IMonikerVtbl VT_URLMonikerImpl =
1006 {
1007     URLMonikerImpl_QueryInterface,
1008     URLMonikerImpl_AddRef,
1009     URLMonikerImpl_Release,
1010     URLMonikerImpl_GetClassID,
1011     URLMonikerImpl_IsDirty,
1012     URLMonikerImpl_Load,
1013     URLMonikerImpl_Save,
1014     URLMonikerImpl_GetSizeMax,
1015     URLMonikerImpl_BindToObject,
1016     URLMonikerImpl_BindToStorage,
1017     URLMonikerImpl_Reduce,
1018     URLMonikerImpl_ComposeWith,
1019     URLMonikerImpl_Enum,
1020     URLMonikerImpl_IsEqual,
1021     URLMonikerImpl_Hash,
1022     URLMonikerImpl_IsRunning,
1023     URLMonikerImpl_GetTimeOfLastChange,
1024     URLMonikerImpl_Inverse,
1025     URLMonikerImpl_CommonPrefixWith,
1026     URLMonikerImpl_RelativePathTo,
1027     URLMonikerImpl_GetDisplayName,
1028     URLMonikerImpl_ParseDisplayName,
1029     URLMonikerImpl_IsSystemMoniker
1030 };
1031
1032 /******************************************************************************
1033  *         URLMoniker_Construct (local function)
1034  *******************************************************************************/
1035 static HRESULT URLMonikerImpl_Construct(URLMonikerImpl* This, LPCOLESTR lpszLeftURLName, LPCOLESTR lpszURLName)
1036 {
1037     HRESULT hres;
1038     DWORD sizeStr = 0;
1039
1040     TRACE("(%p,%s,%s)\n",This,debugstr_w(lpszLeftURLName),debugstr_w(lpszURLName));
1041
1042     This->lpvtbl = &VT_URLMonikerImpl;
1043     This->ref = 0;
1044
1045     This->URLName = heap_alloc(INTERNET_MAX_URL_LENGTH*sizeof(WCHAR));
1046
1047     if(lpszLeftURLName)
1048         hres = CoInternetCombineUrl(lpszLeftURLName, lpszURLName, URL_FILE_USE_PATHURL,
1049                 This->URLName, INTERNET_MAX_URL_LENGTH, &sizeStr, 0);
1050     else
1051         hres = CoInternetParseUrl(lpszURLName, PARSE_CANONICALIZE, URL_FILE_USE_PATHURL,
1052                 This->URLName, INTERNET_MAX_URL_LENGTH, &sizeStr, 0);
1053
1054     if(FAILED(hres)) {
1055         heap_free(This->URLName);
1056         return hres;
1057     }
1058
1059     URLMON_LockModule();
1060
1061     if(sizeStr != INTERNET_MAX_URL_LENGTH)
1062         This->URLName = heap_realloc(This->URLName, (sizeStr+1)*sizeof(WCHAR));
1063
1064     TRACE("URLName = %s\n", debugstr_w(This->URLName));
1065
1066     return S_OK;
1067 }
1068
1069 /***********************************************************************
1070  *           CreateURLMonikerEx (URLMON.@)
1071  *
1072  * Create a url moniker.
1073  *
1074  * PARAMS
1075  *    pmkContext [I] Context
1076  *    szURL      [I] Url to create the moniker for
1077  *    ppmk       [O] Destination for created moniker.
1078  *    dwFlags    [I] Flags.
1079  *
1080  * RETURNS
1081  *    Success: S_OK. ppmk contains the created IMoniker object.
1082  *    Failure: MK_E_SYNTAX if szURL is not a valid url, or
1083  *             E_OUTOFMEMORY if memory allocation fails.
1084  */
1085 HRESULT WINAPI CreateURLMonikerEx(IMoniker *pmkContext, LPCWSTR szURL, IMoniker **ppmk, DWORD dwFlags)
1086 {
1087     URLMonikerImpl *obj;
1088     HRESULT hres;
1089     LPOLESTR lefturl = NULL;
1090
1091     TRACE("(%p, %s, %p, %08x)\n", pmkContext, debugstr_w(szURL), ppmk, dwFlags);
1092
1093     if (dwFlags & URL_MK_UNIFORM) FIXME("ignoring flag URL_MK_UNIFORM\n");
1094
1095     if(!(obj = heap_alloc(sizeof(*obj))))
1096         return E_OUTOFMEMORY;
1097
1098     if(pmkContext) {
1099         IBindCtx* bind;
1100         DWORD dwMksys = 0;
1101         IMoniker_IsSystemMoniker(pmkContext, &dwMksys);
1102         if(dwMksys == MKSYS_URLMONIKER && SUCCEEDED(CreateBindCtx(0, &bind))) {
1103             IMoniker_GetDisplayName(pmkContext, bind, NULL, &lefturl);
1104             TRACE("lefturl = %s\n", debugstr_w(lefturl));
1105             IBindCtx_Release(bind);
1106         }
1107     }
1108         
1109     hres = URLMonikerImpl_Construct(obj, lefturl, szURL);
1110     CoTaskMemFree(lefturl);
1111     if(SUCCEEDED(hres))
1112         hres = URLMonikerImpl_QueryInterface((IMoniker*)obj, &IID_IMoniker, (void**)ppmk);
1113     else
1114         heap_free(obj);
1115     return hres;
1116 }
1117
1118 /**********************************************************************
1119  *           CreateURLMoniker (URLMON.@)
1120  *
1121  * Create a url moniker.
1122  *
1123  * PARAMS
1124  *    pmkContext [I] Context
1125  *    szURL      [I] Url to create the moniker for
1126  *    ppmk       [O] Destination for created moniker.
1127  *
1128  * RETURNS
1129  *    Success: S_OK. ppmk contains the created IMoniker object.
1130  *    Failure: MK_E_SYNTAX if szURL is not a valid url, or
1131  *             E_OUTOFMEMORY if memory allocation fails.
1132  */
1133 HRESULT WINAPI CreateURLMoniker(IMoniker *pmkContext, LPCWSTR szURL, IMoniker **ppmk)
1134 {
1135     return CreateURLMonikerEx(pmkContext, szURL, ppmk, URL_MK_LEGACY);
1136 }
1137
1138 /***********************************************************************
1139  *           CoInternetQueryInfo (URLMON.@)
1140  *
1141  * Retrieves information relevant to a specified URL
1142  *
1143  * RETURNS
1144  *    S_OK                      success
1145  *    S_FALSE                   buffer too small
1146  *    INET_E_QUERYOPTIONUNKNOWN invalid option
1147  *
1148  */
1149 HRESULT WINAPI CoInternetQueryInfo(LPCWSTR pwzUrl, QUERYOPTION QueryOption,
1150   DWORD dwQueryFlags, LPVOID pvBuffer, DWORD cbBuffer, DWORD * pcbBuffer,
1151   DWORD dwReserved)
1152 {
1153   FIXME("(%s, %x, %x, %p, %x, %p, %x): stub\n", debugstr_w(pwzUrl),
1154     QueryOption, dwQueryFlags, pvBuffer, cbBuffer, pcbBuffer, dwReserved);
1155   return S_OK;
1156 }
1157
1158 /***********************************************************************
1159  *           IsAsyncMoniker (URLMON.@)
1160  */
1161 HRESULT WINAPI IsAsyncMoniker(IMoniker *pmk)
1162 {
1163     IUnknown *am;
1164     
1165     TRACE("(%p)\n", pmk);
1166     if(!pmk)
1167         return E_INVALIDARG;
1168     if(SUCCEEDED(IMoniker_QueryInterface(pmk, &IID_IAsyncMoniker, (void**)&am))) {
1169         IUnknown_Release(am);
1170         return S_OK;
1171     }
1172     return S_FALSE;
1173 }
1174
1175 /***********************************************************************
1176  *           BindAsyncMoniker (URLMON.@)
1177  *
1178  * Bind a bind status callback to an asynchronous URL Moniker.
1179  *
1180  * PARAMS
1181  *  pmk           [I] Moniker object to bind status callback to
1182  *  grfOpt        [I] Options, seems not used
1183  *  pbsc          [I] Status callback to bind
1184  *  iidResult     [I] Interface to return
1185  *  ppvResult     [O] Resulting asynchronous moniker object
1186  *
1187  * RETURNS
1188  *    Success: S_OK.
1189  *    Failure: E_INVALIDARG, if any argument is invalid, or
1190  *             E_OUTOFMEMORY if memory allocation fails.
1191  */
1192 HRESULT WINAPI BindAsyncMoniker(IMoniker *pmk, DWORD grfOpt, IBindStatusCallback *pbsc, REFIID iidResult, LPVOID *ppvResult)
1193 {
1194     LPBC pbc = NULL;
1195     HRESULT hr = E_INVALIDARG;
1196
1197     if (pmk && ppvResult)
1198     {
1199         *ppvResult = NULL;
1200
1201         hr = CreateAsyncBindCtx(0, pbsc, NULL, &pbc);
1202         if (hr == NOERROR)
1203         {
1204             hr = IMoniker_BindToObject(pmk, pbc, NULL, iidResult, ppvResult);
1205             IBindCtx_Release(pbc);
1206         }
1207     }
1208     return hr;
1209 }
1210
1211 /***********************************************************************
1212  *           URLDownloadToFileA (URLMON.@)
1213  *
1214  * Downloads URL szURL to rile szFileName and call lpfnCB callback to
1215  * report progress.
1216  *
1217  * PARAMS
1218  *  pCaller    [I] controlling IUnknown interface.
1219  *  szURL      [I] URL of the file to download
1220  *  szFileName [I] file name to store the content of the URL
1221  *  dwReserved [I] reserved - set to 0
1222  *  lpfnCB     [I] callback for progress report
1223  *
1224  * RETURNS
1225  *  S_OK on success
1226  *  E_OUTOFMEMORY when going out of memory
1227  */
1228 HRESULT WINAPI URLDownloadToFileA(LPUNKNOWN pCaller,
1229                                   LPCSTR szURL,
1230                                   LPCSTR szFileName,
1231                                   DWORD dwReserved,
1232                                   LPBINDSTATUSCALLBACK lpfnCB)
1233 {
1234     UNICODE_STRING szURL_w, szFileName_w;
1235
1236     if ((szURL == NULL) || (szFileName == NULL)) {
1237         FIXME("(%p,%s,%s,%08x,%p) cannot accept NULL strings !\n", pCaller, debugstr_a(szURL), debugstr_a(szFileName), dwReserved, lpfnCB);
1238         return E_INVALIDARG; /* The error code is not specified in this case... */
1239     }
1240     
1241     if (RtlCreateUnicodeStringFromAsciiz(&szURL_w, szURL)) {
1242         if (RtlCreateUnicodeStringFromAsciiz(&szFileName_w, szFileName)) {
1243             HRESULT ret = URLDownloadToFileW(pCaller, szURL_w.Buffer, szFileName_w.Buffer, dwReserved, lpfnCB);
1244
1245             RtlFreeUnicodeString(&szURL_w);
1246             RtlFreeUnicodeString(&szFileName_w);
1247             
1248             return ret;
1249         } else {
1250             RtlFreeUnicodeString(&szURL_w);
1251         }
1252     }
1253     
1254     FIXME("(%p,%s,%s,%08x,%p) could not allocate W strings !\n", pCaller, szURL, szFileName, dwReserved, lpfnCB);
1255     return E_OUTOFMEMORY;
1256 }
1257
1258 /***********************************************************************
1259  *           URLDownloadToFileW (URLMON.@)
1260  *
1261  * Downloads URL szURL to rile szFileName and call lpfnCB callback to
1262  * report progress.
1263  *
1264  * PARAMS
1265  *  pCaller    [I] controlling IUnknown interface.
1266  *  szURL      [I] URL of the file to download
1267  *  szFileName [I] file name to store the content of the URL
1268  *  dwReserved [I] reserved - set to 0
1269  *  lpfnCB     [I] callback for progress report
1270  *
1271  * RETURNS
1272  *  S_OK on success
1273  *  E_OUTOFMEMORY when going out of memory
1274  */
1275 HRESULT WINAPI URLDownloadToFileW(LPUNKNOWN pCaller,
1276                                   LPCWSTR szURL,
1277                                   LPCWSTR szFileName,
1278                                   DWORD dwReserved,
1279                                   LPBINDSTATUSCALLBACK lpfnCB)
1280 {
1281     HINTERNET hinternet, hcon, hreq;
1282     BOOL r;
1283     CHAR buffer[0x1000];
1284     DWORD sz, total, written;
1285     DWORD total_size = 0xFFFFFFFF, arg_size = sizeof(total_size);
1286     URL_COMPONENTSW url;
1287     WCHAR host[0x80], path[0x100];
1288     HANDLE hfile;
1289     static const WCHAR wszAppName[]={'u','r','l','m','o','n','.','d','l','l',0};
1290
1291     /* Note: all error codes would need to be checked agains real Windows behaviour... */
1292     TRACE("(%p,%s,%s,%08x,%p) stub!\n", pCaller, debugstr_w(szURL), debugstr_w(szFileName), dwReserved, lpfnCB);
1293
1294     if ((szURL == NULL) || (szFileName == NULL)) {
1295         FIXME(" cannot accept NULL strings !\n");
1296         return E_INVALIDARG;
1297     }
1298
1299     /* Would be better to use the application name here rather than 'urlmon' :-/ */
1300     hinternet = InternetOpenW(wszAppName, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
1301     if (hinternet == NULL) {
1302         return E_OUTOFMEMORY;
1303     }                                                                                                                             
1304
1305     memset(&url, 0, sizeof(url));
1306     url.dwStructSize = sizeof(url);
1307     url.lpszHostName = host;
1308     url.dwHostNameLength = sizeof(host);
1309     url.lpszUrlPath = path;
1310     url.dwUrlPathLength = sizeof(path);
1311
1312     if (!InternetCrackUrlW(szURL, 0, 0, &url)) {
1313         InternetCloseHandle(hinternet);
1314         return E_OUTOFMEMORY;
1315     }
1316
1317     if (lpfnCB) {
1318         if (IBindStatusCallback_OnProgress(lpfnCB, 0, 0, BINDSTATUS_CONNECTING, url.lpszHostName) == E_ABORT) {
1319             InternetCloseHandle(hinternet);
1320             return S_OK;
1321         }
1322     }
1323     
1324     hcon = InternetConnectW(hinternet, url.lpszHostName, url.nPort,
1325                             url.lpszUserName, url.lpszPassword,
1326                             INTERNET_SERVICE_HTTP, 0, 0);
1327     if (!hcon) {
1328         InternetCloseHandle(hinternet);
1329         return E_OUTOFMEMORY;
1330     }
1331     
1332     hreq = HttpOpenRequestW(hcon, NULL, url.lpszUrlPath, NULL, NULL, NULL, 0, 0);
1333     if (!hreq) {
1334         InternetCloseHandle(hinternet);
1335         InternetCloseHandle(hcon);
1336         return E_OUTOFMEMORY;
1337     }                                                                                                                             
1338
1339     if (!HttpSendRequestW(hreq, NULL, 0, NULL, 0)) {
1340         InternetCloseHandle(hinternet);
1341         InternetCloseHandle(hcon);
1342         InternetCloseHandle(hreq);
1343         return E_OUTOFMEMORY;
1344     }
1345     
1346     if (HttpQueryInfoW(hreq, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER,
1347                        &total_size, &arg_size, NULL)) {
1348         TRACE(" total size : %d\n", total_size);
1349     }
1350     
1351     hfile = CreateFileW(szFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
1352                         FILE_ATTRIBUTE_NORMAL, NULL );
1353     if (hfile == INVALID_HANDLE_VALUE) {
1354         return E_ACCESSDENIED;
1355     }
1356     
1357     if (lpfnCB) {
1358         if (IBindStatusCallback_OnProgress(lpfnCB, 0, total_size != 0xFFFFFFFF ? total_size : 0,
1359                                            BINDSTATUS_BEGINDOWNLOADDATA, szURL) == E_ABORT) {
1360             InternetCloseHandle(hreq);
1361             InternetCloseHandle(hcon);
1362             InternetCloseHandle(hinternet);
1363             CloseHandle(hfile);
1364             return S_OK;
1365         }
1366     }
1367     
1368     total = 0;
1369     while (1) {
1370         r = InternetReadFile(hreq, buffer, sizeof(buffer), &sz);
1371         if (!r) {
1372             InternetCloseHandle(hreq);
1373             InternetCloseHandle(hcon);
1374             InternetCloseHandle(hinternet);
1375             
1376             CloseHandle(hfile);
1377             return E_OUTOFMEMORY;           
1378         }
1379         if (!sz)
1380             break;
1381         
1382         total += sz;
1383
1384         if (lpfnCB) {
1385             if (IBindStatusCallback_OnProgress(lpfnCB, total, total_size != 0xFFFFFFFF ? total_size : 0,
1386                                                BINDSTATUS_DOWNLOADINGDATA, szURL) == E_ABORT) {
1387                 InternetCloseHandle(hreq);
1388                 InternetCloseHandle(hcon);
1389                 InternetCloseHandle(hinternet);
1390                 CloseHandle(hfile);
1391                 return S_OK;
1392             }
1393         }
1394         
1395         if (!WriteFile(hfile, buffer, sz, &written, NULL)) {
1396             InternetCloseHandle(hreq);
1397             InternetCloseHandle(hcon);
1398             InternetCloseHandle(hinternet);
1399             
1400             CloseHandle(hfile);
1401             return E_OUTOFMEMORY;
1402         }
1403     }
1404
1405     if (lpfnCB) {
1406         if (IBindStatusCallback_OnProgress(lpfnCB, total, total_size != 0xFFFFFFFF ? total_size : 0,
1407                                            BINDSTATUS_ENDDOWNLOADDATA, szURL) == E_ABORT) {
1408             InternetCloseHandle(hreq);
1409             InternetCloseHandle(hcon);
1410             InternetCloseHandle(hinternet);
1411             CloseHandle(hfile);
1412             return S_OK;
1413         }
1414     }
1415     
1416     InternetCloseHandle(hreq);
1417     InternetCloseHandle(hcon);
1418     InternetCloseHandle(hinternet);
1419     
1420     CloseHandle(hfile);
1421
1422     return S_OK;
1423 }
1424
1425 /***********************************************************************
1426  *           URLDownloadToCacheFileA (URLMON.@)
1427  */
1428 HRESULT WINAPI URLDownloadToCacheFileA(LPUNKNOWN lpUnkCaller, LPCSTR szURL, LPSTR szFileName,
1429         DWORD dwBufLength, DWORD dwReserved, LPBINDSTATUSCALLBACK pBSC)
1430 {
1431     LPWSTR url = NULL, file_name = NULL;
1432     int len;
1433     HRESULT hres;
1434
1435     TRACE("(%p %s %p %d %d %p)\n", lpUnkCaller, debugstr_a(szURL), szFileName,
1436             dwBufLength, dwReserved, pBSC);
1437
1438     if(szURL) {
1439         len = MultiByteToWideChar(CP_ACP, 0, szURL, -1, NULL, 0);
1440         url = heap_alloc(len*sizeof(WCHAR));
1441         MultiByteToWideChar(CP_ACP, 0, szURL, -1, url, -1);
1442     }
1443
1444     if(szFileName)
1445         file_name = heap_alloc(dwBufLength*sizeof(WCHAR));
1446
1447     hres = URLDownloadToCacheFileW(lpUnkCaller, url, file_name, dwBufLength*sizeof(WCHAR),
1448             dwReserved, pBSC);
1449
1450     if(SUCCEEDED(hres) && file_name)
1451         WideCharToMultiByte(CP_ACP, 0, file_name, -1, szFileName, dwBufLength, NULL, NULL);
1452
1453     heap_free(url);
1454     heap_free(file_name);
1455
1456     return hres;
1457 }
1458
1459 /***********************************************************************
1460  *           URLDownloadToCacheFileW (URLMON.@)
1461  */
1462 HRESULT WINAPI URLDownloadToCacheFileW(LPUNKNOWN lpUnkCaller, LPCWSTR szURL, LPWSTR szFileName,
1463                 DWORD dwBufLength, DWORD dwReserved, LPBINDSTATUSCALLBACK pBSC)
1464 {
1465     WCHAR cache_path[MAX_PATH + 1];
1466     FILETIME expire, modified;
1467     HRESULT hr;
1468     LPWSTR ext;
1469
1470     static WCHAR header[] = {
1471         'H','T','T','P','/','1','.','0',' ','2','0','0',' ',
1472         'O','K','\\','r','\\','n','\\','r','\\','n',0
1473     };
1474
1475     TRACE("(%p, %s, %p, %d, %d, %p)\n", lpUnkCaller, debugstr_w(szURL),
1476           szFileName, dwBufLength, dwReserved, pBSC);
1477
1478     if (!szURL || !szFileName)
1479         return E_INVALIDARG;
1480
1481     ext = PathFindExtensionW(szURL);
1482
1483     if (!CreateUrlCacheEntryW(szURL, 0, ext, cache_path, 0))
1484         return E_FAIL;
1485
1486     hr = URLDownloadToFileW(lpUnkCaller, szURL, cache_path, 0, pBSC);
1487     if (FAILED(hr))
1488         return hr;
1489
1490     expire.dwHighDateTime = 0;
1491     expire.dwLowDateTime = 0;
1492     modified.dwHighDateTime = 0;
1493     modified.dwLowDateTime = 0;
1494
1495     if (!CommitUrlCacheEntryW(szURL, cache_path, expire, modified, NORMAL_CACHE_ENTRY,
1496                               header, sizeof(header), NULL, NULL))
1497         return E_FAIL;
1498
1499     if (lstrlenW(cache_path) > dwBufLength)
1500         return E_OUTOFMEMORY;
1501
1502     lstrcpyW(szFileName, cache_path);
1503
1504     return S_OK;
1505 }
1506
1507 /***********************************************************************
1508  *           HlinkSimpleNavigateToString (URLMON.@)
1509  */
1510 HRESULT WINAPI HlinkSimpleNavigateToString( LPCWSTR szTarget,
1511     LPCWSTR szLocation, LPCWSTR szTargetFrameName, IUnknown *pUnk,
1512     IBindCtx *pbc, IBindStatusCallback *pbsc, DWORD grfHLNF, DWORD dwReserved)
1513 {
1514     FIXME("%s\n", debugstr_w( szTarget ) );
1515     return E_NOTIMPL;
1516 }
1517
1518 /***********************************************************************
1519  *           HlinkNavigateString (URLMON.@)
1520  */
1521 HRESULT WINAPI HlinkNavigateString( IUnknown *pUnk, LPCWSTR szTarget )
1522 {
1523     TRACE("%p %s\n", pUnk, debugstr_w( szTarget ) );
1524     return HlinkSimpleNavigateToString( 
1525                szTarget, NULL, NULL, pUnk, NULL, NULL, 0, 0 );
1526 }
1527
1528 /***********************************************************************
1529  *           GetSoftwareUpdateInfo (URLMON.@)
1530  */
1531 HRESULT WINAPI GetSoftwareUpdateInfo( LPCWSTR szDistUnit, LPSOFTDISTINFO psdi )
1532 {
1533     FIXME("%s %p\n", debugstr_w(szDistUnit), psdi );
1534     return E_FAIL;
1535 }