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