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