Fixed exception handling on MacOS.
[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  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 #define COM_NO_WINDOWS_H
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=%ld\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=%ld\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)->(%ld): 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                                             NULL);
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, BINDSTATUS_ENDDOWNLOADDATA, NULL);
248     IBindStatusCallback_OnDataAvailable(This->pbscb, BSCF_LASTDATANOTIFICATION, This->total_read, &fmt, &stg);
249     if (hr)
250     {
251         WCHAR *pwchError = 0;
252
253         FormatMessageW (FORMAT_MESSAGE_FROM_SYSTEM |
254                          FORMAT_MESSAGE_ALLOCATE_BUFFER,
255                         NULL, (DWORD) hr,
256                         0, (LPWSTR) &pwchError,
257                         0, NULL);
258         if (!pwchError)
259         {
260             static WCHAR achFormat[] = { '%', '0', '8', 'x', 0 };
261
262             pwchError =(WCHAR *) LocalAlloc(LMEM_FIXED, sizeof(WCHAR) * 9);
263             wsprintfW(pwchError, achFormat, hr);
264         }
265         IBindStatusCallback_OnStopBinding(This->pbscb, hr, pwchError);
266         LocalFree(pwchError);
267     }
268     else
269     {
270         IBindStatusCallback_OnStopBinding(This->pbscb, hr, NULL);
271     }
272     IBindStatusCallback_Release(This->pbscb);
273     This->pbscb = 0;
274 }
275
276 static const IBindingVtbl BindingVtbl =
277 {
278     Binding_QueryInterface,
279     Binding_AddRef,
280     Binding_Release,
281     Binding_Abort,
282     Binding_Suspend,
283     Binding_Resume,
284     Binding_SetPriority,
285     Binding_GetPriority,
286     Binding_GetBindResult
287 };
288
289 /* filemoniker data structure */
290 typedef struct {
291
292     const IMonikerVtbl* lpvtbl;  /* VTable relative to the IMoniker interface.*/
293
294     LONG ref; /* reference counter for this object */
295
296     LPOLESTR URLName; /* URL string identified by this URLmoniker */
297 } URLMonikerImpl;
298
299 /*******************************************************************************
300  *        URLMoniker_QueryInterface
301  *******************************************************************************/
302 static HRESULT WINAPI URLMonikerImpl_QueryInterface(IMoniker* iface,REFIID riid,void** ppvObject)
303 {
304     URLMonikerImpl *This = (URLMonikerImpl *)iface;
305
306     TRACE("(%p)->(%s,%p)\n",This,debugstr_guid(riid),ppvObject);
307
308     /* Perform a sanity check on the parameters.*/
309     if ( (This==0) || (ppvObject==0) )
310         return E_INVALIDARG;
311
312     /* Initialize the return parameter */
313     *ppvObject = 0;
314
315     /* Compare the riid with the interface IDs implemented by this object.*/
316     if (IsEqualIID(&IID_IUnknown, riid)      ||
317         IsEqualIID(&IID_IPersist, riid)      ||
318         IsEqualIID(&IID_IPersistStream,riid) ||
319         IsEqualIID(&IID_IMoniker, riid)
320        )
321         *ppvObject = iface;
322
323     /* Check that we obtained an interface.*/
324     if ((*ppvObject)==0)
325         return E_NOINTERFACE;
326
327     /* Query Interface always increases the reference count by one when it is successful */
328     IMoniker_AddRef(iface);
329
330     return S_OK;
331 }
332
333 /******************************************************************************
334  *        URLMoniker_AddRef
335  ******************************************************************************/
336 static ULONG WINAPI URLMonikerImpl_AddRef(IMoniker* iface)
337 {
338     URLMonikerImpl *This = (URLMonikerImpl *)iface;
339     ULONG refCount = InterlockedIncrement(&This->ref);
340
341     TRACE("(%p)->(ref before=%lu)\n",This, refCount - 1);
342
343     return refCount;
344 }
345
346 /******************************************************************************
347  *        URLMoniker_Release
348  ******************************************************************************/
349 static ULONG WINAPI URLMonikerImpl_Release(IMoniker* iface)
350 {
351     URLMonikerImpl *This = (URLMonikerImpl *)iface;
352     ULONG refCount = InterlockedDecrement(&This->ref);
353
354     TRACE("(%p)->(ref before=%lu)\n",This, refCount + 1);
355
356     /* destroy the object if there's no more reference on it */
357     if (!refCount) {
358         HeapFree(GetProcessHeap(),0,This->URLName);
359         HeapFree(GetProcessHeap(),0,This);
360
361         URLMON_UnlockModule();
362     }
363
364     return refCount;
365 }
366
367
368 /******************************************************************************
369  *        URLMoniker_GetClassID
370  ******************************************************************************/
371 static HRESULT WINAPI URLMonikerImpl_GetClassID(IMoniker* iface,
372                                                 CLSID *pClassID)/* Pointer to CLSID of object */
373 {
374     URLMonikerImpl *This = (URLMonikerImpl *)iface;
375
376     TRACE("(%p,%p)\n",This,pClassID);
377
378     if (pClassID==NULL)
379         return E_POINTER;
380     /* Windows always returns CLSID_StdURLMoniker */
381     *pClassID = CLSID_StdURLMoniker;
382     return S_OK;
383 }
384
385 /******************************************************************************
386  *        URLMoniker_IsDirty
387  ******************************************************************************/
388 static HRESULT WINAPI URLMonikerImpl_IsDirty(IMoniker* iface)
389 {
390     URLMonikerImpl *This = (URLMonikerImpl *)iface;
391     /* Note that the OLE-provided implementations of the IPersistStream::IsDirty
392        method in the OLE-provided moniker interfaces always return S_FALSE because
393        their internal state never changes. */
394
395     TRACE("(%p)\n",This);
396
397     return S_FALSE;
398 }
399
400 /******************************************************************************
401  *        URLMoniker_Load
402  *
403  * NOTE
404  *  Writes a ULONG containing length of unicode string, followed
405  *  by that many unicode characters
406  ******************************************************************************/
407 static HRESULT WINAPI URLMonikerImpl_Load(IMoniker* iface,IStream* pStm)
408 {
409     URLMonikerImpl *This = (URLMonikerImpl *)iface;
410     
411     HRESULT res;
412     ULONG len;
413     ULONG got;
414     TRACE("(%p,%p)\n",This,pStm);
415
416     if(!pStm)
417         return E_INVALIDARG;
418
419     res = IStream_Read(pStm, &len, sizeof(ULONG), &got);
420     if(SUCCEEDED(res)) {
421         if(got == sizeof(ULONG)) {
422             HeapFree(GetProcessHeap(), 0, This->URLName);
423             This->URLName=HeapAlloc(GetProcessHeap(),0,sizeof(WCHAR)*(len+1));
424             if(!This->URLName)
425                 res = E_OUTOFMEMORY;
426             else {
427                 res = IStream_Read(pStm, This->URLName, len, NULL);
428                 This->URLName[len] = 0;
429             }
430         }
431         else
432             res = E_FAIL;
433     }
434     return res;
435 }
436
437 /******************************************************************************
438  *        URLMoniker_Save
439  ******************************************************************************/
440 static HRESULT WINAPI URLMonikerImpl_Save(IMoniker* iface,
441                                           IStream* pStm,/* pointer to the stream where the object is to be saved */
442                                           BOOL fClearDirty)/* Specifies whether to clear the dirty flag */
443 {
444     URLMonikerImpl *This = (URLMonikerImpl *)iface;
445
446     HRESULT res;
447     ULONG len;
448     TRACE("(%p,%p,%d)\n",This,pStm,fClearDirty);
449
450     if(!pStm)
451         return E_INVALIDARG;
452
453     len = strlenW(This->URLName);
454     res=IStream_Write(pStm,&len,sizeof(ULONG),NULL);
455     if(SUCCEEDED(res))
456         res=IStream_Write(pStm,&This->URLName,len*sizeof(WCHAR),NULL);
457     return res;
458
459 }
460
461 /******************************************************************************
462  *        URLMoniker_GetSizeMax
463  ******************************************************************************/
464 static HRESULT WINAPI URLMonikerImpl_GetSizeMax(IMoniker* iface,
465                                                 ULARGE_INTEGER* pcbSize)/* Pointer to size of stream needed to save object */
466 {
467     URLMonikerImpl *This = (URLMonikerImpl *)iface;
468
469     TRACE("(%p,%p)\n",This,pcbSize);
470
471     if(!pcbSize)
472         return E_INVALIDARG;
473
474     pcbSize->u.LowPart = sizeof(ULONG) + (strlenW(This->URLName) * sizeof(WCHAR));
475     pcbSize->u.HighPart = 0;
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 typedef struct {
499     enum {OnProgress, OnDataAvailable} callback;
500 } URLMON_CallbackData;
501
502
503 #if 0
504 static LRESULT CALLBACK URLMON_WndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
505 {
506     return DefWindowProcA(hwnd, msg, wparam, lparam);
507 }
508
509 static void PostOnProgress(URLMonikerImpl *This, UINT progress, UINT maxprogress, DWORD status, LPCWSTR *str)
510 {
511 }
512
513 static void CALLBACK URLMON_InternetCallback(HINTERNET hinet, /*DWORD_PTR*/ DWORD context, DWORD status,
514                                              void *status_info, DWORD status_info_len)
515 {
516     URLMonikerImpl *This = (URLMonikerImpl *)context;
517     TRACE("handle %p this %p status %08lx\n", hinet, This, status);
518
519     if(This->filesize == -1) {
520         switch(status) {
521         case INTERNET_STATUS_RESOLVING_NAME:
522             PostOnProgess(This, 0, 0, BINDSTATUS_FINDINGRESOURCE, status_info);
523             break;
524         case INTERNET_STATUS_CONNECTING_TO_SERVER:
525             PostOnProgress(This, 0, 0, BINDSTATUS_CONNECTING, NULL);
526             break;
527         case INTERNET_STATUS_SENDING_REQUEST:
528             PostOnProgress(This, 0, 0, BINDSTATUS_SENDINGREQUEST, NULL);
529             break;
530         case INTERNET_REQUEST_COMPLETE:
531           {
532               DWORD len, lensz = sizeof(len);
533
534             HttpQueryInfoW(hrequest, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &len, &lensz, NULL);
535             TRACE("res = %ld gle = %08lx url len = %ld\n", hres, GetLastError(), len);
536             This->filesize = len;
537             break;
538           }
539         }
540     }
541
542     return;
543 }
544 #endif
545
546
547 /******************************************************************************
548  *        URLMoniker_BindToStorage
549  ******************************************************************************/
550 static HRESULT WINAPI URLMonikerImpl_BindToStorage(IMoniker* iface,
551                                                    IBindCtx* pbc,
552                                                    IMoniker* pmkToLeft,
553                                                    REFIID riid,
554                                                    VOID** ppvObject)
555 {
556     URLMonikerImpl *This = (URLMonikerImpl *)iface;
557     HRESULT hres;
558     BINDINFO bi;
559     DWORD bindf;
560     WCHAR szFileName[MAX_PATH + 1];
561     Binding *bind;
562     int len;
563
564     if(pmkToLeft) {
565         FIXME("pmkToLeft != NULL\n");
566         return E_NOTIMPL;
567     }
568     if(!IsEqualIID(&IID_IStream, riid)) {
569         FIXME("unsupported iid\n");
570         return E_NOTIMPL;
571     }
572
573     bind = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(Binding));
574     bind->lpVtbl = &BindingVtbl;
575     bind->ref = 1;
576     URLMON_LockModule();
577
578     len = lstrlenW(This->URLName)+1;
579     bind->URLName = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
580     memcpy(bind->URLName, This->URLName, len*sizeof(WCHAR));
581
582     hres = UMCreateStreamOnCacheFile(bind->URLName, 0, szFileName, &bind->hCacheFile, &bind->pstrCache);
583
584     if(SUCCEEDED(hres)) {
585         TRACE("Created stream...\n");
586
587         *ppvObject = (void *) bind->pstrCache;
588         IStream_AddRef((IStream *) bind->pstrCache);
589
590         hres = IBindCtx_GetObjectParam(pbc, (LPOLESTR)BSCBHolder, (IUnknown**)&bind->pbscb);
591         if(SUCCEEDED(hres)) {
592             TRACE("Got IBindStatusCallback...\n");
593
594             memset(&bi, 0, sizeof(bi));
595             bi.cbSize = sizeof(bi);
596             bindf = 0;
597             hres = IBindStatusCallback_GetBindInfo(bind->pbscb, &bindf, &bi);
598             if(SUCCEEDED(hres)) {
599                 WCHAR *urlcopy, *tmpwc;
600                 URL_COMPONENTSW url;
601                 WCHAR *host, *path, *partial_path, *user, *pass;
602                 DWORD lensz = sizeof(bind->expected_size);
603                 DWORD dwService = 0;
604                 BOOL bSuccess;
605
606                 TRACE("got bindinfo. bindf = %08lx extrainfo = %s bindinfof = %08lx bindverb = %08lx iid %s\n",
607                       bindf, debugstr_w(bi.szExtraInfo), bi.grfBindInfoF, bi.dwBindVerb, debugstr_guid(&bi.iid));
608                 hres = IBindStatusCallback_OnStartBinding(bind->pbscb, 0, (IBinding*)bind);
609                 TRACE("OnStartBinding rets %08lx\n", hres);
610
611                 /* This class will accept URLs with the backslash in them. But InternetCrackURL will not - it
612                  * requires forward slashes (this is the behaviour of Microsoft's INETAPI). So we need to make
613                  * a copy of the URL here and change the backslash to a forward slash everywhere it appears -
614                  * but only before any '#' or '?', after which backslash should be left alone.
615                  */
616                 urlcopy = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * (lstrlenW(bind->URLName) + 1));
617                 lstrcpyW(urlcopy, bind->URLName);
618                 for (tmpwc = urlcopy; *tmpwc && *tmpwc != '#' && *tmpwc != '?'; ++tmpwc)
619                     if (*tmpwc == '\\')
620                             *tmpwc = '/';
621
622 #if 0
623                 if(!registered_wndclass) {
624                     WNDCLASSA urlmon_wndclass = {0, URLMON_WndProc,0, 0, URLMON_hInstance, 0, 0, 0, NULL, "URLMON_Callback_Window_Class"};
625                     RegisterClassA(&urlmon_wndclass);
626                     registered_wndclass = TRUE;
627                 }
628
629                 This->hwndCallback = CreateWindowA("URLMON_Callback_Window_Class", NULL, 0, 0, 0, 0, 0, 0, 0,
630                                                    URLMON_hInstance, NULL);
631
632 #endif
633                 bind->expected_size = 0;
634                 bind->total_read = 0;
635
636                 memset(&url, 0, sizeof(url));
637                 url.dwStructSize = sizeof(url);
638                 url.dwSchemeLength = url.dwHostNameLength = url.dwUrlPathLength = url.dwUserNameLength = url.dwPasswordLength = 1;
639                 InternetCrackUrlW(urlcopy, 0, ICU_ESCAPE, &url);
640                 host = HeapAlloc(GetProcessHeap(), 0, (url.dwHostNameLength + 1) * sizeof(WCHAR));
641                 memcpy(host, url.lpszHostName, url.dwHostNameLength * sizeof(WCHAR));
642                 host[url.dwHostNameLength] = '\0';
643                 path = HeapAlloc(GetProcessHeap(), 0, (url.dwUrlPathLength + 1) * sizeof(WCHAR));
644                 memcpy(path, url.lpszUrlPath, url.dwUrlPathLength * sizeof(WCHAR));
645                 path[url.dwUrlPathLength] = '\0';
646                 if (url.dwUserNameLength)
647                 {
648                     user = HeapAlloc(GetProcessHeap(), 0, ((url.dwUserNameLength + 1) * sizeof(WCHAR)));
649                     memcpy(user, url.lpszUserName, url.dwUserNameLength * sizeof(WCHAR));
650                     user[url.dwUserNameLength] = 0;
651                 }
652                 else
653                 {
654                     user = 0;
655                 }
656                 if (url.dwPasswordLength)
657                 {
658                     pass = HeapAlloc(GetProcessHeap(), 0, ((url.dwPasswordLength + 1) * sizeof(WCHAR)));
659                     memcpy(pass, url.lpszPassword, url.dwPasswordLength * sizeof(WCHAR));
660                     pass[url.dwPasswordLength] = 0;
661                 }
662                 else
663                 {
664                     pass = 0;
665                 }
666
667                 switch ((DWORD) url.nScheme)
668                 {
669                 case INTERNET_SCHEME_FTP:
670                 case INTERNET_SCHEME_GOPHER:
671                 case INTERNET_SCHEME_HTTP:
672                 case INTERNET_SCHEME_HTTPS:
673
674                     bind->hinternet = InternetOpenA("User Agent", 0, NULL, NULL, 0 /*INTERNET_FLAG_ASYNC*/);
675 /*                  InternetSetStatusCallback(bind->hinternet, URLMON_InternetCallback);*/
676                     if (!bind->hinternet)
677                     {
678                             hres = HRESULT_FROM_WIN32(GetLastError());
679                             break;
680                     }
681
682                     switch ((DWORD) url.nScheme)
683                     {
684                     case INTERNET_SCHEME_FTP:
685                         if (!url.nPort)
686                             url.nPort = INTERNET_DEFAULT_FTP_PORT;
687                         dwService = INTERNET_SERVICE_FTP;
688                         break;
689     
690                     case INTERNET_SCHEME_GOPHER:
691                         if (!url.nPort)
692                             url.nPort = INTERNET_DEFAULT_GOPHER_PORT;
693                         dwService = INTERNET_SERVICE_GOPHER;
694                         break;
695
696                     case INTERNET_SCHEME_HTTP:
697                         if (!url.nPort)
698                             url.nPort = INTERNET_DEFAULT_HTTP_PORT;
699                         dwService = INTERNET_SERVICE_HTTP;
700                         break;
701
702                     case INTERNET_SCHEME_HTTPS:
703                         if (!url.nPort)
704                             url.nPort = INTERNET_DEFAULT_HTTPS_PORT;
705                         dwService = INTERNET_SERVICE_HTTP;
706                         break;
707                     }
708
709                     bind->hconnect = InternetConnectW(bind->hinternet, host, url.nPort, user, pass,
710                                                       dwService, 0, (DWORD)bind);
711                     if (!bind->hconnect)
712                     {
713                             hres = HRESULT_FROM_WIN32(GetLastError());
714                             CloseHandle(bind->hinternet);
715                             break;
716                     }
717
718                     hres = IBindStatusCallback_OnProgress(bind->pbscb, 0, 0, 0x22, NULL);
719                     hres = IBindStatusCallback_OnProgress(bind->pbscb, 0, 0, BINDSTATUS_FINDINGRESOURCE, NULL);
720                     hres = IBindStatusCallback_OnProgress(bind->pbscb, 0, 0, BINDSTATUS_CONNECTING, NULL);
721                     hres = IBindStatusCallback_OnProgress(bind->pbscb, 0, 0, BINDSTATUS_SENDINGREQUEST, NULL);
722
723                     bSuccess = FALSE;
724
725                     switch (dwService)
726                     {
727                     case INTERNET_SERVICE_GOPHER:
728                         bind->hrequest = GopherOpenFileW(bind->hconnect,
729                                                          path,
730                                                          0,
731                                                          INTERNET_FLAG_RELOAD,
732                                                          0);
733                         if (bind->hrequest)
734                                 bSuccess = TRUE;
735                         else
736                                 hres = HRESULT_FROM_WIN32(GetLastError());
737                         break;
738
739                     case INTERNET_SERVICE_FTP:
740                         bind->hrequest = FtpOpenFileW(bind->hconnect,
741                                                       path,
742                                                       GENERIC_READ,
743                                                       FTP_TRANSFER_TYPE_BINARY |
744                                                        INTERNET_FLAG_TRANSFER_BINARY |
745                                                        INTERNET_FLAG_RELOAD,
746                                                       0);
747                         if (bind->hrequest)
748                                 bSuccess = TRUE;
749                         else
750                                 hres = HRESULT_FROM_WIN32(GetLastError());
751                         break;
752
753                     case INTERNET_SERVICE_HTTP:
754                         bind->hrequest = HttpOpenRequestW(bind->hconnect, NULL, path, NULL, NULL, NULL, 0, (DWORD)bind);
755                         if (!bind->hrequest)
756                         {
757                                 hres = HRESULT_FROM_WIN32(GetLastError());
758                         }
759                         else if (!HttpSendRequestW(bind->hrequest, NULL, 0, NULL, 0))
760                         {
761                                 hres = HRESULT_FROM_WIN32(GetLastError());
762                                 InternetCloseHandle(bind->hrequest);
763                         }
764                         else
765                         {
766                                 HttpQueryInfoW(bind->hrequest,
767                                                HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER,
768                                                &bind->expected_size,
769                                                &lensz,
770                                                NULL);
771                                 bSuccess = TRUE;
772                         }
773                         break;
774                     }
775                     if(bSuccess)
776                     {
777                         TRACE("res = %ld gle = %08lx url len = %ld\n", hres, GetLastError(), bind->expected_size);
778
779                         IBindStatusCallback_OnProgress(bind->pbscb, 0, 0, BINDSTATUS_CACHEFILENAMEAVAILABLE, szFileName);
780
781                         while(1) {
782                             char buf[4096];
783                             DWORD bufread;
784                             if(InternetReadFile(bind->hrequest, buf, sizeof(buf), &bufread)) {
785                                 TRACE("read %ld bytes %s...\n", bufread, debugstr_an(buf, 10));
786                                 if(bufread == 0) break;
787                                 hres = Binding_MoreCacheData(bind, buf, bufread);
788                             } else
789                                 break;
790                         }
791                         InternetCloseHandle(bind->hrequest);
792                             hres = S_OK;
793                     }
794             
795                     InternetCloseHandle(bind->hconnect);
796                     InternetCloseHandle(bind->hinternet);
797                     break;
798
799                 case INTERNET_SCHEME_FILE:
800                     partial_path = bind->URLName + 5; /* Skip the "file:" part */
801                     if ((partial_path[0] != '/' && partial_path[0] != '\\') ||
802                         (partial_path[1] != '/' && partial_path[1] != '\\'))
803                     {
804                         hres = E_FAIL;
805                     }
806                     else
807                     {
808                         HANDLE h;
809
810                         partial_path += 2;
811                         if (partial_path[0] == '/' || partial_path[0] == '\\')
812                             ++partial_path;
813                         h = CreateFileW(partial_path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0 );
814                         if (h == (HANDLE) HFILE_ERROR)
815                         {
816                             hres = HRESULT_FROM_WIN32(GetLastError());
817                         }
818                         else
819                         {
820                             char buf[4096];
821                             DWORD bufread;
822
823                             IBindStatusCallback_OnProgress(bind->pbscb, 0, 0, BINDSTATUS_CACHEFILENAMEAVAILABLE, szFileName);
824
825                             while (ReadFile(h, buf, sizeof(buf), &bufread, NULL) && bufread > 0)
826                                 hres = Binding_MoreCacheData(bind, buf, bufread);
827
828                             CloseHandle(h);
829                             hres = S_OK;
830                         }
831                     }
832                         
833                     break;
834
835                 default:
836                     FIXME("Unsupported URI scheme");
837                     break;
838                 }
839                 Binding_CloseCacheDownload(bind);
840                 Binding_FinishedDownload(bind, hres);
841
842                 if (user)
843                     HeapFree(GetProcessHeap(), 0, user);
844                 if (pass)
845                     HeapFree(GetProcessHeap(), 0, pass);
846                 HeapFree(GetProcessHeap(), 0, path);
847                 HeapFree(GetProcessHeap(), 0, host);
848                 HeapFree(GetProcessHeap(), 0, urlcopy);
849             }
850         }
851     }
852
853     IBinding_Release((IBinding*)bind);
854
855     return hres;
856 }
857
858 /******************************************************************************
859  *        URLMoniker_Reduce
860  ******************************************************************************/
861 static HRESULT WINAPI URLMonikerImpl_Reduce(IMoniker* iface,
862                                             IBindCtx* pbc,
863                                             DWORD dwReduceHowFar,
864                                             IMoniker** ppmkToLeft,
865                                             IMoniker** ppmkReduced)
866 {
867     URLMonikerImpl *This = (URLMonikerImpl *)iface;
868     
869     TRACE("(%p,%p,%ld,%p,%p)\n",This,pbc,dwReduceHowFar,ppmkToLeft,ppmkReduced);
870
871     if(!ppmkReduced)
872         return E_INVALIDARG;
873
874     URLMonikerImpl_AddRef(iface);
875     *ppmkReduced = iface;
876     return MK_S_REDUCED_TO_SELF;
877 }
878
879 /******************************************************************************
880  *        URLMoniker_ComposeWith
881  ******************************************************************************/
882 static HRESULT WINAPI URLMonikerImpl_ComposeWith(IMoniker* iface,
883                                                  IMoniker* pmkRight,
884                                                  BOOL fOnlyIfNotGeneric,
885                                                  IMoniker** ppmkComposite)
886 {
887     URLMonikerImpl *This = (URLMonikerImpl *)iface;
888     FIXME("(%p)->(%p,%d,%p): stub\n",This,pmkRight,fOnlyIfNotGeneric,ppmkComposite);
889
890     return E_NOTIMPL;
891 }
892
893 /******************************************************************************
894  *        URLMoniker_Enum
895  ******************************************************************************/
896 static HRESULT WINAPI URLMonikerImpl_Enum(IMoniker* iface,BOOL fForward, IEnumMoniker** ppenumMoniker)
897 {
898     URLMonikerImpl *This = (URLMonikerImpl *)iface;
899     TRACE("(%p,%d,%p)\n",This,fForward,ppenumMoniker);
900
901     if(!ppenumMoniker)
902         return E_INVALIDARG;
903
904     /* Does not support sub-monikers */
905     *ppenumMoniker = NULL;
906     return S_OK;
907 }
908
909 /******************************************************************************
910  *        URLMoniker_IsEqual
911  ******************************************************************************/
912 static HRESULT WINAPI URLMonikerImpl_IsEqual(IMoniker* iface,IMoniker* pmkOtherMoniker)
913 {
914     URLMonikerImpl *This = (URLMonikerImpl *)iface;
915     CLSID clsid;
916     LPOLESTR urlPath;
917     IBindCtx* bind;
918     HRESULT res;
919
920     TRACE("(%p,%p)\n",This,pmkOtherMoniker);
921
922     if(pmkOtherMoniker==NULL)
923         return E_INVALIDARG;
924
925     IMoniker_GetClassID(pmkOtherMoniker,&clsid);
926
927     if(!IsEqualCLSID(&clsid,&CLSID_StdURLMoniker))
928         return S_FALSE;
929
930     res = CreateBindCtx(0,&bind);
931     if(FAILED(res))
932         return res;
933
934     res = S_FALSE;
935     if(SUCCEEDED(IMoniker_GetDisplayName(pmkOtherMoniker,bind,NULL,&urlPath))) {
936         int result = lstrcmpiW(urlPath, This->URLName);
937         CoTaskMemFree(urlPath);
938         if(result == 0)
939             res = S_OK;
940     }
941     IUnknown_Release(bind);
942     return res;
943 }
944
945
946 /******************************************************************************
947  *        URLMoniker_Hash
948  ******************************************************************************/
949 static HRESULT WINAPI URLMonikerImpl_Hash(IMoniker* iface,DWORD* pdwHash)
950 {
951     URLMonikerImpl *This = (URLMonikerImpl *)iface;
952     
953     int  h = 0,i,skip,len;
954     int  off = 0;
955     LPOLESTR val;
956
957     TRACE("(%p,%p)\n",This,pdwHash);
958
959     if(!pdwHash)
960         return E_INVALIDARG;
961
962     val = This->URLName;
963     len = lstrlenW(val);
964
965     if(len < 16) {
966         for(i = len ; i > 0; i--) {
967             h = (h * 37) + val[off++];
968         }
969     }
970     else {
971         /* only sample some characters */
972         skip = len / 8;
973         for(i = len; i > 0; i -= skip, off += skip) {
974             h = (h * 39) + val[off];
975         }
976     }
977     *pdwHash = h;
978     return S_OK;
979 }
980
981 /******************************************************************************
982  *        URLMoniker_IsRunning
983  ******************************************************************************/
984 static HRESULT WINAPI URLMonikerImpl_IsRunning(IMoniker* iface,
985                                                IBindCtx* pbc,
986                                                IMoniker* pmkToLeft,
987                                                IMoniker* pmkNewlyRunning)
988 {
989     URLMonikerImpl *This = (URLMonikerImpl *)iface;
990     FIXME("(%p)->(%p,%p,%p): stub\n",This,pbc,pmkToLeft,pmkNewlyRunning);
991
992     return E_NOTIMPL;
993 }
994
995 /******************************************************************************
996  *        URLMoniker_GetTimeOfLastChange
997  ******************************************************************************/
998 static HRESULT WINAPI URLMonikerImpl_GetTimeOfLastChange(IMoniker* iface,
999                                                          IBindCtx* pbc,
1000                                                          IMoniker* pmkToLeft,
1001                                                          FILETIME* pFileTime)
1002 {
1003     URLMonikerImpl *This = (URLMonikerImpl *)iface;
1004     FIXME("(%p)->(%p,%p,%p): stub\n",This,pbc,pmkToLeft,pFileTime);
1005
1006     return E_NOTIMPL;
1007 }
1008
1009 /******************************************************************************
1010  *        URLMoniker_Inverse
1011  ******************************************************************************/
1012 static HRESULT WINAPI URLMonikerImpl_Inverse(IMoniker* iface,IMoniker** ppmk)
1013 {
1014     URLMonikerImpl *This = (URLMonikerImpl *)iface;
1015     TRACE("(%p,%p)\n",This,ppmk);
1016
1017     return MK_E_NOINVERSE;
1018 }
1019
1020 /******************************************************************************
1021  *        URLMoniker_CommonPrefixWith
1022  ******************************************************************************/
1023 static HRESULT WINAPI URLMonikerImpl_CommonPrefixWith(IMoniker* iface,IMoniker* pmkOther,IMoniker** ppmkPrefix)
1024 {
1025     URLMonikerImpl *This = (URLMonikerImpl *)iface;
1026     FIXME("(%p)->(%p,%p): stub\n",This,pmkOther,ppmkPrefix);
1027
1028     return E_NOTIMPL;
1029 }
1030
1031 /******************************************************************************
1032  *        URLMoniker_RelativePathTo
1033  ******************************************************************************/
1034 static HRESULT WINAPI URLMonikerImpl_RelativePathTo(IMoniker* iface,IMoniker* pmOther, IMoniker** ppmkRelPath)
1035 {
1036     URLMonikerImpl *This = (URLMonikerImpl *)iface;
1037     FIXME("(%p)->(%p,%p): stub\n",This,pmOther,ppmkRelPath);
1038
1039     return E_NOTIMPL;
1040 }
1041
1042 /******************************************************************************
1043  *        URLMoniker_GetDisplayName
1044  ******************************************************************************/
1045 static HRESULT WINAPI URLMonikerImpl_GetDisplayName(IMoniker* iface,
1046                                                     IBindCtx* pbc,
1047                                                     IMoniker* pmkToLeft,
1048                                                     LPOLESTR *ppszDisplayName)
1049 {
1050     URLMonikerImpl *This = (URLMonikerImpl *)iface;
1051     
1052     int len;
1053     
1054     TRACE("(%p,%p,%p,%p)\n",This,pbc,pmkToLeft,ppszDisplayName);
1055     
1056     if(!ppszDisplayName)
1057         return E_INVALIDARG;
1058     
1059     /* FIXME: If this is a partial URL, try and get a URL moniker from SZ_URLCONTEXT in the bind context,
1060         then look at pmkToLeft to try and complete the URL
1061     */
1062     len = lstrlenW(This->URLName)+1;
1063     *ppszDisplayName = CoTaskMemAlloc(len*sizeof(WCHAR));
1064     if(!*ppszDisplayName)
1065         return E_OUTOFMEMORY;
1066     lstrcpyW(*ppszDisplayName, This->URLName);
1067     return S_OK;
1068 }
1069
1070 /******************************************************************************
1071  *        URLMoniker_ParseDisplayName
1072  ******************************************************************************/
1073 static HRESULT WINAPI URLMonikerImpl_ParseDisplayName(IMoniker* iface,
1074                                                       IBindCtx* pbc,
1075                                                       IMoniker* pmkToLeft,
1076                                                       LPOLESTR pszDisplayName,
1077                                                       ULONG* pchEaten,
1078                                                       IMoniker** ppmkOut)
1079 {
1080     URLMonikerImpl *This = (URLMonikerImpl *)iface;
1081     FIXME("(%p)->(%p,%p,%p,%p,%p): stub\n",This,pbc,pmkToLeft,pszDisplayName,pchEaten,ppmkOut);
1082
1083     return E_NOTIMPL;
1084 }
1085
1086 /******************************************************************************
1087  *        URLMoniker_IsSystemMoniker
1088  ******************************************************************************/
1089 static HRESULT WINAPI URLMonikerImpl_IsSystemMoniker(IMoniker* iface,DWORD* pwdMksys)
1090 {
1091     URLMonikerImpl *This = (URLMonikerImpl *)iface;
1092     TRACE("(%p,%p)\n",This,pwdMksys);
1093
1094     if(!pwdMksys)
1095         return E_INVALIDARG;
1096
1097     *pwdMksys = MKSYS_URLMONIKER;
1098     return S_OK;
1099 }
1100
1101 /********************************************************************************/
1102 /* Virtual function table for the URLMonikerImpl class which  include IPersist,*/
1103 /* IPersistStream and IMoniker functions.                                       */
1104 static const IMonikerVtbl VT_URLMonikerImpl =
1105 {
1106     URLMonikerImpl_QueryInterface,
1107     URLMonikerImpl_AddRef,
1108     URLMonikerImpl_Release,
1109     URLMonikerImpl_GetClassID,
1110     URLMonikerImpl_IsDirty,
1111     URLMonikerImpl_Load,
1112     URLMonikerImpl_Save,
1113     URLMonikerImpl_GetSizeMax,
1114     URLMonikerImpl_BindToObject,
1115     URLMonikerImpl_BindToStorage,
1116     URLMonikerImpl_Reduce,
1117     URLMonikerImpl_ComposeWith,
1118     URLMonikerImpl_Enum,
1119     URLMonikerImpl_IsEqual,
1120     URLMonikerImpl_Hash,
1121     URLMonikerImpl_IsRunning,
1122     URLMonikerImpl_GetTimeOfLastChange,
1123     URLMonikerImpl_Inverse,
1124     URLMonikerImpl_CommonPrefixWith,
1125     URLMonikerImpl_RelativePathTo,
1126     URLMonikerImpl_GetDisplayName,
1127     URLMonikerImpl_ParseDisplayName,
1128     URLMonikerImpl_IsSystemMoniker
1129 };
1130
1131 /******************************************************************************
1132  *         URLMoniker_Construct (local function)
1133  *******************************************************************************/
1134 static HRESULT URLMonikerImpl_Construct(URLMonikerImpl* This, LPCOLESTR lpszLeftURLName, LPCOLESTR lpszURLName)
1135 {
1136     HRESULT hres;
1137     DWORD sizeStr = INTERNET_MAX_URL_LENGTH;
1138
1139     TRACE("(%p,%s,%s)\n",This,debugstr_w(lpszLeftURLName),debugstr_w(lpszURLName));
1140     memset(This, 0, sizeof(*This));
1141
1142     /* Initialize the virtual function table. */
1143     This->lpvtbl = &VT_URLMonikerImpl;
1144     This->ref = 0;
1145
1146     if(lpszLeftURLName) {
1147         hres = UrlCombineW(lpszLeftURLName, lpszURLName, NULL, &sizeStr, 0);
1148         if(FAILED(hres)) {
1149             return hres;
1150         }
1151         sizeStr++;
1152     }
1153     else
1154         sizeStr = lstrlenW(lpszURLName)+1;
1155
1156     This->URLName=HeapAlloc(GetProcessHeap(),0,sizeof(WCHAR)*(sizeStr));
1157
1158     if (This->URLName==NULL)
1159         return E_OUTOFMEMORY;
1160
1161     if(lpszLeftURLName) {
1162         hres = UrlCombineW(lpszLeftURLName, lpszURLName, This->URLName, &sizeStr, 0);
1163         if(FAILED(hres)) {
1164             HeapFree(GetProcessHeap(), 0, This->URLName);
1165             return hres;
1166         }
1167     }
1168     else
1169         strcpyW(This->URLName,lpszURLName);
1170
1171     URLMON_LockModule();
1172
1173     return S_OK;
1174 }
1175
1176 /***********************************************************************
1177  *           CreateAsyncBindCtx (URLMON.@)
1178  */
1179 HRESULT WINAPI CreateAsyncBindCtx(DWORD reserved, IBindStatusCallback *callback,
1180     IEnumFORMATETC *format, IBindCtx **pbind)
1181 {
1182     TRACE("(%08lx %p %p %p)\n", reserved, callback, format, pbind);
1183
1184     if(!callback)
1185         return E_INVALIDARG;
1186
1187     return CreateAsyncBindCtxEx(NULL, 0, callback, format, pbind, 0);
1188 }
1189 /***********************************************************************
1190  *           CreateAsyncBindCtxEx (URLMON.@)
1191  *
1192  * Create an asynchronous bind context.
1193  */ 
1194 HRESULT WINAPI CreateAsyncBindCtxEx(IBindCtx *ibind, DWORD options,
1195     IBindStatusCallback *callback, IEnumFORMATETC *format, IBindCtx** pbind,
1196     DWORD reserved)
1197 {
1198     HRESULT hres;
1199     BIND_OPTS bindopts;
1200     IBindCtx *bctx;
1201
1202     TRACE("(%p %08lx %p %p %p %ld)\n", ibind, options, callback, format, pbind, reserved);
1203
1204     if(!pbind)
1205         return E_INVALIDARG;
1206
1207     if(options)
1208         FIXME("not supported options %08lx", options);
1209     if(format)
1210         FIXME("format is not supported\n");
1211
1212     if(reserved)
1213         WARN("reserved=%ld\n", reserved);
1214
1215     hres = CreateBindCtx(0, &bctx);
1216     if(FAILED(hres))
1217         return hres;
1218
1219     bindopts.cbStruct = sizeof(BIND_OPTS);
1220     bindopts.grfFlags = BIND_MAYBOTHERUSER;
1221     bindopts.grfMode = STGM_READWRITE | STGM_SHARE_EXCLUSIVE;
1222     bindopts.dwTickCountDeadline = 0;
1223     IBindCtx_SetBindOptions(bctx, &bindopts);
1224
1225     if(callback)
1226         RegisterBindStatusCallback(bctx, callback, NULL, 0);
1227
1228     *pbind = bctx;
1229
1230     return S_OK;
1231 }
1232
1233
1234 /***********************************************************************
1235  *           CreateURLMoniker (URLMON.@)
1236  *
1237  * Create a url moniker.
1238  *
1239  * PARAMS
1240  *    pmkContext [I] Context
1241  *    szURL      [I] Url to create the moniker for
1242  *    ppmk       [O] Destination for created moniker.
1243  *
1244  * RETURNS
1245  *    Success: S_OK. ppmk contains the created IMoniker object.
1246  *    Failure: MK_E_SYNTAX if szURL is not a valid url, or
1247  *             E_OUTOFMEMORY if memory allocation fails.
1248  */
1249 HRESULT WINAPI CreateURLMoniker(IMoniker *pmkContext, LPCWSTR szURL, IMoniker **ppmk)
1250 {
1251     URLMonikerImpl *obj;
1252     HRESULT hres;
1253     IID iid = IID_IMoniker;
1254     LPOLESTR lefturl = NULL;
1255
1256     TRACE("(%p, %s, %p)\n", pmkContext, debugstr_w(szURL), ppmk);
1257
1258     if(!(obj = HeapAlloc(GetProcessHeap(), 0, sizeof(*obj))))
1259         return E_OUTOFMEMORY;
1260
1261     if(pmkContext) {
1262         IBindCtx* bind;
1263         DWORD dwMksys = 0;
1264         IMoniker_IsSystemMoniker(pmkContext, &dwMksys);
1265         if(dwMksys == MKSYS_URLMONIKER && SUCCEEDED(CreateBindCtx(0, &bind))) {
1266             IMoniker_GetDisplayName(pmkContext, bind, NULL, &lefturl);
1267             TRACE("lefturl = %s\n", debugstr_w(lefturl));
1268             IBindCtx_Release(bind);
1269         }
1270     }
1271         
1272     hres = URLMonikerImpl_Construct(obj, lefturl, szURL);
1273     CoTaskMemFree(lefturl);
1274     if(SUCCEEDED(hres))
1275         hres = URLMonikerImpl_QueryInterface((IMoniker*)obj, &iid, (void**)ppmk);
1276     else
1277         HeapFree(GetProcessHeap(), 0, obj);
1278     return hres;
1279 }
1280
1281 /***********************************************************************
1282  *           CoInternetQueryInfo (URLMON.@)
1283  *
1284  * Retrieves information relevant to a specified URL
1285  *
1286  * RETURNS
1287  *    S_OK                      success
1288  *    S_FALSE                   buffer too small
1289  *    INET_E_QUERYOPTIONUNKNOWN invalid option
1290  *
1291  */
1292 HRESULT WINAPI CoInternetQueryInfo(LPCWSTR pwzUrl, QUERYOPTION QueryOption,
1293   DWORD dwQueryFlags, LPVOID pvBuffer, DWORD cbBuffer, DWORD * pcbBuffer,
1294   DWORD dwReserved)
1295 {
1296   FIXME("(%s, %x, %lx, %p, %lx, %p, %lx): stub\n", debugstr_w(pwzUrl),
1297     QueryOption, dwQueryFlags, pvBuffer, cbBuffer, pcbBuffer, dwReserved);
1298   return S_OK;
1299 }
1300
1301 /***********************************************************************
1302  *           IsAsyncMoniker (URLMON.@)
1303  */
1304 HRESULT WINAPI IsAsyncMoniker(IMoniker *pmk)
1305 {
1306     IUnknown *am;
1307     
1308     TRACE("(%p)\n", pmk);
1309     if(!pmk)
1310         return E_INVALIDARG;
1311     if(SUCCEEDED(IMoniker_QueryInterface(pmk, &IID_IAsyncMoniker, (void**)&am))) {
1312         IUnknown_Release(am);
1313         return S_OK;
1314     }
1315     return S_FALSE;
1316 }
1317
1318 /***********************************************************************
1319  *           RegisterBindStatusCallback (URLMON.@)
1320  *
1321  * Register a bind status callback.
1322  *
1323  * PARAMS
1324  *  pbc           [I] Binding context
1325  *  pbsc          [I] Callback to register
1326  *  ppbscPrevious [O] Destination for previous callback
1327  *  dwReserved    [I] Reserved, must be 0.
1328  *
1329  * RETURNS
1330  *    Success: S_OK.
1331  *    Failure: E_INVALIDARG, if any argument is invalid, or
1332  *             E_OUTOFMEMORY if memory allocation fails.
1333  */
1334 HRESULT WINAPI RegisterBindStatusCallback(
1335     IBindCtx *pbc,
1336     IBindStatusCallback *pbsc,
1337     IBindStatusCallback **ppbscPrevious,
1338     DWORD dwReserved)
1339 {
1340     IBindStatusCallback *prev;
1341
1342     TRACE("(%p,%p,%p,%lu)\n", pbc, pbsc, ppbscPrevious, dwReserved);
1343
1344     if (pbc == NULL || pbsc == NULL)
1345         return E_INVALIDARG;
1346
1347     if (SUCCEEDED(IBindCtx_GetObjectParam(pbc, (LPOLESTR)BSCBHolder, (IUnknown **)&prev)))
1348     {
1349         IBindCtx_RevokeObjectParam(pbc, (LPOLESTR)BSCBHolder);
1350         if (ppbscPrevious)
1351             *ppbscPrevious = prev;
1352         else
1353             IBindStatusCallback_Release(prev);
1354     }
1355
1356     return IBindCtx_RegisterObjectParam(pbc, (LPOLESTR)BSCBHolder, (IUnknown *)pbsc);
1357 }
1358
1359 /***********************************************************************
1360  *           RevokeBindStatusCallback (URLMON.@)
1361  *
1362  * Unregister a bind status callback.
1363  *
1364  *  pbc           [I] Binding context
1365  *  pbsc          [I] Callback to unregister
1366  *
1367  * RETURNS
1368  *    Success: S_OK.
1369  *    Failure: E_INVALIDARG, if any argument is invalid, or
1370  *             E_FAIL if pbsc wasn't registered with pbc.
1371  */
1372 HRESULT WINAPI RevokeBindStatusCallback(
1373     IBindCtx *pbc,
1374     IBindStatusCallback *pbsc)
1375 {
1376     IBindStatusCallback *callback;
1377     HRESULT hr = E_FAIL;
1378
1379         TRACE("(%p,%p)\n", pbc, pbsc);
1380
1381     if (pbc == NULL || pbsc == NULL)
1382         return E_INVALIDARG;
1383
1384     if (SUCCEEDED(IBindCtx_GetObjectParam(pbc, (LPOLESTR)BSCBHolder, (IUnknown **)&callback)))
1385     {
1386         if (callback == pbsc)
1387         {
1388             IBindCtx_RevokeObjectParam(pbc, (LPOLESTR)BSCBHolder);
1389             hr = S_OK;
1390         }
1391         IBindStatusCallback_Release(pbsc);
1392     }
1393
1394     return hr;
1395 }
1396
1397 /***********************************************************************
1398  *           URLDownloadToFileA (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 URLDownloadToFileA(LPUNKNOWN pCaller,
1415                                   LPCSTR szURL,
1416                                   LPCSTR szFileName,
1417                                   DWORD dwReserved,
1418                                   LPBINDSTATUSCALLBACK lpfnCB)
1419 {
1420     UNICODE_STRING szURL_w, szFileName_w;
1421
1422     if ((szURL == NULL) || (szFileName == NULL)) {
1423         FIXME("(%p,%s,%s,%08lx,%p) cannot accept NULL strings !\n", pCaller, debugstr_a(szURL), debugstr_a(szFileName), dwReserved, lpfnCB);
1424         return E_INVALIDARG; /* The error code is not specified in this case... */
1425     }
1426     
1427     if (RtlCreateUnicodeStringFromAsciiz(&szURL_w, szURL)) {
1428         if (RtlCreateUnicodeStringFromAsciiz(&szFileName_w, szFileName)) {
1429             HRESULT ret = URLDownloadToFileW(pCaller, szURL_w.Buffer, szFileName_w.Buffer, dwReserved, lpfnCB);
1430
1431             RtlFreeUnicodeString(&szURL_w);
1432             RtlFreeUnicodeString(&szFileName_w);
1433             
1434             return ret;
1435         } else {
1436             RtlFreeUnicodeString(&szURL_w);
1437         }
1438     }
1439     
1440     FIXME("(%p,%s,%s,%08lx,%p) could not allocate W strings !\n", pCaller, szURL, szFileName, dwReserved, lpfnCB);
1441     return E_OUTOFMEMORY;
1442 }
1443
1444 /***********************************************************************
1445  *           URLDownloadToFileW (URLMON.@)
1446  *
1447  * Downloads URL szURL to rile szFileName and call lpfnCB callback to
1448  * report progress.
1449  *
1450  * PARAMS
1451  *  pCaller    [I] controlling IUnknown interface.
1452  *  szURL      [I] URL of the file to download
1453  *  szFileName [I] file name to store the content of the URL
1454  *  dwReserved [I] reserved - set to 0
1455  *  lpfnCB     [I] callback for progress report
1456  *
1457  * RETURNS
1458  *  S_OK on success
1459  *  E_OUTOFMEMORY when going out of memory
1460  */
1461 HRESULT WINAPI URLDownloadToFileW(LPUNKNOWN pCaller,
1462                                   LPCWSTR szURL,
1463                                   LPCWSTR szFileName,
1464                                   DWORD dwReserved,
1465                                   LPBINDSTATUSCALLBACK lpfnCB)
1466 {
1467     HINTERNET hinternet, hcon, hreq;
1468     BOOL r;
1469     CHAR buffer[0x1000];
1470     DWORD sz, total, written;
1471     DWORD total_size = 0xFFFFFFFF, arg_size = sizeof(total_size);
1472     URL_COMPONENTSW url;
1473     WCHAR host[0x80], path[0x100];
1474     HANDLE hfile;
1475     static const WCHAR wszAppName[]={'u','r','l','m','o','n','.','d','l','l',0};
1476
1477     /* Note: all error codes would need to be checked agains real Windows behaviour... */
1478     TRACE("(%p,%s,%s,%08lx,%p) stub!\n", pCaller, debugstr_w(szURL), debugstr_w(szFileName), dwReserved, lpfnCB);
1479
1480     if ((szURL == NULL) || (szFileName == NULL)) {
1481         FIXME(" cannot accept NULL strings !\n");
1482         return E_INVALIDARG;
1483     }
1484
1485     /* Would be better to use the application name here rather than 'urlmon' :-/ */
1486     hinternet = InternetOpenW(wszAppName, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
1487     if (hinternet == NULL) {
1488         return E_OUTOFMEMORY;
1489     }                                                                                                                             
1490
1491     memset(&url, 0, sizeof(url));
1492     url.dwStructSize = sizeof(url);
1493     url.lpszHostName = host;
1494     url.dwHostNameLength = sizeof(host);
1495     url.lpszUrlPath = path;
1496     url.dwUrlPathLength = sizeof(path);
1497
1498     if (!InternetCrackUrlW(szURL, 0, 0, &url)) {
1499         InternetCloseHandle(hinternet);
1500         return E_OUTOFMEMORY;
1501     }
1502
1503     if (lpfnCB) {
1504         if (IBindStatusCallback_OnProgress(lpfnCB, 0, 0, BINDSTATUS_CONNECTING, url.lpszHostName) == E_ABORT) {
1505             InternetCloseHandle(hinternet);
1506             return S_OK;
1507         }
1508     }
1509     
1510     hcon = InternetConnectW(hinternet, url.lpszHostName, url.nPort,
1511                             url.lpszUserName, url.lpszPassword,
1512                             INTERNET_SERVICE_HTTP, 0, 0);
1513     if (!hcon) {
1514         InternetCloseHandle(hinternet);
1515         return E_OUTOFMEMORY;
1516     }
1517     
1518     hreq = HttpOpenRequestW(hcon, NULL, url.lpszUrlPath, NULL, NULL, NULL, 0, 0);
1519     if (!hreq) {
1520         InternetCloseHandle(hinternet);
1521         InternetCloseHandle(hcon);
1522         return E_OUTOFMEMORY;
1523     }                                                                                                                             
1524
1525     if (!HttpSendRequestW(hreq, NULL, 0, NULL, 0)) {
1526         InternetCloseHandle(hinternet);
1527         InternetCloseHandle(hcon);
1528         InternetCloseHandle(hreq);
1529         return E_OUTOFMEMORY;
1530     }
1531     
1532     if (HttpQueryInfoW(hreq, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER,
1533                        &total_size, &arg_size, NULL)) {
1534         TRACE(" total size : %ld\n", total_size);
1535     }
1536     
1537     hfile = CreateFileW(szFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
1538                         FILE_ATTRIBUTE_NORMAL, NULL );
1539     if (hfile == INVALID_HANDLE_VALUE) {
1540         return E_ACCESSDENIED;
1541     }
1542     
1543     if (lpfnCB) {
1544         if (IBindStatusCallback_OnProgress(lpfnCB, 0, total_size != 0xFFFFFFFF ? total_size : 0,
1545                                            BINDSTATUS_BEGINDOWNLOADDATA, szURL) == E_ABORT) {
1546             InternetCloseHandle(hreq);
1547             InternetCloseHandle(hcon);
1548             InternetCloseHandle(hinternet);
1549             CloseHandle(hfile);
1550             return S_OK;
1551         }
1552     }
1553     
1554     total = 0;
1555     while (1) {
1556         r = InternetReadFile(hreq, buffer, sizeof(buffer), &sz);
1557         if (!r) {
1558             InternetCloseHandle(hreq);
1559             InternetCloseHandle(hcon);
1560             InternetCloseHandle(hinternet);
1561             
1562             CloseHandle(hfile);
1563             return E_OUTOFMEMORY;           
1564         }
1565         if (!sz)
1566             break;
1567         
1568         total += sz;
1569
1570         if (lpfnCB) {
1571             if (IBindStatusCallback_OnProgress(lpfnCB, total, total_size != 0xFFFFFFFF ? total_size : 0,
1572                                                BINDSTATUS_DOWNLOADINGDATA, szURL) == E_ABORT) {
1573                 InternetCloseHandle(hreq);
1574                 InternetCloseHandle(hcon);
1575                 InternetCloseHandle(hinternet);
1576                 CloseHandle(hfile);
1577                 return S_OK;
1578             }
1579         }
1580         
1581         if (!WriteFile(hfile, buffer, sz, &written, NULL)) {
1582             InternetCloseHandle(hreq);
1583             InternetCloseHandle(hcon);
1584             InternetCloseHandle(hinternet);
1585             
1586             CloseHandle(hfile);
1587             return E_OUTOFMEMORY;
1588         }
1589     }
1590
1591     if (lpfnCB) {
1592         if (IBindStatusCallback_OnProgress(lpfnCB, total, total_size != 0xFFFFFFFF ? total_size : 0,
1593                                            BINDSTATUS_ENDDOWNLOADDATA, szURL) == E_ABORT) {
1594             InternetCloseHandle(hreq);
1595             InternetCloseHandle(hcon);
1596             InternetCloseHandle(hinternet);
1597             CloseHandle(hfile);
1598             return S_OK;
1599         }
1600     }
1601     
1602     InternetCloseHandle(hreq);
1603     InternetCloseHandle(hcon);
1604     InternetCloseHandle(hinternet);
1605     
1606     CloseHandle(hfile);
1607
1608     return S_OK;
1609 }
1610
1611 /***********************************************************************
1612  *           HlinkSimpleNavigateToString (URLMON.@)
1613  */
1614 HRESULT WINAPI HlinkSimpleNavigateToString( LPCWSTR szTarget,
1615     LPCWSTR szLocation, LPCWSTR szTargetFrameName, IUnknown *pUnk,
1616     IBindCtx *pbc, IBindStatusCallback *pbsc, DWORD grfHLNF, DWORD dwReserved)
1617 {
1618     FIXME("%s\n", debugstr_w( szTarget ) );
1619     return E_NOTIMPL;
1620 }
1621
1622 /***********************************************************************
1623  *           HlinkNavigateString (URLMON.@)
1624  */
1625 HRESULT WINAPI HlinkNavigateString( IUnknown *pUnk, LPCWSTR szTarget )
1626 {
1627     TRACE("%p %s\n", pUnk, debugstr_w( szTarget ) );
1628     return HlinkSimpleNavigateToString( 
1629                szTarget, NULL, NULL, pUnk, NULL, NULL, 0, 0 );
1630 }
1631
1632 /***********************************************************************
1633  *           GetSoftwareUpdateInfo (URLMON.@)
1634  */
1635 HRESULT WINAPI GetSoftwareUpdateInfo( LPCWSTR szDistUnit, LPSOFTDISTINFO psdi )
1636 {
1637     FIXME("%s %p\n", debugstr_w(szDistUnit), psdi );
1638     return E_FAIL;
1639 }