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