cards: Fix description of cdtTerm.
[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 #include "shlwapi.h"
22
23 #include "wine/debug.h"
24
25 WINE_DEFAULT_DEBUG_CHANNEL(urlmon);
26
27 static WCHAR cbinding_contextW[] = {'C','B','i','n','d','i','n','g',' ','C','o','n','t','e','x','t',0};
28 static WCHAR bscb_holderW[] = { '_','B','S','C','B','_','H','o','l','d','e','r','_',0 };
29
30 typedef struct Binding Binding;
31
32 struct _task_header_t;
33
34 typedef void (*task_proc_t)(Binding*, struct _task_header_t*);
35
36 typedef struct _task_header_t {
37     task_proc_t proc;
38     struct _task_header_t *next;
39 } task_header_t;
40
41 typedef struct {
42     const IUnknownVtbl *lpUnknownVtbl;
43
44     LONG ref;
45
46     IInternetProtocolEx *protocol;
47
48     BYTE buf[1024*8];
49     DWORD size;
50     BOOL init;
51     HANDLE file;
52     HRESULT hres;
53
54     LPWSTR cache_file;
55 } stgmed_buf_t;
56
57 typedef struct _stgmed_obj_t stgmed_obj_t;
58
59 typedef struct {
60     void (*release)(stgmed_obj_t*);
61     HRESULT (*fill_stgmed)(stgmed_obj_t*,STGMEDIUM*);
62     HRESULT (*get_result)(stgmed_obj_t*,DWORD,void**);
63 } stgmed_obj_vtbl;
64
65 struct _stgmed_obj_t {
66     const stgmed_obj_vtbl *vtbl;
67 };
68
69 #define STGMEDUNK(x)  ((IUnknown*) &(x)->lpUnknownVtbl)
70
71 typedef enum {
72     BEFORE_DOWNLOAD,
73     DOWNLOADING,
74     END_DOWNLOAD
75 } download_state_t;
76
77 #define BINDING_LOCKED    0x0001
78 #define BINDING_STOPPED   0x0002
79 #define BINDING_OBJAVAIL  0x0004
80 #define BINDING_ABORTED   0x0008
81
82 struct Binding {
83     const IBindingVtbl               *lpBindingVtbl;
84     const IInternetProtocolSinkVtbl  *lpIInternetProtocolSinkVtbl;
85     const IInternetBindInfoVtbl      *lpInternetBindInfoVtbl;
86     const IWinInetHttpInfoVtbl       *lpWinInetHttpInfoVtbl;
87     const IServiceProviderVtbl       *lpServiceProviderVtbl;
88
89     LONG ref;
90
91     IBindStatusCallback *callback;
92     IInternetProtocolEx *protocol;
93     IServiceProvider *service_provider;
94
95     stgmed_buf_t *stgmed_buf;
96     stgmed_obj_t *stgmed_obj;
97
98     BINDINFO bindinfo;
99     DWORD bindf;
100     BOOL to_object;
101     LPWSTR mime;
102     UINT clipboard_format;
103     LPWSTR url;
104     LPWSTR redirect_url;
105     IID iid;
106     BOOL report_mime;
107     BOOL use_cache_file;
108     DWORD state;
109     HRESULT hres;
110     download_state_t download_state;
111     IUnknown *obj;
112     IMoniker *mon;
113     IBindCtx *bctx;
114     HWND notif_hwnd;
115
116     CRITICAL_SECTION section;
117 };
118
119 #define BINDING(x)   ((IBinding*)               &(x)->lpBindingVtbl)
120 #define BINDINF(x)   ((IInternetBindInfo*)      &(x)->lpInternetBindInfoVtbl)
121 #define INETINFO(x)  ((IWinInetHttpInfo*)       &(x)->lpWinInetHttpInfoVtbl)
122 #define SERVPROV(x)  ((IServiceProvider*)       &(x)->lpServiceProviderVtbl)
123
124 #define STREAM(x) ((IStream*) &(x)->lpStreamVtbl)
125 #define HTTPNEG2(x) ((IHttpNegotiate2*) &(x)->lpHttpNegotiate2Vtbl)
126
127 static void fill_stgmed_buffer(stgmed_buf_t *buf)
128 {
129     DWORD read = 0;
130
131     if(sizeof(buf->buf) == buf->size)
132         return;
133
134     buf->hres = IInternetProtocol_Read(buf->protocol, buf->buf+buf->size,
135             sizeof(buf->buf)-buf->size, &read);
136     buf->size += read;
137     if(read > 0)
138         buf->init = TRUE;
139 }
140
141 static void read_protocol_data(stgmed_buf_t *stgmed_buf)
142 {
143     BYTE buf[8192];
144     DWORD read;
145     HRESULT hres;
146
147     fill_stgmed_buffer(stgmed_buf);
148     if(stgmed_buf->size < sizeof(stgmed_buf->buf))
149         return;
150
151     do hres = IInternetProtocol_Read(stgmed_buf->protocol, buf, sizeof(buf), &read);
152     while(hres == S_OK);
153 }
154
155 static void dump_BINDINFO(BINDINFO *bi)
156 {
157     static const char * const BINDINFOF_str[] = {
158         "#0",
159         "BINDINFOF_URLENCODESTGMEDDATA",
160         "BINDINFOF_URLENCODEDEXTRAINFO"
161     };
162
163     static const char * const BINDVERB_str[] = {
164         "BINDVERB_GET",
165         "BINDVERB_POST",
166         "BINDVERB_PUT",
167         "BINDVERB_CUSTOM"
168     };
169
170     TRACE("\n"
171             "BINDINFO = {\n"
172             "    %d, %s,\n"
173             "    {%d, %p, %p},\n"
174             "    %s,\n"
175             "    %s,\n"
176             "    %s,\n"
177             "    %d, %08x, %d, %d\n"
178             "    {%d %p %x},\n"
179             "    %s\n"
180             "    %p, %d\n"
181             "}\n",
182
183             bi->cbSize, debugstr_w(bi->szExtraInfo),
184             bi->stgmedData.tymed, bi->stgmedData.u.hGlobal, bi->stgmedData.pUnkForRelease,
185             bi->grfBindInfoF > BINDINFOF_URLENCODEDEXTRAINFO
186                 ? "unknown" : BINDINFOF_str[bi->grfBindInfoF],
187             bi->dwBindVerb > BINDVERB_CUSTOM
188                 ? "unknown" : BINDVERB_str[bi->dwBindVerb],
189             debugstr_w(bi->szCustomVerb),
190             bi->cbstgmedData, bi->dwOptions, bi->dwOptionsFlags, bi->dwCodePage,
191             bi->securityAttributes.nLength,
192             bi->securityAttributes.lpSecurityDescriptor,
193             bi->securityAttributes.bInheritHandle,
194             debugstr_guid(&bi->iid),
195             bi->pUnk, bi->dwReserved
196             );
197 }
198
199 static void mime_available(Binding *This, LPCWSTR mime)
200 {
201     heap_free(This->mime);
202     This->mime = heap_strdupW(mime);
203
204     if(!This->mime || !This->report_mime)
205         return;
206
207     IBindStatusCallback_OnProgress(This->callback, 0, 0, BINDSTATUS_MIMETYPEAVAILABLE, This->mime);
208
209     This->clipboard_format = RegisterClipboardFormatW(This->mime);
210 }
211
212 static void stop_binding(Binding *binding, HRESULT hres, LPCWSTR str)
213 {
214     if(binding->state & BINDING_LOCKED) {
215         IInternetProtocol_UnlockRequest(binding->protocol);
216         binding->state &= ~BINDING_LOCKED;
217     }
218
219     if(!(binding->state & BINDING_STOPPED)) {
220         binding->state |= BINDING_STOPPED;
221
222         IBindStatusCallback_OnStopBinding(binding->callback, hres, str);
223         binding->hres = hres;
224     }
225 }
226
227 static LPWSTR get_mime_clsid(LPCWSTR mime, CLSID *clsid)
228 {
229     LPWSTR key_name, ret;
230     DWORD res, type, size;
231     HKEY hkey;
232     int len;
233     HRESULT hres;
234
235     static const WCHAR mime_keyW[] =
236         {'M','I','M','E','\\','D','a','t','a','b','a','s','e','\\',
237          'C','o','n','t','e','n','t',' ','T','y','p','e','\\'};
238     static const WCHAR clsidW[] = {'C','L','S','I','D',0};
239
240     len = strlenW(mime)+1;
241     key_name = heap_alloc(sizeof(mime_keyW) + len*sizeof(WCHAR));
242     memcpy(key_name, mime_keyW, sizeof(mime_keyW));
243     strcpyW(key_name + sizeof(mime_keyW)/sizeof(WCHAR), mime);
244
245     res = RegOpenKeyW(HKEY_CLASSES_ROOT, key_name, &hkey);
246     heap_free(key_name);
247     if(res != ERROR_SUCCESS) {
248         WARN("Could not open MIME key: %x\n", res);
249         return NULL;
250     }
251
252     size = 50*sizeof(WCHAR);
253     ret = heap_alloc(size);
254     res = RegQueryValueExW(hkey, clsidW, NULL, &type, (LPBYTE)ret, &size);
255     RegCloseKey(hkey);
256     if(res != ERROR_SUCCESS) {
257         WARN("Could not get CLSID: %08x\n", res);
258         heap_free(ret);
259         return NULL;
260     }
261
262     hres = CLSIDFromString(ret, clsid);
263     if(FAILED(hres)) {
264         WARN("Could not parse CLSID: %08x\n", hres);
265         heap_free(ret);
266         return NULL;
267     }
268
269     return ret;
270 }
271
272 static void load_doc_mon(Binding *binding, IPersistMoniker *persist)
273 {
274     IBindCtx *bctx;
275     HRESULT hres;
276
277     hres = CreateAsyncBindCtxEx(binding->bctx, 0, NULL, NULL, &bctx, 0);
278     if(FAILED(hres)) {
279         WARN("CreateAsyncBindCtxEx failed: %08x\n", hres);
280         return;
281     }
282
283     IBindCtx_RevokeObjectParam(bctx, bscb_holderW);
284     IBindCtx_RegisterObjectParam(bctx, cbinding_contextW, (IUnknown*)BINDING(binding));
285
286     hres = IPersistMoniker_Load(persist, binding->download_state == END_DOWNLOAD, binding->mon, bctx, 0x12);
287     IBindCtx_RevokeObjectParam(bctx, cbinding_contextW);
288     IBindCtx_Release(bctx);
289     if(FAILED(hres))
290         FIXME("Load failed: %08x\n", hres);
291 }
292
293 static HRESULT create_mime_object(Binding *binding, const CLSID *clsid, LPCWSTR clsid_str)
294 {
295     IPersistMoniker *persist;
296     HRESULT hres;
297
298     hres = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER|CLSCTX_INPROC_HANDLER,
299                             &binding->iid, (void**)&binding->obj);
300     if(FAILED(hres)) {
301         WARN("CoCreateInstance failed: %08x\n", hres);
302         return INET_E_CANNOT_INSTANTIATE_OBJECT;
303     }
304
305     binding->state |= BINDING_OBJAVAIL;
306
307     hres = IUnknown_QueryInterface(binding->obj, &IID_IPersistMoniker, (void**)&persist);
308     if(SUCCEEDED(hres)) {
309         IMonikerProp *prop;
310
311         hres = IPersistMoniker_QueryInterface(persist, &IID_IMonikerProp, (void**)&prop);
312         if(SUCCEEDED(hres)) {
313             IMonikerProp_PutProperty(prop, MIMETYPEPROP, binding->mime);
314             IMonikerProp_PutProperty(prop, CLASSIDPROP, clsid_str);
315             IMonikerProp_Release(prop);
316         }
317
318         load_doc_mon(binding, persist);
319
320         IPersistMoniker_Release(persist);
321     }else {
322         FIXME("Could not get IPersistMoniker: %08x\n", hres);
323         /* FIXME: Try query IPersistFile */
324     }
325
326     IBindStatusCallback_OnObjectAvailable(binding->callback, &binding->iid, binding->obj);
327
328     return S_OK;
329 }
330
331 static void create_object(Binding *binding)
332 {
333     LPWSTR clsid_str;
334     CLSID clsid;
335     HRESULT hres;
336
337     if(!binding->mime) {
338         FIXME("MIME not available\n");
339         return;
340     }
341
342     if(!(clsid_str = get_mime_clsid(binding->mime, &clsid))) {
343         FIXME("Could not find object for MIME %s\n", debugstr_w(binding->mime));
344         return;
345     }
346
347     IBindStatusCallback_OnProgress(binding->callback, 0, 0, BINDSTATUS_CLASSIDAVAILABLE, clsid_str);
348     IBindStatusCallback_OnProgress(binding->callback, 0, 0, BINDSTATUS_BEGINSYNCOPERATION, NULL);
349
350     hres = create_mime_object(binding, &clsid, clsid_str);
351     heap_free(clsid_str);
352
353     IBindStatusCallback_OnProgress(binding->callback, 0, 0, BINDSTATUS_ENDSYNCOPERATION, NULL);
354
355     stop_binding(binding, hres, NULL);
356     if(FAILED(hres))
357         IInternetProtocol_Terminate(binding->protocol, 0);
358 }
359
360 static void cache_file_available(Binding *This, const WCHAR *file_name)
361 {
362     heap_free(This->stgmed_buf->cache_file);
363     This->stgmed_buf->cache_file = heap_strdupW(file_name);
364
365     if(This->use_cache_file) {
366         This->stgmed_buf->file = CreateFileW(file_name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
367                 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
368         if(This->stgmed_buf->file == INVALID_HANDLE_VALUE)
369             WARN("CreateFile failed: %u\n", GetLastError());
370     }
371 }
372
373 #define STGMEDUNK_THIS(iface) DEFINE_THIS(stgmed_buf_t, Unknown, iface)
374
375 static HRESULT WINAPI StgMedUnk_QueryInterface(IUnknown *iface, REFIID riid, void **ppv)
376 {
377     stgmed_buf_t *This = STGMEDUNK_THIS(iface);
378
379     *ppv = NULL;
380
381     if(IsEqualGUID(riid, &IID_IUnknown)) {
382         TRACE("(%p)->(IID_IUnknown %p)\n", This, ppv);
383
384         *ppv = STGMEDUNK(This);
385         IUnknown_AddRef(STGMEDUNK(This));
386         return S_OK;
387     }
388
389     TRACE("(%p)->(%s %p)\n", This, debugstr_guid(riid), ppv);
390     return E_NOINTERFACE;
391 }
392
393 static ULONG WINAPI StgMedUnk_AddRef(IUnknown *iface)
394 {
395     stgmed_buf_t *This = STGMEDUNK_THIS(iface);
396     LONG ref = InterlockedIncrement(&This->ref);
397
398     TRACE("(%p) ref=%d\n", This, ref);
399
400     return ref;
401 }
402
403 static ULONG WINAPI StgMedUnk_Release(IUnknown *iface)
404 {
405     stgmed_buf_t *This = STGMEDUNK_THIS(iface);
406     LONG ref = InterlockedDecrement(&This->ref);
407
408     TRACE("(%p) ref=%d\n", This, ref);
409
410     if(!ref) {
411         if(This->file != INVALID_HANDLE_VALUE)
412             CloseHandle(This->file);
413         IInternetProtocol_Release(This->protocol);
414         heap_free(This->cache_file);
415         heap_free(This);
416
417         URLMON_UnlockModule();
418     }
419
420     return ref;
421 }
422
423 #undef STGMEDUNK_THIS
424
425 static const IUnknownVtbl StgMedUnkVtbl = {
426     StgMedUnk_QueryInterface,
427     StgMedUnk_AddRef,
428     StgMedUnk_Release
429 };
430
431 static stgmed_buf_t *create_stgmed_buf(IInternetProtocolEx *protocol)
432 {
433     stgmed_buf_t *ret = heap_alloc(sizeof(*ret));
434
435     ret->lpUnknownVtbl = &StgMedUnkVtbl;
436     ret->ref = 1;
437     ret->size = 0;
438     ret->init = FALSE;
439     ret->file = INVALID_HANDLE_VALUE;
440     ret->hres = S_OK;
441     ret->cache_file = NULL;
442
443     IInternetProtocol_AddRef(protocol);
444     ret->protocol = protocol;
445
446     URLMON_LockModule();
447
448     return ret;
449 }
450
451 typedef struct {
452     stgmed_obj_t stgmed_obj;
453     const IStreamVtbl *lpStreamVtbl;
454
455     LONG ref;
456
457     stgmed_buf_t *buf;
458 } ProtocolStream;
459
460 #define STREAM_THIS(iface) DEFINE_THIS(ProtocolStream, Stream, iface)
461
462 static HRESULT WINAPI ProtocolStream_QueryInterface(IStream *iface,
463                                                           REFIID riid, void **ppv)
464 {
465     ProtocolStream *This = STREAM_THIS(iface);
466
467     *ppv = NULL;
468
469     if(IsEqualGUID(&IID_IUnknown, riid)) {
470         TRACE("(%p)->(IID_IUnknown %p)\n", This, ppv);
471         *ppv = STREAM(This);
472     }else if(IsEqualGUID(&IID_ISequentialStream, riid)) {
473         TRACE("(%p)->(IID_ISequentialStream %p)\n", This, ppv);
474         *ppv = STREAM(This);
475     }else if(IsEqualGUID(&IID_IStream, riid)) {
476         TRACE("(%p)->(IID_IStream %p)\n", This, ppv);
477         *ppv = STREAM(This);
478     }
479
480     if(*ppv) {
481         IStream_AddRef(STREAM(This));
482         return S_OK;
483     }
484
485     WARN("(%p)->(%s %p)\n", This, debugstr_guid(riid), ppv);
486     return E_NOINTERFACE;
487 }
488
489 static ULONG WINAPI ProtocolStream_AddRef(IStream *iface)
490 {
491     ProtocolStream *This = STREAM_THIS(iface);
492     LONG ref = InterlockedIncrement(&This->ref);
493
494     TRACE("(%p) ref=%d\n", This, ref);
495
496     return ref;
497 }
498
499 static ULONG WINAPI ProtocolStream_Release(IStream *iface)
500 {
501     ProtocolStream *This = STREAM_THIS(iface);
502     LONG ref = InterlockedDecrement(&This->ref);
503
504     TRACE("(%p) ref=%d\n", This, ref);
505
506     if(!ref) {
507         IUnknown_Release(STGMEDUNK(This->buf));
508         heap_free(This);
509
510         URLMON_UnlockModule();
511     }
512
513     return ref;
514 }
515
516 static HRESULT WINAPI ProtocolStream_Read(IStream *iface, void *pv,
517                                           ULONG cb, ULONG *pcbRead)
518 {
519     ProtocolStream *This = STREAM_THIS(iface);
520     DWORD read = 0, pread = 0;
521     HRESULT hres;
522
523     TRACE("(%p)->(%p %d %p)\n", This, pv, cb, pcbRead);
524
525     if(This->buf->file != INVALID_HANDLE_VALUE) {
526         if (!ReadFile(This->buf->file, pv, cb, &read, NULL))
527             return INET_E_DOWNLOAD_FAILURE;
528
529         if(pcbRead)
530             *pcbRead = read;
531         return read ? S_OK : S_FALSE;
532     }
533
534     if(This->buf->size) {
535         read = cb;
536
537         if(read > This->buf->size)
538             read = This->buf->size;
539
540         memcpy(pv, This->buf->buf, read);
541
542         if(read < This->buf->size)
543             memmove(This->buf->buf, This->buf->buf+read, This->buf->size-read);
544         This->buf->size -= read;
545     }
546
547     if(read == cb) {
548         if (pcbRead)
549             *pcbRead = read;
550         return S_OK;
551     }
552
553     hres = This->buf->hres = IInternetProtocol_Read(This->buf->protocol, (PBYTE)pv+read, cb-read, &pread);
554     if (pcbRead)
555         *pcbRead = read + pread;
556
557     if(hres == E_PENDING)
558         return E_PENDING;
559     else if(FAILED(hres))
560         FIXME("Read failed: %08x\n", hres);
561
562     return read || pread ? S_OK : S_FALSE;
563 }
564
565 static HRESULT WINAPI ProtocolStream_Write(IStream *iface, const void *pv,
566                                           ULONG cb, ULONG *pcbWritten)
567 {
568     ProtocolStream *This = STREAM_THIS(iface);
569
570     TRACE("(%p)->(%p %d %p)\n", This, pv, cb, pcbWritten);
571
572     return STG_E_ACCESSDENIED;
573 }
574
575 static HRESULT WINAPI ProtocolStream_Seek(IStream *iface, LARGE_INTEGER dlibMove,
576                                          DWORD dwOrigin, ULARGE_INTEGER *plibNewPosition)
577 {
578     ProtocolStream *This = STREAM_THIS(iface);
579     FIXME("(%p)->(%d %08x %p)\n", This, dlibMove.u.LowPart, dwOrigin, plibNewPosition);
580     return E_NOTIMPL;
581 }
582
583 static HRESULT WINAPI ProtocolStream_SetSize(IStream *iface, ULARGE_INTEGER libNewSize)
584 {
585     ProtocolStream *This = STREAM_THIS(iface);
586     FIXME("(%p)->(%d)\n", This, libNewSize.u.LowPart);
587     return E_NOTIMPL;
588 }
589
590 static HRESULT WINAPI ProtocolStream_CopyTo(IStream *iface, IStream *pstm,
591         ULARGE_INTEGER cb, ULARGE_INTEGER *pcbRead, ULARGE_INTEGER *pcbWritten)
592 {
593     ProtocolStream *This = STREAM_THIS(iface);
594     FIXME("(%p)->(%p %d %p %p)\n", This, pstm, cb.u.LowPart, pcbRead, pcbWritten);
595     return E_NOTIMPL;
596 }
597
598 static HRESULT WINAPI ProtocolStream_Commit(IStream *iface, DWORD grfCommitFlags)
599 {
600     ProtocolStream *This = STREAM_THIS(iface);
601
602     TRACE("(%p)->(%08x)\n", This, grfCommitFlags);
603
604     return E_NOTIMPL;
605 }
606
607 static HRESULT WINAPI ProtocolStream_Revert(IStream *iface)
608 {
609     ProtocolStream *This = STREAM_THIS(iface);
610
611     TRACE("(%p)\n", This);
612
613     return E_NOTIMPL;
614 }
615
616 static HRESULT WINAPI ProtocolStream_LockRegion(IStream *iface, ULARGE_INTEGER libOffset,
617                                                ULARGE_INTEGER cb, DWORD dwLockType)
618 {
619     ProtocolStream *This = STREAM_THIS(iface);
620     FIXME("(%p)->(%d %d %d)\n", This, libOffset.u.LowPart, cb.u.LowPart, dwLockType);
621     return E_NOTIMPL;
622 }
623
624 static HRESULT WINAPI ProtocolStream_UnlockRegion(IStream *iface,
625         ULARGE_INTEGER libOffset, ULARGE_INTEGER cb, DWORD dwLockType)
626 {
627     ProtocolStream *This = STREAM_THIS(iface);
628     FIXME("(%p)->(%d %d %d)\n", This, libOffset.u.LowPart, cb.u.LowPart, dwLockType);
629     return E_NOTIMPL;
630 }
631
632 static HRESULT WINAPI ProtocolStream_Stat(IStream *iface, STATSTG *pstatstg,
633                                          DWORD dwStatFlag)
634 {
635     ProtocolStream *This = STREAM_THIS(iface);
636     TRACE("(%p)->(%p %08x)\n", This, pstatstg, dwStatFlag);
637
638     if(!pstatstg)
639         return E_FAIL;
640
641     memset(pstatstg, 0, sizeof(STATSTG));
642
643     if(!(dwStatFlag&STATFLAG_NONAME) && This->buf->cache_file) {
644         pstatstg->pwcsName = CoTaskMemAlloc((lstrlenW(This->buf->cache_file)+1)*sizeof(WCHAR));
645         if(!pstatstg->pwcsName)
646             return STG_E_INSUFFICIENTMEMORY;
647
648         lstrcpyW(pstatstg->pwcsName, This->buf->cache_file);
649     }
650
651     pstatstg->type = STGTY_STREAM;
652     if(This->buf->file != INVALID_HANDLE_VALUE) {
653         GetFileSizeEx(This->buf->file, (PLARGE_INTEGER)&pstatstg->cbSize);
654         GetFileTime(This->buf->file, &pstatstg->ctime, &pstatstg->atime, &pstatstg->mtime);
655         if(pstatstg->cbSize.QuadPart)
656             pstatstg->grfMode = GENERIC_READ;
657     }
658
659     return S_OK;
660 }
661
662 static HRESULT WINAPI ProtocolStream_Clone(IStream *iface, IStream **ppstm)
663 {
664     ProtocolStream *This = STREAM_THIS(iface);
665     FIXME("(%p)->(%p)\n", This, ppstm);
666     return E_NOTIMPL;
667 }
668
669 #undef STREAM_THIS
670
671 static const IStreamVtbl ProtocolStreamVtbl = {
672     ProtocolStream_QueryInterface,
673     ProtocolStream_AddRef,
674     ProtocolStream_Release,
675     ProtocolStream_Read,
676     ProtocolStream_Write,
677     ProtocolStream_Seek,
678     ProtocolStream_SetSize,
679     ProtocolStream_CopyTo,
680     ProtocolStream_Commit,
681     ProtocolStream_Revert,
682     ProtocolStream_LockRegion,
683     ProtocolStream_UnlockRegion,
684     ProtocolStream_Stat,
685     ProtocolStream_Clone
686 };
687
688 static void stgmed_stream_release(stgmed_obj_t *obj)
689 {
690     ProtocolStream *stream = (ProtocolStream*)obj;
691     IStream_Release(STREAM(stream));
692 }
693
694 static HRESULT stgmed_stream_fill_stgmed(stgmed_obj_t *obj, STGMEDIUM *stgmed)
695 {
696     ProtocolStream *stream = (ProtocolStream*)obj;
697
698     stgmed->tymed = TYMED_ISTREAM;
699     stgmed->u.pstm = STREAM(stream);
700     stgmed->pUnkForRelease = STGMEDUNK(stream->buf);
701
702     return S_OK;
703 }
704
705 static HRESULT stgmed_stream_get_result(stgmed_obj_t *obj, DWORD bindf, void **result)
706 {
707     ProtocolStream *stream = (ProtocolStream*)obj;
708
709     if(!(bindf & BINDF_ASYNCHRONOUS) && stream->buf->file == INVALID_HANDLE_VALUE
710        && (stream->buf->hres != S_FALSE || stream->buf->size))
711         return INET_E_DATA_NOT_AVAILABLE;
712
713     IStream_AddRef(STREAM(stream));
714     *result = STREAM(stream);
715     return S_OK;
716 }
717
718 static const stgmed_obj_vtbl stgmed_stream_vtbl = {
719     stgmed_stream_release,
720     stgmed_stream_fill_stgmed,
721     stgmed_stream_get_result
722 };
723
724 typedef struct {
725     stgmed_obj_t stgmed_obj;
726     stgmed_buf_t *buf;
727 } stgmed_file_obj_t;
728
729 static stgmed_obj_t *create_stgmed_stream(stgmed_buf_t *buf)
730 {
731     ProtocolStream *ret = heap_alloc(sizeof(ProtocolStream));
732
733     ret->stgmed_obj.vtbl = &stgmed_stream_vtbl;
734     ret->lpStreamVtbl = &ProtocolStreamVtbl;
735     ret->ref = 1;
736
737     IUnknown_AddRef(STGMEDUNK(buf));
738     ret->buf = buf;
739
740     URLMON_LockModule();
741
742     return &ret->stgmed_obj;
743 }
744
745 static void stgmed_file_release(stgmed_obj_t *obj)
746 {
747     stgmed_file_obj_t *file_obj = (stgmed_file_obj_t*)obj;
748
749     IUnknown_Release(STGMEDUNK(file_obj->buf));
750     heap_free(file_obj);
751 }
752
753 static HRESULT stgmed_file_fill_stgmed(stgmed_obj_t *obj, STGMEDIUM *stgmed)
754 {
755     stgmed_file_obj_t *file_obj = (stgmed_file_obj_t*)obj;
756
757     if(!file_obj->buf->cache_file) {
758         WARN("cache_file not set\n");
759         return INET_E_DATA_NOT_AVAILABLE;
760     }
761
762     read_protocol_data(file_obj->buf);
763
764     stgmed->tymed = TYMED_FILE;
765     stgmed->u.lpszFileName = file_obj->buf->cache_file;
766     stgmed->pUnkForRelease = STGMEDUNK(file_obj->buf);
767
768     return S_OK;
769 }
770
771 static HRESULT stgmed_file_get_result(stgmed_obj_t *obj, DWORD bindf, void **result)
772 {
773     return bindf & BINDF_ASYNCHRONOUS ? MK_S_ASYNCHRONOUS : S_OK;
774 }
775
776 static const stgmed_obj_vtbl stgmed_file_vtbl = {
777     stgmed_file_release,
778     stgmed_file_fill_stgmed,
779     stgmed_file_get_result
780 };
781
782 static stgmed_obj_t *create_stgmed_file(stgmed_buf_t *buf)
783 {
784     stgmed_file_obj_t *ret = heap_alloc(sizeof(*ret));
785
786     ret->stgmed_obj.vtbl = &stgmed_file_vtbl;
787
788     IUnknown_AddRef(STGMEDUNK(buf));
789     ret->buf = buf;
790
791     return &ret->stgmed_obj;
792 }
793
794 #define BINDING_THIS(iface) DEFINE_THIS(Binding, Binding, iface)
795
796 static HRESULT WINAPI Binding_QueryInterface(IBinding *iface, REFIID riid, void **ppv)
797 {
798     Binding *This = BINDING_THIS(iface);
799
800     *ppv = NULL;
801
802     if(IsEqualGUID(&IID_IUnknown, riid)) {
803         TRACE("(%p)->(IID_IUnknown %p)\n", This, ppv);
804         *ppv = BINDING(This);
805     }else if(IsEqualGUID(&IID_IBinding, riid)) {
806         TRACE("(%p)->(IID_IBinding %p)\n", This, ppv);
807         *ppv = BINDING(This);
808     }else if(IsEqualGUID(&IID_IInternetProtocolSink, riid)) {
809         TRACE("(%p)->(IID_IInternetProtocolSink %p)\n", This, ppv);
810         *ppv = PROTSINK(This);
811     }else if(IsEqualGUID(&IID_IInternetBindInfo, riid)) {
812         TRACE("(%p)->(IID_IInternetBindInfo %p)\n", This, ppv);
813         *ppv = BINDINF(This);
814     }else if(IsEqualGUID(&IID_IServiceProvider, riid)) {
815         TRACE("(%p)->(IID_IServiceProvider %p)\n", This, ppv);
816         *ppv = SERVPROV(This);
817     }else if(IsEqualGUID(&IID_IWinInetInfo, riid)) {
818         TRACE("(%p)->(IID_IWinInetInfo %p)\n", This, ppv);
819
820         /* NOTE: This violidates COM rules, but tests prove that we should do it */
821         if(!get_wininet_info(This->protocol))
822            return E_NOINTERFACE;
823
824         *ppv = INETINFO(This);
825     }else if(IsEqualGUID(&IID_IWinInetHttpInfo, riid)) {
826         IWinInetHttpInfo *http_info;
827         IWinInetInfo *info;
828         HRESULT hres;
829
830         TRACE("(%p)->(IID_IWinInetHttpInfo %p)\n", This, ppv);
831
832         info = get_wininet_info(This->protocol);
833         if(!info)
834             return E_NOINTERFACE;
835
836         hres = IWinInetInfo_QueryInterface(info, &IID_IWinInetHttpInfo, (void**)&http_info);
837         if(FAILED(hres))
838             return E_NOINTERFACE;
839
840         IWinInetHttpInfo_Release(http_info);
841         *ppv = INETINFO(This);
842     }
843
844     if(*ppv) {
845         IBinding_AddRef(BINDING(This));
846         return S_OK;
847     }
848
849     WARN("Unsupported interface %s\n", debugstr_guid(riid));
850     return E_NOINTERFACE;
851 }
852
853 static ULONG WINAPI Binding_AddRef(IBinding *iface)
854 {
855     Binding *This = BINDING_THIS(iface);
856     LONG ref = InterlockedIncrement(&This->ref);
857
858     TRACE("(%p) ref=%d\n", This, ref);
859
860     return ref;
861 }
862
863 static ULONG WINAPI Binding_Release(IBinding *iface)
864 {
865     Binding *This = BINDING_THIS(iface);
866     LONG ref = InterlockedDecrement(&This->ref);
867
868     TRACE("(%p) ref=%d\n", This, ref);
869
870     if(!ref) {
871         if(This->notif_hwnd)
872             release_notif_hwnd(This->notif_hwnd);
873         if(This->mon)
874             IMoniker_Release(This->mon);
875         if(This->callback)
876             IBindStatusCallback_Release(This->callback);
877         if(This->protocol)
878             IInternetProtocol_Release(This->protocol);
879         if(This->service_provider)
880             IServiceProvider_Release(This->service_provider);
881         if(This->stgmed_buf)
882             IUnknown_Release(STGMEDUNK(This->stgmed_buf));
883         if(This->stgmed_obj)
884             This->stgmed_obj->vtbl->release(This->stgmed_obj);
885         if(This->obj)
886             IUnknown_Release(This->obj);
887         if(This->bctx)
888             IBindCtx_Release(This->bctx);
889
890         ReleaseBindInfo(&This->bindinfo);
891         This->section.DebugInfo->Spare[0] = 0;
892         DeleteCriticalSection(&This->section);
893         SysFreeString(This->url);
894         heap_free(This->mime);
895         heap_free(This->redirect_url);
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 = (SysStringLen(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_NOINTERFACE;
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(IUri *uri)
1403 {
1404     DWORD scheme;
1405     HRESULT hres;
1406
1407     hres = IUri_GetScheme(uri, &scheme);
1408     if(FAILED(hres))
1409         return FALSE;
1410
1411     switch(scheme) {
1412     case URL_SCHEME_FILE:
1413     case URL_SCHEME_FTP:
1414     case URL_SCHEME_GOPHER:
1415     case URL_SCHEME_HTTP:
1416     case URL_SCHEME_HTTPS:
1417     case URL_SCHEME_MK:
1418         return TRUE;
1419     }
1420
1421     return FALSE;
1422 }
1423
1424 static HRESULT Binding_Create(IMoniker *mon, Binding *binding_ctx, IUri *uri, IBindCtx *pbc,
1425         BOOL to_obj, REFIID riid, Binding **binding)
1426 {
1427     Binding *ret;
1428     HRESULT hres;
1429
1430     URLMON_LockModule();
1431
1432     ret = heap_alloc_zero(sizeof(Binding));
1433
1434     ret->lpBindingVtbl              = &BindingVtbl;
1435     ret->lpIInternetProtocolSinkVtbl = &InternetProtocolSinkVtbl;
1436     ret->lpInternetBindInfoVtbl     = &InternetBindInfoVtbl;
1437     ret->lpWinInetHttpInfoVtbl      = &WinInetHttpInfoVtbl;
1438     ret->lpServiceProviderVtbl      = &ServiceProviderVtbl;
1439
1440     ret->ref = 1;
1441
1442     ret->to_object = to_obj;
1443     ret->iid = *riid;
1444     ret->notif_hwnd = get_notif_hwnd();
1445     ret->report_mime = !binding_ctx;
1446     ret->download_state = BEFORE_DOWNLOAD;
1447
1448     if(to_obj) {
1449         IBindCtx_AddRef(pbc);
1450         ret->bctx = pbc;
1451     }
1452
1453     if(mon) {
1454         IMoniker_AddRef(mon);
1455         ret->mon = mon;
1456     }
1457
1458     ret->bindinfo.cbSize = sizeof(BINDINFO);
1459
1460     InitializeCriticalSection(&ret->section);
1461     ret->section.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": Binding.section");
1462
1463     hres = get_callback(pbc, &ret->callback);
1464     if(FAILED(hres)) {
1465         WARN("Could not get IBindStatusCallback\n");
1466         IBinding_Release(BINDING(ret));
1467         return hres;
1468     }
1469
1470     IBindStatusCallback_QueryInterface(ret->callback, &IID_IServiceProvider,
1471                                        (void**)&ret->service_provider);
1472
1473     if(binding_ctx) {
1474         ret->protocol = binding_ctx->protocol;
1475         IInternetProtocol_AddRef(ret->protocol);
1476     }else {
1477         hres = create_binding_protocol(TRUE, &ret->protocol);
1478         if(FAILED(hres)) {
1479             WARN("Could not get protocol handler\n");
1480             IBinding_Release(BINDING(ret));
1481             return hres;
1482         }
1483     }
1484
1485     hres = IBindStatusCallback_GetBindInfo(ret->callback, &ret->bindf, &ret->bindinfo);
1486     if(FAILED(hres)) {
1487         WARN("GetBindInfo failed: %08x\n", hres);
1488         IBinding_Release(BINDING(ret));
1489         return hres;
1490     }
1491
1492     TRACE("bindf %08x\n", ret->bindf);
1493     dump_BINDINFO(&ret->bindinfo);
1494
1495     ret->bindf |= BINDF_FROMURLMON;
1496     if(to_obj)
1497         ret->bindinfo.dwOptions |= 0x100000;
1498
1499     if(!(ret->bindf & BINDF_ASYNCHRONOUS) || !(ret->bindf & BINDF_PULLDATA)) {
1500         ret->bindf |= BINDF_NEEDFILE;
1501         ret->use_cache_file = TRUE;
1502     }else if(!is_urlmon_protocol(uri)) {
1503         ret->bindf |= BINDF_NEEDFILE;
1504     }
1505
1506     hres = IUri_GetDisplayUri(uri, &ret->url);
1507     if(FAILED(hres)) {
1508         IBinding_Release(BINDING(ret));
1509         return hres;
1510     }
1511
1512     if(binding_ctx) {
1513         ret->stgmed_buf = binding_ctx->stgmed_buf;
1514         IUnknown_AddRef(STGMEDUNK(ret->stgmed_buf));
1515         ret->clipboard_format = binding_ctx->clipboard_format;
1516     }else {
1517         ret->stgmed_buf = create_stgmed_buf(ret->protocol);
1518     }
1519
1520     if(to_obj) {
1521         ret->stgmed_obj = NULL;
1522     }else if(IsEqualGUID(&IID_IStream, riid)) {
1523         ret->stgmed_obj = create_stgmed_stream(ret->stgmed_buf);
1524     }else if(IsEqualGUID(&IID_IUnknown, riid)) {
1525         ret->bindf |= BINDF_NEEDFILE;
1526         ret->stgmed_obj = create_stgmed_file(ret->stgmed_buf);
1527     }else {
1528         FIXME("Unsupported riid %s\n", debugstr_guid(riid));
1529         IBinding_Release(BINDING(ret));
1530         return E_NOTIMPL;
1531     }
1532
1533     *binding = ret;
1534     return S_OK;
1535 }
1536
1537 static HRESULT start_binding(IMoniker *mon, Binding *binding_ctx, IUri *uri, IBindCtx *pbc,
1538                              BOOL to_obj, REFIID riid, Binding **ret)
1539 {
1540     Binding *binding = NULL;
1541     HRESULT hres;
1542     MSG msg;
1543
1544     hres = Binding_Create(mon, binding_ctx, uri, pbc, to_obj, riid, &binding);
1545     if(FAILED(hres))
1546         return hres;
1547
1548     hres = IBindStatusCallback_OnStartBinding(binding->callback, 0, BINDING(binding));
1549     if(FAILED(hres)) {
1550         WARN("OnStartBinding failed: %08x\n", hres);
1551         stop_binding(binding, INET_E_DOWNLOAD_FAILURE, NULL);
1552         IBinding_Release(BINDING(binding));
1553         return hres;
1554     }
1555
1556     if(binding_ctx) {
1557         set_binding_sink(binding->protocol, PROTSINK(binding), BINDINF(binding));
1558         if(binding_ctx->redirect_url)
1559             IBindStatusCallback_OnProgress(binding->callback, 0, 0, BINDSTATUS_REDIRECTING, binding_ctx->redirect_url);
1560         report_data(binding, BSCF_FIRSTDATANOTIFICATION | (binding_ctx->download_state == END_DOWNLOAD ? BSCF_LASTDATANOTIFICATION : 0),
1561                 0, 0);
1562     }else {
1563         hres = IInternetProtocolEx_StartEx(binding->protocol, uri, PROTSINK(binding),
1564                  BINDINF(binding), PI_APARTMENTTHREADED|PI_MIMEVERIFICATION, 0);
1565
1566         TRACE("start ret %08x\n", hres);
1567
1568         if(FAILED(hres) && hres != E_PENDING) {
1569             stop_binding(binding, hres, NULL);
1570             IBinding_Release(BINDING(binding));
1571
1572             return hres;
1573         }
1574     }
1575
1576     while(!(binding->bindf & BINDF_ASYNCHRONOUS) &&
1577           !(binding->state & BINDING_STOPPED)) {
1578         MsgWaitForMultipleObjects(0, NULL, FALSE, 5000, QS_POSTMESSAGE);
1579         while (PeekMessageW(&msg, binding->notif_hwnd, WM_USER, WM_USER+117, PM_REMOVE|PM_NOYIELD)) {
1580             TranslateMessage(&msg);
1581             DispatchMessageW(&msg);
1582         }
1583     }
1584
1585     *ret = binding;
1586     return S_OK;
1587 }
1588
1589 HRESULT bind_to_storage(IUri *uri, IBindCtx *pbc, REFIID riid, void **ppv)
1590 {
1591     Binding *binding = NULL, *binding_ctx;
1592     HRESULT hres;
1593
1594     *ppv = NULL;
1595
1596     binding_ctx = get_bctx_binding(pbc);
1597
1598     hres = start_binding(NULL, binding_ctx, uri, pbc, FALSE, riid, &binding);
1599     if(binding_ctx)
1600         IBinding_Release(BINDING(binding_ctx));
1601     if(FAILED(hres))
1602         return hres;
1603
1604     if(binding->hres == S_OK && binding->stgmed_buf->init) {
1605         if((binding->state & BINDING_STOPPED) && (binding->state & BINDING_LOCKED))
1606             IInternetProtocol_UnlockRequest(binding->protocol);
1607
1608         hres = binding->stgmed_obj->vtbl->get_result(binding->stgmed_obj, binding->bindf, ppv);
1609     }else if(binding->bindf & BINDF_ASYNCHRONOUS) {
1610         hres = MK_S_ASYNCHRONOUS;
1611     }else {
1612         hres = FAILED(binding->hres) ? binding->hres : S_OK;
1613     }
1614
1615     IBinding_Release(BINDING(binding));
1616
1617     return hres;
1618 }
1619
1620 HRESULT bind_to_object(IMoniker *mon, IUri *uri, IBindCtx *pbc, REFIID riid, void **ppv)
1621 {
1622     Binding *binding;
1623     HRESULT hres;
1624
1625     *ppv = NULL;
1626
1627     hres = start_binding(mon, NULL, uri, pbc, TRUE, riid, &binding);
1628     if(FAILED(hres))
1629         return hres;
1630
1631     if(binding->hres != S_OK) {
1632         hres = SUCCEEDED(binding->hres) ? S_OK : binding->hres;
1633     }else if(binding->bindf & BINDF_ASYNCHRONOUS) {
1634         hres = MK_S_ASYNCHRONOUS;
1635     }else {
1636         *ppv = binding->obj;
1637         IUnknown_AddRef(binding->obj);
1638         hres = S_OK;
1639     }
1640
1641     IBinding_Release(BINDING(binding));
1642
1643     return hres;
1644 }