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