urlmon: Simplified path canonicalization functions.
[wine] / dlls / urlmon / binding.c
1 /*
2  * Copyright 2005-2007 Jacek Caban for CodeWeavers
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
17  */
18
19 #include "urlmon_main.h"
20 #include "winreg.h"
21
22 #include "wine/debug.h"
23
24 WINE_DEFAULT_DEBUG_CHANNEL(urlmon);
25
26 static WCHAR cbinding_contextW[] = {'C','B','i','n','d','i','n','g',' ','C','o','n','t','e','x','t',0};
27 static WCHAR bscb_holderW[] = { '_','B','S','C','B','_','H','o','l','d','e','r','_',0 };
28
29 typedef struct Binding Binding;
30
31 struct _task_header_t;
32
33 typedef void (*task_proc_t)(Binding*, struct _task_header_t*);
34
35 typedef struct _task_header_t {
36     task_proc_t proc;
37     struct _task_header_t *next;
38 } task_header_t;
39
40 typedef struct {
41     const IUnknownVtbl *lpUnknownVtbl;
42
43     LONG ref;
44
45     IInternetProtocol *protocol;
46
47     BYTE buf[1024*8];
48     DWORD size;
49     BOOL init;
50     HANDLE file;
51     HRESULT hres;
52
53     LPWSTR cache_file;
54 } stgmed_buf_t;
55
56 typedef struct _stgmed_obj_t stgmed_obj_t;
57
58 typedef struct {
59     void (*release)(stgmed_obj_t*);
60     HRESULT (*fill_stgmed)(stgmed_obj_t*,STGMEDIUM*);
61     HRESULT (*get_result)(stgmed_obj_t*,DWORD,void**);
62 } stgmed_obj_vtbl;
63
64 struct _stgmed_obj_t {
65     const stgmed_obj_vtbl *vtbl;
66 };
67
68 #define STGMEDUNK(x)  ((IUnknown*) &(x)->lpUnknownVtbl)
69
70 typedef enum {
71     BEFORE_DOWNLOAD,
72     DOWNLOADING,
73     END_DOWNLOAD
74 } download_state_t;
75
76 #define BINDING_LOCKED    0x0001
77 #define BINDING_STOPPED   0x0002
78 #define BINDING_OBJAVAIL  0x0004
79 #define BINDING_ABORTED   0x0008
80
81 struct Binding {
82     const IBindingVtbl               *lpBindingVtbl;
83     const IInternetProtocolSinkVtbl  *lpIInternetProtocolSinkVtbl;
84     const IInternetBindInfoVtbl      *lpInternetBindInfoVtbl;
85     const IWinInetHttpInfoVtbl       *lpWinInetHttpInfoVtbl;
86     const IServiceProviderVtbl       *lpServiceProviderVtbl;
87
88     LONG ref;
89
90     IBindStatusCallback *callback;
91     IInternetProtocol *protocol;
92     IServiceProvider *service_provider;
93
94     stgmed_buf_t *stgmed_buf;
95     stgmed_obj_t *stgmed_obj;
96
97     BINDINFO bindinfo;
98     DWORD bindf;
99     BOOL to_object;
100     LPWSTR mime;
101     UINT clipboard_format;
102     LPWSTR url;
103     LPWSTR redirect_url;
104     IID iid;
105     BOOL report_mime;
106     BOOL use_cache_file;
107     DWORD state;
108     HRESULT hres;
109     download_state_t download_state;
110     IUnknown *obj;
111     IMoniker *mon;
112     IBindCtx *bctx;
113     HWND notif_hwnd;
114
115     CRITICAL_SECTION section;
116 };
117
118 #define BINDING(x)   ((IBinding*)               &(x)->lpBindingVtbl)
119 #define BINDINF(x)   ((IInternetBindInfo*)      &(x)->lpInternetBindInfoVtbl)
120 #define INETINFO(x)  ((IWinInetHttpInfo*)       &(x)->lpWinInetHttpInfoVtbl)
121 #define SERVPROV(x)  ((IServiceProvider*)       &(x)->lpServiceProviderVtbl)
122
123 #define STREAM(x) ((IStream*) &(x)->lpStreamVtbl)
124 #define HTTPNEG2(x) ((IHttpNegotiate2*) &(x)->lpHttpNegotiate2Vtbl)
125
126 static void fill_stgmed_buffer(stgmed_buf_t *buf)
127 {
128     DWORD read = 0;
129
130     if(sizeof(buf->buf) == buf->size)
131         return;
132
133     buf->hres = IInternetProtocol_Read(buf->protocol, buf->buf+buf->size,
134             sizeof(buf->buf)-buf->size, &read);
135     buf->size += read;
136     if(read > 0)
137         buf->init = TRUE;
138 }
139
140 static void read_protocol_data(stgmed_buf_t *stgmed_buf)
141 {
142     BYTE buf[8192];
143     DWORD read;
144     HRESULT hres;
145
146     fill_stgmed_buffer(stgmed_buf);
147     if(stgmed_buf->size < sizeof(stgmed_buf->buf))
148         return;
149
150     do hres = IInternetProtocol_Read(stgmed_buf->protocol, buf, sizeof(buf), &read);
151     while(hres == S_OK);
152 }
153
154 static void dump_BINDINFO(BINDINFO *bi)
155 {
156     static const char * const BINDINFOF_str[] = {
157         "#0",
158         "BINDINFOF_URLENCODESTGMEDDATA",
159         "BINDINFOF_URLENCODEDEXTRAINFO"
160     };
161
162     static const char * const BINDVERB_str[] = {
163         "BINDVERB_GET",
164         "BINDVERB_POST",
165         "BINDVERB_PUT",
166         "BINDVERB_CUSTOM"
167     };
168
169     TRACE("\n"
170             "BINDINFO = {\n"
171             "    %d, %s,\n"
172             "    {%d, %p, %p},\n"
173             "    %s,\n"
174             "    %s,\n"
175             "    %s,\n"
176             "    %d, %08x, %d, %d\n"
177             "    {%d %p %x},\n"
178             "    %s\n"
179             "    %p, %d\n"
180             "}\n",
181
182             bi->cbSize, debugstr_w(bi->szExtraInfo),
183             bi->stgmedData.tymed, bi->stgmedData.u.hGlobal, bi->stgmedData.pUnkForRelease,
184             bi->grfBindInfoF > BINDINFOF_URLENCODEDEXTRAINFO
185                 ? "unknown" : BINDINFOF_str[bi->grfBindInfoF],
186             bi->dwBindVerb > BINDVERB_CUSTOM
187                 ? "unknown" : BINDVERB_str[bi->dwBindVerb],
188             debugstr_w(bi->szCustomVerb),
189             bi->cbstgmedData, bi->dwOptions, bi->dwOptionsFlags, bi->dwCodePage,
190             bi->securityAttributes.nLength,
191             bi->securityAttributes.lpSecurityDescriptor,
192             bi->securityAttributes.bInheritHandle,
193             debugstr_guid(&bi->iid),
194             bi->pUnk, bi->dwReserved
195             );
196 }
197
198 static void mime_available(Binding *This, LPCWSTR mime)
199 {
200     heap_free(This->mime);
201     This->mime = heap_strdupW(mime);
202
203     if(!This->mime || !This->report_mime)
204         return;
205
206     IBindStatusCallback_OnProgress(This->callback, 0, 0, BINDSTATUS_MIMETYPEAVAILABLE, This->mime);
207
208     This->clipboard_format = RegisterClipboardFormatW(This->mime);
209 }
210
211 static void stop_binding(Binding *binding, HRESULT hres, LPCWSTR str)
212 {
213     if(binding->state & BINDING_LOCKED) {
214         IInternetProtocol_UnlockRequest(binding->protocol);
215         binding->state &= ~BINDING_LOCKED;
216     }
217
218     if(!(binding->state & BINDING_STOPPED)) {
219         binding->state |= BINDING_STOPPED;
220
221         IBindStatusCallback_OnStopBinding(binding->callback, hres, str);
222         binding->hres = hres;
223     }
224 }
225
226 static LPWSTR get_mime_clsid(LPCWSTR mime, CLSID *clsid)
227 {
228     LPWSTR key_name, ret;
229     DWORD res, type, size;
230     HKEY hkey;
231     int len;
232     HRESULT hres;
233
234     static const WCHAR mime_keyW[] =
235         {'M','I','M','E','\\','D','a','t','a','b','a','s','e','\\',
236          'C','o','n','t','e','n','t',' ','T','y','p','e','\\'};
237     static const WCHAR clsidW[] = {'C','L','S','I','D',0};
238
239     len = strlenW(mime)+1;
240     key_name = heap_alloc(sizeof(mime_keyW) + len*sizeof(WCHAR));
241     memcpy(key_name, mime_keyW, sizeof(mime_keyW));
242     strcpyW(key_name + sizeof(mime_keyW)/sizeof(WCHAR), mime);
243
244     res = RegOpenKeyW(HKEY_CLASSES_ROOT, key_name, &hkey);
245     heap_free(key_name);
246     if(res != ERROR_SUCCESS) {
247         WARN("Could not open MIME key: %x\n", res);
248         return NULL;
249     }
250
251     size = 50*sizeof(WCHAR);
252     ret = heap_alloc(size);
253     res = RegQueryValueExW(hkey, clsidW, NULL, &type, (LPBYTE)ret, &size);
254     RegCloseKey(hkey);
255     if(res != ERROR_SUCCESS) {
256         WARN("Could not get CLSID: %08x\n", res);
257         heap_free(ret);
258         return NULL;
259     }
260
261     hres = CLSIDFromString(ret, clsid);
262     if(FAILED(hres)) {
263         WARN("Could not parse CLSID: %08x\n", hres);
264         heap_free(ret);
265         return NULL;
266     }
267
268     return ret;
269 }
270
271 static void load_doc_mon(Binding *binding, IPersistMoniker *persist)
272 {
273     IBindCtx *bctx;
274     HRESULT hres;
275
276     hres = CreateAsyncBindCtxEx(binding->bctx, 0, NULL, NULL, &bctx, 0);
277     if(FAILED(hres)) {
278         WARN("CreateAsyncBindCtxEx failed: %08x\n", hres);
279         return;
280     }
281
282     IBindCtx_RevokeObjectParam(bctx, bscb_holderW);
283     IBindCtx_RegisterObjectParam(bctx, cbinding_contextW, (IUnknown*)BINDING(binding));
284
285     hres = IPersistMoniker_Load(persist, binding->download_state == END_DOWNLOAD, binding->mon, bctx, 0x12);
286     IBindCtx_RevokeObjectParam(bctx, cbinding_contextW);
287     IBindCtx_Release(bctx);
288     if(FAILED(hres))
289         FIXME("Load failed: %08x\n", hres);
290 }
291
292 static HRESULT create_mime_object(Binding *binding, const CLSID *clsid, LPCWSTR clsid_str)
293 {
294     IPersistMoniker *persist;
295     HRESULT hres;
296
297     hres = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER|CLSCTX_INPROC_HANDLER,
298                             &binding->iid, (void**)&binding->obj);
299     if(FAILED(hres)) {
300         WARN("CoCreateInstance failed: %08x\n", hres);
301         return INET_E_CANNOT_INSTANTIATE_OBJECT;
302     }
303
304     binding->state |= BINDING_OBJAVAIL;
305
306     hres = IUnknown_QueryInterface(binding->obj, &IID_IPersistMoniker, (void**)&persist);
307     if(SUCCEEDED(hres)) {
308         IMonikerProp *prop;
309
310         hres = IPersistMoniker_QueryInterface(persist, &IID_IMonikerProp, (void**)&prop);
311         if(SUCCEEDED(hres)) {
312             IMonikerProp_PutProperty(prop, MIMETYPEPROP, binding->mime);
313             IMonikerProp_PutProperty(prop, CLASSIDPROP, clsid_str);
314             IMonikerProp_Release(prop);
315         }
316
317         load_doc_mon(binding, persist);
318
319         IPersistMoniker_Release(persist);
320     }else {
321         FIXME("Could not get IPersistMoniker: %08x\n", hres);
322         /* FIXME: Try query IPersistFile */
323     }
324
325     IBindStatusCallback_OnObjectAvailable(binding->callback, &binding->iid, binding->obj);
326
327     return S_OK;
328 }
329
330 static void create_object(Binding *binding)
331 {
332     LPWSTR clsid_str;
333     CLSID clsid;
334     HRESULT hres;
335
336     if(!binding->mime) {
337         FIXME("MIME not available\n");
338         return;
339     }
340
341     if(!(clsid_str = get_mime_clsid(binding->mime, &clsid))) {
342         FIXME("Could not find object for MIME %s\n", debugstr_w(binding->mime));
343         return;
344     }
345
346     IBindStatusCallback_OnProgress(binding->callback, 0, 0, BINDSTATUS_CLASSIDAVAILABLE, clsid_str);
347     IBindStatusCallback_OnProgress(binding->callback, 0, 0, BINDSTATUS_BEGINSYNCOPERATION, NULL);
348
349     hres = create_mime_object(binding, &clsid, clsid_str);
350     heap_free(clsid_str);
351
352     IBindStatusCallback_OnProgress(binding->callback, 0, 0, BINDSTATUS_ENDSYNCOPERATION, NULL);
353
354     stop_binding(binding, hres, NULL);
355     if(FAILED(hres))
356         IInternetProtocol_Terminate(binding->protocol, 0);
357 }
358
359 static void cache_file_available(Binding *This, const WCHAR *file_name)
360 {
361     heap_free(This->stgmed_buf->cache_file);
362     This->stgmed_buf->cache_file = heap_strdupW(file_name);
363
364     if(This->use_cache_file) {
365         This->stgmed_buf->file = CreateFileW(file_name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
366                 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
367         if(This->stgmed_buf->file == INVALID_HANDLE_VALUE)
368             WARN("CreateFile failed: %u\n", GetLastError());
369     }
370 }
371
372 #define STGMEDUNK_THIS(iface) DEFINE_THIS(stgmed_buf_t, Unknown, iface)
373
374 static HRESULT WINAPI StgMedUnk_QueryInterface(IUnknown *iface, REFIID riid, void **ppv)
375 {
376     stgmed_buf_t *This = STGMEDUNK_THIS(iface);
377
378     *ppv = NULL;
379
380     if(IsEqualGUID(riid, &IID_IUnknown)) {
381         TRACE("(%p)->(IID_IUnknown %p)\n", This, ppv);
382
383         *ppv = STGMEDUNK(This);
384         IUnknown_AddRef(STGMEDUNK(This));
385         return S_OK;
386     }
387
388     TRACE("(%p)->(%s %p)\n", This, debugstr_guid(riid), ppv);
389     return E_NOINTERFACE;
390 }
391
392 static ULONG WINAPI StgMedUnk_AddRef(IUnknown *iface)
393 {
394     stgmed_buf_t *This = STGMEDUNK_THIS(iface);
395     LONG ref = InterlockedIncrement(&This->ref);
396
397     TRACE("(%p) ref=%d\n", This, ref);
398
399     return ref;
400 }
401
402 static ULONG WINAPI StgMedUnk_Release(IUnknown *iface)
403 {
404     stgmed_buf_t *This = STGMEDUNK_THIS(iface);
405     LONG ref = InterlockedDecrement(&This->ref);
406
407     TRACE("(%p) ref=%d\n", This, ref);
408
409     if(!ref) {
410         if(This->file != INVALID_HANDLE_VALUE)
411             CloseHandle(This->file);
412         IInternetProtocol_Release(This->protocol);
413         heap_free(This->cache_file);
414         heap_free(This);
415
416         URLMON_UnlockModule();
417     }
418
419     return ref;
420 }
421
422 #undef STGMEDUNK_THIS
423
424 static const IUnknownVtbl StgMedUnkVtbl = {
425     StgMedUnk_QueryInterface,
426     StgMedUnk_AddRef,
427     StgMedUnk_Release
428 };
429
430 static stgmed_buf_t *create_stgmed_buf(IInternetProtocol *protocol)
431 {
432     stgmed_buf_t *ret = heap_alloc(sizeof(*ret));
433
434     ret->lpUnknownVtbl = &StgMedUnkVtbl;
435     ret->ref = 1;
436     ret->size = 0;
437     ret->init = FALSE;
438     ret->file = INVALID_HANDLE_VALUE;
439     ret->hres = S_OK;
440     ret->cache_file = NULL;
441
442     IInternetProtocol_AddRef(protocol);
443     ret->protocol = protocol;
444
445     URLMON_LockModule();
446
447     return ret;
448 }
449
450 typedef struct {
451     stgmed_obj_t stgmed_obj;
452     const IStreamVtbl *lpStreamVtbl;
453
454     LONG ref;
455
456     stgmed_buf_t *buf;
457 } ProtocolStream;
458
459 #define STREAM_THIS(iface) DEFINE_THIS(ProtocolStream, Stream, iface)
460
461 static HRESULT WINAPI ProtocolStream_QueryInterface(IStream *iface,
462                                                           REFIID riid, void **ppv)
463 {
464     ProtocolStream *This = STREAM_THIS(iface);
465
466     *ppv = NULL;
467
468     if(IsEqualGUID(&IID_IUnknown, riid)) {
469         TRACE("(%p)->(IID_IUnknown %p)\n", This, ppv);
470         *ppv = STREAM(This);
471     }else if(IsEqualGUID(&IID_ISequentialStream, riid)) {
472         TRACE("(%p)->(IID_ISequentialStream %p)\n", This, ppv);
473         *ppv = STREAM(This);
474     }else if(IsEqualGUID(&IID_IStream, riid)) {
475         TRACE("(%p)->(IID_IStream %p)\n", This, ppv);
476         *ppv = STREAM(This);
477     }
478
479     if(*ppv) {
480         IStream_AddRef(STREAM(This));
481         return S_OK;
482     }
483
484     WARN("(%p)->(%s %p)\n", This, debugstr_guid(riid), ppv);
485     return E_NOINTERFACE;
486 }
487
488 static ULONG WINAPI ProtocolStream_AddRef(IStream *iface)
489 {
490     ProtocolStream *This = STREAM_THIS(iface);
491     LONG ref = InterlockedIncrement(&This->ref);
492
493     TRACE("(%p) ref=%d\n", This, ref);
494
495     return ref;
496 }
497
498 static ULONG WINAPI ProtocolStream_Release(IStream *iface)
499 {
500     ProtocolStream *This = STREAM_THIS(iface);
501     LONG ref = InterlockedDecrement(&This->ref);
502
503     TRACE("(%p) ref=%d\n", This, ref);
504
505     if(!ref) {
506         IUnknown_Release(STGMEDUNK(This->buf));
507         heap_free(This);
508
509         URLMON_UnlockModule();
510     }
511
512     return ref;
513 }
514
515 static HRESULT WINAPI ProtocolStream_Read(IStream *iface, void *pv,
516                                           ULONG cb, ULONG *pcbRead)
517 {
518     ProtocolStream *This = STREAM_THIS(iface);
519     DWORD read = 0, pread = 0;
520     HRESULT hres;
521
522     TRACE("(%p)->(%p %d %p)\n", This, pv, cb, pcbRead);
523
524     if(This->buf->file != INVALID_HANDLE_VALUE) {
525         if (!ReadFile(This->buf->file, pv, cb, &read, NULL))
526             return INET_E_DOWNLOAD_FAILURE;
527
528         if(pcbRead)
529             *pcbRead = read;
530         return read ? S_OK : S_FALSE;
531     }
532
533     if(This->buf->size) {
534         read = cb;
535
536         if(read > This->buf->size)
537             read = This->buf->size;
538
539         memcpy(pv, This->buf->buf, read);
540
541         if(read < This->buf->size)
542             memmove(This->buf->buf, This->buf->buf+read, This->buf->size-read);
543         This->buf->size -= read;
544     }
545
546     if(read == cb) {
547         if (pcbRead)
548             *pcbRead = read;
549         return S_OK;
550     }
551
552     hres = This->buf->hres = IInternetProtocol_Read(This->buf->protocol, (PBYTE)pv+read, cb-read, &pread);
553     if (pcbRead)
554         *pcbRead = read + pread;
555
556     if(hres == E_PENDING)
557         return E_PENDING;
558     else if(FAILED(hres))
559         FIXME("Read failed: %08x\n", hres);
560
561     return read || pread ? S_OK : S_FALSE;
562 }
563
564 static HRESULT WINAPI ProtocolStream_Write(IStream *iface, const void *pv,
565                                           ULONG cb, ULONG *pcbWritten)
566 {
567     ProtocolStream *This = STREAM_THIS(iface);
568
569     TRACE("(%p)->(%p %d %p)\n", This, pv, cb, pcbWritten);
570
571     return STG_E_ACCESSDENIED;
572 }
573
574 static HRESULT WINAPI ProtocolStream_Seek(IStream *iface, LARGE_INTEGER dlibMove,
575                                          DWORD dwOrigin, ULARGE_INTEGER *plibNewPosition)
576 {
577     ProtocolStream *This = STREAM_THIS(iface);
578     FIXME("(%p)->(%d %08x %p)\n", This, dlibMove.u.LowPart, dwOrigin, plibNewPosition);
579     return E_NOTIMPL;
580 }
581
582 static HRESULT WINAPI ProtocolStream_SetSize(IStream *iface, ULARGE_INTEGER libNewSize)
583 {
584     ProtocolStream *This = STREAM_THIS(iface);
585     FIXME("(%p)->(%d)\n", This, libNewSize.u.LowPart);
586     return E_NOTIMPL;
587 }
588
589 static HRESULT WINAPI ProtocolStream_CopyTo(IStream *iface, IStream *pstm,
590         ULARGE_INTEGER cb, ULARGE_INTEGER *pcbRead, ULARGE_INTEGER *pcbWritten)
591 {
592     ProtocolStream *This = STREAM_THIS(iface);
593     FIXME("(%p)->(%p %d %p %p)\n", This, pstm, cb.u.LowPart, pcbRead, pcbWritten);
594     return E_NOTIMPL;
595 }
596
597 static HRESULT WINAPI ProtocolStream_Commit(IStream *iface, DWORD grfCommitFlags)
598 {
599     ProtocolStream *This = STREAM_THIS(iface);
600
601     TRACE("(%p)->(%08x)\n", This, grfCommitFlags);
602
603     return E_NOTIMPL;
604 }
605
606 static HRESULT WINAPI ProtocolStream_Revert(IStream *iface)
607 {
608     ProtocolStream *This = STREAM_THIS(iface);
609
610     TRACE("(%p)\n", This);
611
612     return E_NOTIMPL;
613 }
614
615 static HRESULT WINAPI ProtocolStream_LockRegion(IStream *iface, ULARGE_INTEGER libOffset,
616                                                ULARGE_INTEGER cb, DWORD dwLockType)
617 {
618     ProtocolStream *This = STREAM_THIS(iface);
619     FIXME("(%p)->(%d %d %d)\n", This, libOffset.u.LowPart, cb.u.LowPart, dwLockType);
620     return E_NOTIMPL;
621 }
622
623 static HRESULT WINAPI ProtocolStream_UnlockRegion(IStream *iface,
624         ULARGE_INTEGER libOffset, ULARGE_INTEGER cb, DWORD dwLockType)
625 {
626     ProtocolStream *This = STREAM_THIS(iface);
627     FIXME("(%p)->(%d %d %d)\n", This, libOffset.u.LowPart, cb.u.LowPart, dwLockType);
628     return E_NOTIMPL;
629 }
630
631 static HRESULT WINAPI ProtocolStream_Stat(IStream *iface, STATSTG *pstatstg,
632                                          DWORD dwStatFlag)
633 {
634     ProtocolStream *This = STREAM_THIS(iface);
635     TRACE("(%p)->(%p %08x)\n", This, pstatstg, dwStatFlag);
636
637     if(!pstatstg)
638         return E_FAIL;
639
640     memset(pstatstg, 0, sizeof(STATSTG));
641
642     if(!(dwStatFlag&STATFLAG_NONAME) && This->buf->cache_file) {
643         pstatstg->pwcsName = CoTaskMemAlloc((lstrlenW(This->buf->cache_file)+1)*sizeof(WCHAR));
644         if(!pstatstg->pwcsName)
645             return STG_E_INSUFFICIENTMEMORY;
646
647         lstrcpyW(pstatstg->pwcsName, This->buf->cache_file);
648     }
649
650     pstatstg->type = STGTY_STREAM;
651     if(This->buf->file != INVALID_HANDLE_VALUE) {
652         GetFileSizeEx(This->buf->file, (PLARGE_INTEGER)&pstatstg->cbSize);
653         GetFileTime(This->buf->file, &pstatstg->ctime, &pstatstg->atime, &pstatstg->mtime);
654         if(pstatstg->cbSize.QuadPart)
655             pstatstg->grfMode = GENERIC_READ;
656     }
657
658     return S_OK;
659 }
660
661 static HRESULT WINAPI ProtocolStream_Clone(IStream *iface, IStream **ppstm)
662 {
663     ProtocolStream *This = STREAM_THIS(iface);
664     FIXME("(%p)->(%p)\n", This, ppstm);
665     return E_NOTIMPL;
666 }
667
668 #undef STREAM_THIS
669
670 static const IStreamVtbl ProtocolStreamVtbl = {
671     ProtocolStream_QueryInterface,
672     ProtocolStream_AddRef,
673     ProtocolStream_Release,
674     ProtocolStream_Read,
675     ProtocolStream_Write,
676     ProtocolStream_Seek,
677     ProtocolStream_SetSize,
678     ProtocolStream_CopyTo,
679     ProtocolStream_Commit,
680     ProtocolStream_Revert,
681     ProtocolStream_LockRegion,
682     ProtocolStream_UnlockRegion,
683     ProtocolStream_Stat,
684     ProtocolStream_Clone
685 };
686
687 static void stgmed_stream_release(stgmed_obj_t *obj)
688 {
689     ProtocolStream *stream = (ProtocolStream*)obj;
690     IStream_Release(STREAM(stream));
691 }
692
693 static HRESULT stgmed_stream_fill_stgmed(stgmed_obj_t *obj, STGMEDIUM *stgmed)
694 {
695     ProtocolStream *stream = (ProtocolStream*)obj;
696
697     stgmed->tymed = TYMED_ISTREAM;
698     stgmed->u.pstm = STREAM(stream);
699     stgmed->pUnkForRelease = STGMEDUNK(stream->buf);
700
701     return S_OK;
702 }
703
704 static HRESULT stgmed_stream_get_result(stgmed_obj_t *obj, DWORD bindf, void **result)
705 {
706     ProtocolStream *stream = (ProtocolStream*)obj;
707
708     if(!(bindf & BINDF_ASYNCHRONOUS) && stream->buf->file == INVALID_HANDLE_VALUE
709        && (stream->buf->hres != S_FALSE || stream->buf->size))
710         return INET_E_DATA_NOT_AVAILABLE;
711
712     IStream_AddRef(STREAM(stream));
713     *result = STREAM(stream);
714     return S_OK;
715 }
716
717 static const stgmed_obj_vtbl stgmed_stream_vtbl = {
718     stgmed_stream_release,
719     stgmed_stream_fill_stgmed,
720     stgmed_stream_get_result
721 };
722
723 typedef struct {
724     stgmed_obj_t stgmed_obj;
725     stgmed_buf_t *buf;
726 } stgmed_file_obj_t;
727
728 static stgmed_obj_t *create_stgmed_stream(stgmed_buf_t *buf)
729 {
730     ProtocolStream *ret = heap_alloc(sizeof(ProtocolStream));
731
732     ret->stgmed_obj.vtbl = &stgmed_stream_vtbl;
733     ret->lpStreamVtbl = &ProtocolStreamVtbl;
734     ret->ref = 1;
735
736     IUnknown_AddRef(STGMEDUNK(buf));
737     ret->buf = buf;
738
739     URLMON_LockModule();
740
741     return &ret->stgmed_obj;
742 }
743
744 static void stgmed_file_release(stgmed_obj_t *obj)
745 {
746     stgmed_file_obj_t *file_obj = (stgmed_file_obj_t*)obj;
747
748     IUnknown_Release(STGMEDUNK(file_obj->buf));
749     heap_free(file_obj);
750 }
751
752 static HRESULT stgmed_file_fill_stgmed(stgmed_obj_t *obj, STGMEDIUM *stgmed)
753 {
754     stgmed_file_obj_t *file_obj = (stgmed_file_obj_t*)obj;
755
756     if(!file_obj->buf->cache_file) {
757         WARN("cache_file not set\n");
758         return INET_E_DATA_NOT_AVAILABLE;
759     }
760
761     read_protocol_data(file_obj->buf);
762
763     stgmed->tymed = TYMED_FILE;
764     stgmed->u.lpszFileName = file_obj->buf->cache_file;
765     stgmed->pUnkForRelease = STGMEDUNK(file_obj->buf);
766
767     return S_OK;
768 }
769
770 static HRESULT stgmed_file_get_result(stgmed_obj_t *obj, DWORD bindf, void **result)
771 {
772     return bindf & BINDF_ASYNCHRONOUS ? MK_S_ASYNCHRONOUS : S_OK;
773 }
774
775 static const stgmed_obj_vtbl stgmed_file_vtbl = {
776     stgmed_file_release,
777     stgmed_file_fill_stgmed,
778     stgmed_file_get_result
779 };
780
781 static stgmed_obj_t *create_stgmed_file(stgmed_buf_t *buf)
782 {
783     stgmed_file_obj_t *ret = heap_alloc(sizeof(*ret));
784
785     ret->stgmed_obj.vtbl = &stgmed_file_vtbl;
786
787     IUnknown_AddRef(STGMEDUNK(buf));
788     ret->buf = buf;
789
790     return &ret->stgmed_obj;
791 }
792
793 #define BINDING_THIS(iface) DEFINE_THIS(Binding, Binding, iface)
794
795 static HRESULT WINAPI Binding_QueryInterface(IBinding *iface, REFIID riid, void **ppv)
796 {
797     Binding *This = BINDING_THIS(iface);
798
799     *ppv = NULL;
800
801     if(IsEqualGUID(&IID_IUnknown, riid)) {
802         TRACE("(%p)->(IID_IUnknown %p)\n", This, ppv);
803         *ppv = BINDING(This);
804     }else if(IsEqualGUID(&IID_IBinding, riid)) {
805         TRACE("(%p)->(IID_IBinding %p)\n", This, ppv);
806         *ppv = BINDING(This);
807     }else if(IsEqualGUID(&IID_IInternetProtocolSink, riid)) {
808         TRACE("(%p)->(IID_IInternetProtocolSink %p)\n", This, ppv);
809         *ppv = PROTSINK(This);
810     }else if(IsEqualGUID(&IID_IInternetBindInfo, riid)) {
811         TRACE("(%p)->(IID_IInternetBindInfo %p)\n", This, ppv);
812         *ppv = BINDINF(This);
813     }else if(IsEqualGUID(&IID_IServiceProvider, riid)) {
814         TRACE("(%p)->(IID_IServiceProvider %p)\n", This, ppv);
815         *ppv = SERVPROV(This);
816     }else if(IsEqualGUID(&IID_IWinInetInfo, riid)) {
817         TRACE("(%p)->(IID_IWinInetInfo %p)\n", This, ppv);
818
819         /* NOTE: This violidates COM rules, but tests prove that we should do it */
820         if(!get_wininet_info(This->protocol))
821            return E_NOINTERFACE;
822
823         *ppv = INETINFO(This);
824     }else if(IsEqualGUID(&IID_IWinInetHttpInfo, riid)) {
825         IWinInetHttpInfo *http_info;
826         IWinInetInfo *info;
827         HRESULT hres;
828
829         TRACE("(%p)->(IID_IWinInetHttpInfo %p)\n", This, ppv);
830
831         info = get_wininet_info(This->protocol);
832         if(!info)
833             return E_NOINTERFACE;
834
835         hres = IWinInetInfo_QueryInterface(info, &IID_IWinInetHttpInfo, (void**)&http_info);
836         if(FAILED(hres))
837             return E_NOINTERFACE;
838
839         IWinInetHttpInfo_Release(http_info);
840         *ppv = INETINFO(This);
841     }
842
843     if(*ppv) {
844         IBinding_AddRef(BINDING(This));
845         return S_OK;
846     }
847
848     WARN("Unsupported interface %s\n", debugstr_guid(riid));
849     return E_NOINTERFACE;
850 }
851
852 static ULONG WINAPI Binding_AddRef(IBinding *iface)
853 {
854     Binding *This = BINDING_THIS(iface);
855     LONG ref = InterlockedIncrement(&This->ref);
856
857     TRACE("(%p) ref=%d\n", This, ref);
858
859     return ref;
860 }
861
862 static ULONG WINAPI Binding_Release(IBinding *iface)
863 {
864     Binding *This = BINDING_THIS(iface);
865     LONG ref = InterlockedDecrement(&This->ref);
866
867     TRACE("(%p) ref=%d\n", This, ref);
868
869     if(!ref) {
870         if(This->notif_hwnd)
871             release_notif_hwnd(This->notif_hwnd);
872         if(This->mon)
873             IMoniker_Release(This->mon);
874         if(This->callback)
875             IBindStatusCallback_Release(This->callback);
876         if(This->protocol)
877             IInternetProtocol_Release(This->protocol);
878         if(This->service_provider)
879             IServiceProvider_Release(This->service_provider);
880         if(This->stgmed_buf)
881             IUnknown_Release(STGMEDUNK(This->stgmed_buf));
882         if(This->stgmed_obj)
883             This->stgmed_obj->vtbl->release(This->stgmed_obj);
884         if(This->obj)
885             IUnknown_Release(This->obj);
886         if(This->bctx)
887             IBindCtx_Release(This->bctx);
888
889         ReleaseBindInfo(&This->bindinfo);
890         This->section.DebugInfo->Spare[0] = 0;
891         DeleteCriticalSection(&This->section);
892         heap_free(This->mime);
893         heap_free(This->redirect_url);
894         heap_free(This->url);
895
896         heap_free(This);
897
898         URLMON_UnlockModule();
899     }
900
901     return ref;
902 }
903
904 static HRESULT WINAPI Binding_Abort(IBinding *iface)
905 {
906     Binding *This = BINDING_THIS(iface);
907     HRESULT hres;
908
909     TRACE("(%p)\n", This);
910
911     if(This->state & BINDING_ABORTED)
912         return E_FAIL;
913
914     hres = IInternetProtocol_Abort(This->protocol, E_ABORT, ERROR_SUCCESS);
915     if(FAILED(hres))
916         return hres;
917
918     This->state |= BINDING_ABORTED;
919     return S_OK;
920 }
921
922 static HRESULT WINAPI Binding_Suspend(IBinding *iface)
923 {
924     Binding *This = BINDING_THIS(iface);
925     FIXME("(%p)\n", This);
926     return E_NOTIMPL;
927 }
928
929 static HRESULT WINAPI Binding_Resume(IBinding *iface)
930 {
931     Binding *This = BINDING_THIS(iface);
932     FIXME("(%p)\n", This);
933     return E_NOTIMPL;
934 }
935
936 static HRESULT WINAPI Binding_SetPriority(IBinding *iface, LONG nPriority)
937 {
938     Binding *This = BINDING_THIS(iface);
939     FIXME("(%p)->(%d)\n", This, nPriority);
940     return E_NOTIMPL;
941 }
942
943 static HRESULT WINAPI Binding_GetPriority(IBinding *iface, LONG *pnPriority)
944 {
945     Binding *This = BINDING_THIS(iface);
946     FIXME("(%p)->(%p)\n", This, pnPriority);
947     return E_NOTIMPL;
948 }
949
950 static HRESULT WINAPI Binding_GetBindResult(IBinding *iface, CLSID *pclsidProtocol,
951         DWORD *pdwResult, LPOLESTR *pszResult, DWORD *pdwReserved)
952 {
953     Binding *This = BINDING_THIS(iface);
954     FIXME("(%p)->(%p %p %p %p)\n", This, pclsidProtocol, pdwResult, pszResult, pdwReserved);
955     return E_NOTIMPL;
956 }
957
958 static Binding *get_bctx_binding(IBindCtx *bctx)
959 {
960     IBinding *binding;
961     IUnknown *unk;
962     HRESULT hres;
963
964     hres = IBindCtx_GetObjectParam(bctx, cbinding_contextW, &unk);
965     if(FAILED(hres))
966         return NULL;
967
968     hres = IUnknown_QueryInterface(unk, &IID_IBinding, (void*)&binding);
969     IUnknown_Release(unk);
970     if(FAILED(hres))
971         return NULL;
972
973     /* FIXME!!! */
974     return BINDING_THIS(binding);
975 }
976
977 #undef BINDING_THIS
978
979 static const IBindingVtbl BindingVtbl = {
980     Binding_QueryInterface,
981     Binding_AddRef,
982     Binding_Release,
983     Binding_Abort,
984     Binding_Suspend,
985     Binding_Resume,
986     Binding_SetPriority,
987     Binding_GetPriority,
988     Binding_GetBindResult
989 };
990
991 #define PROTSINK_THIS(iface) DEFINE_THIS(Binding, IInternetProtocolSink, iface)
992
993 static HRESULT WINAPI InternetProtocolSink_QueryInterface(IInternetProtocolSink *iface,
994         REFIID riid, void **ppv)
995 {
996     Binding *This = PROTSINK_THIS(iface);
997     return IBinding_QueryInterface(BINDING(This), riid, ppv);
998 }
999
1000 static ULONG WINAPI InternetProtocolSink_AddRef(IInternetProtocolSink *iface)
1001 {
1002     Binding *This = PROTSINK_THIS(iface);
1003     return IBinding_AddRef(BINDING(This));
1004 }
1005
1006 static ULONG WINAPI InternetProtocolSink_Release(IInternetProtocolSink *iface)
1007 {
1008     Binding *This = PROTSINK_THIS(iface);
1009     return IBinding_Release(BINDING(This));
1010 }
1011
1012 static HRESULT WINAPI InternetProtocolSink_Switch(IInternetProtocolSink *iface,
1013         PROTOCOLDATA *pProtocolData)
1014 {
1015     Binding *This = PROTSINK_THIS(iface);
1016
1017     WARN("(%p)->(%p)\n", This, pProtocolData);
1018
1019     return E_FAIL;
1020 }
1021
1022 static void on_progress(Binding *This, ULONG progress, ULONG progress_max,
1023                         ULONG status_code, LPCWSTR status_text)
1024 {
1025     IBindStatusCallback_OnProgress(This->callback, progress, progress_max,
1026             status_code, status_text);
1027 }
1028
1029 static HRESULT WINAPI InternetProtocolSink_ReportProgress(IInternetProtocolSink *iface,
1030         ULONG ulStatusCode, LPCWSTR szStatusText)
1031 {
1032     Binding *This = PROTSINK_THIS(iface);
1033
1034     TRACE("(%p)->(%u %s)\n", This, ulStatusCode, debugstr_w(szStatusText));
1035
1036     switch(ulStatusCode) {
1037     case BINDSTATUS_FINDINGRESOURCE:
1038         on_progress(This, 0, 0, BINDSTATUS_FINDINGRESOURCE, szStatusText);
1039         break;
1040     case BINDSTATUS_CONNECTING:
1041         on_progress(This, 0, 0, BINDSTATUS_CONNECTING, szStatusText);
1042         break;
1043     case BINDSTATUS_REDIRECTING:
1044         heap_free(This->redirect_url);
1045         This->redirect_url = heap_strdupW(szStatusText);
1046         on_progress(This, 0, 0, BINDSTATUS_REDIRECTING, szStatusText);
1047         break;
1048     case BINDSTATUS_BEGINDOWNLOADDATA:
1049         fill_stgmed_buffer(This->stgmed_buf);
1050         break;
1051     case BINDSTATUS_SENDINGREQUEST:
1052         on_progress(This, 0, 0, BINDSTATUS_SENDINGREQUEST, szStatusText);
1053         break;
1054     case BINDSTATUS_PROTOCOLCLASSID:
1055         break;
1056     case BINDSTATUS_MIMETYPEAVAILABLE:
1057     case BINDSTATUS_VERIFIEDMIMETYPEAVAILABLE:
1058         mime_available(This, szStatusText);
1059         break;
1060     case BINDSTATUS_CACHEFILENAMEAVAILABLE:
1061         cache_file_available(This, szStatusText);
1062         break;
1063     case BINDSTATUS_DECODING:
1064         IBindStatusCallback_OnProgress(This->callback, 0, 0, BINDSTATUS_DECODING, szStatusText);
1065         break;
1066     case BINDSTATUS_LOADINGMIMEHANDLER:
1067         on_progress(This, 0, 0, BINDSTATUS_LOADINGMIMEHANDLER, szStatusText);
1068         break;
1069     case BINDSTATUS_DIRECTBIND: /* FIXME: Handle BINDSTATUS_DIRECTBIND in BindProtocol */
1070         This->report_mime = FALSE;
1071         break;
1072     case BINDSTATUS_ACCEPTRANGES:
1073         break;
1074     default:
1075         FIXME("Unhandled status code %d\n", ulStatusCode);
1076         return E_NOTIMPL;
1077     };
1078
1079     return S_OK;
1080 }
1081
1082 static void report_data(Binding *This, DWORD bscf, ULONG progress, ULONG progress_max)
1083 {
1084     FORMATETC formatetc = {0, NULL, 1, -1, TYMED_ISTREAM};
1085     BOOL sent_begindownloaddata = FALSE;
1086
1087     TRACE("(%p)->(%d %u %u)\n", This, bscf, progress, progress_max);
1088
1089     if(This->download_state == END_DOWNLOAD || (This->state & (BINDING_STOPPED|BINDING_ABORTED)))
1090         return;
1091
1092     if(This->stgmed_buf->file != INVALID_HANDLE_VALUE)
1093         read_protocol_data(This->stgmed_buf);
1094     else if(This->download_state == BEFORE_DOWNLOAD)
1095         fill_stgmed_buffer(This->stgmed_buf);
1096
1097     if(This->download_state == BEFORE_DOWNLOAD) {
1098         This->download_state = DOWNLOADING;
1099         sent_begindownloaddata = TRUE;
1100         IBindStatusCallback_OnProgress(This->callback, progress, progress_max,
1101                 BINDSTATUS_BEGINDOWNLOADDATA, This->url);
1102
1103         if(This->stgmed_buf->cache_file)
1104             IBindStatusCallback_OnProgress(This->callback, progress, progress_max,
1105                     BINDSTATUS_CACHEFILENAMEAVAILABLE, This->stgmed_buf->cache_file);
1106     }
1107
1108     if(This->stgmed_buf->hres == S_FALSE || (bscf & BSCF_LASTDATANOTIFICATION)) {
1109         This->download_state = END_DOWNLOAD;
1110         IBindStatusCallback_OnProgress(This->callback, progress, progress_max,
1111                 BINDSTATUS_ENDDOWNLOADDATA, This->url);
1112     }else if(!sent_begindownloaddata) {
1113         IBindStatusCallback_OnProgress(This->callback, progress, progress_max,
1114                 BINDSTATUS_DOWNLOADINGDATA, This->url);
1115     }
1116
1117     if(This->state & (BINDING_STOPPED|BINDING_ABORTED))
1118         return;
1119
1120     if(This->to_object) {
1121         if(!(This->state & BINDING_OBJAVAIL)) {
1122             IBinding_AddRef(BINDING(This));
1123             create_object(This);
1124             IBinding_Release(BINDING(This));
1125         }
1126     }else {
1127         STGMEDIUM stgmed;
1128         HRESULT hres;
1129
1130         if(!(This->state & BINDING_LOCKED)) {
1131             HRESULT hres = IInternetProtocol_LockRequest(This->protocol, 0);
1132             if(SUCCEEDED(hres))
1133                 This->state |= BINDING_LOCKED;
1134         }
1135
1136         hres = This->stgmed_obj->vtbl->fill_stgmed(This->stgmed_obj, &stgmed);
1137         if(FAILED(hres)) {
1138             stop_binding(This, hres, NULL);
1139             return;
1140         }
1141
1142         formatetc.tymed = stgmed.tymed;
1143         formatetc.cfFormat = This->clipboard_format;
1144
1145         IBindStatusCallback_OnDataAvailable(This->callback, bscf, progress,
1146                 &formatetc, &stgmed);
1147
1148         if(This->download_state == END_DOWNLOAD)
1149             stop_binding(This, S_OK, NULL);
1150     }
1151 }
1152
1153 static HRESULT WINAPI InternetProtocolSink_ReportData(IInternetProtocolSink *iface,
1154         DWORD grfBSCF, ULONG ulProgress, ULONG ulProgressMax)
1155 {
1156     Binding *This = PROTSINK_THIS(iface);
1157
1158     TRACE("(%p)->(%d %u %u)\n", This, grfBSCF, ulProgress, ulProgressMax);
1159
1160     report_data(This, grfBSCF, ulProgress, ulProgressMax);
1161     return S_OK;
1162 }
1163
1164 static HRESULT WINAPI InternetProtocolSink_ReportResult(IInternetProtocolSink *iface,
1165         HRESULT hrResult, DWORD dwError, LPCWSTR szResult)
1166 {
1167     Binding *This = PROTSINK_THIS(iface);
1168
1169     TRACE("(%p)->(%08x %d %s)\n", This, hrResult, dwError, debugstr_w(szResult));
1170
1171     stop_binding(This, hrResult, szResult);
1172     IInternetProtocol_Terminate(This->protocol, 0);
1173     return S_OK;
1174 }
1175
1176 #undef PROTSINK_THIS
1177
1178 static const IInternetProtocolSinkVtbl InternetProtocolSinkVtbl = {
1179     InternetProtocolSink_QueryInterface,
1180     InternetProtocolSink_AddRef,
1181     InternetProtocolSink_Release,
1182     InternetProtocolSink_Switch,
1183     InternetProtocolSink_ReportProgress,
1184     InternetProtocolSink_ReportData,
1185     InternetProtocolSink_ReportResult
1186 };
1187
1188 #define BINDINF_THIS(iface) DEFINE_THIS(Binding, InternetBindInfo, iface)
1189
1190 static HRESULT WINAPI InternetBindInfo_QueryInterface(IInternetBindInfo *iface,
1191         REFIID riid, void **ppv)
1192 {
1193     Binding *This = BINDINF_THIS(iface);
1194     return IBinding_QueryInterface(BINDING(This), riid, ppv);
1195 }
1196
1197 static ULONG WINAPI InternetBindInfo_AddRef(IInternetBindInfo *iface)
1198 {
1199     Binding *This = BINDINF_THIS(iface);
1200     return IBinding_AddRef(BINDING(This));
1201 }
1202
1203 static ULONG WINAPI InternetBindInfo_Release(IInternetBindInfo *iface)
1204 {
1205     Binding *This = BINDINF_THIS(iface);
1206     return IBinding_Release(BINDING(This));
1207 }
1208
1209 static HRESULT WINAPI InternetBindInfo_GetBindInfo(IInternetBindInfo *iface,
1210         DWORD *grfBINDF, BINDINFO *pbindinfo)
1211 {
1212     Binding *This = BINDINF_THIS(iface);
1213
1214     TRACE("(%p)->(%p %p)\n", This, grfBINDF, pbindinfo);
1215
1216     *grfBINDF = This->bindf;
1217
1218     *pbindinfo = This->bindinfo;
1219
1220     if(pbindinfo->szExtraInfo || pbindinfo->szCustomVerb)
1221         FIXME("copy strings\n");
1222
1223     if(pbindinfo->stgmedData.pUnkForRelease)
1224         IUnknown_AddRef(pbindinfo->stgmedData.pUnkForRelease);
1225
1226     if(pbindinfo->pUnk)
1227         IUnknown_AddRef(pbindinfo->pUnk);
1228
1229     return S_OK;
1230 }
1231
1232 static HRESULT WINAPI InternetBindInfo_GetBindString(IInternetBindInfo *iface,
1233         ULONG ulStringType, LPOLESTR *ppwzStr, ULONG cEl, ULONG *pcElFetched)
1234 {
1235     Binding *This = BINDINF_THIS(iface);
1236
1237     TRACE("(%p)->(%d %p %d %p)\n", This, ulStringType, ppwzStr, cEl, pcElFetched);
1238
1239     switch(ulStringType) {
1240     case BINDSTRING_ACCEPT_MIMES: {
1241         static const WCHAR wszMimes[] = {'*','/','*',0};
1242
1243         if(!ppwzStr || !pcElFetched)
1244             return E_INVALIDARG;
1245
1246         ppwzStr[0] = CoTaskMemAlloc(sizeof(wszMimes));
1247         memcpy(ppwzStr[0], wszMimes, sizeof(wszMimes));
1248         *pcElFetched = 1;
1249         return S_OK;
1250     }
1251     case BINDSTRING_USER_AGENT: {
1252         IInternetBindInfo *bindinfo = NULL;
1253         HRESULT hres;
1254
1255         hres = IBindStatusCallback_QueryInterface(This->callback, &IID_IInternetBindInfo,
1256                                                   (void**)&bindinfo);
1257         if(FAILED(hres))
1258             return hres;
1259
1260         hres = IInternetBindInfo_GetBindString(bindinfo, ulStringType, ppwzStr,
1261                                                cEl, pcElFetched);
1262         IInternetBindInfo_Release(bindinfo);
1263
1264         return hres;
1265     }
1266     case BINDSTRING_URL: {
1267         DWORD size = (strlenW(This->url)+1) * sizeof(WCHAR);
1268
1269         if(!ppwzStr || !pcElFetched)
1270             return E_INVALIDARG;
1271
1272         *ppwzStr = CoTaskMemAlloc(size);
1273         memcpy(*ppwzStr, This->url, size);
1274         *pcElFetched = 1;
1275         return S_OK;
1276     }
1277     }
1278
1279     FIXME("not supported string type %d\n", ulStringType);
1280     return E_NOTIMPL;
1281 }
1282
1283 #undef BINDF_THIS
1284
1285 static const IInternetBindInfoVtbl InternetBindInfoVtbl = {
1286     InternetBindInfo_QueryInterface,
1287     InternetBindInfo_AddRef,
1288     InternetBindInfo_Release,
1289     InternetBindInfo_GetBindInfo,
1290     InternetBindInfo_GetBindString
1291 };
1292
1293 #define INETINFO_THIS(iface) DEFINE_THIS(Binding, WinInetHttpInfo, iface)
1294
1295 static HRESULT WINAPI WinInetHttpInfo_QueryInterface(IWinInetHttpInfo *iface, REFIID riid, void **ppv)
1296 {
1297     Binding *This = INETINFO_THIS(iface);
1298     return IBinding_QueryInterface(BINDING(This), riid, ppv);
1299 }
1300
1301 static ULONG WINAPI WinInetHttpInfo_AddRef(IWinInetHttpInfo *iface)
1302 {
1303     Binding *This = INETINFO_THIS(iface);
1304     return IBinding_AddRef(BINDING(This));
1305 }
1306
1307 static ULONG WINAPI WinInetHttpInfo_Release(IWinInetHttpInfo *iface)
1308 {
1309     Binding *This = INETINFO_THIS(iface);
1310     return IBinding_Release(BINDING(This));
1311 }
1312
1313 static HRESULT WINAPI WinInetHttpInfo_QueryOption(IWinInetHttpInfo *iface, DWORD dwOption,
1314         void *pBuffer, DWORD *pcbBuffer)
1315 {
1316     Binding *This = INETINFO_THIS(iface);
1317     FIXME("(%p)->(%x %p %p)\n", This, dwOption, pBuffer, pcbBuffer);
1318     return E_NOTIMPL;
1319 }
1320
1321 static HRESULT WINAPI WinInetHttpInfo_QueryInfo(IWinInetHttpInfo *iface, DWORD dwOption,
1322         void *pBuffer, DWORD *pcbBuffer, DWORD *pdwFlags, DWORD *pdwReserved)
1323 {
1324     Binding *This = INETINFO_THIS(iface);
1325     FIXME("(%p)->(%x %p %p %p %p)\n", This, dwOption, pBuffer, pcbBuffer, pdwFlags, pdwReserved);
1326     return E_NOTIMPL;
1327 }
1328
1329 #undef INETINFO_THIS
1330
1331 static const IWinInetHttpInfoVtbl WinInetHttpInfoVtbl = {
1332     WinInetHttpInfo_QueryInterface,
1333     WinInetHttpInfo_AddRef,
1334     WinInetHttpInfo_Release,
1335     WinInetHttpInfo_QueryOption,
1336     WinInetHttpInfo_QueryInfo
1337 };
1338
1339 #define SERVPROV_THIS(iface) DEFINE_THIS(Binding, ServiceProvider, iface)
1340
1341 static HRESULT WINAPI ServiceProvider_QueryInterface(IServiceProvider *iface,
1342         REFIID riid, void **ppv)
1343 {
1344     Binding *This = SERVPROV_THIS(iface);
1345     return IBinding_QueryInterface(BINDING(This), riid, ppv);
1346 }
1347
1348 static ULONG WINAPI ServiceProvider_AddRef(IServiceProvider *iface)
1349 {
1350     Binding *This = SERVPROV_THIS(iface);
1351     return IBinding_AddRef(BINDING(This));
1352 }
1353
1354 static ULONG WINAPI ServiceProvider_Release(IServiceProvider *iface)
1355 {
1356     Binding *This = SERVPROV_THIS(iface);
1357     return IBinding_Release(BINDING(This));
1358 }
1359
1360 static HRESULT WINAPI ServiceProvider_QueryService(IServiceProvider *iface,
1361         REFGUID guidService, REFIID riid, void **ppv)
1362 {
1363     Binding *This = SERVPROV_THIS(iface);
1364     HRESULT hres;
1365
1366     TRACE("(%p)->(%s %s %p)\n", This, debugstr_guid(guidService), debugstr_guid(riid), ppv);
1367
1368     if(This->service_provider) {
1369         hres = IServiceProvider_QueryService(This->service_provider, guidService,
1370                                              riid, ppv);
1371         if(SUCCEEDED(hres))
1372             return hres;
1373     }
1374
1375     WARN("unknown service %s\n", debugstr_guid(guidService));
1376     return E_NOTIMPL;
1377 }
1378
1379 #undef SERVPROV_THIS
1380
1381 static const IServiceProviderVtbl ServiceProviderVtbl = {
1382     ServiceProvider_QueryInterface,
1383     ServiceProvider_AddRef,
1384     ServiceProvider_Release,
1385     ServiceProvider_QueryService
1386 };
1387
1388 static HRESULT get_callback(IBindCtx *pbc, IBindStatusCallback **callback)
1389 {
1390     IUnknown *unk;
1391     HRESULT hres;
1392
1393     hres = IBindCtx_GetObjectParam(pbc, bscb_holderW, &unk);
1394     if(FAILED(hres))
1395         return create_default_callback(callback);
1396
1397     hres = IUnknown_QueryInterface(unk, &IID_IBindStatusCallback, (void**)callback);
1398     IUnknown_Release(unk);
1399     return hres;
1400 }
1401
1402 static BOOL is_urlmon_protocol(LPCWSTR url)
1403 {
1404     static const WCHAR wszCdl[] = {'c','d','l'};
1405     static const WCHAR wszFile[] = {'f','i','l','e'};
1406     static const WCHAR wszFtp[]  = {'f','t','p'};
1407     static const WCHAR wszGopher[] = {'g','o','p','h','e','r'};
1408     static const WCHAR wszHttp[] = {'h','t','t','p'};
1409     static const WCHAR wszHttps[] = {'h','t','t','p','s'};
1410     static const WCHAR wszMk[]   = {'m','k'};
1411
1412     static const struct {
1413         LPCWSTR scheme;
1414         int len;
1415     } protocol_list[] = {
1416         {wszCdl,    sizeof(wszCdl)   /sizeof(WCHAR)},
1417         {wszFile,   sizeof(wszFile)  /sizeof(WCHAR)},
1418         {wszFtp,    sizeof(wszFtp)   /sizeof(WCHAR)},
1419         {wszGopher, sizeof(wszGopher)/sizeof(WCHAR)},
1420         {wszHttp,   sizeof(wszHttp)  /sizeof(WCHAR)},
1421         {wszHttps,  sizeof(wszHttps) /sizeof(WCHAR)},
1422         {wszMk,     sizeof(wszMk)    /sizeof(WCHAR)}
1423     };
1424
1425     unsigned int i;
1426     int len = lstrlenW(url);
1427
1428     for(i=0; i < sizeof(protocol_list)/sizeof(protocol_list[0]); i++) {
1429         if(len >= protocol_list[i].len
1430            && !memcmp(url, protocol_list[i].scheme, protocol_list[i].len*sizeof(WCHAR)))
1431             return TRUE;
1432     }
1433
1434     return FALSE;
1435 }
1436
1437 static HRESULT Binding_Create(IMoniker *mon, Binding *binding_ctx, LPCWSTR url, IBindCtx *pbc,
1438         BOOL to_obj, REFIID riid, Binding **binding)
1439 {
1440     Binding *ret;
1441     HRESULT hres;
1442
1443     URLMON_LockModule();
1444
1445     ret = heap_alloc_zero(sizeof(Binding));
1446
1447     ret->lpBindingVtbl              = &BindingVtbl;
1448     ret->lpIInternetProtocolSinkVtbl = &InternetProtocolSinkVtbl;
1449     ret->lpInternetBindInfoVtbl     = &InternetBindInfoVtbl;
1450     ret->lpWinInetHttpInfoVtbl      = &WinInetHttpInfoVtbl;
1451     ret->lpServiceProviderVtbl      = &ServiceProviderVtbl;
1452
1453     ret->ref = 1;
1454
1455     ret->to_object = to_obj;
1456     ret->iid = *riid;
1457     ret->notif_hwnd = get_notif_hwnd();
1458     ret->report_mime = !binding_ctx;
1459     ret->download_state = BEFORE_DOWNLOAD;
1460
1461     if(to_obj) {
1462         IBindCtx_AddRef(pbc);
1463         ret->bctx = pbc;
1464     }
1465
1466     if(mon) {
1467         IMoniker_AddRef(mon);
1468         ret->mon = mon;
1469     }
1470
1471     ret->bindinfo.cbSize = sizeof(BINDINFO);
1472
1473     InitializeCriticalSection(&ret->section);
1474     ret->section.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": Binding.section");
1475
1476     hres = get_callback(pbc, &ret->callback);
1477     if(FAILED(hres)) {
1478         WARN("Could not get IBindStatusCallback\n");
1479         IBinding_Release(BINDING(ret));
1480         return hres;
1481     }
1482
1483     IBindStatusCallback_QueryInterface(ret->callback, &IID_IServiceProvider,
1484                                        (void**)&ret->service_provider);
1485
1486     if(binding_ctx) {
1487         ret->protocol = binding_ctx->protocol;
1488         IInternetProtocol_AddRef(ret->protocol);
1489     }else {
1490         hres = create_binding_protocol(url, TRUE, &ret->protocol);
1491         if(FAILED(hres)) {
1492             WARN("Could not get protocol handler\n");
1493             IBinding_Release(BINDING(ret));
1494             return hres;
1495         }
1496     }
1497
1498     hres = IBindStatusCallback_GetBindInfo(ret->callback, &ret->bindf, &ret->bindinfo);
1499     if(FAILED(hres)) {
1500         WARN("GetBindInfo failed: %08x\n", hres);
1501         IBinding_Release(BINDING(ret));
1502         return hres;
1503     }
1504
1505     TRACE("bindf %08x\n", ret->bindf);
1506     dump_BINDINFO(&ret->bindinfo);
1507
1508     ret->bindf |= BINDF_FROMURLMON;
1509     if(to_obj)
1510         ret->bindinfo.dwOptions |= 0x100000;
1511
1512     if(!(ret->bindf & BINDF_ASYNCHRONOUS)) {
1513         ret->bindf |= BINDF_NEEDFILE;
1514         ret->use_cache_file = TRUE;
1515     }else if(!is_urlmon_protocol(url)) {
1516         ret->bindf |= BINDF_NEEDFILE;
1517     }
1518
1519     ret->url = heap_strdupW(url);
1520
1521     if(binding_ctx) {
1522         ret->stgmed_buf = binding_ctx->stgmed_buf;
1523         IUnknown_AddRef(STGMEDUNK(ret->stgmed_buf));
1524         ret->clipboard_format = binding_ctx->clipboard_format;
1525     }else {
1526         ret->stgmed_buf = create_stgmed_buf(ret->protocol);
1527     }
1528
1529     if(to_obj) {
1530         ret->stgmed_obj = NULL;
1531     }else if(IsEqualGUID(&IID_IStream, riid)) {
1532         ret->stgmed_obj = create_stgmed_stream(ret->stgmed_buf);
1533     }else if(IsEqualGUID(&IID_IUnknown, riid)) {
1534         ret->bindf |= BINDF_NEEDFILE;
1535         ret->stgmed_obj = create_stgmed_file(ret->stgmed_buf);
1536     }else {
1537         FIXME("Unsupported riid %s\n", debugstr_guid(riid));
1538         IBinding_Release(BINDING(ret));
1539         return E_NOTIMPL;
1540     }
1541
1542     *binding = ret;
1543     return S_OK;
1544 }
1545
1546 static HRESULT start_binding(IMoniker *mon, Binding *binding_ctx, LPCWSTR url, IBindCtx *pbc,
1547                              BOOL to_obj, REFIID riid, Binding **ret)
1548 {
1549     Binding *binding = NULL;
1550     HRESULT hres;
1551     MSG msg;
1552
1553     hres = Binding_Create(mon, binding_ctx, url, pbc, to_obj, riid, &binding);
1554     if(FAILED(hres))
1555         return hres;
1556
1557     hres = IBindStatusCallback_OnStartBinding(binding->callback, 0, BINDING(binding));
1558     if(FAILED(hres)) {
1559         WARN("OnStartBinding failed: %08x\n", hres);
1560         stop_binding(binding, INET_E_DOWNLOAD_FAILURE, NULL);
1561         IBinding_Release(BINDING(binding));
1562         return hres;
1563     }
1564
1565     if(binding_ctx) {
1566         set_binding_sink(binding->protocol, PROTSINK(binding), BINDINF(binding));
1567         if(binding_ctx->redirect_url)
1568             IBindStatusCallback_OnProgress(binding->callback, 0, 0, BINDSTATUS_REDIRECTING, binding_ctx->redirect_url);
1569         report_data(binding, BSCF_FIRSTDATANOTIFICATION | (binding_ctx->download_state == END_DOWNLOAD ? BSCF_LASTDATANOTIFICATION : 0),
1570                 0, 0);
1571     }else {
1572         hres = IInternetProtocol_Start(binding->protocol, url, PROTSINK(binding),
1573                  BINDINF(binding), PI_APARTMENTTHREADED|PI_MIMEVERIFICATION, 0);
1574
1575         TRACE("start ret %08x\n", hres);
1576
1577         if(FAILED(hres) && hres != E_PENDING) {
1578             stop_binding(binding, hres, NULL);
1579             IBinding_Release(BINDING(binding));
1580
1581             return hres;
1582         }
1583     }
1584
1585     while(!(binding->bindf & BINDF_ASYNCHRONOUS) &&
1586           !(binding->state & BINDING_STOPPED)) {
1587         MsgWaitForMultipleObjects(0, NULL, FALSE, 5000, QS_POSTMESSAGE);
1588         while (PeekMessageW(&msg, binding->notif_hwnd, WM_USER, WM_USER+117, PM_REMOVE|PM_NOYIELD)) {
1589             TranslateMessage(&msg);
1590             DispatchMessageW(&msg);
1591         }
1592     }
1593
1594     *ret = binding;
1595     return S_OK;
1596 }
1597
1598 HRESULT bind_to_storage(LPCWSTR url, IBindCtx *pbc, REFIID riid, void **ppv)
1599 {
1600     Binding *binding = NULL, *binding_ctx;
1601     HRESULT hres;
1602
1603     *ppv = NULL;
1604
1605     binding_ctx = get_bctx_binding(pbc);
1606
1607     hres = start_binding(NULL, binding_ctx, url, pbc, FALSE, riid, &binding);
1608     if(binding_ctx)
1609         IBinding_Release(BINDING(binding_ctx));
1610     if(FAILED(hres))
1611         return hres;
1612
1613     if(binding->hres == S_OK && binding->stgmed_buf->init) {
1614         if((binding->state & BINDING_STOPPED) && (binding->state & BINDING_LOCKED))
1615             IInternetProtocol_UnlockRequest(binding->protocol);
1616
1617         hres = binding->stgmed_obj->vtbl->get_result(binding->stgmed_obj, binding->bindf, ppv);
1618     }else if(binding->bindf & BINDF_ASYNCHRONOUS) {
1619         hres = MK_S_ASYNCHRONOUS;
1620     }else {
1621         hres = FAILED(binding->hres) ? binding->hres : S_OK;
1622     }
1623
1624     IBinding_Release(BINDING(binding));
1625
1626     return hres;
1627 }
1628
1629 HRESULT bind_to_object(IMoniker *mon, LPCWSTR url, IBindCtx *pbc, REFIID riid, void **ppv)
1630 {
1631     Binding *binding;
1632     HRESULT hres;
1633
1634     *ppv = NULL;
1635
1636     hres = start_binding(mon, NULL, url, pbc, TRUE, riid, &binding);
1637     if(FAILED(hres))
1638         return hres;
1639
1640     if(binding->hres != S_OK) {
1641         hres = SUCCEEDED(binding->hres) ? S_OK : binding->hres;
1642     }else if(binding->bindf & BINDF_ASYNCHRONOUS) {
1643         hres = MK_S_ASYNCHRONOUS;
1644     }else {
1645         *ppv = binding->obj;
1646         IUnknown_AddRef(binding->obj);
1647         hres = S_OK;
1648     }
1649
1650     IBinding_Release(BINDING(binding));
1651
1652     return hres;
1653 }