setupapi: Implement SetupDiGetDeviceInterfaceDetailA/W.
[wine] / dlls / urlmon / umon.c
1 /*
2  * UrlMon
3  *
4  * Copyright 1999 Ulrich Czekalla for Corel Corporation
5  * Copyright 2002 Huw D M Davies for CodeWeavers
6  * Copyright 2005 Jacek Caban for CodeWeavers
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22
23 #include <stdarg.h>
24 #include <stdio.h>
25
26 #define COBJMACROS
27 #define NONAMELESSUNION
28 #define NONAMELESSSTRUCT
29
30 #include "windef.h"
31 #include "winbase.h"
32 #include "winreg.h"
33 #include "winternl.h"
34 #include "winuser.h"
35 #include "objbase.h"
36 #include "wine/debug.h"
37 #include "wine/unicode.h"
38 #include "ole2.h"
39 #include "urlmon.h"
40 #include "wininet.h"
41 #include "shlwapi.h"
42 #include "urlmon_main.h"
43
44 WINE_DEFAULT_DEBUG_CHANNEL(urlmon);
45
46 /* native urlmon.dll uses this key, too */
47 static WCHAR BSCBHolder[] = { '_','B','S','C','B','_','H','o','l','d','e','r','_',0 };
48
49 /*static BOOL registered_wndclass = FALSE;*/
50
51 typedef struct {
52     const IBindingVtbl *lpVtbl;
53
54     LONG ref;
55
56     LPWSTR URLName;
57
58     HWND hwndCallback;
59     IBindCtx *pBC;
60     HINTERNET hinternet, hconnect, hrequest;
61     HANDLE hCacheFile;
62     IUMCacheStream *pstrCache;
63     IBindStatusCallback *pbscb;
64     DWORD total_read, expected_size;
65 } Binding;
66
67 static HRESULT WINAPI Binding_QueryInterface(IBinding* iface, REFIID riid, void **ppvObject)
68 {
69     Binding *This = (Binding*)iface;
70
71     TRACE("(%p)->(%s,%p)\n", This, debugstr_guid(riid), ppvObject);
72
73     if((This == NULL) || (ppvObject == NULL))
74         return E_INVALIDARG;
75
76     if (IsEqualIID(&IID_IUnknown, riid) || IsEqualIID(&IID_IBinding, riid)) {
77         *ppvObject = iface;
78         IBinding_AddRef(iface);
79         return S_OK;
80     }
81
82     *ppvObject = NULL;
83     return E_NOINTERFACE;
84 }
85
86 static ULONG WINAPI Binding_AddRef(IBinding* iface)
87 {
88     Binding *This = (Binding*)iface;
89     ULONG ref = InterlockedIncrement(&This->ref);
90
91     TRACE("(%p) ref=%d\n", This, ref);
92
93     return ref;
94 }
95
96 static ULONG WINAPI Binding_Release(IBinding* iface)
97 {
98     Binding *This = (Binding*)iface;
99     ULONG ref = InterlockedDecrement(&This->ref);
100
101     TRACE("(%p) ref=%d\n",This, ref);
102
103     if(!ref) {
104         HeapFree(GetProcessHeap(), 0, This->URLName);
105         if (This->hCacheFile)
106             CloseHandle(This->hCacheFile);
107         if (This->pstrCache)
108         {
109             UMCloseCacheFileStream(This->pstrCache);
110             IStream_Release((IStream *)This->pstrCache);
111         }
112         if (This->pbscb)
113             IBindStatusCallback_Release(This->pbscb);
114
115         HeapFree(GetProcessHeap(), 0, This);
116
117         URLMON_UnlockModule();
118     }
119
120     return ref;
121 }
122
123 static HRESULT WINAPI Binding_Abort(IBinding* iface)
124 {
125     Binding *This = (Binding*)iface;
126
127     FIXME("(%p): stub\n", This);
128
129     return E_NOTIMPL;
130 }
131
132 static HRESULT WINAPI Binding_GetBindResult(IBinding* iface, CLSID* pclsidProtocol, DWORD* pdwResult, LPOLESTR* pszResult, DWORD* pdwReserved)
133 {
134     Binding *This = (Binding*)iface;
135
136     FIXME("(%p)->(%p, %p, %p, %p): stub\n", This, pclsidProtocol, pdwResult, pszResult, pdwReserved);
137
138     return E_NOTIMPL;
139 }
140
141 static HRESULT WINAPI Binding_GetPriority(IBinding* iface, LONG* pnPriority)
142 {
143     Binding *This = (Binding*)iface;
144
145     FIXME("(%p)->(%p): stub\n", This, pnPriority);
146
147     return E_NOTIMPL;
148 }
149
150 static HRESULT WINAPI Binding_Resume(IBinding* iface)
151 {
152     Binding *This = (Binding*)iface;
153
154     FIXME("(%p): stub\n", This);
155
156     return E_NOTIMPL;
157 }
158
159 static HRESULT WINAPI Binding_SetPriority(IBinding* iface, LONG nPriority)
160 {
161     Binding *This = (Binding*)iface;
162
163     FIXME("(%p)->(%d): stub\n", This, nPriority);
164
165     return E_NOTIMPL;
166 }
167
168 static HRESULT WINAPI Binding_Suspend(IBinding* iface)
169 {
170     Binding *This = (Binding*)iface;
171
172     FIXME("(%p): stub\n", This);
173
174     return E_NOTIMPL;
175 }
176
177 static void Binding_CloseCacheDownload(Binding *This)
178 {
179     CloseHandle(This->hCacheFile);
180     This->hCacheFile = 0;
181     UMCloseCacheFileStream(This->pstrCache);
182     IStream_Release((IStream *)This->pstrCache);
183     This->pstrCache = 0;
184 }
185
186 static HRESULT Binding_MoreCacheData(Binding *This, char *buf, DWORD dwBytes)
187 {
188     DWORD written;
189
190     if (WriteFile(This->hCacheFile, buf, dwBytes, &written, NULL) && written == dwBytes)
191     {
192         HRESULT hr;
193
194         This->total_read += written;
195         hr = IBindStatusCallback_OnProgress(This->pbscb,
196                                             This->total_read + written,
197                                             This->expected_size,
198                                             (This->total_read == written) ?
199                                                 BINDSTATUS_BEGINDOWNLOADDATA :
200                                                 BINDSTATUS_DOWNLOADINGDATA,
201                                             This->URLName);
202         if (!hr)
203         {
204             STGMEDIUM stg;
205             FORMATETC fmt;
206
207             fmt.cfFormat = 0;
208             fmt.ptd = NULL;
209             fmt.dwAspect = 0;
210             fmt.lindex = -1;
211             fmt.tymed = TYMED_ISTREAM;
212
213             stg.tymed = TYMED_ISTREAM;
214             stg.u.pstm = (IStream *)This->pstrCache;
215             stg.pUnkForRelease = NULL;
216
217             hr = IBindStatusCallback_OnDataAvailable(This->pbscb,
218                                                      (This->total_read == written) ?
219                                                          BSCF_FIRSTDATANOTIFICATION :
220                                                          BSCF_INTERMEDIATEDATANOTIFICATION,
221                                                      This->total_read + written,
222                                                      &fmt,
223                                                      &stg);
224         }
225         if (written < dwBytes)
226             return STG_E_MEDIUMFULL;
227         else
228             return hr;
229     }
230     return HRESULT_FROM_WIN32(GetLastError());
231 }
232
233 static void Binding_FinishedDownload(Binding *This, HRESULT hr)
234 {
235     STGMEDIUM stg;
236     FORMATETC fmt;
237
238     fmt.ptd = NULL;
239     fmt.dwAspect = 0;
240     fmt.lindex = -1;
241     fmt.tymed = TYMED_ISTREAM;
242
243     stg.tymed = TYMED_ISTREAM;
244     stg.u.pstm = (IStream *)This->pstrCache;
245     stg.pUnkForRelease = NULL;
246
247     IBindStatusCallback_OnProgress(This->pbscb, This->total_read, This->expected_size,
248                                    BINDSTATUS_ENDDOWNLOADDATA, This->URLName);
249     IBindStatusCallback_OnDataAvailable(This->pbscb, BSCF_LASTDATANOTIFICATION, This->total_read, &fmt, &stg);
250     if (hr)
251     {
252         WCHAR *pwchError = 0;
253
254         FormatMessageW (FORMAT_MESSAGE_FROM_SYSTEM |
255                          FORMAT_MESSAGE_ALLOCATE_BUFFER,
256                         NULL, (DWORD) hr,
257                         0, (LPWSTR) &pwchError,
258                         0, NULL);
259         if (!pwchError)
260         {
261             static const WCHAR achFormat[] = { '%', '0', '8', 'x', 0 };
262
263             pwchError =(WCHAR *) LocalAlloc(LMEM_FIXED, sizeof(WCHAR) * 9);
264             wsprintfW(pwchError, achFormat, hr);
265         }
266         IBindStatusCallback_OnStopBinding(This->pbscb, hr, pwchError);
267         LocalFree(pwchError);
268     }
269     else
270     {
271         IBindStatusCallback_OnStopBinding(This->pbscb, hr, NULL);
272     }
273     IBindStatusCallback_Release(This->pbscb);
274     This->pbscb = 0;
275 }
276
277 static const IBindingVtbl BindingVtbl =
278 {
279     Binding_QueryInterface,
280     Binding_AddRef,
281     Binding_Release,
282     Binding_Abort,
283     Binding_Suspend,
284     Binding_Resume,
285     Binding_SetPriority,
286     Binding_GetPriority,
287     Binding_GetBindResult
288 };
289
290 /* filemoniker data structure */
291 typedef struct {
292
293     const IMonikerVtbl* lpvtbl;  /* VTable relative to the IMoniker interface.*/
294
295     LONG ref; /* reference counter for this object */
296
297     LPOLESTR URLName; /* URL string identified by this URLmoniker */
298 } URLMonikerImpl;
299
300 /*******************************************************************************
301  *        URLMoniker_QueryInterface
302  *******************************************************************************/
303 static HRESULT WINAPI URLMonikerImpl_QueryInterface(IMoniker* iface,REFIID riid,void** ppvObject)
304 {
305     URLMonikerImpl *This = (URLMonikerImpl *)iface;
306
307     TRACE("(%p)->(%s,%p)\n",This,debugstr_guid(riid),ppvObject);
308
309     /* Perform a sanity check on the parameters.*/
310     if ( (This==0) || (ppvObject==0) )
311         return E_INVALIDARG;
312
313     /* Initialize the return parameter */
314     *ppvObject = 0;
315
316     /* Compare the riid with the interface IDs implemented by this object.*/
317     if (IsEqualIID(&IID_IUnknown, riid)      ||
318         IsEqualIID(&IID_IPersist, riid)      ||
319         IsEqualIID(&IID_IPersistStream,riid) ||
320         IsEqualIID(&IID_IMoniker, riid)
321        )
322         *ppvObject = iface;
323
324     /* Check that we obtained an interface.*/
325     if ((*ppvObject)==0)
326         return E_NOINTERFACE;
327
328     /* Query Interface always increases the reference count by one when it is successful */
329     IMoniker_AddRef(iface);
330
331     return S_OK;
332 }
333
334 /******************************************************************************
335  *        URLMoniker_AddRef
336  ******************************************************************************/
337 static ULONG WINAPI URLMonikerImpl_AddRef(IMoniker* iface)
338 {
339     URLMonikerImpl *This = (URLMonikerImpl *)iface;
340     ULONG refCount = InterlockedIncrement(&This->ref);
341
342     TRACE("(%p) ref=%u\n",This, refCount);
343
344     return refCount;
345 }
346
347 /******************************************************************************
348  *        URLMoniker_Release
349  ******************************************************************************/
350 static ULONG WINAPI URLMonikerImpl_Release(IMoniker* iface)
351 {
352     URLMonikerImpl *This = (URLMonikerImpl *)iface;
353     ULONG refCount = InterlockedDecrement(&This->ref);
354
355     TRACE("(%p) ref=%u\n",This, refCount);
356
357     /* destroy the object if there's no more reference on it */
358     if (!refCount) {
359         HeapFree(GetProcessHeap(),0,This->URLName);
360         HeapFree(GetProcessHeap(),0,This);
361
362         URLMON_UnlockModule();
363     }
364
365     return refCount;
366 }
367
368
369 /******************************************************************************
370  *        URLMoniker_GetClassID
371  ******************************************************************************/
372 static HRESULT WINAPI URLMonikerImpl_GetClassID(IMoniker* iface,
373                                                 CLSID *pClassID)/* Pointer to CLSID of object */
374 {
375     URLMonikerImpl *This = (URLMonikerImpl *)iface;
376
377     TRACE("(%p,%p)\n",This,pClassID);
378
379     if (pClassID==NULL)
380         return E_POINTER;
381     /* Windows always returns CLSID_StdURLMoniker */
382     *pClassID = CLSID_StdURLMoniker;
383     return S_OK;
384 }
385
386 /******************************************************************************
387  *        URLMoniker_IsDirty
388  ******************************************************************************/
389 static HRESULT WINAPI URLMonikerImpl_IsDirty(IMoniker* iface)
390 {
391     URLMonikerImpl *This = (URLMonikerImpl *)iface;
392     /* Note that the OLE-provided implementations of the IPersistStream::IsDirty
393        method in the OLE-provided moniker interfaces always return S_FALSE because
394        their internal state never changes. */
395
396     TRACE("(%p)\n",This);
397
398     return S_FALSE;
399 }
400
401 /******************************************************************************
402  *        URLMoniker_Load
403  *
404  * NOTE
405  *  Writes a ULONG containing length of unicode string, followed
406  *  by that many unicode characters
407  ******************************************************************************/
408 static HRESULT WINAPI URLMonikerImpl_Load(IMoniker* iface,IStream* pStm)
409 {
410     URLMonikerImpl *This = (URLMonikerImpl *)iface;
411     
412     HRESULT res;
413     ULONG size;
414     ULONG got;
415     TRACE("(%p,%p)\n",This,pStm);
416
417     if(!pStm)
418         return E_INVALIDARG;
419
420     res = IStream_Read(pStm, &size, sizeof(ULONG), &got);
421     if(SUCCEEDED(res)) {
422         if(got == sizeof(ULONG)) {
423             HeapFree(GetProcessHeap(), 0, This->URLName);
424             This->URLName=HeapAlloc(GetProcessHeap(),0,size);
425             if(!This->URLName)
426                 res = E_OUTOFMEMORY;
427             else {
428                 res = IStream_Read(pStm, This->URLName, size, NULL);
429                 This->URLName[size/sizeof(WCHAR) - 1] = 0;
430             }
431         }
432         else
433             res = E_FAIL;
434     }
435     return res;
436 }
437
438 /******************************************************************************
439  *        URLMoniker_Save
440  ******************************************************************************/
441 static HRESULT WINAPI URLMonikerImpl_Save(IMoniker* iface,
442                                           IStream* pStm,/* pointer to the stream where the object is to be saved */
443                                           BOOL fClearDirty)/* Specifies whether to clear the dirty flag */
444 {
445     URLMonikerImpl *This = (URLMonikerImpl *)iface;
446
447     HRESULT res;
448     ULONG size;
449     TRACE("(%p,%p,%d)\n",This,pStm,fClearDirty);
450
451     if(!pStm)
452         return E_INVALIDARG;
453
454     size = (strlenW(This->URLName) + 1)*sizeof(WCHAR);
455     res=IStream_Write(pStm,&size,sizeof(ULONG),NULL);
456     if(SUCCEEDED(res))
457         res=IStream_Write(pStm,This->URLName,size,NULL);
458     return res;
459
460 }
461
462 /******************************************************************************
463  *        URLMoniker_GetSizeMax
464  ******************************************************************************/
465 static HRESULT WINAPI URLMonikerImpl_GetSizeMax(IMoniker* iface,
466                                                 ULARGE_INTEGER* pcbSize)/* Pointer to size of stream needed to save object */
467 {
468     URLMonikerImpl *This = (URLMonikerImpl *)iface;
469
470     TRACE("(%p,%p)\n",This,pcbSize);
471
472     if(!pcbSize)
473         return E_INVALIDARG;
474
475     pcbSize->QuadPart = sizeof(ULONG) + ((strlenW(This->URLName)+1) * sizeof(WCHAR));
476     return S_OK;
477 }
478
479 /******************************************************************************
480  *                  URLMoniker_BindToObject
481  ******************************************************************************/
482 static HRESULT WINAPI URLMonikerImpl_BindToObject(IMoniker* iface,
483                                                   IBindCtx* pbc,
484                                                   IMoniker* pmkToLeft,
485                                                   REFIID riid,
486                                                   VOID** ppvResult)
487 {
488     URLMonikerImpl *This = (URLMonikerImpl *)iface;
489
490     *ppvResult=0;
491
492     FIXME("(%p)->(%p,%p,%s,%p): stub\n",This,pbc,pmkToLeft,debugstr_guid(riid),
493           ppvResult);
494
495     return E_NOTIMPL;
496 }
497
498 /******************************************************************************
499  *        URLMoniker_BindToStorage
500  ******************************************************************************/
501 static HRESULT URLMonikerImpl_BindToStorage_hack(LPCWSTR URLName,
502                                                    IBindCtx* pbc,
503                                                    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 = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(Binding));
521     bind->lpVtbl = &BindingVtbl;
522     bind->ref = 1;
523     URLMON_LockModule();
524
525     len = lstrlenW(URLName)+1;
526     bind->URLName = HeapAlloc(GetProcessHeap(), 0, 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 = HeapAlloc(GetProcessHeap(), 0, (url.dwHostNameLength + 1) * sizeof(WCHAR));
565                 memcpy(host, url.lpszHostName, url.dwHostNameLength * sizeof(WCHAR));
566                 host[url.dwHostNameLength] = '\0';
567                 path = HeapAlloc(GetProcessHeap(), 0, (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 = HeapAlloc(GetProcessHeap(), 0, ((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 = HeapAlloc(GetProcessHeap(), 0, ((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                 HeapFree(GetProcessHeap(), 0, user);
715                 HeapFree(GetProcessHeap(), 0, pass);
716                 HeapFree(GetProcessHeap(), 0, path);
717                 HeapFree(GetProcessHeap(), 0, 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 = HeapAlloc(GetProcessHeap(), 0, 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         HeapFree(GetProcessHeap(), 0, This->URLName);
1056         return hres;
1057     }
1058
1059     URLMON_LockModule();
1060
1061     if(sizeStr != INTERNET_MAX_URL_LENGTH)
1062         This->URLName = HeapReAlloc(GetProcessHeap(), 0, 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 = HeapAlloc(GetProcessHeap(), 0, 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         HeapFree(GetProcessHeap(), 0, 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  *           RegisterBindStatusCallback (URLMON.@)
1213  *
1214  * Register a bind status callback.
1215  *
1216  * PARAMS
1217  *  pbc           [I] Binding context
1218  *  pbsc          [I] Callback to register
1219  *  ppbscPrevious [O] Destination for previous callback
1220  *  dwReserved    [I] Reserved, must be 0.
1221  *
1222  * RETURNS
1223  *    Success: S_OK.
1224  *    Failure: E_INVALIDARG, if any argument is invalid, or
1225  *             E_OUTOFMEMORY if memory allocation fails.
1226  */
1227 HRESULT WINAPI RegisterBindStatusCallback(
1228     IBindCtx *pbc,
1229     IBindStatusCallback *pbsc,
1230     IBindStatusCallback **ppbscPrevious,
1231     DWORD dwReserved)
1232 {
1233     IBindStatusCallback *prev;
1234
1235     TRACE("(%p,%p,%p,%u)\n", pbc, pbsc, ppbscPrevious, dwReserved);
1236
1237     if (pbc == NULL || pbsc == NULL)
1238         return E_INVALIDARG;
1239
1240     if (SUCCEEDED(IBindCtx_GetObjectParam(pbc, BSCBHolder, (IUnknown **)&prev)))
1241     {
1242         IBindCtx_RevokeObjectParam(pbc, BSCBHolder);
1243         if (ppbscPrevious)
1244             *ppbscPrevious = prev;
1245         else
1246             IBindStatusCallback_Release(prev);
1247     }
1248
1249     return IBindCtx_RegisterObjectParam(pbc, BSCBHolder, (IUnknown *)pbsc);
1250 }
1251
1252 /***********************************************************************
1253  *           RevokeBindStatusCallback (URLMON.@)
1254  *
1255  * Unregister a bind status callback.
1256  *
1257  *  pbc           [I] Binding context
1258  *  pbsc          [I] Callback to unregister
1259  *
1260  * RETURNS
1261  *    Success: S_OK.
1262  *    Failure: E_INVALIDARG, if any argument is invalid, or
1263  *             E_FAIL if pbsc wasn't registered with pbc.
1264  */
1265 HRESULT WINAPI RevokeBindStatusCallback(
1266     IBindCtx *pbc,
1267     IBindStatusCallback *pbsc)
1268 {
1269     IBindStatusCallback *callback;
1270     HRESULT hr = E_FAIL;
1271
1272         TRACE("(%p,%p)\n", pbc, pbsc);
1273
1274     if (pbc == NULL || pbsc == NULL)
1275         return E_INVALIDARG;
1276
1277     if (SUCCEEDED(IBindCtx_GetObjectParam(pbc, BSCBHolder, (IUnknown **)&callback)))
1278     {
1279         if (callback == pbsc)
1280         {
1281             IBindCtx_RevokeObjectParam(pbc, BSCBHolder);
1282             hr = S_OK;
1283         }
1284         IBindStatusCallback_Release(pbsc);
1285     }
1286
1287     return hr;
1288 }
1289
1290 /***********************************************************************
1291  *           URLDownloadToFileA (URLMON.@)
1292  *
1293  * Downloads URL szURL to rile szFileName and call lpfnCB callback to
1294  * report progress.
1295  *
1296  * PARAMS
1297  *  pCaller    [I] controlling IUnknown interface.
1298  *  szURL      [I] URL of the file to download
1299  *  szFileName [I] file name to store the content of the URL
1300  *  dwReserved [I] reserved - set to 0
1301  *  lpfnCB     [I] callback for progress report
1302  *
1303  * RETURNS
1304  *  S_OK on success
1305  *  E_OUTOFMEMORY when going out of memory
1306  */
1307 HRESULT WINAPI URLDownloadToFileA(LPUNKNOWN pCaller,
1308                                   LPCSTR szURL,
1309                                   LPCSTR szFileName,
1310                                   DWORD dwReserved,
1311                                   LPBINDSTATUSCALLBACK lpfnCB)
1312 {
1313     UNICODE_STRING szURL_w, szFileName_w;
1314
1315     if ((szURL == NULL) || (szFileName == NULL)) {
1316         FIXME("(%p,%s,%s,%08x,%p) cannot accept NULL strings !\n", pCaller, debugstr_a(szURL), debugstr_a(szFileName), dwReserved, lpfnCB);
1317         return E_INVALIDARG; /* The error code is not specified in this case... */
1318     }
1319     
1320     if (RtlCreateUnicodeStringFromAsciiz(&szURL_w, szURL)) {
1321         if (RtlCreateUnicodeStringFromAsciiz(&szFileName_w, szFileName)) {
1322             HRESULT ret = URLDownloadToFileW(pCaller, szURL_w.Buffer, szFileName_w.Buffer, dwReserved, lpfnCB);
1323
1324             RtlFreeUnicodeString(&szURL_w);
1325             RtlFreeUnicodeString(&szFileName_w);
1326             
1327             return ret;
1328         } else {
1329             RtlFreeUnicodeString(&szURL_w);
1330         }
1331     }
1332     
1333     FIXME("(%p,%s,%s,%08x,%p) could not allocate W strings !\n", pCaller, szURL, szFileName, dwReserved, lpfnCB);
1334     return E_OUTOFMEMORY;
1335 }
1336
1337 /***********************************************************************
1338  *           URLDownloadToFileW (URLMON.@)
1339  *
1340  * Downloads URL szURL to rile szFileName and call lpfnCB callback to
1341  * report progress.
1342  *
1343  * PARAMS
1344  *  pCaller    [I] controlling IUnknown interface.
1345  *  szURL      [I] URL of the file to download
1346  *  szFileName [I] file name to store the content of the URL
1347  *  dwReserved [I] reserved - set to 0
1348  *  lpfnCB     [I] callback for progress report
1349  *
1350  * RETURNS
1351  *  S_OK on success
1352  *  E_OUTOFMEMORY when going out of memory
1353  */
1354 HRESULT WINAPI URLDownloadToFileW(LPUNKNOWN pCaller,
1355                                   LPCWSTR szURL,
1356                                   LPCWSTR szFileName,
1357                                   DWORD dwReserved,
1358                                   LPBINDSTATUSCALLBACK lpfnCB)
1359 {
1360     HINTERNET hinternet, hcon, hreq;
1361     BOOL r;
1362     CHAR buffer[0x1000];
1363     DWORD sz, total, written;
1364     DWORD total_size = 0xFFFFFFFF, arg_size = sizeof(total_size);
1365     URL_COMPONENTSW url;
1366     WCHAR host[0x80], path[0x100];
1367     HANDLE hfile;
1368     static const WCHAR wszAppName[]={'u','r','l','m','o','n','.','d','l','l',0};
1369
1370     /* Note: all error codes would need to be checked agains real Windows behaviour... */
1371     TRACE("(%p,%s,%s,%08x,%p) stub!\n", pCaller, debugstr_w(szURL), debugstr_w(szFileName), dwReserved, lpfnCB);
1372
1373     if ((szURL == NULL) || (szFileName == NULL)) {
1374         FIXME(" cannot accept NULL strings !\n");
1375         return E_INVALIDARG;
1376     }
1377
1378     /* Would be better to use the application name here rather than 'urlmon' :-/ */
1379     hinternet = InternetOpenW(wszAppName, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
1380     if (hinternet == NULL) {
1381         return E_OUTOFMEMORY;
1382     }                                                                                                                             
1383
1384     memset(&url, 0, sizeof(url));
1385     url.dwStructSize = sizeof(url);
1386     url.lpszHostName = host;
1387     url.dwHostNameLength = sizeof(host);
1388     url.lpszUrlPath = path;
1389     url.dwUrlPathLength = sizeof(path);
1390
1391     if (!InternetCrackUrlW(szURL, 0, 0, &url)) {
1392         InternetCloseHandle(hinternet);
1393         return E_OUTOFMEMORY;
1394     }
1395
1396     if (lpfnCB) {
1397         if (IBindStatusCallback_OnProgress(lpfnCB, 0, 0, BINDSTATUS_CONNECTING, url.lpszHostName) == E_ABORT) {
1398             InternetCloseHandle(hinternet);
1399             return S_OK;
1400         }
1401     }
1402     
1403     hcon = InternetConnectW(hinternet, url.lpszHostName, url.nPort,
1404                             url.lpszUserName, url.lpszPassword,
1405                             INTERNET_SERVICE_HTTP, 0, 0);
1406     if (!hcon) {
1407         InternetCloseHandle(hinternet);
1408         return E_OUTOFMEMORY;
1409     }
1410     
1411     hreq = HttpOpenRequestW(hcon, NULL, url.lpszUrlPath, NULL, NULL, NULL, 0, 0);
1412     if (!hreq) {
1413         InternetCloseHandle(hinternet);
1414         InternetCloseHandle(hcon);
1415         return E_OUTOFMEMORY;
1416     }                                                                                                                             
1417
1418     if (!HttpSendRequestW(hreq, NULL, 0, NULL, 0)) {
1419         InternetCloseHandle(hinternet);
1420         InternetCloseHandle(hcon);
1421         InternetCloseHandle(hreq);
1422         return E_OUTOFMEMORY;
1423     }
1424     
1425     if (HttpQueryInfoW(hreq, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER,
1426                        &total_size, &arg_size, NULL)) {
1427         TRACE(" total size : %d\n", total_size);
1428     }
1429     
1430     hfile = CreateFileW(szFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
1431                         FILE_ATTRIBUTE_NORMAL, NULL );
1432     if (hfile == INVALID_HANDLE_VALUE) {
1433         return E_ACCESSDENIED;
1434     }
1435     
1436     if (lpfnCB) {
1437         if (IBindStatusCallback_OnProgress(lpfnCB, 0, total_size != 0xFFFFFFFF ? total_size : 0,
1438                                            BINDSTATUS_BEGINDOWNLOADDATA, szURL) == E_ABORT) {
1439             InternetCloseHandle(hreq);
1440             InternetCloseHandle(hcon);
1441             InternetCloseHandle(hinternet);
1442             CloseHandle(hfile);
1443             return S_OK;
1444         }
1445     }
1446     
1447     total = 0;
1448     while (1) {
1449         r = InternetReadFile(hreq, buffer, sizeof(buffer), &sz);
1450         if (!r) {
1451             InternetCloseHandle(hreq);
1452             InternetCloseHandle(hcon);
1453             InternetCloseHandle(hinternet);
1454             
1455             CloseHandle(hfile);
1456             return E_OUTOFMEMORY;           
1457         }
1458         if (!sz)
1459             break;
1460         
1461         total += sz;
1462
1463         if (lpfnCB) {
1464             if (IBindStatusCallback_OnProgress(lpfnCB, total, total_size != 0xFFFFFFFF ? total_size : 0,
1465                                                BINDSTATUS_DOWNLOADINGDATA, szURL) == E_ABORT) {
1466                 InternetCloseHandle(hreq);
1467                 InternetCloseHandle(hcon);
1468                 InternetCloseHandle(hinternet);
1469                 CloseHandle(hfile);
1470                 return S_OK;
1471             }
1472         }
1473         
1474         if (!WriteFile(hfile, buffer, sz, &written, NULL)) {
1475             InternetCloseHandle(hreq);
1476             InternetCloseHandle(hcon);
1477             InternetCloseHandle(hinternet);
1478             
1479             CloseHandle(hfile);
1480             return E_OUTOFMEMORY;
1481         }
1482     }
1483
1484     if (lpfnCB) {
1485         if (IBindStatusCallback_OnProgress(lpfnCB, total, total_size != 0xFFFFFFFF ? total_size : 0,
1486                                            BINDSTATUS_ENDDOWNLOADDATA, szURL) == E_ABORT) {
1487             InternetCloseHandle(hreq);
1488             InternetCloseHandle(hcon);
1489             InternetCloseHandle(hinternet);
1490             CloseHandle(hfile);
1491             return S_OK;
1492         }
1493     }
1494     
1495     InternetCloseHandle(hreq);
1496     InternetCloseHandle(hcon);
1497     InternetCloseHandle(hinternet);
1498     
1499     CloseHandle(hfile);
1500
1501     return S_OK;
1502 }
1503
1504 /***********************************************************************
1505  *           URLDownloadToCacheFileA (URLMON.@)
1506  */
1507 HRESULT WINAPI URLDownloadToCacheFileA(LPUNKNOWN lpUnkCaller, LPCSTR szURL, LPSTR szFileName,
1508         DWORD dwBufLength, DWORD dwReserved, LPBINDSTATUSCALLBACK pBSC)
1509 {
1510     LPWSTR url = NULL, file_name = NULL;
1511     int len;
1512     HRESULT hres;
1513
1514     TRACE("(%p %s %p %d %d %p)\n", lpUnkCaller, debugstr_a(szURL), szFileName,
1515             dwBufLength, dwReserved, pBSC);
1516
1517     if(szURL) {
1518         len = MultiByteToWideChar(CP_ACP, 0, szURL, -1, NULL, 0);
1519         url = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1520         MultiByteToWideChar(CP_ACP, 0, szURL, -1, url, -1);
1521     }
1522
1523     if(szFileName)
1524         file_name = HeapAlloc(GetProcessHeap(), 0, dwBufLength*sizeof(WCHAR));
1525
1526     hres = URLDownloadToCacheFileW(lpUnkCaller, url, file_name, dwBufLength*sizeof(WCHAR),
1527             dwReserved, pBSC);
1528
1529     if(SUCCEEDED(hres) && file_name)
1530         WideCharToMultiByte(CP_ACP, 0, file_name, -1, szFileName, dwBufLength, NULL, NULL);
1531
1532     HeapFree(GetProcessHeap(), 0, url);
1533     HeapFree(GetProcessHeap(), 0, file_name);
1534
1535     return hres;
1536 }
1537
1538 /***********************************************************************
1539  *           URLDownloadToCacheFileW (URLMON.@)
1540  */
1541 HRESULT WINAPI URLDownloadToCacheFileW(LPUNKNOWN lpUnkCaller, LPCWSTR szURL, LPWSTR szFileName,
1542                 DWORD dwBufLength, DWORD dwReserved, LPBINDSTATUSCALLBACK pBSC)
1543 {
1544     WCHAR cache_path[MAX_PATH + 1];
1545     FILETIME expire, modified;
1546     HRESULT hr;
1547     LPWSTR ext;
1548
1549     static WCHAR header[] = {
1550         'H','T','T','P','/','1','.','0',' ','2','0','0',' ',
1551         'O','K','\\','r','\\','n','\\','r','\\','n',0
1552     };
1553
1554     TRACE("(%p, %s, %p, %d, %d, %p)\n", lpUnkCaller, debugstr_w(szURL),
1555           szFileName, dwBufLength, dwReserved, pBSC);
1556
1557     if (!szURL || !szFileName)
1558         return E_INVALIDARG;
1559
1560     ext = PathFindExtensionW(szURL);
1561
1562     if (!CreateUrlCacheEntryW(szURL, 0, ext, cache_path, 0))
1563         return E_FAIL;
1564
1565     hr = URLDownloadToFileW(lpUnkCaller, szURL, cache_path, 0, pBSC);
1566     if (FAILED(hr))
1567         return hr;
1568
1569     expire.dwHighDateTime = 0;
1570     expire.dwLowDateTime = 0;
1571     modified.dwHighDateTime = 0;
1572     modified.dwLowDateTime = 0;
1573
1574     if (!CommitUrlCacheEntryW(szURL, cache_path, expire, modified, NORMAL_CACHE_ENTRY,
1575                               header, sizeof(header), NULL, NULL))
1576         return E_FAIL;
1577
1578     if (lstrlenW(cache_path) > dwBufLength)
1579         return E_OUTOFMEMORY;
1580
1581     lstrcpyW(szFileName, cache_path);
1582
1583     return S_OK;
1584 }
1585
1586 /***********************************************************************
1587  *           HlinkSimpleNavigateToString (URLMON.@)
1588  */
1589 HRESULT WINAPI HlinkSimpleNavigateToString( LPCWSTR szTarget,
1590     LPCWSTR szLocation, LPCWSTR szTargetFrameName, IUnknown *pUnk,
1591     IBindCtx *pbc, IBindStatusCallback *pbsc, DWORD grfHLNF, DWORD dwReserved)
1592 {
1593     FIXME("%s\n", debugstr_w( szTarget ) );
1594     return E_NOTIMPL;
1595 }
1596
1597 /***********************************************************************
1598  *           HlinkNavigateString (URLMON.@)
1599  */
1600 HRESULT WINAPI HlinkNavigateString( IUnknown *pUnk, LPCWSTR szTarget )
1601 {
1602     TRACE("%p %s\n", pUnk, debugstr_w( szTarget ) );
1603     return HlinkSimpleNavigateToString( 
1604                szTarget, NULL, NULL, pUnk, NULL, NULL, 0, 0 );
1605 }
1606
1607 /***********************************************************************
1608  *           GetSoftwareUpdateInfo (URLMON.@)
1609  */
1610 HRESULT WINAPI GetSoftwareUpdateInfo( LPCWSTR szDistUnit, LPSOFTDISTINFO psdi )
1611 {
1612     FIXME("%s %p\n", debugstr_w(szDistUnit), psdi );
1613     return E_FAIL;
1614 }