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