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