wineserver: Don't use O_CREAT and O_EXCL when attempting to open directories.
[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     default:
1187         FIXME("Unhandled status code %d\n", ulStatusCode);
1188         return E_NOTIMPL;
1189     };
1190
1191     return S_OK;
1192 }
1193
1194 static void report_data(Binding *This, DWORD bscf, ULONG progress, ULONG progress_max)
1195 {
1196     FORMATETC formatetc = {0, NULL, 1, -1, TYMED_ISTREAM};
1197     BOOL sent_begindownloaddata = FALSE;
1198
1199     TRACE("(%p)->(%d %u %u)\n", This, bscf, progress, progress_max);
1200
1201     if(This->download_state == END_DOWNLOAD)
1202         return;
1203
1204     if(GetCurrentThreadId() != This->apartment_thread)
1205         FIXME("called from worker thread\n");
1206
1207     if(This->report_mime)
1208         mime_available(This, NULL, TRUE);
1209
1210     if(This->download_state == BEFORE_DOWNLOAD) {
1211         fill_stgmed_buffer(This->stgmed_buf);
1212
1213         This->download_state = DOWNLOADING;
1214         sent_begindownloaddata = TRUE;
1215         IBindStatusCallback_OnProgress(This->callback, progress, progress_max,
1216                 BINDSTATUS_BEGINDOWNLOADDATA, This->url);
1217
1218         if(This->stgmed_buf->cache_file)
1219             IBindStatusCallback_OnProgress(This->callback, progress, progress_max,
1220                     BINDSTATUS_CACHEFILENAMEAVAILABLE, This->stgmed_buf->cache_file);
1221     }
1222
1223     if(This->stgmed_buf->hres == S_FALSE || (bscf & BSCF_LASTDATANOTIFICATION)) {
1224         This->download_state = END_DOWNLOAD;
1225         IBindStatusCallback_OnProgress(This->callback, progress, progress_max,
1226                 BINDSTATUS_ENDDOWNLOADDATA, This->url);
1227     }else if(!sent_begindownloaddata) {
1228         IBindStatusCallback_OnProgress(This->callback, progress, progress_max,
1229                 BINDSTATUS_DOWNLOADINGDATA, This->url);
1230     }
1231
1232     if(This->to_object) {
1233         if(!(This->state & BINDING_OBJAVAIL))
1234             create_object(This);
1235     }else {
1236         STGMEDIUM stgmed;
1237         HRESULT hres;
1238
1239         if(!(This->state & BINDING_LOCKED)) {
1240             HRESULT hres = IInternetProtocol_LockRequest(This->protocol, 0);
1241             if(SUCCEEDED(hres))
1242                 This->state |= BINDING_LOCKED;
1243         }
1244
1245         hres = This->stgmed_obj->vtbl->fill_stgmed(This->stgmed_obj, &stgmed);
1246         if(FAILED(hres)) {
1247             stop_binding(This, hres, NULL);
1248             return;
1249         }
1250
1251         formatetc.tymed = stgmed.tymed;
1252         formatetc.cfFormat = This->clipboard_format;
1253
1254         IBindStatusCallback_OnDataAvailable(This->callback, bscf, progress,
1255                 &formatetc, &stgmed);
1256
1257         if(This->download_state == END_DOWNLOAD)
1258             stop_binding(This, S_OK, NULL);
1259     }
1260 }
1261
1262 typedef struct {
1263     task_header_t header;
1264     DWORD bscf;
1265     ULONG progress;
1266     ULONG progress_max;
1267 } report_data_task_t;
1268
1269 static void report_data_proc(Binding *binding, task_header_t *t)
1270 {
1271     report_data_task_t *task = (report_data_task_t*)t;
1272
1273     report_data(binding, task->bscf, task->progress, task->progress_max);
1274
1275     heap_free(task);
1276 }
1277
1278 static HRESULT WINAPI InternetProtocolSink_ReportData(IInternetProtocolSink *iface,
1279         DWORD grfBSCF, ULONG ulProgress, ULONG ulProgressMax)
1280 {
1281     Binding *This = PROTSINK_THIS(iface);
1282
1283     TRACE("(%p)->(%d %u %u)\n", This, grfBSCF, ulProgress, ulProgressMax);
1284
1285     if(GetCurrentThreadId() != This->apartment_thread)
1286         FIXME("called from worked hread\n");
1287
1288     if(This->continue_call) {
1289         report_data_task_t *task = heap_alloc(sizeof(report_data_task_t));
1290         task->bscf = grfBSCF;
1291         task->progress = ulProgress;
1292         task->progress_max = ulProgressMax;
1293
1294         push_task(This, &task->header, report_data_proc);
1295     }else {
1296         report_data(This, grfBSCF, ulProgress, ulProgressMax);
1297     }
1298
1299     return S_OK;
1300 }
1301
1302 typedef struct {
1303     task_header_t header;
1304
1305     HRESULT hres;
1306     LPWSTR str;
1307 } report_result_task_t;
1308
1309 static void report_result_proc(Binding *binding, task_header_t *t)
1310 {
1311     report_result_task_t *task = (report_result_task_t*)t;
1312
1313     IInternetProtocol_Terminate(binding->protocol, 0);
1314
1315     stop_binding(binding, task->hres, task->str);
1316
1317     heap_free(task->str);
1318     heap_free(task);
1319 }
1320
1321 static HRESULT WINAPI InternetProtocolSink_ReportResult(IInternetProtocolSink *iface,
1322         HRESULT hrResult, DWORD dwError, LPCWSTR szResult)
1323 {
1324     Binding *This = PROTSINK_THIS(iface);
1325
1326     TRACE("(%p)->(%08x %d %s)\n", This, hrResult, dwError, debugstr_w(szResult));
1327
1328     if(GetCurrentThreadId() == This->apartment_thread && !This->continue_call) {
1329         IInternetProtocol_Terminate(This->protocol, 0);
1330         stop_binding(This, hrResult, szResult);
1331     }else {
1332         report_result_task_t *task = heap_alloc(sizeof(report_result_task_t));
1333
1334         task->hres = hrResult;
1335         task->str = heap_strdupW(szResult);
1336
1337         push_task(This, &task->header, report_result_proc);
1338     }
1339
1340     return S_OK;
1341 }
1342
1343 #undef PROTSINK_THIS
1344
1345 static const IInternetProtocolSinkVtbl InternetProtocolSinkVtbl = {
1346     InternetProtocolSink_QueryInterface,
1347     InternetProtocolSink_AddRef,
1348     InternetProtocolSink_Release,
1349     InternetProtocolSink_Switch,
1350     InternetProtocolSink_ReportProgress,
1351     InternetProtocolSink_ReportData,
1352     InternetProtocolSink_ReportResult
1353 };
1354
1355 #define BINDINF_THIS(iface) DEFINE_THIS(Binding, InternetBindInfo, iface)
1356
1357 static HRESULT WINAPI InternetBindInfo_QueryInterface(IInternetBindInfo *iface,
1358         REFIID riid, void **ppv)
1359 {
1360     Binding *This = BINDINF_THIS(iface);
1361     return IBinding_QueryInterface(BINDING(This), riid, ppv);
1362 }
1363
1364 static ULONG WINAPI InternetBindInfo_AddRef(IInternetBindInfo *iface)
1365 {
1366     Binding *This = BINDINF_THIS(iface);
1367     return IBinding_AddRef(BINDING(This));
1368 }
1369
1370 static ULONG WINAPI InternetBindInfo_Release(IInternetBindInfo *iface)
1371 {
1372     Binding *This = BINDINF_THIS(iface);
1373     return IBinding_Release(BINDING(This));
1374 }
1375
1376 static HRESULT WINAPI InternetBindInfo_GetBindInfo(IInternetBindInfo *iface,
1377         DWORD *grfBINDF, BINDINFO *pbindinfo)
1378 {
1379     Binding *This = BINDINF_THIS(iface);
1380
1381     TRACE("(%p)->(%p %p)\n", This, grfBINDF, pbindinfo);
1382
1383     *grfBINDF = This->bindf;
1384
1385     *pbindinfo = This->bindinfo;
1386
1387     if(pbindinfo->szExtraInfo || pbindinfo->szCustomVerb)
1388         FIXME("copy strings\n");
1389
1390     if(pbindinfo->stgmedData.pUnkForRelease)
1391         IUnknown_AddRef(pbindinfo->stgmedData.pUnkForRelease);
1392
1393     if(pbindinfo->pUnk)
1394         IUnknown_AddRef(pbindinfo->pUnk);
1395
1396     return S_OK;
1397 }
1398
1399 static HRESULT WINAPI InternetBindInfo_GetBindString(IInternetBindInfo *iface,
1400         ULONG ulStringType, LPOLESTR *ppwzStr, ULONG cEl, ULONG *pcElFetched)
1401 {
1402     Binding *This = BINDINF_THIS(iface);
1403
1404     TRACE("(%p)->(%d %p %d %p)\n", This, ulStringType, ppwzStr, cEl, pcElFetched);
1405
1406     switch(ulStringType) {
1407     case BINDSTRING_ACCEPT_MIMES: {
1408         static const WCHAR wszMimes[] = {'*','/','*',0};
1409
1410         if(!ppwzStr || !pcElFetched)
1411             return E_INVALIDARG;
1412
1413         ppwzStr[0] = CoTaskMemAlloc(sizeof(wszMimes));
1414         memcpy(ppwzStr[0], wszMimes, sizeof(wszMimes));
1415         *pcElFetched = 1;
1416         return S_OK;
1417     }
1418     case BINDSTRING_USER_AGENT: {
1419         IInternetBindInfo *bindinfo = NULL;
1420         HRESULT hres;
1421
1422         hres = IBindStatusCallback_QueryInterface(This->callback, &IID_IInternetBindInfo,
1423                                                   (void**)&bindinfo);
1424         if(FAILED(hres))
1425             return hres;
1426
1427         hres = IInternetBindInfo_GetBindString(bindinfo, ulStringType, ppwzStr,
1428                                                cEl, pcElFetched);
1429         IInternetBindInfo_Release(bindinfo);
1430
1431         return hres;
1432     }
1433     }
1434
1435     FIXME("not supported string type %d\n", ulStringType);
1436     return E_NOTIMPL;
1437 }
1438
1439 #undef BINDF_THIS
1440
1441 static const IInternetBindInfoVtbl InternetBindInfoVtbl = {
1442     InternetBindInfo_QueryInterface,
1443     InternetBindInfo_AddRef,
1444     InternetBindInfo_Release,
1445     InternetBindInfo_GetBindInfo,
1446     InternetBindInfo_GetBindString
1447 };
1448
1449 #define SERVPROV_THIS(iface) DEFINE_THIS(Binding, ServiceProvider, iface)
1450
1451 static HRESULT WINAPI ServiceProvider_QueryInterface(IServiceProvider *iface,
1452         REFIID riid, void **ppv)
1453 {
1454     Binding *This = SERVPROV_THIS(iface);
1455     return IBinding_QueryInterface(BINDING(This), riid, ppv);
1456 }
1457
1458 static ULONG WINAPI ServiceProvider_AddRef(IServiceProvider *iface)
1459 {
1460     Binding *This = SERVPROV_THIS(iface);
1461     return IBinding_AddRef(BINDING(This));
1462 }
1463
1464 static ULONG WINAPI ServiceProvider_Release(IServiceProvider *iface)
1465 {
1466     Binding *This = SERVPROV_THIS(iface);
1467     return IBinding_Release(BINDING(This));
1468 }
1469
1470 static HRESULT WINAPI ServiceProvider_QueryService(IServiceProvider *iface,
1471         REFGUID guidService, REFIID riid, void **ppv)
1472 {
1473     Binding *This = SERVPROV_THIS(iface);
1474     HRESULT hres;
1475
1476     TRACE("(%p)->(%s %s %p)\n", This, debugstr_guid(guidService), debugstr_guid(riid), ppv);
1477
1478     if(This->service_provider) {
1479         hres = IServiceProvider_QueryService(This->service_provider, guidService,
1480                                              riid, ppv);
1481         if(SUCCEEDED(hres))
1482             return hres;
1483     }
1484
1485     WARN("unknown service %s\n", debugstr_guid(guidService));
1486     return E_NOTIMPL;
1487 }
1488
1489 #undef SERVPROV_THIS
1490
1491 static const IServiceProviderVtbl ServiceProviderVtbl = {
1492     ServiceProvider_QueryInterface,
1493     ServiceProvider_AddRef,
1494     ServiceProvider_Release,
1495     ServiceProvider_QueryService
1496 };
1497
1498 static HRESULT get_callback(IBindCtx *pbc, IBindStatusCallback **callback)
1499 {
1500     IUnknown *unk;
1501     HRESULT hres;
1502
1503     hres = IBindCtx_GetObjectParam(pbc, bscb_holderW, &unk);
1504     if(SUCCEEDED(hres)) {
1505         hres = IUnknown_QueryInterface(unk, &IID_IBindStatusCallback, (void**)callback);
1506         IUnknown_Release(unk);
1507     }
1508
1509     return SUCCEEDED(hres) ? S_OK : INET_E_DATA_NOT_AVAILABLE;
1510 }
1511
1512 static BOOL is_urlmon_protocol(LPCWSTR url)
1513 {
1514     static const WCHAR wszCdl[] = {'c','d','l'};
1515     static const WCHAR wszFile[] = {'f','i','l','e'};
1516     static const WCHAR wszFtp[]  = {'f','t','p'};
1517     static const WCHAR wszGopher[] = {'g','o','p','h','e','r'};
1518     static const WCHAR wszHttp[] = {'h','t','t','p'};
1519     static const WCHAR wszHttps[] = {'h','t','t','p','s'};
1520     static const WCHAR wszMk[]   = {'m','k'};
1521
1522     static const struct {
1523         LPCWSTR scheme;
1524         int len;
1525     } protocol_list[] = {
1526         {wszCdl,    sizeof(wszCdl)   /sizeof(WCHAR)},
1527         {wszFile,   sizeof(wszFile)  /sizeof(WCHAR)},
1528         {wszFtp,    sizeof(wszFtp)   /sizeof(WCHAR)},
1529         {wszGopher, sizeof(wszGopher)/sizeof(WCHAR)},
1530         {wszHttp,   sizeof(wszHttp)  /sizeof(WCHAR)},
1531         {wszHttps,  sizeof(wszHttps) /sizeof(WCHAR)},
1532         {wszMk,     sizeof(wszMk)    /sizeof(WCHAR)}
1533     };
1534
1535     unsigned int i;
1536     int len = lstrlenW(url);
1537
1538     for(i=0; i < sizeof(protocol_list)/sizeof(protocol_list[0]); i++) {
1539         if(len >= protocol_list[i].len
1540            && !memcmp(url, protocol_list[i].scheme, protocol_list[i].len*sizeof(WCHAR)))
1541             return TRUE;
1542     }
1543
1544     return FALSE;
1545 }
1546
1547 static HRESULT Binding_Create(IMoniker *mon, Binding *binding_ctx, LPCWSTR url, IBindCtx *pbc,
1548         BOOL to_obj, REFIID riid, Binding **binding)
1549 {
1550     Binding *ret;
1551     HRESULT hres;
1552
1553     URLMON_LockModule();
1554
1555     ret = heap_alloc_zero(sizeof(Binding));
1556
1557     ret->lpBindingVtbl              = &BindingVtbl;
1558     ret->lpInternetProtocolSinkVtbl = &InternetProtocolSinkVtbl;
1559     ret->lpInternetBindInfoVtbl     = &InternetBindInfoVtbl;
1560     ret->lpServiceProviderVtbl      = &ServiceProviderVtbl;
1561
1562     ret->ref = 1;
1563
1564     ret->to_object = to_obj;
1565     ret->iid = *riid;
1566     ret->apartment_thread = GetCurrentThreadId();
1567     ret->notif_hwnd = get_notif_hwnd();
1568     ret->report_mime = !binding_ctx;
1569     ret->download_state = BEFORE_DOWNLOAD;
1570
1571     if(to_obj) {
1572         IBindCtx_AddRef(pbc);
1573         ret->bctx = pbc;
1574     }
1575
1576     if(mon) {
1577         IMoniker_AddRef(mon);
1578         ret->mon = mon;
1579     }
1580
1581     ret->bindinfo.cbSize = sizeof(BINDINFO);
1582
1583     InitializeCriticalSection(&ret->section);
1584     ret->section.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": Binding.section");
1585
1586     hres = get_callback(pbc, &ret->callback);
1587     if(FAILED(hres)) {
1588         WARN("Could not get IBindStatusCallback\n");
1589         IBinding_Release(BINDING(ret));
1590         return hres;
1591     }
1592
1593     IBindStatusCallback_QueryInterface(ret->callback, &IID_IServiceProvider,
1594                                        (void**)&ret->service_provider);
1595
1596     if(binding_ctx) {
1597         ret->protocol = binding_ctx->protocol;
1598         IInternetProtocol_AddRef(ret->protocol);
1599     }else {
1600         hres = create_binding_protocol(url, TRUE, &ret->protocol);
1601         if(FAILED(hres)) {
1602             WARN("Could not get protocol handler\n");
1603             IBinding_Release(BINDING(ret));
1604             return hres;
1605         }
1606     }
1607
1608     hres = IBindStatusCallback_GetBindInfo(ret->callback, &ret->bindf, &ret->bindinfo);
1609     if(FAILED(hres)) {
1610         WARN("GetBindInfo failed: %08x\n", hres);
1611         IBinding_Release(BINDING(ret));
1612         return hres;
1613     }
1614
1615     TRACE("bindf %08x\n", ret->bindf);
1616     dump_BINDINFO(&ret->bindinfo);
1617
1618     ret->bindf |= BINDF_FROMURLMON;
1619     if(to_obj)
1620         ret->bindinfo.dwOptions |= 0x100000;
1621
1622     if(!is_urlmon_protocol(url))
1623         ret->bindf |= BINDF_NEEDFILE;
1624
1625     ret->url = heap_strdupW(url);
1626
1627     if(binding_ctx) {
1628         ret->stgmed_buf = binding_ctx->stgmed_buf;
1629         IUnknown_AddRef(STGMEDUNK(ret->stgmed_buf));
1630         ret->clipboard_format = binding_ctx->clipboard_format;
1631     }else {
1632         ret->stgmed_buf = create_stgmed_buf(ret->protocol);
1633     }
1634
1635     if(to_obj) {
1636         ret->stgmed_obj = NULL;
1637     }else if(IsEqualGUID(&IID_IStream, riid)) {
1638         ret->stgmed_obj = create_stgmed_stream(ret->stgmed_buf);
1639     }else if(IsEqualGUID(&IID_IUnknown, riid)) {
1640         ret->bindf |= BINDF_NEEDFILE;
1641         ret->stgmed_obj = create_stgmed_file(ret->stgmed_buf);
1642     }else {
1643         FIXME("Unsupported riid %s\n", debugstr_guid(riid));
1644         IBinding_Release(BINDING(ret));
1645         return E_NOTIMPL;
1646     }
1647
1648     *binding = ret;
1649     return S_OK;
1650 }
1651
1652 static HRESULT start_binding(IMoniker *mon, Binding *binding_ctx, LPCWSTR url, IBindCtx *pbc,
1653                              BOOL to_obj, REFIID riid, Binding **ret)
1654 {
1655     Binding *binding = NULL;
1656     HRESULT hres;
1657     MSG msg;
1658
1659     hres = Binding_Create(mon, binding_ctx, url, pbc, to_obj, riid, &binding);
1660     if(FAILED(hres))
1661         return hres;
1662
1663     hres = IBindStatusCallback_OnStartBinding(binding->callback, 0, BINDING(binding));
1664     if(FAILED(hres)) {
1665         WARN("OnStartBinding failed: %08x\n", hres);
1666         stop_binding(binding, INET_E_DOWNLOAD_FAILURE, NULL);
1667         IBinding_Release(BINDING(binding));
1668         return hres;
1669     }
1670
1671     if(binding_ctx) {
1672         set_binding_sink(binding->protocol, PROTSINK(binding));
1673         report_data(binding, 0, 0, 0);
1674     }else {
1675         hres = IInternetProtocol_Start(binding->protocol, url, PROTSINK(binding),
1676                  BINDINF(binding), 0, 0);
1677
1678         TRACE("start ret %08x\n", hres);
1679
1680         if(FAILED(hres) && hres != E_PENDING) {
1681             stop_binding(binding, hres, NULL);
1682             IBinding_Release(BINDING(binding));
1683
1684             return hres;
1685         }
1686     }
1687
1688     while(!(binding->bindf & BINDF_ASYNCHRONOUS) &&
1689           !(binding->state & BINDING_STOPPED)) {
1690         MsgWaitForMultipleObjects(0, NULL, FALSE, 5000, QS_POSTMESSAGE);
1691         while (PeekMessageW(&msg, binding->notif_hwnd, WM_USER, WM_USER+117, PM_REMOVE|PM_NOYIELD)) {
1692             TranslateMessage(&msg);
1693             DispatchMessageW(&msg);
1694         }
1695     }
1696
1697     *ret = binding;
1698     return S_OK;
1699 }
1700
1701 HRESULT bind_to_storage(LPCWSTR url, IBindCtx *pbc, REFIID riid, void **ppv)
1702 {
1703     Binding *binding = NULL, *binding_ctx;
1704     HRESULT hres;
1705
1706     *ppv = NULL;
1707
1708     binding_ctx = get_bctx_binding(pbc);
1709
1710     hres = start_binding(NULL, binding_ctx, url, pbc, FALSE, riid, &binding);
1711     if(binding_ctx)
1712         IBinding_Release(BINDING(binding_ctx));
1713     if(FAILED(hres))
1714         return hres;
1715
1716     if(binding->hres == S_OK && binding->stgmed_buf->init) {
1717         if((binding->state & BINDING_STOPPED) && (binding->state & BINDING_LOCKED))
1718             IInternetProtocol_UnlockRequest(binding->protocol);
1719
1720         *ppv = binding->stgmed_obj->vtbl->get_result(binding->stgmed_obj);
1721     }
1722
1723     IBinding_Release(BINDING(binding));
1724
1725     return *ppv ? S_OK : MK_S_ASYNCHRONOUS;
1726 }
1727
1728 HRESULT bind_to_object(IMoniker *mon, LPCWSTR url, IBindCtx *pbc, REFIID riid, void **ppv)
1729 {
1730     Binding *binding;
1731     HRESULT hres;
1732
1733     *ppv = NULL;
1734
1735     hres = start_binding(mon, NULL, url, pbc, TRUE, riid, &binding);
1736     if(FAILED(hres))
1737         return hres;
1738
1739     if(binding->hres != S_OK) {
1740         hres = SUCCEEDED(binding->hres) ? S_OK : binding->hres;
1741     }else if(binding->bindf & BINDF_ASYNCHRONOUS) {
1742         hres = MK_S_ASYNCHRONOUS;
1743     }else {
1744         *ppv = binding->obj;
1745         IUnknown_AddRef(binding->obj);
1746         hres = S_OK;
1747     }
1748
1749     IBinding_Release(BINDING(binding));
1750
1751     return hres;
1752 }