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