Allocate space for terminating null.
[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 /* filemoniker data structure */
52 typedef struct URLMonikerImpl{
53
54     IMonikerVtbl*  lpvtbl1;  /* VTable relative to the IMoniker interface.*/
55     IBindingVtbl*  lpvtbl2;  /* VTable to IBinding interface */
56
57     ULONG ref; /* reference counter for this object */
58
59     LPOLESTR URLName; /* URL string identified by this URLmoniker */
60
61     HWND hwndCallback;
62     IBindCtx *pBC;
63     HINTERNET hinternet, hconnect, hrequest;
64 } URLMonikerImpl;
65
66 /*******************************************************************************
67  *        URLMoniker_QueryInterface
68  *******************************************************************************/
69 static HRESULT WINAPI URLMonikerImpl_QueryInterface(IMoniker* iface,REFIID riid,void** ppvObject)
70 {
71     URLMonikerImpl *This = (URLMonikerImpl *)iface;
72
73     TRACE("(%p)->(%s,%p)\n",This,debugstr_guid(riid),ppvObject);
74
75     /* Perform a sanity check on the parameters.*/
76     if ( (This==0) || (ppvObject==0) )
77         return E_INVALIDARG;
78
79     /* Initialize the return parameter */
80     *ppvObject = 0;
81
82     /* Compare the riid with the interface IDs implemented by this object.*/
83     if (IsEqualIID(&IID_IUnknown, riid)      ||
84         IsEqualIID(&IID_IPersist, riid)      ||
85         IsEqualIID(&IID_IPersistStream,riid) ||
86         IsEqualIID(&IID_IMoniker, riid)
87        )
88         *ppvObject = iface;
89
90     /* Check that we obtained an interface.*/
91     if ((*ppvObject)==0)
92         return E_NOINTERFACE;
93
94     /* Query Interface always increases the reference count by one when it is successful */
95     IMoniker_AddRef(iface);
96
97     return S_OK;
98 }
99
100 /******************************************************************************
101  *        URLMoniker_AddRef
102  ******************************************************************************/
103 static ULONG WINAPI URLMonikerImpl_AddRef(IMoniker* iface)
104 {
105     URLMonikerImpl *This = (URLMonikerImpl *)iface;
106     ULONG refCount = InterlockedIncrement(&This->ref);
107
108     TRACE("(%p)->(ref before=%lu)\n",This, refCount - 1);
109
110     URLMON_LockModule();
111
112     return refCount;
113 }
114
115 /******************************************************************************
116  *        URLMoniker_Release
117  ******************************************************************************/
118 static ULONG WINAPI URLMonikerImpl_Release(IMoniker* iface)
119 {
120     URLMonikerImpl *This = (URLMonikerImpl *)iface;
121     ULONG refCount = InterlockedDecrement(&This->ref);
122
123     TRACE("(%p)->(ref before=%lu)\n",This, refCount + 1);
124
125     /* destroy the object if there's no more reference on it */
126     if (!refCount) {
127         HeapFree(GetProcessHeap(),0,This->URLName);
128         HeapFree(GetProcessHeap(),0,This);
129     }
130
131     URLMON_UnlockModule();
132
133     return refCount;
134 }
135
136 /******************************************************************************
137  *        URLMoniker_GetClassID
138  ******************************************************************************/
139 static HRESULT WINAPI URLMonikerImpl_GetClassID(IMoniker* iface,
140                                                 CLSID *pClassID)/* Pointer to CLSID of object */
141 {
142     URLMonikerImpl *This = (URLMonikerImpl *)iface;
143
144     TRACE("(%p,%p)\n",This,pClassID);
145
146     if (pClassID==NULL)
147         return E_POINTER;
148     /* Windows always returns CLSID_StdURLMoniker */
149     *pClassID = CLSID_StdURLMoniker;
150     return S_OK;
151 }
152
153 /******************************************************************************
154  *        URLMoniker_IsDirty
155  ******************************************************************************/
156 static HRESULT WINAPI URLMonikerImpl_IsDirty(IMoniker* iface)
157 {
158     URLMonikerImpl *This = (URLMonikerImpl *)iface;
159     /* Note that the OLE-provided implementations of the IPersistStream::IsDirty
160        method in the OLE-provided moniker interfaces always return S_FALSE because
161        their internal state never changes. */
162
163     TRACE("(%p)\n",This);
164
165     return S_FALSE;
166 }
167
168 /******************************************************************************
169  *        URLMoniker_Load
170  *
171  * NOTE
172  *  Writes a ULONG containing length of unicode string, followed
173  *  by that many unicode characters
174  ******************************************************************************/
175 static HRESULT WINAPI URLMonikerImpl_Load(IMoniker* iface,IStream* pStm)
176 {
177     URLMonikerImpl *This = (URLMonikerImpl *)iface;
178     
179     HRESULT res;
180     ULONG len;
181     ULONG got;
182     TRACE("(%p,%p)\n",This,pStm);
183
184     if(!pStm)
185         return E_INVALIDARG;
186
187     res = IStream_Read(pStm, &len, sizeof(ULONG), &got);
188     if(SUCCEEDED(res)) {
189         if(got == sizeof(ULONG)) {
190             HeapFree(GetProcessHeap(), 0, This->URLName);
191             This->URLName=HeapAlloc(GetProcessHeap(),0,sizeof(WCHAR)*(len+1));
192             if(!This->URLName)
193                 res = E_OUTOFMEMORY;
194             else {
195                 res = IStream_Read(pStm, This->URLName, len, NULL);
196                 This->URLName[len] = 0;
197             }
198         }
199         else
200             res = E_FAIL;
201     }
202     return res;
203 }
204
205 /******************************************************************************
206  *        URLMoniker_Save
207  ******************************************************************************/
208 static HRESULT WINAPI URLMonikerImpl_Save(IMoniker* iface,
209                                           IStream* pStm,/* pointer to the stream where the object is to be saved */
210                                           BOOL fClearDirty)/* Specifies whether to clear the dirty flag */
211 {
212     URLMonikerImpl *This = (URLMonikerImpl *)iface;
213
214     HRESULT res;
215     ULONG len;
216     TRACE("(%p,%p,%d)\n",This,pStm,fClearDirty);
217
218     if(!pStm)
219         return E_INVALIDARG;
220
221     len = strlenW(This->URLName);
222     res=IStream_Write(pStm,&len,sizeof(ULONG),NULL);
223     if(SUCCEEDED(res))
224         res=IStream_Write(pStm,&This->URLName,len*sizeof(WCHAR),NULL);
225     return res;
226
227 }
228
229 /******************************************************************************
230  *        URLMoniker_GetSizeMax
231  ******************************************************************************/
232 static HRESULT WINAPI URLMonikerImpl_GetSizeMax(IMoniker* iface,
233                                                 ULARGE_INTEGER* pcbSize)/* Pointer to size of stream needed to save object */
234 {
235     URLMonikerImpl *This = (URLMonikerImpl *)iface;
236
237     TRACE("(%p,%p)\n",This,pcbSize);
238
239     if(!pcbSize)
240         return E_INVALIDARG;
241
242     pcbSize->u.LowPart = sizeof(ULONG) + (strlenW(This->URLName) * sizeof(WCHAR));
243     pcbSize->u.HighPart = 0;
244     return S_OK;
245 }
246
247 /******************************************************************************
248  *                  URLMoniker_BindToObject
249  ******************************************************************************/
250 static HRESULT WINAPI URLMonikerImpl_BindToObject(IMoniker* iface,
251                                                   IBindCtx* pbc,
252                                                   IMoniker* pmkToLeft,
253                                                   REFIID riid,
254                                                   VOID** ppvResult)
255 {
256     URLMonikerImpl *This = (URLMonikerImpl *)iface;
257
258     *ppvResult=0;
259
260     FIXME("(%p)->(%p,%p,%s,%p): stub\n",This,pbc,pmkToLeft,debugstr_guid(riid),
261           ppvResult);
262
263     return E_NOTIMPL;
264 }
265
266 typedef struct {
267     enum {OnProgress, OnDataAvailable} callback;
268 } URLMON_CallbackData;
269
270
271 #if 0
272 static LRESULT CALLBACK URLMON_WndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
273 {
274     return DefWindowProcA(hwnd, msg, wparam, lparam);
275 }
276
277 static void PostOnProgress(URLMonikerImpl *This, UINT progress, UINT maxprogress, DWORD status, LPCWSTR *str)
278 {
279 }
280
281 static void CALLBACK URLMON_InternetCallback(HINTERNET hinet, /*DWORD_PTR*/ DWORD context, DWORD status,
282                                              void *status_info, DWORD status_info_len)
283 {
284     URLMonikerImpl *This = (URLMonikerImpl *)context;
285     TRACE("handle %p this %p status %08lx\n", hinet, This, status);
286
287     if(This->filesize == -1) {
288         switch(status) {
289         case INTERNET_STATUS_RESOLVING_NAME:
290             PostOnProgess(This, 0, 0, BINDSTATUS_FINDINGRESOURCE, status_info);
291             break;
292         case INTERNET_STATUS_CONNECTING_TO_SERVER:
293             PostOnProgress(This, 0, 0, BINDSTATUS_CONNECTING, NULL);
294             break;
295         case INTERNET_STATUS_SENDING_REQUEST:
296             PostOnProgress(This, 0, 0, BINDSTATUS_SENDINGREQUEST, NULL);
297             break;
298         case INTERNET_REQUEST_COMPLETE:
299           {
300               DWORD len, lensz = sizeof(len);
301
302             HttpQueryInfoW(hrequest, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &len, &lensz, NULL);
303             TRACE("res = %ld gle = %08lx url len = %ld\n", hres, GetLastError(), len);
304             This->filesize = len;
305             break;
306           }
307         }
308     }
309
310     return;
311 }
312 #endif
313 /******************************************************************************
314  *        URLMoniker_BindToStorage
315  ******************************************************************************/
316 static HRESULT WINAPI URLMonikerImpl_BindToStorage(IMoniker* iface,
317                                                    IBindCtx* pbc,
318                                                    IMoniker* pmkToLeft,
319                                                    REFIID riid,
320                                                    VOID** ppvObject)
321 {
322     URLMonikerImpl *This = (URLMonikerImpl *)iface;
323     HRESULT hres;
324     IBindStatusCallback *pbscb;
325     BINDINFO bi;
326     DWORD bindf;
327     IStream *pstr;
328
329     FIXME("(%p)->(%p,%p,%s,%p): stub\n",This,pbc,pmkToLeft,debugstr_guid(riid),ppvObject);
330     if(pmkToLeft) {
331         FIXME("pmkToLeft != NULL\n");
332         return E_NOTIMPL;
333     }
334     if(!IsEqualIID(&IID_IStream, riid)) {
335         FIXME("unsupported iid\n");
336         return E_NOTIMPL;
337     }
338
339     /* FIXME This is a bad hack (tm).  We should clearly download to a temporary file.
340        We also need to implement IStream ourselves so that IStream_Read can return
341        E_PENDING */
342
343     hres = CreateStreamOnHGlobal(0, TRUE, &pstr);
344
345     if(SUCCEEDED(hres)) {
346         TRACE("Created dummy stream...\n");
347
348         hres = IBindCtx_GetObjectParam(pbc, (LPOLESTR)BSCBHolder, (IUnknown**)&pbscb);
349         if(SUCCEEDED(hres)) {
350             TRACE("Got IBindStatusCallback...\n");
351
352             memset(&bi, 0, sizeof(bi));
353             bi.cbSize = sizeof(bi);
354             bindf = 0;
355             hres = IBindStatusCallback_GetBindInfo(pbscb, &bindf, &bi);
356             if(SUCCEEDED(hres)) {
357                 URL_COMPONENTSW url;
358                 WCHAR *host, *path;
359                 DWORD len, lensz = sizeof(len), total_read = 0;
360                 LARGE_INTEGER last_read_pos;
361                 FORMATETC fmt;
362                 STGMEDIUM stg;
363
364                 TRACE("got bindinfo. bindf = %08lx extrainfo = %s bindinfof = %08lx bindverb = %08lx iid %s\n",
365                       bindf, debugstr_w(bi.szExtraInfo), bi.grfBindInfoF, bi.dwBindVerb, debugstr_guid(&bi.iid));
366                 hres = IBindStatusCallback_OnStartBinding(pbscb, 0, (IBinding*)&This->lpvtbl2);
367                 TRACE("OnStartBinding rets %08lx\n", hres);
368
369 #if 0
370                 if(!registered_wndclass) {
371                     WNDCLASSA urlmon_wndclass = {0, URLMON_WndProc,0, 0, URLMON_hInstance, 0, 0, 0, NULL, "URLMON_Callback_Window_Class"};
372                     RegisterClassA(&urlmon_wndclass);
373                     registered_wndclass = TRUE;
374                 }
375
376                 This->hwndCallback = CreateWindowA("URLMON_Callback_Window_Class", NULL, 0, 0, 0, 0, 0, 0, 0,
377                                                    URLMON_hInstance, NULL);
378
379 #endif
380                 memset(&url, 0, sizeof(url));
381                 url.dwStructSize = sizeof(url);
382                 url.dwSchemeLength = url.dwHostNameLength = url.dwUrlPathLength = 1;
383                 InternetCrackUrlW(This->URLName, 0, 0, &url);
384                 host = HeapAlloc(GetProcessHeap(), 0, (url.dwHostNameLength + 1) * sizeof(WCHAR));
385                 memcpy(host, url.lpszHostName, url.dwHostNameLength * sizeof(WCHAR));
386                 host[url.dwHostNameLength] = '\0';
387                 path = HeapAlloc(GetProcessHeap(), 0, (url.dwUrlPathLength + 1) * sizeof(WCHAR));
388                 memcpy(path, url.lpszUrlPath, url.dwUrlPathLength * sizeof(WCHAR));
389                 path[url.dwUrlPathLength] = '\0';
390
391                 This->hinternet = InternetOpenA("User Agent", 0, NULL, NULL, 0 /*INTERNET_FLAG_ASYNC*/);
392 /*              InternetSetStatusCallback(This->hinternet, URLMON_InternetCallback);*/
393
394                 This->hconnect = InternetConnectW(This->hinternet, host, INTERNET_DEFAULT_HTTP_PORT, NULL, NULL,
395                                                   INTERNET_SERVICE_HTTP, 0, (DWORD)This);
396                 This->hrequest = HttpOpenRequestW(This->hconnect, NULL, path, NULL, NULL, NULL, 0, (DWORD)This);
397
398                 hres = IBindStatusCallback_OnProgress(pbscb, 0, 0, 0x22, NULL);
399                 hres = IBindStatusCallback_OnProgress(pbscb, 0, 0, BINDSTATUS_FINDINGRESOURCE, NULL);
400                 hres = IBindStatusCallback_OnProgress(pbscb, 0, 0, BINDSTATUS_CONNECTING, NULL);
401                 hres = IBindStatusCallback_OnProgress(pbscb, 0, 0, BINDSTATUS_SENDINGREQUEST, NULL);
402                 hres = E_OUTOFMEMORY; /* FIXME */
403                 if(HttpSendRequestW(This->hrequest, NULL, 0, NULL, 0)) {
404                     len = 0;
405                     HttpQueryInfoW(This->hrequest, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &len, &lensz, NULL);
406
407                     TRACE("res = %ld gle = %08lx url len = %ld\n", hres, GetLastError(), len);
408
409                     last_read_pos.u.LowPart = last_read_pos.u.HighPart = 0;
410                     fmt.cfFormat = 0;
411                     fmt.ptd = NULL;
412                     fmt.dwAspect = 0;
413                     fmt.lindex = -1;
414                     fmt.tymed = TYMED_ISTREAM;
415                     stg.tymed = TYMED_ISTREAM;
416                     stg.u.pstm = pstr;
417                     stg.pUnkForRelease = NULL;
418
419                     while(1) {
420                         char buf[4096];
421                         DWORD bufread;
422                         DWORD written;
423                         if(InternetReadFile(This->hrequest, buf, sizeof(buf), &bufread)) {
424                             TRACE("read %ld bytes %s...\n", bufread, debugstr_an(buf, 10));
425                             if(bufread == 0) break;
426                             IStream_Write(pstr, buf, bufread, &written);
427                             total_read += bufread;
428                             IStream_Seek(pstr, last_read_pos, STREAM_SEEK_SET, NULL);
429                             hres = IBindStatusCallback_OnProgress(pbscb, total_read, len, (total_read == bufread) ?
430                                                                   BINDSTATUS_BEGINDOWNLOADDATA :
431                                                                   BINDSTATUS_DOWNLOADINGDATA, NULL);
432                             hres = IBindStatusCallback_OnDataAvailable(pbscb,
433                                                                        (total_read == bufread) ? BSCF_FIRSTDATANOTIFICATION :
434                                                                        BSCF_INTERMEDIATEDATANOTIFICATION,
435                                                                        total_read, &fmt, &stg);
436                             last_read_pos.u.LowPart += bufread; /* FIXME */
437                         } else
438                             break;
439                     }
440                     hres = IBindStatusCallback_OnProgress(pbscb, total_read, len, BINDSTATUS_ENDDOWNLOADDATA, NULL);
441                     hres = IBindStatusCallback_OnDataAvailable(pbscb, BSCF_LASTDATANOTIFICATION, total_read, &fmt, &stg);
442                     TRACE("OnDataAvail rets %08lx\n", hres);
443                     hres = IBindStatusCallback_OnStopBinding(pbscb, S_OK, NULL);
444                     TRACE("OnStop rets %08lx\n", hres);
445                     hres = S_OK;
446                 }
447                 InternetCloseHandle(This->hrequest);
448                 InternetCloseHandle(This->hconnect);
449                 InternetCloseHandle(This->hinternet);
450                 IBindStatusCallback_Release(pbscb);
451             }
452         }
453     }
454     *ppvObject = (VOID*)pstr;
455     return hres;
456 }
457
458 /******************************************************************************
459  *        URLMoniker_Reduce
460  ******************************************************************************/
461 static HRESULT WINAPI URLMonikerImpl_Reduce(IMoniker* iface,
462                                             IBindCtx* pbc,
463                                             DWORD dwReduceHowFar,
464                                             IMoniker** ppmkToLeft,
465                                             IMoniker** ppmkReduced)
466 {
467     URLMonikerImpl *This = (URLMonikerImpl *)iface;
468     
469     TRACE("(%p,%p,%ld,%p,%p)\n",This,pbc,dwReduceHowFar,ppmkToLeft,ppmkReduced);
470
471     if(!ppmkReduced)
472         return E_INVALIDARG;
473
474     URLMonikerImpl_AddRef(iface);
475     *ppmkReduced = iface;
476     return MK_S_REDUCED_TO_SELF;
477 }
478
479 /******************************************************************************
480  *        URLMoniker_ComposeWith
481  ******************************************************************************/
482 static HRESULT WINAPI URLMonikerImpl_ComposeWith(IMoniker* iface,
483                                                  IMoniker* pmkRight,
484                                                  BOOL fOnlyIfNotGeneric,
485                                                  IMoniker** ppmkComposite)
486 {
487     URLMonikerImpl *This = (URLMonikerImpl *)iface;
488     FIXME("(%p)->(%p,%d,%p): stub\n",This,pmkRight,fOnlyIfNotGeneric,ppmkComposite);
489
490     return E_NOTIMPL;
491 }
492
493 /******************************************************************************
494  *        URLMoniker_Enum
495  ******************************************************************************/
496 static HRESULT WINAPI URLMonikerImpl_Enum(IMoniker* iface,BOOL fForward, IEnumMoniker** ppenumMoniker)
497 {
498     URLMonikerImpl *This = (URLMonikerImpl *)iface;
499     TRACE("(%p,%d,%p)\n",This,fForward,ppenumMoniker);
500
501     if(!ppenumMoniker)
502         return E_INVALIDARG;
503
504     /* Does not support sub-monikers */
505     *ppenumMoniker = NULL;
506     return S_OK;
507 }
508
509 /******************************************************************************
510  *        URLMoniker_IsEqual
511  ******************************************************************************/
512 static HRESULT WINAPI URLMonikerImpl_IsEqual(IMoniker* iface,IMoniker* pmkOtherMoniker)
513 {
514     URLMonikerImpl *This = (URLMonikerImpl *)iface;
515     CLSID clsid;
516     LPOLESTR urlPath;
517     IBindCtx* bind;
518     HRESULT res;
519
520     TRACE("(%p,%p)\n",This,pmkOtherMoniker);
521
522     if(pmkOtherMoniker==NULL)
523         return E_INVALIDARG;
524
525     IMoniker_GetClassID(pmkOtherMoniker,&clsid);
526
527     if(!IsEqualCLSID(&clsid,&CLSID_StdURLMoniker))
528         return S_FALSE;
529
530     res = CreateBindCtx(0,&bind);
531     if(FAILED(res))
532         return res;
533
534     res = S_FALSE;
535     if(SUCCEEDED(IMoniker_GetDisplayName(pmkOtherMoniker,bind,NULL,&urlPath))) {
536         int result = lstrcmpiW(urlPath, This->URLName);
537         CoTaskMemFree(urlPath);
538         if(result == 0)
539             res = S_OK;
540     }
541     IUnknown_Release(bind);
542     return res;
543 }
544
545
546 /******************************************************************************
547  *        URLMoniker_Hash
548  ******************************************************************************/
549 static HRESULT WINAPI URLMonikerImpl_Hash(IMoniker* iface,DWORD* pdwHash)
550 {
551     URLMonikerImpl *This = (URLMonikerImpl *)iface;
552     
553     int  h = 0,i,skip,len;
554     int  off = 0;
555     LPOLESTR val;
556
557     TRACE("(%p,%p)\n",This,pdwHash);
558
559     if(!pdwHash)
560         return E_INVALIDARG;
561
562     val = This->URLName;
563     len = lstrlenW(val);
564
565     if(len < 16) {
566         for(i = len ; i > 0; i--) {
567             h = (h * 37) + val[off++];
568         }
569     }
570     else {
571         /* only sample some characters */
572         skip = len / 8;
573         for(i = len; i > 0; i -= skip, off += skip) {
574             h = (h * 39) + val[off];
575         }
576     }
577     *pdwHash = h;
578     return S_OK;
579 }
580
581 /******************************************************************************
582  *        URLMoniker_IsRunning
583  ******************************************************************************/
584 static HRESULT WINAPI URLMonikerImpl_IsRunning(IMoniker* iface,
585                                                IBindCtx* pbc,
586                                                IMoniker* pmkToLeft,
587                                                IMoniker* pmkNewlyRunning)
588 {
589     URLMonikerImpl *This = (URLMonikerImpl *)iface;
590     FIXME("(%p)->(%p,%p,%p): stub\n",This,pbc,pmkToLeft,pmkNewlyRunning);
591
592     return E_NOTIMPL;
593 }
594
595 /******************************************************************************
596  *        URLMoniker_GetTimeOfLastChange
597  ******************************************************************************/
598 static HRESULT WINAPI URLMonikerImpl_GetTimeOfLastChange(IMoniker* iface,
599                                                          IBindCtx* pbc,
600                                                          IMoniker* pmkToLeft,
601                                                          FILETIME* pFileTime)
602 {
603     URLMonikerImpl *This = (URLMonikerImpl *)iface;
604     FIXME("(%p)->(%p,%p,%p): stub\n",This,pbc,pmkToLeft,pFileTime);
605
606     return E_NOTIMPL;
607 }
608
609 /******************************************************************************
610  *        URLMoniker_Inverse
611  ******************************************************************************/
612 static HRESULT WINAPI URLMonikerImpl_Inverse(IMoniker* iface,IMoniker** ppmk)
613 {
614     URLMonikerImpl *This = (URLMonikerImpl *)iface;
615     TRACE("(%p,%p)\n",This,ppmk);
616
617     return MK_E_NOINVERSE;
618 }
619
620 /******************************************************************************
621  *        URLMoniker_CommonPrefixWith
622  ******************************************************************************/
623 static HRESULT WINAPI URLMonikerImpl_CommonPrefixWith(IMoniker* iface,IMoniker* pmkOther,IMoniker** ppmkPrefix)
624 {
625     URLMonikerImpl *This = (URLMonikerImpl *)iface;
626     FIXME("(%p)->(%p,%p): stub\n",This,pmkOther,ppmkPrefix);
627
628     return E_NOTIMPL;
629 }
630
631 /******************************************************************************
632  *        URLMoniker_RelativePathTo
633  ******************************************************************************/
634 static HRESULT WINAPI URLMonikerImpl_RelativePathTo(IMoniker* iface,IMoniker* pmOther, IMoniker** ppmkRelPath)
635 {
636     URLMonikerImpl *This = (URLMonikerImpl *)iface;
637     FIXME("(%p)->(%p,%p): stub\n",This,pmOther,ppmkRelPath);
638
639     return E_NOTIMPL;
640 }
641
642 /******************************************************************************
643  *        URLMoniker_GetDisplayName
644  ******************************************************************************/
645 static HRESULT WINAPI URLMonikerImpl_GetDisplayName(IMoniker* iface,
646                                                     IBindCtx* pbc,
647                                                     IMoniker* pmkToLeft,
648                                                     LPOLESTR *ppszDisplayName)
649 {
650     URLMonikerImpl *This = (URLMonikerImpl *)iface;
651     
652     int len;
653     
654     TRACE("(%p,%p,%p,%p)\n",This,pbc,pmkToLeft,ppszDisplayName);
655     
656     if(!ppszDisplayName)
657         return E_INVALIDARG;
658     
659     /* FIXME: If this is a partial URL, try and get a URL moniker from SZ_URLCONTEXT in the bind context,
660         then look at pmkToLeft to try and complete the URL
661     */
662     len = lstrlenW(This->URLName)+1;
663     *ppszDisplayName = CoTaskMemAlloc(len*sizeof(WCHAR));
664     if(!*ppszDisplayName)
665         return E_OUTOFMEMORY;
666     lstrcpyW(*ppszDisplayName, This->URLName);
667     return S_OK;
668 }
669
670 /******************************************************************************
671  *        URLMoniker_ParseDisplayName
672  ******************************************************************************/
673 static HRESULT WINAPI URLMonikerImpl_ParseDisplayName(IMoniker* iface,
674                                                       IBindCtx* pbc,
675                                                       IMoniker* pmkToLeft,
676                                                       LPOLESTR pszDisplayName,
677                                                       ULONG* pchEaten,
678                                                       IMoniker** ppmkOut)
679 {
680     URLMonikerImpl *This = (URLMonikerImpl *)iface;
681     FIXME("(%p)->(%p,%p,%p,%p,%p): stub\n",This,pbc,pmkToLeft,pszDisplayName,pchEaten,ppmkOut);
682
683     return E_NOTIMPL;
684 }
685
686 /******************************************************************************
687  *        URLMoniker_IsSystemMoniker
688  ******************************************************************************/
689 static HRESULT WINAPI URLMonikerImpl_IsSystemMoniker(IMoniker* iface,DWORD* pwdMksys)
690 {
691     URLMonikerImpl *This = (URLMonikerImpl *)iface;
692     TRACE("(%p,%p)\n",This,pwdMksys);
693
694     if(!pwdMksys)
695         return E_INVALIDARG;
696
697     *pwdMksys = MKSYS_URLMONIKER;
698     return S_OK;
699 }
700
701 static HRESULT WINAPI URLMonikerImpl_IBinding_QueryInterface(IBinding* iface,REFIID riid,void** ppvObject)
702 {
703     ICOM_THIS_MULTI(URLMonikerImpl, lpvtbl2, iface);
704
705     TRACE("(%p)->(%s,%p)\n",This,debugstr_guid(riid),ppvObject);
706
707     /* Perform a sanity check on the parameters.*/
708     if ( (This==0) || (ppvObject==0) )
709         return E_INVALIDARG;
710
711     /* Initialize the return parameter */
712     *ppvObject = 0;
713
714     /* Compare the riid with the interface IDs implemented by this object.*/
715     if (IsEqualIID(&IID_IUnknown, riid) || IsEqualIID(&IID_IBinding, riid))
716         *ppvObject = iface;
717
718     /* Check that we obtained an interface.*/
719     if ((*ppvObject)==0)
720         return E_NOINTERFACE;
721
722     /* Query Interface always increases the reference count by one when it is successful */
723     IBinding_AddRef(iface);
724
725     return S_OK;
726
727 }
728
729 static ULONG WINAPI URLMonikerImpl_IBinding_AddRef(IBinding* iface)
730 {
731     ICOM_THIS_MULTI(URLMonikerImpl, lpvtbl2, iface);
732     TRACE("(%p)\n",This);
733
734     return URLMonikerImpl_AddRef((IMoniker*)This);
735 }
736
737 static ULONG WINAPI URLMonikerImpl_IBinding_Release(IBinding* iface)
738 {
739     ICOM_THIS_MULTI(URLMonikerImpl, lpvtbl2, iface);
740     TRACE("(%p)\n",This);
741
742     return URLMonikerImpl_Release((IMoniker*)This);
743 }
744
745 static HRESULT WINAPI URLMonikerImpl_IBinding_Abort(IBinding* iface)
746 {
747     ICOM_THIS_MULTI(URLMonikerImpl, lpvtbl2, iface);
748     FIXME("(%p): stub\n", This);
749
750     return E_NOTIMPL;
751 }
752
753 static HRESULT WINAPI URLMonikerImpl_IBinding_GetBindResult(IBinding* iface, CLSID* pclsidProtocol, DWORD* pdwResult, LPOLESTR* pszResult, DWORD* pdwReserved)
754 {
755     ICOM_THIS_MULTI(URLMonikerImpl, lpvtbl2, iface);
756     FIXME("(%p)->(%p, %p, %p, %p): stub\n", This, pclsidProtocol, pdwResult, pszResult, pdwReserved);
757
758     return E_NOTIMPL;
759 }
760
761 static HRESULT WINAPI URLMonikerImpl_IBinding_GetPriority(IBinding* iface, LONG* pnPriority)
762 {
763     ICOM_THIS_MULTI(URLMonikerImpl, lpvtbl2, iface);
764     FIXME("(%p)->(%p): stub\n", This, pnPriority);
765
766     return E_NOTIMPL;
767 }
768
769 static HRESULT WINAPI URLMonikerImpl_IBinding_Resume(IBinding* iface)
770 {
771     ICOM_THIS_MULTI(URLMonikerImpl, lpvtbl2, iface);
772     FIXME("(%p): stub\n", This);
773
774     return E_NOTIMPL;
775 }
776
777 static HRESULT WINAPI URLMonikerImpl_IBinding_SetPriority(IBinding* iface, LONG nPriority)
778 {
779     ICOM_THIS_MULTI(URLMonikerImpl, lpvtbl2, iface);
780     FIXME("(%p)->(%ld): stub\n", This, nPriority);
781
782     return E_NOTIMPL;
783 }
784
785 static HRESULT WINAPI URLMonikerImpl_IBinding_Suspend(IBinding* iface)
786 {
787     ICOM_THIS_MULTI(URLMonikerImpl, lpvtbl2, iface);
788     FIXME("(%p): stub\n", This);
789
790     return E_NOTIMPL;
791 }
792
793 /********************************************************************************/
794 /* Virtual function table for the URLMonikerImpl class which  include IPersist,*/
795 /* IPersistStream and IMoniker functions.                                       */
796 static IMonikerVtbl VT_URLMonikerImpl =
797 {
798     URLMonikerImpl_QueryInterface,
799     URLMonikerImpl_AddRef,
800     URLMonikerImpl_Release,
801     URLMonikerImpl_GetClassID,
802     URLMonikerImpl_IsDirty,
803     URLMonikerImpl_Load,
804     URLMonikerImpl_Save,
805     URLMonikerImpl_GetSizeMax,
806     URLMonikerImpl_BindToObject,
807     URLMonikerImpl_BindToStorage,
808     URLMonikerImpl_Reduce,
809     URLMonikerImpl_ComposeWith,
810     URLMonikerImpl_Enum,
811     URLMonikerImpl_IsEqual,
812     URLMonikerImpl_Hash,
813     URLMonikerImpl_IsRunning,
814     URLMonikerImpl_GetTimeOfLastChange,
815     URLMonikerImpl_Inverse,
816     URLMonikerImpl_CommonPrefixWith,
817     URLMonikerImpl_RelativePathTo,
818     URLMonikerImpl_GetDisplayName,
819     URLMonikerImpl_ParseDisplayName,
820     URLMonikerImpl_IsSystemMoniker
821 };
822
823 static IBindingVtbl VTBinding_URLMonikerImpl =
824 {
825     URLMonikerImpl_IBinding_QueryInterface,
826     URLMonikerImpl_IBinding_AddRef,
827     URLMonikerImpl_IBinding_Release,
828     URLMonikerImpl_IBinding_Abort,
829     URLMonikerImpl_IBinding_Suspend,
830     URLMonikerImpl_IBinding_Resume,
831     URLMonikerImpl_IBinding_SetPriority,
832     URLMonikerImpl_IBinding_GetPriority,
833     URLMonikerImpl_IBinding_GetBindResult
834 };
835
836 /******************************************************************************
837  *         URLMoniker_Construct (local function)
838  *******************************************************************************/
839 static HRESULT URLMonikerImpl_Construct(URLMonikerImpl* This, LPCOLESTR lpszLeftURLName, LPCOLESTR lpszURLName)
840 {
841     HRESULT hres;
842     DWORD sizeStr;
843
844     TRACE("(%p,%s,%s)\n",This,debugstr_w(lpszLeftURLName),debugstr_w(lpszURLName));
845     memset(This, 0, sizeof(*This));
846
847     /* Initialize the virtual function table. */
848     This->lpvtbl1      = &VT_URLMonikerImpl;
849     This->lpvtbl2      = &VTBinding_URLMonikerImpl;
850     This->ref          = 0;
851
852     if(lpszLeftURLName) {
853         hres = UrlCombineW(lpszLeftURLName, lpszURLName, NULL, &sizeStr, 0);
854         if(FAILED(hres)) {
855             return hres;
856         }
857         sizeStr++;
858     }
859     else
860         sizeStr = lstrlenW(lpszURLName)+1;
861
862     This->URLName=HeapAlloc(GetProcessHeap(),0,sizeof(WCHAR)*(sizeStr));
863
864     if (This->URLName==NULL)
865         return E_OUTOFMEMORY;
866
867     if(lpszLeftURLName) {
868         hres = UrlCombineW(lpszLeftURLName, lpszURLName, This->URLName, &sizeStr, 0);
869         if(FAILED(hres)) {
870             HeapFree(GetProcessHeap(), 0, This->URLName);
871             return hres;
872         }
873     }
874     else
875         strcpyW(This->URLName,lpszURLName);
876
877     return S_OK;
878 }
879
880 /***********************************************************************
881  *           CreateAsyncBindCtx (URLMON.@)
882  */
883 HRESULT WINAPI CreateAsyncBindCtx(DWORD reserved, IBindStatusCallback *callback,
884     IEnumFORMATETC *format, IBindCtx **pbind)
885 {
886     HRESULT hres;
887     BIND_OPTS bindopts;
888     IBindCtx *bctx;
889
890     TRACE("(%08lx %p %p %p)\n", reserved, callback, format, pbind);
891
892     if(!callback)
893         return E_INVALIDARG;
894     if(format)
895         FIXME("format is not supported yet\n");
896
897     hres = CreateBindCtx(0, &bctx);
898     if(FAILED(hres))
899         return hres;
900
901     bindopts.cbStruct = sizeof(BIND_OPTS);
902     bindopts.grfFlags = BIND_MAYBOTHERUSER;
903     bindopts.grfMode = STGM_READWRITE | STGM_SHARE_EXCLUSIVE;
904     bindopts.dwTickCountDeadline = 0;
905     IBindCtx_SetBindOptions(bctx, &bindopts);
906
907     hres = IBindCtx_RegisterObjectParam(bctx, (LPOLESTR)BSCBHolder, (IUnknown*)callback);
908     if(FAILED(hres)) {
909         IBindCtx_Release(bctx);
910         return hres;
911     }
912
913     *pbind = bctx;
914
915     return S_OK;
916 }
917 /***********************************************************************
918  *           CreateAsyncBindCtxEx (URLMON.@)
919  *
920  * Create an asynchronous bind context.
921  *
922  * FIXME
923  *   Not implemented.
924  */ 
925 HRESULT WINAPI CreateAsyncBindCtxEx(IBindCtx *ibind, DWORD options,
926     IBindStatusCallback *callback, IEnumFORMATETC *format, IBindCtx** pbind,
927     DWORD reserved)
928 {
929      FIXME("stub, returns failure\n");
930      return E_INVALIDARG;
931 }
932
933
934 /***********************************************************************
935  *           CreateURLMoniker (URLMON.@)
936  *
937  * Create a url moniker.
938  *
939  * PARAMS
940  *    pmkContext [I] Context
941  *    szURL      [I] Url to create the moniker for
942  *    ppmk       [O] Destination for created moniker.
943  *
944  * RETURNS
945  *    Success: S_OK. ppmk contains the created IMoniker object.
946  *    Failure: MK_E_SYNTAX if szURL is not a valid url, or
947  *             E_OUTOFMEMORY if memory allocation fails.
948  */
949 HRESULT WINAPI CreateURLMoniker(IMoniker *pmkContext, LPCWSTR szURL, IMoniker **ppmk)
950 {
951     URLMonikerImpl *obj;
952     HRESULT hres;
953     IID iid = IID_IMoniker;
954     LPOLESTR lefturl = NULL;
955
956     TRACE("(%p, %s, %p)\n", pmkContext, debugstr_w(szURL), ppmk);
957
958     if(!(obj = HeapAlloc(GetProcessHeap(), 0, sizeof(*obj))))
959         return E_OUTOFMEMORY;
960
961     if(pmkContext) {
962         CLSID clsid;
963         IBindCtx* bind;
964         IMoniker_GetClassID(pmkContext, &clsid);
965         if(IsEqualCLSID(&clsid, &CLSID_StdURLMoniker) && SUCCEEDED(CreateBindCtx(0, &bind))) {
966             URLMonikerImpl_GetDisplayName(pmkContext, bind, NULL, &lefturl);
967             IBindCtx_Release(bind);
968         }
969     }
970         
971     hres = URLMonikerImpl_Construct(obj, lefturl, szURL);
972     CoTaskMemFree(lefturl);
973     if(SUCCEEDED(hres))
974         hres = URLMonikerImpl_QueryInterface((IMoniker*)obj, &iid, (void**)ppmk);
975     else
976         HeapFree(GetProcessHeap(), 0, obj);
977     return hres;
978 }
979
980
981 /***********************************************************************
982  *           CoInternetGetSession (URLMON.@)
983  *
984  * Create a new internet session and return an IInternetSession interface
985  * representing it.
986  *
987  * PARAMS
988  *    dwSessionMode      [I] Mode for the internet session
989  *    ppIInternetSession [O] Destination for creates IInternetSession object
990  *    dwReserved         [I] Reserved, must be 0.
991  *
992  * RETURNS
993  *    Success: S_OK. ppIInternetSession contains the IInternetSession interface.
994  *    Failure: E_INVALIDARG, if any argument is invalid, or
995  *             E_OUTOFMEMORY if memory allocation fails.
996  */
997 HRESULT WINAPI CoInternetGetSession(DWORD dwSessionMode, IInternetSession **ppIInternetSession, DWORD dwReserved)
998 {
999     FIXME("(%ld, %p, %ld): stub\n", dwSessionMode, ppIInternetSession, dwReserved);
1000
1001     if(dwSessionMode) {
1002       ERR("dwSessionMode: %ld, must be zero\n", dwSessionMode);
1003     }
1004
1005     if(dwReserved) {
1006       ERR("dwReserved: %ld, must be zero\n", dwReserved);
1007     }
1008
1009     *ppIInternetSession=NULL;
1010     return E_OUTOFMEMORY;
1011 }
1012
1013 /***********************************************************************
1014  *           CoInternetQueryInfo (URLMON.@)
1015  *
1016  * Retrieves information relevant to a specified URL
1017  *
1018  * RETURNS
1019  *    S_OK                      success
1020  *    S_FALSE                   buffer too small
1021  *    INET_E_QUERYOPTIONUNKNOWN invalid option
1022  *
1023  */
1024 HRESULT WINAPI CoInternetQueryInfo(LPCWSTR pwzUrl, QUERYOPTION QueryOption,
1025   DWORD dwQueryFlags, LPVOID pvBuffer, DWORD cbBuffer, DWORD * pcbBuffer,
1026   DWORD dwReserved)
1027 {
1028   FIXME("(%s, %x, %lx, %p, %lx, %p, %lx): stub\n", debugstr_w(pwzUrl),
1029     QueryOption, dwQueryFlags, pvBuffer, cbBuffer, pcbBuffer, dwReserved);
1030   return S_OK;
1031 }
1032
1033 static BOOL URLMON_IsBinary(LPVOID pBuffer, DWORD cbSize)
1034 {
1035     unsigned int i, binarycount = 0;
1036     unsigned char *buff = pBuffer;
1037     for(i=0; i<cbSize; i++) {
1038         if(buff[i] < 32)
1039             binarycount++;
1040     }
1041     return binarycount > (cbSize-binarycount);
1042 }
1043
1044 /***********************************************************************
1045  *           FindMimeFromData (URLMON.@)
1046  *
1047  * Determines the Multipurpose Internet Mail Extensions (MIME) type from the data provided.
1048  *
1049  * NOTE
1050  *  See http://msdn.microsoft.com/workshop/networking/moniker/overview/appendix_a.asp
1051  */
1052 HRESULT WINAPI FindMimeFromData(LPBC pBC, LPCWSTR pwzUrl, LPVOID pBuffer,
1053    DWORD cbSize, LPCWSTR pwzMimeProposed, DWORD dwMimeFlags,
1054    LPWSTR* ppwzMimeOut, DWORD dwReserved)
1055 {
1056     static const WCHAR szBinaryMime[] = {'a','p','p','l','i','c','a','t','i','o','n','/','o','c','t','e','t','-','s','t','r','e','a','m','\0'};
1057     static const WCHAR szTextMime[] = {'t','e','x','t','/','p','l','a','i','n','\0'};
1058     static const WCHAR szContentType[] = {'C','o','n','t','e','n','t',' ','T','y','p','e','\0'};
1059     WCHAR szTmpMime[256];
1060     LPCWSTR mimeType = NULL;
1061     HKEY hKey = NULL;
1062
1063     TRACE("(%p,%s,%p,%ld,%s,0x%lx,%p,0x%lx)\n", pBC, debugstr_w(pwzUrl), pBuffer, cbSize,
1064           debugstr_w(pwzMimeProposed), dwMimeFlags, ppwzMimeOut, dwReserved);
1065
1066     if((!pwzUrl && (!pBuffer || cbSize <= 0)) || !ppwzMimeOut)
1067         return E_INVALIDARG;
1068
1069     if(pwzMimeProposed)
1070         mimeType = pwzMimeProposed;
1071     else {
1072         /* Try and find the mime type in the registry */
1073         if(pwzUrl) {
1074             LPWSTR ext = strrchrW(pwzUrl, '.');
1075             if(ext) {
1076                 DWORD dwSize;
1077                 if(!RegOpenKeyExW(HKEY_CLASSES_ROOT, ext, 0, 0, &hKey)) {
1078                     if(!RegQueryValueExW(hKey, szContentType, NULL, NULL, (LPBYTE)szTmpMime, &dwSize)) {
1079                         mimeType = szTmpMime;
1080                     }
1081                     RegCloseKey(hKey);
1082                 }
1083             }
1084         }
1085     }
1086     if(!mimeType && pBuffer && cbSize > 0)
1087         mimeType = URLMON_IsBinary(pBuffer, cbSize)?szBinaryMime:szTextMime;
1088
1089     TRACE("Using %s\n", debugstr_w(mimeType));
1090     *ppwzMimeOut = CoTaskMemAlloc((lstrlenW(mimeType)+1)*sizeof(WCHAR));
1091     if(!*ppwzMimeOut) return E_OUTOFMEMORY;
1092     lstrcpyW(*ppwzMimeOut, mimeType);
1093     return S_OK;
1094 }
1095
1096 /***********************************************************************
1097  *           IsAsyncMoniker (URLMON.@)
1098  */
1099 HRESULT WINAPI IsAsyncMoniker(IMoniker *pmk)
1100 {
1101     IUnknown *am;
1102     
1103     TRACE("(%p)\n", pmk);
1104     if(!pmk)
1105         return E_INVALIDARG;
1106     if(SUCCEEDED(IMoniker_QueryInterface(pmk, &IID_IAsyncMoniker, (void**)&am))) {
1107         IUnknown_Release(am);
1108         return S_OK;
1109     }
1110     return S_FALSE;
1111 }
1112
1113 /***********************************************************************
1114  *           RegisterBindStatusCallback (URLMON.@)
1115  *
1116  * Register a bind status callback.
1117  *
1118  * PARAMS
1119  *  pbc           [I] Binding context
1120  *  pbsc          [I] Callback to register
1121  *  ppbscPrevious [O] Destination for previous callback
1122  *  dwReserved    [I] Reserved, must be 0.
1123  *
1124  * RETURNS
1125  *    Success: S_OK.
1126  *    Failure: E_INVALIDARG, if any argument is invalid, or
1127  *             E_OUTOFMEMORY if memory allocation fails.
1128  */
1129 HRESULT WINAPI RegisterBindStatusCallback(
1130     IBindCtx *pbc,
1131     IBindStatusCallback *pbsc,
1132     IBindStatusCallback **ppbscPrevious,
1133     DWORD dwReserved)
1134 {
1135     IBindStatusCallback *prev;
1136
1137     TRACE("(%p,%p,%p,%lu)\n", pbc, pbsc, ppbscPrevious, dwReserved);
1138
1139     if (pbc == NULL || pbsc == NULL)
1140         return E_INVALIDARG;
1141
1142     if (SUCCEEDED(IBindCtx_GetObjectParam(pbc, (LPOLESTR)BSCBHolder, (IUnknown **)&prev)))
1143     {
1144         IBindCtx_RevokeObjectParam(pbc, (LPOLESTR)BSCBHolder);
1145         if (ppbscPrevious)
1146             *ppbscPrevious = prev;
1147         else
1148             IBindStatusCallback_Release(prev);
1149     }
1150
1151         return IBindCtx_RegisterObjectParam(pbc, (LPOLESTR)BSCBHolder, (IUnknown *)pbsc);
1152 }
1153
1154 /***********************************************************************
1155  *           RevokeBindStatusCallback (URLMON.@)
1156  *
1157  * Unregister a bind status callback.
1158  *
1159  *  pbc           [I] Binding context
1160  *  pbsc          [I] Callback to unregister
1161  *
1162  * RETURNS
1163  *    Success: S_OK.
1164  *    Failure: E_INVALIDARG, if any argument is invalid, or
1165  *             E_FAIL if pbsc wasn't registered with pbc.
1166  */
1167 HRESULT WINAPI RevokeBindStatusCallback(
1168     IBindCtx *pbc,
1169     IBindStatusCallback *pbsc)
1170 {
1171     IBindStatusCallback *callback;
1172     HRESULT hr = E_FAIL;
1173
1174         TRACE("(%p,%p)\n", pbc, pbsc);
1175
1176     if (pbc == NULL || pbsc == NULL)
1177         return E_INVALIDARG;
1178
1179     if (SUCCEEDED(IBindCtx_GetObjectParam(pbc, (LPOLESTR)BSCBHolder, (IUnknown **)&callback)))
1180     {
1181         if (callback == pbsc)
1182         {
1183             IBindCtx_RevokeObjectParam(pbc, (LPOLESTR)BSCBHolder);
1184             hr = S_OK;
1185         }
1186         IBindStatusCallback_Release(pbsc);
1187     }
1188
1189     return hr;
1190 }
1191
1192 /***********************************************************************
1193  *           ReleaseBindInfo (URLMON.@)
1194  *
1195  * Release the resources used by the specified BINDINFO structure.
1196  *
1197  * PARAMS
1198  *  pbindinfo [I] BINDINFO to release.
1199  *
1200  * RETURNS
1201  *  Nothing.
1202  */
1203 void WINAPI ReleaseBindInfo(BINDINFO* pbindinfo)
1204 {
1205     FIXME("(%p)stub!\n", pbindinfo);
1206 }
1207
1208 /***********************************************************************
1209  *           URLDownloadToFileA (URLMON.@)
1210  *
1211  * Downloads URL szURL to rile szFileName and call lpfnCB callback to
1212  * report progress.
1213  *
1214  * PARAMS
1215  *  pCaller    [I] controlling IUnknown interface.
1216  *  szURL      [I] URL of the file to download
1217  *  szFileName [I] file name to store the content of the URL
1218  *  dwReserved [I] reserved - set to 0
1219  *  lpfnCB     [I] callback for progress report
1220  *
1221  * RETURNS
1222  *  S_OK on success
1223  *  E_OUTOFMEMORY when going out of memory
1224  */
1225 HRESULT WINAPI URLDownloadToFileA(LPUNKNOWN pCaller,
1226                                   LPCSTR szURL,
1227                                   LPCSTR szFileName,
1228                                   DWORD dwReserved,
1229                                   LPBINDSTATUSCALLBACK lpfnCB)
1230 {
1231     UNICODE_STRING szURL_w, szFileName_w;
1232
1233     if ((szURL == NULL) || (szFileName == NULL)) {
1234         FIXME("(%p,%s,%s,%08lx,%p) cannot accept NULL strings !\n", pCaller, debugstr_a(szURL), debugstr_a(szFileName), dwReserved, lpfnCB);
1235         return E_INVALIDARG; /* The error code is not specified in this case... */
1236     }
1237     
1238     if (RtlCreateUnicodeStringFromAsciiz(&szURL_w, szURL)) {
1239         if (RtlCreateUnicodeStringFromAsciiz(&szFileName_w, szFileName)) {
1240             HRESULT ret = URLDownloadToFileW(pCaller, szURL_w.Buffer, szFileName_w.Buffer, dwReserved, lpfnCB);
1241
1242             RtlFreeUnicodeString(&szURL_w);
1243             RtlFreeUnicodeString(&szFileName_w);
1244             
1245             return ret;
1246         } else {
1247             RtlFreeUnicodeString(&szURL_w);
1248         }
1249     }
1250     
1251     FIXME("(%p,%s,%s,%08lx,%p) could not allocate W strings !\n", pCaller, szURL, szFileName, dwReserved, lpfnCB);
1252     return E_OUTOFMEMORY;
1253 }
1254
1255 /***********************************************************************
1256  *           URLDownloadToFileW (URLMON.@)
1257  *
1258  * Downloads URL szURL to rile szFileName and call lpfnCB callback to
1259  * report progress.
1260  *
1261  * PARAMS
1262  *  pCaller    [I] controlling IUnknown interface.
1263  *  szURL      [I] URL of the file to download
1264  *  szFileName [I] file name to store the content of the URL
1265  *  dwReserved [I] reserved - set to 0
1266  *  lpfnCB     [I] callback for progress report
1267  *
1268  * RETURNS
1269  *  S_OK on success
1270  *  E_OUTOFMEMORY when going out of memory
1271  */
1272 HRESULT WINAPI URLDownloadToFileW(LPUNKNOWN pCaller,
1273                                   LPCWSTR szURL,
1274                                   LPCWSTR szFileName,
1275                                   DWORD dwReserved,
1276                                   LPBINDSTATUSCALLBACK lpfnCB)
1277 {
1278     HINTERNET hinternet, hcon, hreq;
1279     BOOL r;
1280     CHAR buffer[0x1000];
1281     DWORD sz, total, written;
1282     DWORD total_size = 0xFFFFFFFF, arg_size = sizeof(total_size);
1283     URL_COMPONENTSW url;
1284     WCHAR host[0x80], path[0x100];
1285     HANDLE hfile;
1286     static const WCHAR wszAppName[]={'u','r','l','m','o','n','.','d','l','l',0};
1287
1288     /* Note: all error codes would need to be checked agains real Windows behaviour... */
1289     TRACE("(%p,%s,%s,%08lx,%p) stub!\n", pCaller, debugstr_w(szURL), debugstr_w(szFileName), dwReserved, lpfnCB);
1290
1291     if ((szURL == NULL) || (szFileName == NULL)) {
1292         FIXME(" cannot accept NULL strings !\n");
1293         return E_INVALIDARG;
1294     }
1295
1296     /* Would be better to use the application name here rather than 'urlmon' :-/ */
1297     hinternet = InternetOpenW(wszAppName, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
1298     if (hinternet == NULL) {
1299         return E_OUTOFMEMORY;
1300     }                                                                                                                             
1301
1302     memset(&url, 0, sizeof(url));
1303     url.dwStructSize = sizeof(url);
1304     url.lpszHostName = host;
1305     url.dwHostNameLength = sizeof(host);
1306     url.lpszUrlPath = path;
1307     url.dwUrlPathLength = sizeof(path);
1308
1309     if (!InternetCrackUrlW(szURL, 0, 0, &url)) {
1310         InternetCloseHandle(hinternet);
1311         return E_OUTOFMEMORY;
1312     }
1313
1314     if (lpfnCB) {
1315         if (IBindStatusCallback_OnProgress(lpfnCB, 0, 0, BINDSTATUS_CONNECTING, url.lpszHostName) == E_ABORT) {
1316             InternetCloseHandle(hinternet);
1317             return S_OK;
1318         }
1319     }
1320     
1321     hcon = InternetConnectW(hinternet, url.lpszHostName, url.nPort,
1322                             url.lpszUserName, url.lpszPassword,
1323                             INTERNET_SERVICE_HTTP, 0, 0);
1324     if (!hcon) {
1325         InternetCloseHandle(hinternet);
1326         return E_OUTOFMEMORY;
1327     }
1328     
1329     hreq = HttpOpenRequestW(hcon, NULL, url.lpszUrlPath, NULL, NULL, NULL, 0, 0);
1330     if (!hreq) {
1331         InternetCloseHandle(hinternet);
1332         InternetCloseHandle(hcon);
1333         return E_OUTOFMEMORY;
1334     }                                                                                                                             
1335
1336     if (!HttpSendRequestW(hreq, NULL, 0, NULL, 0)) {
1337         InternetCloseHandle(hinternet);
1338         InternetCloseHandle(hcon);
1339         InternetCloseHandle(hreq);
1340         return E_OUTOFMEMORY;
1341     }
1342     
1343     if (HttpQueryInfoW(hreq, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER,
1344                        &total_size, &arg_size, NULL)) {
1345         TRACE(" total size : %ld\n", total_size);
1346     }
1347     
1348     hfile = CreateFileW(szFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
1349                         FILE_ATTRIBUTE_NORMAL, NULL );
1350     if (hfile == INVALID_HANDLE_VALUE) {
1351         return E_ACCESSDENIED;
1352     }
1353     
1354     if (lpfnCB) {
1355         if (IBindStatusCallback_OnProgress(lpfnCB, 0, total_size != 0xFFFFFFFF ? total_size : 0,
1356                                            BINDSTATUS_BEGINDOWNLOADDATA, szURL) == E_ABORT) {
1357             InternetCloseHandle(hreq);
1358             InternetCloseHandle(hcon);
1359             InternetCloseHandle(hinternet);
1360             CloseHandle(hfile);
1361             return S_OK;
1362         }
1363     }
1364     
1365     total = 0;
1366     while (1) {
1367         r = InternetReadFile(hreq, buffer, sizeof(buffer), &sz);
1368         if (!r) {
1369             InternetCloseHandle(hreq);
1370             InternetCloseHandle(hcon);
1371             InternetCloseHandle(hinternet);
1372             
1373             CloseHandle(hfile);
1374             return E_OUTOFMEMORY;           
1375         }
1376         if (!sz)
1377             break;
1378         
1379         total += sz;
1380
1381         if (lpfnCB) {
1382             if (IBindStatusCallback_OnProgress(lpfnCB, total, total_size != 0xFFFFFFFF ? total_size : 0,
1383                                                BINDSTATUS_DOWNLOADINGDATA, szURL) == E_ABORT) {
1384                 InternetCloseHandle(hreq);
1385                 InternetCloseHandle(hcon);
1386                 InternetCloseHandle(hinternet);
1387                 CloseHandle(hfile);
1388                 return S_OK;
1389             }
1390         }
1391         
1392         if (!WriteFile(hfile, buffer, sz, &written, NULL)) {
1393             InternetCloseHandle(hreq);
1394             InternetCloseHandle(hcon);
1395             InternetCloseHandle(hinternet);
1396             
1397             CloseHandle(hfile);
1398             return E_OUTOFMEMORY;
1399         }
1400     }
1401
1402     if (lpfnCB) {
1403         if (IBindStatusCallback_OnProgress(lpfnCB, total, total_size != 0xFFFFFFFF ? total_size : 0,
1404                                            BINDSTATUS_ENDDOWNLOADDATA, szURL) == E_ABORT) {
1405             InternetCloseHandle(hreq);
1406             InternetCloseHandle(hcon);
1407             InternetCloseHandle(hinternet);
1408             CloseHandle(hfile);
1409             return S_OK;
1410         }
1411     }
1412     
1413     InternetCloseHandle(hreq);
1414     InternetCloseHandle(hcon);
1415     InternetCloseHandle(hinternet);
1416     
1417     CloseHandle(hfile);
1418
1419     return S_OK;
1420 }
1421
1422 /***********************************************************************
1423  *           HlinkSimpleNavigateToString (URLMON.@)
1424  */
1425 HRESULT WINAPI HlinkSimpleNavigateToString( LPCWSTR szTarget,
1426     LPCWSTR szLocation, LPCWSTR szTargetFrameName, IUnknown *pUnk,
1427     IBindCtx *pbc, IBindStatusCallback *pbsc, DWORD grfHLNF, DWORD dwReserved)
1428 {
1429     FIXME("%s\n", debugstr_w( szTarget ) );
1430     return E_NOTIMPL;
1431 }
1432
1433 /***********************************************************************
1434  *           HlinkNavigateString (URLMON.@)
1435  */
1436 HRESULT WINAPI HlinkNavigateString( IUnknown *pUnk, LPCWSTR szTarget )
1437 {
1438     TRACE("%p %s\n", pUnk, debugstr_w( szTarget ) );
1439     return HlinkSimpleNavigateToString( 
1440                szTarget, NULL, NULL, pUnk, NULL, NULL, 0, 0 );
1441 }