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