wininet: Moved connected check out of NETCON_set_timeout.
[wine] / dlls / mshtml / navigate.c
1 /*
2  * Copyright 2006-2010 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 "config.h"
20
21 #include <stdarg.h>
22
23 #define COBJMACROS
24 #define NONAMELESSUNION
25 #define NONAMELESSSTRUCT
26
27 #include "windef.h"
28 #include "winbase.h"
29 #include "winuser.h"
30 #include "winreg.h"
31 #include "ole2.h"
32 #include "hlguids.h"
33 #include "shlguid.h"
34 #include "wininet.h"
35 #include "shlwapi.h"
36
37 #include "wine/debug.h"
38 #include "wine/unicode.h"
39
40 #include "mshtml_private.h"
41
42 WINE_DEFAULT_DEBUG_CHANNEL(mshtml);
43
44 #define CONTENT_LENGTH "Content-Length"
45 #define UTF16_STR "utf-16"
46
47 typedef struct {
48     nsIInputStream nsIInputStream_iface;
49
50     LONG ref;
51
52     char buf[1024];
53     DWORD buf_size;
54 } nsProtocolStream;
55
56 typedef struct {
57     void (*destroy)(BSCallback*);
58     HRESULT (*init_bindinfo)(BSCallback*);
59     HRESULT (*start_binding)(BSCallback*);
60     HRESULT (*stop_binding)(BSCallback*,HRESULT);
61     HRESULT (*read_data)(BSCallback*,IStream*);
62     HRESULT (*on_progress)(BSCallback*,ULONG,LPCWSTR);
63     HRESULT (*on_response)(BSCallback*,DWORD,LPCWSTR);
64     HRESULT (*beginning_transaction)(BSCallback*,WCHAR**);
65 } BSCallbackVtbl;
66
67 struct BSCallback {
68     IBindStatusCallback IBindStatusCallback_iface;
69     IServiceProvider    IServiceProvider_iface;
70     IHttpNegotiate2     IHttpNegotiate2_iface;
71     IInternetBindInfo   IInternetBindInfo_iface;
72
73     const BSCallbackVtbl          *vtbl;
74
75     LONG ref;
76
77     LPWSTR headers;
78     HGLOBAL post_data;
79     ULONG post_data_len;
80     ULONG readed;
81     DWORD bindf;
82     BOOL bindinfo_ready;
83
84     IMoniker *mon;
85     IBinding *binding;
86
87     HTMLDocumentNode *doc;
88
89     struct list entry;
90 };
91
92 static inline nsProtocolStream *impl_from_nsIInputStream(nsIInputStream *iface)
93 {
94     return CONTAINING_RECORD(iface, nsProtocolStream, nsIInputStream_iface);
95 }
96
97 static nsresult NSAPI nsInputStream_QueryInterface(nsIInputStream *iface, nsIIDRef riid,
98         void **result)
99 {
100     nsProtocolStream *This = impl_from_nsIInputStream(iface);
101
102     *result = NULL;
103
104     if(IsEqualGUID(&IID_nsISupports, riid)) {
105         TRACE("(%p)->(IID_nsISupports %p)\n", This, result);
106         *result  = &This->nsIInputStream_iface;
107     }else if(IsEqualGUID(&IID_nsIInputStream, riid)) {
108         TRACE("(%p)->(IID_nsIInputStream %p)\n", This, result);
109         *result  = &This->nsIInputStream_iface;
110     }
111
112     if(*result) {
113         nsIInputStream_AddRef(&This->nsIInputStream_iface);
114         return NS_OK;
115     }
116
117     WARN("unsupported interface %s\n", debugstr_guid(riid));
118     return NS_NOINTERFACE;
119 }
120
121 static nsrefcnt NSAPI nsInputStream_AddRef(nsIInputStream *iface)
122 {
123     nsProtocolStream *This = impl_from_nsIInputStream(iface);
124     LONG ref = InterlockedIncrement(&This->ref);
125
126     TRACE("(%p) ref=%d\n", This, ref);
127
128     return ref;
129 }
130
131
132 static nsrefcnt NSAPI nsInputStream_Release(nsIInputStream *iface)
133 {
134     nsProtocolStream *This = impl_from_nsIInputStream(iface);
135     LONG ref = InterlockedDecrement(&This->ref);
136
137     TRACE("(%p) ref=%d\n", This, ref);
138
139     if(!ref)
140         heap_free(This);
141
142     return ref;
143 }
144
145 static nsresult NSAPI nsInputStream_Close(nsIInputStream *iface)
146 {
147     nsProtocolStream *This = impl_from_nsIInputStream(iface);
148     FIXME("(%p)\n", This);
149     return NS_ERROR_NOT_IMPLEMENTED;
150 }
151
152 static nsresult NSAPI nsInputStream_Available(nsIInputStream *iface, PRUint32 *_retval)
153 {
154     nsProtocolStream *This = impl_from_nsIInputStream(iface);
155     FIXME("(%p)->(%p)\n", This, _retval);
156     return NS_ERROR_NOT_IMPLEMENTED;
157 }
158
159 static nsresult NSAPI nsInputStream_Read(nsIInputStream *iface, char *aBuf, PRUint32 aCount,
160                                          PRUint32 *_retval)
161 {
162     nsProtocolStream *This = impl_from_nsIInputStream(iface);
163     DWORD read = aCount;
164
165     TRACE("(%p)->(%p %d %p)\n", This, aBuf, aCount, _retval);
166
167     if(read > This->buf_size)
168         read = This->buf_size;
169
170     if(read) {
171         memcpy(aBuf, This->buf, read);
172         if(read < This->buf_size)
173             memmove(This->buf, This->buf+read, This->buf_size-read);
174         This->buf_size -= read;
175     }
176
177     *_retval = read;
178     return NS_OK;
179 }
180
181 static nsresult NSAPI nsInputStream_ReadSegments(nsIInputStream *iface,
182         nsresult (WINAPI *aWriter)(nsIInputStream*,void*,const char*,PRUint32,PRUint32,PRUint32*),
183         void *aClousure, PRUint32 aCount, PRUint32 *_retval)
184 {
185     nsProtocolStream *This = impl_from_nsIInputStream(iface);
186     PRUint32 written = 0;
187     nsresult nsres;
188
189     TRACE("(%p)->(%p %p %d %p)\n", This, aWriter, aClousure, aCount, _retval);
190
191     if(!This->buf_size)
192         return S_OK;
193
194     if(aCount > This->buf_size)
195         aCount = This->buf_size;
196
197     nsres = aWriter(&This->nsIInputStream_iface, aClousure, This->buf, 0, aCount, &written);
198     if(NS_FAILED(nsres))
199         TRACE("aWritter failed: %08x\n", nsres);
200     else if(written != This->buf_size)
201         FIXME("written %d != buf_size %d\n", written, This->buf_size);
202
203     This->buf_size -= written; 
204
205     *_retval = written;
206     return nsres;
207 }
208
209 static nsresult NSAPI nsInputStream_IsNonBlocking(nsIInputStream *iface, PRBool *_retval)
210 {
211     nsProtocolStream *This = impl_from_nsIInputStream(iface);
212     FIXME("(%p)->(%p)\n", This, _retval);
213     return NS_ERROR_NOT_IMPLEMENTED;
214 }
215
216 static const nsIInputStreamVtbl nsInputStreamVtbl = {
217     nsInputStream_QueryInterface,
218     nsInputStream_AddRef,
219     nsInputStream_Release,
220     nsInputStream_Close,
221     nsInputStream_Available,
222     nsInputStream_Read,
223     nsInputStream_ReadSegments,
224     nsInputStream_IsNonBlocking
225 };
226
227 static nsProtocolStream *create_nsprotocol_stream(void)
228 {
229     nsProtocolStream *ret = heap_alloc(sizeof(nsProtocolStream));
230
231     ret->nsIInputStream_iface.lpVtbl = &nsInputStreamVtbl;
232     ret->ref = 1;
233     ret->buf_size = 0;
234
235     return ret;
236 }
237
238 static inline BSCallback *impl_from_IBindStatusCallback(IBindStatusCallback *iface)
239 {
240     return CONTAINING_RECORD(iface, BSCallback, IBindStatusCallback_iface);
241 }
242
243 static HRESULT WINAPI BindStatusCallback_QueryInterface(IBindStatusCallback *iface,
244         REFIID riid, void **ppv)
245 {
246     BSCallback *This = impl_from_IBindStatusCallback(iface);
247
248     *ppv = NULL;
249     if(IsEqualGUID(&IID_IUnknown, riid)) {
250         TRACE("(%p)->(IID_IUnknown, %p)\n", This, ppv);
251         *ppv = &This->IBindStatusCallback_iface;
252     }else if(IsEqualGUID(&IID_IBindStatusCallback, riid)) {
253         TRACE("(%p)->(IID_IBindStatusCallback, %p)\n", This, ppv);
254         *ppv = &This->IBindStatusCallback_iface;
255     }else if(IsEqualGUID(&IID_IServiceProvider, riid)) {
256         TRACE("(%p)->(IID_IServiceProvider %p)\n", This, ppv);
257         *ppv = &This->IServiceProvider_iface;
258     }else if(IsEqualGUID(&IID_IHttpNegotiate, riid)) {
259         TRACE("(%p)->(IID_IHttpNegotiate %p)\n", This, ppv);
260         *ppv = &This->IHttpNegotiate2_iface;
261     }else if(IsEqualGUID(&IID_IHttpNegotiate2, riid)) {
262         TRACE("(%p)->(IID_IHttpNegotiate2 %p)\n", This, ppv);
263         *ppv = &This->IHttpNegotiate2_iface;
264     }else if(IsEqualGUID(&IID_IInternetBindInfo, riid)) {
265         TRACE("(%p)->(IID_IInternetBindInfo %p)\n", This, ppv);
266         *ppv = &This->IInternetBindInfo_iface;
267     }
268
269     if(*ppv) {
270         IBindStatusCallback_AddRef(&This->IBindStatusCallback_iface);
271         return S_OK;
272     }
273
274     TRACE("Unsupported riid = %s\n", debugstr_guid(riid));
275     return E_NOINTERFACE;
276 }
277
278 static ULONG WINAPI BindStatusCallback_AddRef(IBindStatusCallback *iface)
279 {
280     BSCallback *This = impl_from_IBindStatusCallback(iface);
281     LONG ref = InterlockedIncrement(&This->ref);
282
283     TRACE("(%p) ref = %d\n", This, ref);
284
285     return ref;
286 }
287
288 static ULONG WINAPI BindStatusCallback_Release(IBindStatusCallback *iface)
289 {
290     BSCallback *This = impl_from_IBindStatusCallback(iface);
291     LONG ref = InterlockedDecrement(&This->ref);
292
293     TRACE("(%p) ref = %d\n", This, ref);
294
295     if(!ref) {
296         if(This->post_data)
297             GlobalFree(This->post_data);
298         if(This->mon)
299             IMoniker_Release(This->mon);
300         if(This->binding)
301             IBinding_Release(This->binding);
302         list_remove(&This->entry);
303         list_init(&This->entry);
304         heap_free(This->headers);
305
306         This->vtbl->destroy(This);
307     }
308
309     return ref;
310 }
311
312 static HRESULT WINAPI BindStatusCallback_OnStartBinding(IBindStatusCallback *iface,
313         DWORD dwReserved, IBinding *pbind)
314 {
315     BSCallback *This = impl_from_IBindStatusCallback(iface);
316
317     TRACE("(%p)->(%d %p)\n", This, dwReserved, pbind);
318
319     IBinding_AddRef(pbind);
320     This->binding = pbind;
321
322     if(This->doc)
323         list_add_head(&This->doc->bindings, &This->entry);
324
325     return This->vtbl->start_binding(This);
326 }
327
328 static HRESULT WINAPI BindStatusCallback_GetPriority(IBindStatusCallback *iface, LONG *pnPriority)
329 {
330     BSCallback *This = impl_from_IBindStatusCallback(iface);
331     FIXME("(%p)->(%p)\n", This, pnPriority);
332     return E_NOTIMPL;
333 }
334
335 static HRESULT WINAPI BindStatusCallback_OnLowResource(IBindStatusCallback *iface, DWORD reserved)
336 {
337     BSCallback *This = impl_from_IBindStatusCallback(iface);
338     FIXME("(%p)->(%d)\n", This, reserved);
339     return E_NOTIMPL;
340 }
341
342 static HRESULT WINAPI BindStatusCallback_OnProgress(IBindStatusCallback *iface, ULONG ulProgress,
343         ULONG ulProgressMax, ULONG ulStatusCode, LPCWSTR szStatusText)
344 {
345     BSCallback *This = impl_from_IBindStatusCallback(iface);
346
347     TRACE("%p)->(%u %u %u %s)\n", This, ulProgress, ulProgressMax, ulStatusCode,
348             debugstr_w(szStatusText));
349
350     return This->vtbl->on_progress(This, ulStatusCode, szStatusText);
351 }
352
353 static HRESULT WINAPI BindStatusCallback_OnStopBinding(IBindStatusCallback *iface,
354         HRESULT hresult, LPCWSTR szError)
355 {
356     BSCallback *This = impl_from_IBindStatusCallback(iface);
357     HRESULT hres;
358
359     TRACE("(%p)->(%08x %s)\n", This, hresult, debugstr_w(szError));
360
361     /* NOTE: IE7 calls GetBindResult here */
362
363     hres = This->vtbl->stop_binding(This, hresult);
364
365     if(This->binding) {
366         IBinding_Release(This->binding);
367         This->binding = NULL;
368     }
369
370     list_remove(&This->entry);
371     list_init(&This->entry);
372     This->doc = NULL;
373
374     return hres;
375 }
376
377 static HRESULT WINAPI BindStatusCallback_GetBindInfo(IBindStatusCallback *iface,
378         DWORD *grfBINDF, BINDINFO *pbindinfo)
379 {
380     BSCallback *This = impl_from_IBindStatusCallback(iface);
381     DWORD size;
382
383     TRACE("(%p)->(%p %p)\n", This, grfBINDF, pbindinfo);
384
385     if(!This->bindinfo_ready) {
386         HRESULT hres;
387
388         hres = This->vtbl->init_bindinfo(This);
389         if(FAILED(hres))
390             return hres;
391
392         This->bindinfo_ready = TRUE;
393     }
394
395     *grfBINDF = This->bindf;
396
397     size = pbindinfo->cbSize;
398     memset(pbindinfo, 0, size);
399     pbindinfo->cbSize = size;
400
401     pbindinfo->cbstgmedData = This->post_data_len;
402     pbindinfo->dwCodePage = CP_UTF8;
403     pbindinfo->dwOptions = 0x80000;
404
405     if(This->post_data) {
406         pbindinfo->dwBindVerb = BINDVERB_POST;
407
408         pbindinfo->stgmedData.tymed = TYMED_HGLOBAL;
409         pbindinfo->stgmedData.u.hGlobal = This->post_data;
410         pbindinfo->stgmedData.pUnkForRelease = (IUnknown*)&This->IBindStatusCallback_iface;
411         IBindStatusCallback_AddRef(&This->IBindStatusCallback_iface);
412     }
413
414     return S_OK;
415 }
416
417 static HRESULT WINAPI BindStatusCallback_OnDataAvailable(IBindStatusCallback *iface,
418         DWORD grfBSCF, DWORD dwSize, FORMATETC *pformatetc, STGMEDIUM *pstgmed)
419 {
420     BSCallback *This = impl_from_IBindStatusCallback(iface);
421
422     TRACE("(%p)->(%08x %d %p %p)\n", This, grfBSCF, dwSize, pformatetc, pstgmed);
423
424     return This->vtbl->read_data(This, pstgmed->u.pstm);
425 }
426
427 static HRESULT WINAPI BindStatusCallback_OnObjectAvailable(IBindStatusCallback *iface,
428         REFIID riid, IUnknown *punk)
429 {
430     BSCallback *This = impl_from_IBindStatusCallback(iface);
431     FIXME("(%p)->(%s %p)\n", This, debugstr_guid(riid), punk);
432     return E_NOTIMPL;
433 }
434
435 static const IBindStatusCallbackVtbl BindStatusCallbackVtbl = {
436     BindStatusCallback_QueryInterface,
437     BindStatusCallback_AddRef,
438     BindStatusCallback_Release,
439     BindStatusCallback_OnStartBinding,
440     BindStatusCallback_GetPriority,
441     BindStatusCallback_OnLowResource,
442     BindStatusCallback_OnProgress,
443     BindStatusCallback_OnStopBinding,
444     BindStatusCallback_GetBindInfo,
445     BindStatusCallback_OnDataAvailable,
446     BindStatusCallback_OnObjectAvailable
447 };
448
449 static inline BSCallback *impl_from_IHttpNegotiate2(IHttpNegotiate2 *iface)
450 {
451     return CONTAINING_RECORD(iface, BSCallback, IHttpNegotiate2_iface);
452 }
453
454 static HRESULT WINAPI HttpNegotiate_QueryInterface(IHttpNegotiate2 *iface,
455                                                    REFIID riid, void **ppv)
456 {
457     BSCallback *This = impl_from_IHttpNegotiate2(iface);
458     return IBindStatusCallback_QueryInterface(&This->IBindStatusCallback_iface, riid, ppv);
459 }
460
461 static ULONG WINAPI HttpNegotiate_AddRef(IHttpNegotiate2 *iface)
462 {
463     BSCallback *This = impl_from_IHttpNegotiate2(iface);
464     return IBindStatusCallback_AddRef(&This->IBindStatusCallback_iface);
465 }
466
467 static ULONG WINAPI HttpNegotiate_Release(IHttpNegotiate2 *iface)
468 {
469     BSCallback *This = impl_from_IHttpNegotiate2(iface);
470     return IBindStatusCallback_Release(&This->IBindStatusCallback_iface);
471 }
472
473 static HRESULT WINAPI HttpNegotiate_BeginningTransaction(IHttpNegotiate2 *iface,
474         LPCWSTR szURL, LPCWSTR szHeaders, DWORD dwReserved, LPWSTR *pszAdditionalHeaders)
475 {
476     BSCallback *This = impl_from_IHttpNegotiate2(iface);
477     HRESULT hres;
478
479     TRACE("(%p)->(%s %s %d %p)\n", This, debugstr_w(szURL), debugstr_w(szHeaders),
480           dwReserved, pszAdditionalHeaders);
481
482     *pszAdditionalHeaders = NULL;
483
484     hres = This->vtbl->beginning_transaction(This, pszAdditionalHeaders);
485     if(hres != S_FALSE)
486         return hres;
487
488     if(This->headers) {
489         DWORD size;
490
491         size = (strlenW(This->headers)+1)*sizeof(WCHAR);
492         *pszAdditionalHeaders = CoTaskMemAlloc(size);
493         if(!*pszAdditionalHeaders)
494             return E_OUTOFMEMORY;
495         memcpy(*pszAdditionalHeaders, This->headers, size);
496     }
497
498     return S_OK;
499 }
500
501 static HRESULT WINAPI HttpNegotiate_OnResponse(IHttpNegotiate2 *iface, DWORD dwResponseCode,
502         LPCWSTR szResponseHeaders, LPCWSTR szRequestHeaders, LPWSTR *pszAdditionalRequestHeaders)
503 {
504     BSCallback *This = impl_from_IHttpNegotiate2(iface);
505
506     TRACE("(%p)->(%d %s %s %p)\n", This, dwResponseCode, debugstr_w(szResponseHeaders),
507           debugstr_w(szRequestHeaders), pszAdditionalRequestHeaders);
508
509     return This->vtbl->on_response(This, dwResponseCode, szResponseHeaders);
510 }
511
512 static HRESULT WINAPI HttpNegotiate_GetRootSecurityId(IHttpNegotiate2 *iface,
513         BYTE *pbSecurityId, DWORD *pcbSecurityId, DWORD_PTR dwReserved)
514 {
515     BSCallback *This = impl_from_IHttpNegotiate2(iface);
516     FIXME("(%p)->(%p %p %ld)\n", This, pbSecurityId, pcbSecurityId, dwReserved);
517     return E_NOTIMPL;
518 }
519
520 static const IHttpNegotiate2Vtbl HttpNegotiate2Vtbl = {
521     HttpNegotiate_QueryInterface,
522     HttpNegotiate_AddRef,
523     HttpNegotiate_Release,
524     HttpNegotiate_BeginningTransaction,
525     HttpNegotiate_OnResponse,
526     HttpNegotiate_GetRootSecurityId
527 };
528
529 static inline BSCallback *impl_from_IInternetBindInfo(IInternetBindInfo *iface)
530 {
531     return CONTAINING_RECORD(iface, BSCallback, IInternetBindInfo_iface);
532 }
533
534 static HRESULT WINAPI InternetBindInfo_QueryInterface(IInternetBindInfo *iface,
535                                                       REFIID riid, void **ppv)
536 {
537     BSCallback *This = impl_from_IInternetBindInfo(iface);
538     return IBindStatusCallback_QueryInterface(&This->IBindStatusCallback_iface, riid, ppv);
539 }
540
541 static ULONG WINAPI InternetBindInfo_AddRef(IInternetBindInfo *iface)
542 {
543     BSCallback *This = impl_from_IInternetBindInfo(iface);
544     return IBindStatusCallback_AddRef(&This->IBindStatusCallback_iface);
545 }
546
547 static ULONG WINAPI InternetBindInfo_Release(IInternetBindInfo *iface)
548 {
549     BSCallback *This = impl_from_IInternetBindInfo(iface);
550     return IBindStatusCallback_Release(&This->IBindStatusCallback_iface);
551 }
552
553 static HRESULT WINAPI InternetBindInfo_GetBindInfo(IInternetBindInfo *iface,
554                                                    DWORD *grfBINDF, BINDINFO *pbindinfo)
555 {
556     BSCallback *This = impl_from_IInternetBindInfo(iface);
557     FIXME("(%p)->(%p %p)\n", This, grfBINDF, pbindinfo);
558     return E_NOTIMPL;
559 }
560
561 static HRESULT WINAPI InternetBindInfo_GetBindString(IInternetBindInfo *iface,
562         ULONG ulStringType, LPOLESTR *ppwzStr, ULONG cEl, ULONG *pcElFetched)
563 {
564     BSCallback *This = impl_from_IInternetBindInfo(iface);
565     FIXME("(%p)->(%u %p %u %p)\n", This, ulStringType, ppwzStr, cEl, pcElFetched);
566     return E_NOTIMPL;
567 }
568
569 static const IInternetBindInfoVtbl InternetBindInfoVtbl = {
570     InternetBindInfo_QueryInterface,
571     InternetBindInfo_AddRef,
572     InternetBindInfo_Release,
573     InternetBindInfo_GetBindInfo,
574     InternetBindInfo_GetBindString
575 };
576
577 static inline BSCallback *impl_from_IServiceProvider(IServiceProvider *iface)
578 {
579     return CONTAINING_RECORD(iface, BSCallback, IServiceProvider_iface);
580 }
581
582 static HRESULT WINAPI BSCServiceProvider_QueryInterface(IServiceProvider *iface,
583                                                         REFIID riid, void **ppv)
584 {
585     BSCallback *This = impl_from_IServiceProvider(iface);
586     return IBindStatusCallback_QueryInterface(&This->IBindStatusCallback_iface, riid, ppv);
587 }
588
589 static ULONG WINAPI BSCServiceProvider_AddRef(IServiceProvider *iface)
590 {
591     BSCallback *This = impl_from_IServiceProvider(iface);
592     return IBindStatusCallback_AddRef(&This->IBindStatusCallback_iface);
593 }
594
595 static ULONG WINAPI BSCServiceProvider_Release(IServiceProvider *iface)
596 {
597     BSCallback *This = impl_from_IServiceProvider(iface);
598     return IBindStatusCallback_Release(&This->IBindStatusCallback_iface);
599 }
600
601 static HRESULT WINAPI BSCServiceProvider_QueryService(IServiceProvider *iface,
602         REFGUID guidService, REFIID riid, void **ppv)
603 {
604     BSCallback *This = impl_from_IServiceProvider(iface);
605     TRACE("(%p)->(%s %s %p)\n", This, debugstr_guid(guidService), debugstr_guid(riid), ppv);
606     return E_NOINTERFACE;
607 }
608
609 static const IServiceProviderVtbl ServiceProviderVtbl = {
610     BSCServiceProvider_QueryInterface,
611     BSCServiceProvider_AddRef,
612     BSCServiceProvider_Release,
613     BSCServiceProvider_QueryService
614 };
615
616 static void init_bscallback(BSCallback *This, const BSCallbackVtbl *vtbl, IMoniker *mon, DWORD bindf)
617 {
618     This->IBindStatusCallback_iface.lpVtbl = &BindStatusCallbackVtbl;
619     This->IServiceProvider_iface.lpVtbl = &ServiceProviderVtbl;
620     This->IHttpNegotiate2_iface.lpVtbl = &HttpNegotiate2Vtbl;
621     This->IInternetBindInfo_iface.lpVtbl = &InternetBindInfoVtbl;
622     This->vtbl = vtbl;
623     This->ref = 1;
624     This->bindf = bindf;
625
626     list_init(&This->entry);
627
628     if(mon)
629         IMoniker_AddRef(mon);
630     This->mon = mon;
631 }
632
633 /* Calls undocumented 84 cmd of CGID_ShellDocView */
634 static void call_docview_84(HTMLDocumentObj *doc)
635 {
636     IOleCommandTarget *olecmd;
637     VARIANT var;
638     HRESULT hres;
639
640     if(!doc->client)
641         return;
642
643     hres = IOleClientSite_QueryInterface(doc->client, &IID_IOleCommandTarget, (void**)&olecmd);
644     if(FAILED(hres))
645         return;
646
647     VariantInit(&var);
648     hres = IOleCommandTarget_Exec(olecmd, &CGID_ShellDocView, 84, 0, NULL, &var);
649     IOleCommandTarget_Release(olecmd);
650     if(SUCCEEDED(hres) && V_VT(&var) != VT_NULL)
651         FIXME("handle result\n");
652 }
653
654 static HRESULT parse_headers(const WCHAR *headers, struct list *headers_list)
655 {
656     const WCHAR *header, *header_end, *colon, *value;
657     HRESULT hres;
658
659     header = headers;
660     while(*header) {
661         if(header[0] == '\r' && header[1] == '\n' && !header[2])
662             break;
663         for(colon = header; *colon && *colon != ':' && *colon != '\r'; colon++);
664         if(*colon != ':')
665             return E_FAIL;
666
667         value = colon+1;
668         while(*value == ' ')
669             value++;
670         if(!*value)
671             return E_FAIL;
672
673         for(header_end = value+1; *header_end && *header_end != '\r'; header_end++);
674
675         hres = set_http_header(headers_list, header, colon-header, value, header_end-value);
676         if(FAILED(hres))
677             return hres;
678
679         header = header_end;
680         if(header[0] == '\r' && header[1] == '\n')
681             header += 2;
682     }
683
684     return S_OK;
685 }
686
687 HRESULT start_binding(HTMLWindow *window, HTMLDocumentNode *doc, BSCallback *bscallback, IBindCtx *bctx)
688 {
689     IStream *str = NULL;
690     HRESULT hres;
691
692     bscallback->doc = doc;
693
694     /* NOTE: IE7 calls IsSystemMoniker here*/
695
696     if(window) {
697         if(bscallback->mon != window->mon)
698             set_current_mon(window, bscallback->mon);
699         call_docview_84(window->doc_obj);
700     }
701
702     if(bctx) {
703         RegisterBindStatusCallback(bctx, &bscallback->IBindStatusCallback_iface, NULL, 0);
704         IBindCtx_AddRef(bctx);
705     }else {
706         hres = CreateAsyncBindCtx(0, &bscallback->IBindStatusCallback_iface, NULL, &bctx);
707         if(FAILED(hres)) {
708             WARN("CreateAsyncBindCtx failed: %08x\n", hres);
709             bscallback->vtbl->stop_binding(bscallback, hres);
710             return hres;
711         }
712     }
713
714     hres = IMoniker_BindToStorage(bscallback->mon, bctx, NULL, &IID_IStream, (void**)&str);
715     IBindCtx_Release(bctx);
716     if(FAILED(hres)) {
717         WARN("BindToStorage failed: %08x\n", hres);
718         bscallback->vtbl->stop_binding(bscallback, hres);
719         return hres;
720     }
721
722     if(str)
723         IStream_Release(str);
724
725     IMoniker_Release(bscallback->mon);
726     bscallback->mon = NULL;
727
728     return S_OK;
729 }
730
731 typedef struct {
732     BSCallback bsc;
733
734     DWORD size;
735     BYTE *buf;
736     HRESULT hres;
737 } BufferBSC;
738
739 static inline BufferBSC *BufferBSC_from_BSCallback(BSCallback *iface)
740 {
741     return CONTAINING_RECORD(iface, BufferBSC, bsc);
742 }
743
744 static void BufferBSC_destroy(BSCallback *bsc)
745 {
746     BufferBSC *This = BufferBSC_from_BSCallback(bsc);
747
748     heap_free(This->buf);
749     heap_free(This);
750 }
751
752 static HRESULT BufferBSC_init_bindinfo(BSCallback *bsc)
753 {
754     return S_OK;
755 }
756
757 static HRESULT BufferBSC_start_binding(BSCallback *bsc)
758 {
759     return S_OK;
760 }
761
762 static HRESULT BufferBSC_stop_binding(BSCallback *bsc, HRESULT result)
763 {
764     BufferBSC *This = BufferBSC_from_BSCallback(bsc);
765
766     This->hres = result;
767
768     if(FAILED(result)) {
769         heap_free(This->buf);
770         This->buf = NULL;
771         This->size = 0;
772     }
773
774     return S_OK;
775 }
776
777 static HRESULT BufferBSC_read_data(BSCallback *bsc, IStream *stream)
778 {
779     BufferBSC *This = BufferBSC_from_BSCallback(bsc);
780     DWORD readed;
781     HRESULT hres;
782
783     if(!This->buf) {
784         This->size = 128;
785         This->buf = heap_alloc(This->size);
786     }
787
788     do {
789         if(This->bsc.readed == This->size) {
790             This->size <<= 1;
791             This->buf = heap_realloc(This->buf, This->size);
792         }
793
794         readed = 0;
795         hres = IStream_Read(stream, This->buf+This->bsc.readed, This->size-This->bsc.readed, &readed);
796         This->bsc.readed += readed;
797     }while(hres == S_OK);
798
799     return S_OK;
800 }
801
802 static HRESULT BufferBSC_on_progress(BSCallback *bsc, ULONG status_code, LPCWSTR status_text)
803 {
804     return S_OK;
805 }
806
807 static HRESULT BufferBSC_on_response(BSCallback *bsc, DWORD response_code,
808         LPCWSTR response_headers)
809 {
810     return S_OK;
811 }
812
813 static HRESULT BufferBSC_beginning_transaction(BSCallback *bsc, WCHAR **additional_headers)
814 {
815     return S_FALSE;
816 }
817
818 static const BSCallbackVtbl BufferBSCVtbl = {
819     BufferBSC_destroy,
820     BufferBSC_init_bindinfo,
821     BufferBSC_start_binding,
822     BufferBSC_stop_binding,
823     BufferBSC_read_data,
824     BufferBSC_on_progress,
825     BufferBSC_on_response,
826     BufferBSC_beginning_transaction
827 };
828
829
830 static BufferBSC *create_bufferbsc(IMoniker *mon)
831 {
832     BufferBSC *ret = heap_alloc_zero(sizeof(*ret));
833
834     init_bscallback(&ret->bsc, &BufferBSCVtbl, mon, 0);
835     ret->hres = E_FAIL;
836
837     return ret;
838 }
839
840 HRESULT bind_mon_to_buffer(HTMLDocumentNode *doc, IMoniker *mon, void **buf, DWORD *size)
841 {
842     BufferBSC *bsc = create_bufferbsc(mon);
843     HRESULT hres;
844
845     *buf = NULL;
846
847     hres = start_binding(NULL, doc, &bsc->bsc, NULL);
848     if(SUCCEEDED(hres)) {
849         hres = bsc->hres;
850         if(SUCCEEDED(hres)) {
851             *buf = bsc->buf;
852             bsc->buf = NULL;
853             *size = bsc->bsc.readed;
854             bsc->size = 0;
855         }
856     }
857
858     IBindStatusCallback_Release(&bsc->bsc.IBindStatusCallback_iface);
859
860     return hres;
861 }
862
863 struct nsChannelBSC {
864     BSCallback bsc;
865
866     HTMLWindow *window;
867
868     nsChannel *nschannel;
869     nsIStreamListener *nslistener;
870     nsISupports *nscontext;
871
872     nsProtocolStream *nsstream;
873 };
874
875 static HRESULT read_post_data_stream(nsChannelBSC *This, nsChannel *nschannel)
876 {
877     PRUint32 data_len = 0, available = 0;
878     char *data, *post_data;
879     nsresult nsres;
880     HRESULT hres = S_OK;
881
882     if(!nschannel->post_data_stream)
883         return S_OK;
884
885     nsres =  nsIInputStream_Available(nschannel->post_data_stream, &available);
886     if(NS_FAILED(nsres))
887         return E_FAIL;
888
889     post_data = data = GlobalAlloc(0, available);
890     if(!data)
891         return E_OUTOFMEMORY;
892
893     nsres = nsIInputStream_Read(nschannel->post_data_stream, data, available, &data_len);
894     if(NS_FAILED(nsres)) {
895         GlobalFree(data);
896         return E_FAIL;
897     }
898
899     if(nschannel->post_data_contains_headers) {
900         if(data_len >= 2 && data[0] == '\r' && data[1] == '\n') {
901             post_data = data+2;
902             data_len -= 2;
903         }else {
904             WCHAR *headers;
905             DWORD size;
906             char *ptr;
907
908             post_data += data_len;
909             for(ptr = data; ptr+4 < data+data_len; ptr++) {
910                 if(!memcmp(ptr, "\r\n\r\n", 4)) {
911                     post_data = ptr+4;
912                     break;
913                 }
914             }
915
916             data_len -= post_data-data;
917
918             size = MultiByteToWideChar(CP_ACP, 0, data, post_data-data, NULL, 0);
919             headers = heap_alloc((size+1)*sizeof(WCHAR));
920             if(headers) {
921                 MultiByteToWideChar(CP_ACP, 0, data, post_data-data, headers, size);
922                 headers[size] = 0;
923                 hres = parse_headers(headers , &nschannel->request_headers);
924                 if(SUCCEEDED(hres))
925                     This->bsc.headers = headers;
926                 else
927                     heap_free(headers);
928             }else {
929                 hres = E_OUTOFMEMORY;
930             }
931         }
932     }
933
934     if(FAILED(hres)) {
935         GlobalFree(data);
936         return hres;
937     }
938
939     if(!data_len) {
940         GlobalFree(data);
941         post_data = NULL;
942     }else if(post_data != data) {
943         char *new_data;
944
945         new_data = GlobalAlloc(0, data_len);
946         if(new_data)
947             memcpy(new_data, post_data, data_len);
948         GlobalFree(data);
949         if(!new_data)
950             return E_OUTOFMEMORY;
951         post_data = new_data;
952     }
953
954     This->bsc.post_data = post_data;
955     This->bsc.post_data_len = data_len;
956     TRACE("post_data = %s\n", debugstr_a(This->bsc.post_data));
957     return S_OK;
958 }
959
960 static HRESULT on_start_nsrequest(nsChannelBSC *This)
961 {
962     nsresult nsres;
963
964     /* FIXME: it's needed for http connections from BindToObject. */
965     if(!This->nschannel->response_status)
966         This->nschannel->response_status = 200;
967
968     nsres = nsIStreamListener_OnStartRequest(This->nslistener,
969             (nsIRequest*)&This->nschannel->nsIHttpChannel_iface, This->nscontext);
970     if(NS_FAILED(nsres)) {
971         FIXME("OnStartRequest failed: %08x\n", nsres);
972         return E_FAIL;
973     }
974
975     if(This->window) {
976         update_window_doc(This->window);
977         if(This->window->doc != This->bsc.doc)
978             This->bsc.doc = This->window->doc;
979         if(This->window->readystate != READYSTATE_LOADING)
980             set_ready_state(This->window, READYSTATE_LOADING);
981     }
982
983     return S_OK;
984 }
985
986 static void on_stop_nsrequest(nsChannelBSC *This, HRESULT result)
987 {
988     nsresult nsres, request_result;
989
990     switch(result) {
991     case S_OK:
992         request_result = NS_OK;
993         break;
994     case E_ABORT:
995         request_result = NS_BINDING_ABORTED;
996         break;
997     default:
998         request_result = NS_ERROR_FAILURE;
999     }
1000
1001     if(!This->bsc.readed && SUCCEEDED(result)) {
1002         TRACE("No data read! Calling OnStartRequest\n");
1003         on_start_nsrequest(This);
1004     }
1005
1006     if(This->nslistener) {
1007         nsres = nsIStreamListener_OnStopRequest(This->nslistener,
1008                  (nsIRequest*)&This->nschannel->nsIHttpChannel_iface, This->nscontext,
1009                  request_result);
1010         if(NS_FAILED(nsres))
1011             WARN("OnStopRequet failed: %08x\n", nsres);
1012     }
1013
1014     if(This->nschannel->load_group) {
1015         nsres = nsILoadGroup_RemoveRequest(This->nschannel->load_group,
1016                 (nsIRequest*)&This->nschannel->nsIHttpChannel_iface, NULL, request_result);
1017         if(NS_FAILED(nsres))
1018             ERR("RemoveRequest failed: %08x\n", nsres);
1019     }
1020 }
1021
1022 static HRESULT read_stream_data(nsChannelBSC *This, IStream *stream)
1023 {
1024     DWORD read;
1025     nsresult nsres;
1026     HRESULT hres;
1027
1028     if(!This->nslistener) {
1029         BYTE buf[1024];
1030
1031         do {
1032             read = 0;
1033             hres = IStream_Read(stream, buf, sizeof(buf), &read);
1034         }while(hres == S_OK && read);
1035
1036         return S_OK;
1037     }
1038
1039     if(!This->nsstream)
1040         This->nsstream = create_nsprotocol_stream();
1041
1042     do {
1043         read = 0;
1044         hres = IStream_Read(stream, This->nsstream->buf+This->nsstream->buf_size,
1045                 sizeof(This->nsstream->buf)-This->nsstream->buf_size, &read);
1046         if(!read)
1047             break;
1048
1049         This->nsstream->buf_size += read;
1050
1051         if(!This->bsc.readed) {
1052             if(This->nsstream->buf_size >= 2
1053                && (BYTE)This->nsstream->buf[0] == 0xff
1054                && (BYTE)This->nsstream->buf[1] == 0xfe)
1055                 This->nschannel->charset = heap_strdupA(UTF16_STR);
1056
1057             if(!This->nschannel->content_type) {
1058                 WCHAR *mime;
1059
1060                 hres = FindMimeFromData(NULL, NULL, This->nsstream->buf, This->nsstream->buf_size, NULL, 0, &mime, 0);
1061                 if(FAILED(hres))
1062                     return hres;
1063
1064                 TRACE("Found MIME %s\n", debugstr_w(mime));
1065
1066                 This->nschannel->content_type = heap_strdupWtoA(mime);
1067                 CoTaskMemFree(mime);
1068                 if(!This->nschannel->content_type)
1069                     return E_OUTOFMEMORY;
1070             }
1071
1072             on_start_nsrequest(This);
1073         }
1074
1075         This->bsc.readed += This->nsstream->buf_size;
1076
1077         nsres = nsIStreamListener_OnDataAvailable(This->nslistener,
1078                 (nsIRequest*)&This->nschannel->nsIHttpChannel_iface, This->nscontext,
1079                 &This->nsstream->nsIInputStream_iface, This->bsc.readed-This->nsstream->buf_size,
1080                 This->nsstream->buf_size);
1081         if(NS_FAILED(nsres))
1082             ERR("OnDataAvailable failed: %08x\n", nsres);
1083
1084         if(This->nsstream->buf_size == sizeof(This->nsstream->buf)) {
1085             ERR("buffer is full\n");
1086             break;
1087         }
1088     }while(hres == S_OK);
1089
1090     return S_OK;
1091 }
1092
1093 typedef struct {
1094     nsIAsyncVerifyRedirectCallback nsIAsyncVerifyRedirectCallback_iface;
1095
1096     LONG ref;
1097
1098     nsChannel *nschannel;
1099     nsChannelBSC *bsc;
1100 } nsRedirectCallback;
1101
1102 static nsRedirectCallback *impl_from_nsIAsyncVerifyRedirectCallback(nsIAsyncVerifyRedirectCallback *iface)
1103 {
1104     return CONTAINING_RECORD(iface, nsRedirectCallback, nsIAsyncVerifyRedirectCallback_iface);
1105 }
1106
1107 static nsresult NSAPI nsAsyncVerifyRedirectCallback_QueryInterface(nsIAsyncVerifyRedirectCallback *iface,
1108         nsIIDRef riid, void **result)
1109 {
1110     nsRedirectCallback *This = impl_from_nsIAsyncVerifyRedirectCallback(iface);
1111
1112     if(IsEqualGUID(&IID_nsISupports, riid)) {
1113         TRACE("(%p)->(IID_nsISuports %p)\n", This, result);
1114         *result = &This->nsIAsyncVerifyRedirectCallback_iface;
1115     }else if(IsEqualGUID(&IID_nsIAsyncVerifyRedirectCallback, riid)) {
1116         TRACE("(%p)->(IID_nsIAsyncVerifyRedirectCallback %p)\n", This, result);
1117         *result = &This->nsIAsyncVerifyRedirectCallback_iface;
1118     }else {
1119         *result = NULL;
1120         WARN("unimplmented iface %s\n", debugstr_guid(riid));
1121         return NS_NOINTERFACE;
1122     }
1123
1124     nsISupports_AddRef((nsISupports*)*result);
1125     return NS_OK;
1126 }
1127
1128 static nsrefcnt NSAPI nsAsyncVerifyRedirectCallback_AddRef(nsIAsyncVerifyRedirectCallback *iface)
1129 {
1130     nsRedirectCallback *This = impl_from_nsIAsyncVerifyRedirectCallback(iface);
1131     LONG ref = InterlockedIncrement(&This->ref);
1132
1133     TRACE("(%p) ref=%d\n", This, ref);
1134
1135     return ref;
1136 }
1137
1138 static nsrefcnt NSAPI nsAsyncVerifyRedirectCallback_Release(nsIAsyncVerifyRedirectCallback *iface)
1139 {
1140     nsRedirectCallback *This = impl_from_nsIAsyncVerifyRedirectCallback(iface);
1141     LONG ref = InterlockedDecrement(&This->ref);
1142
1143     TRACE("(%p) ref=%d\n", This, ref);
1144
1145     if(!ref) {
1146         IBindStatusCallback_Release(&This->bsc->bsc.IBindStatusCallback_iface);
1147         nsIChannel_Release(&This->nschannel->nsIHttpChannel_iface);
1148         heap_free(This);
1149     }
1150
1151     return ref;
1152 }
1153
1154 static nsresult NSAPI nsAsyncVerifyRedirectCallback_AsyncOnChannelRedirect(nsIAsyncVerifyRedirectCallback *iface, nsresult result)
1155 {
1156     nsRedirectCallback *This = impl_from_nsIAsyncVerifyRedirectCallback(iface);
1157
1158     TRACE("(%p)->(%08x)\n", This, result);
1159
1160     if(This->bsc->nschannel)
1161         nsIHttpChannel_Release(&This->bsc->nschannel->nsIHttpChannel_iface);
1162     nsIChannel_AddRef(&This->nschannel->nsIHttpChannel_iface);
1163     This->bsc->nschannel = This->nschannel;
1164
1165     if(This->nschannel->load_group) {
1166         nsresult nsres;
1167
1168         nsres = nsILoadGroup_AddRequest(This->nschannel->load_group, (nsIRequest*)&This->nschannel->nsIHttpChannel_iface,
1169                 NULL);
1170         if(NS_FAILED(nsres))
1171             ERR("AddRequest failed: %08x\n", nsres);
1172     }
1173
1174     return NS_OK;
1175 }
1176
1177 static const nsIAsyncVerifyRedirectCallbackVtbl nsAsyncVerifyRedirectCallbackVtbl = {
1178     nsAsyncVerifyRedirectCallback_QueryInterface,
1179     nsAsyncVerifyRedirectCallback_AddRef,
1180     nsAsyncVerifyRedirectCallback_Release,
1181     nsAsyncVerifyRedirectCallback_AsyncOnChannelRedirect
1182 };
1183
1184 static HRESULT create_redirect_callback(nsChannel *nschannel, nsChannelBSC *bsc, nsRedirectCallback **ret)
1185 {
1186     nsRedirectCallback *callback;
1187
1188     callback = heap_alloc(sizeof(*callback));
1189     if(!callback)
1190         return E_OUTOFMEMORY;
1191
1192     callback->nsIAsyncVerifyRedirectCallback_iface.lpVtbl = &nsAsyncVerifyRedirectCallbackVtbl;
1193     callback->ref = 1;
1194
1195     nsIChannel_AddRef(&nschannel->nsIHttpChannel_iface);
1196     callback->nschannel = nschannel;
1197
1198     IBindStatusCallback_AddRef(&bsc->bsc.IBindStatusCallback_iface);
1199     callback->bsc = bsc;
1200
1201     *ret = callback;
1202     return S_OK;
1203 }
1204
1205 static inline nsChannelBSC *nsChannelBSC_from_BSCallback(BSCallback *iface)
1206 {
1207     return CONTAINING_RECORD(iface, nsChannelBSC, bsc);
1208 }
1209
1210 static void nsChannelBSC_destroy(BSCallback *bsc)
1211 {
1212     nsChannelBSC *This = nsChannelBSC_from_BSCallback(bsc);
1213
1214     if(This->nschannel)
1215         nsIChannel_Release(&This->nschannel->nsIHttpChannel_iface);
1216     if(This->nslistener)
1217         nsIStreamListener_Release(This->nslistener);
1218     if(This->nscontext)
1219         nsISupports_Release(This->nscontext);
1220     if(This->nsstream)
1221         nsIInputStream_Release(&This->nsstream->nsIInputStream_iface);
1222     heap_free(This);
1223 }
1224
1225 static HRESULT nsChannelBSC_start_binding(BSCallback *bsc)
1226 {
1227     nsChannelBSC *This = nsChannelBSC_from_BSCallback(bsc);
1228
1229     if(This->window)
1230         This->window->doc->skip_mutation_notif = FALSE;
1231
1232     return S_OK;
1233 }
1234
1235 static HRESULT nsChannelBSC_init_bindinfo(BSCallback *bsc)
1236 {
1237     nsChannelBSC *This = nsChannelBSC_from_BSCallback(bsc);
1238     HRESULT hres;
1239
1240     if(This->nschannel && This->nschannel->post_data_stream) {
1241         hres = read_post_data_stream(This, This->nschannel);
1242         if(FAILED(hres))
1243             return hres;
1244     }
1245
1246     return S_OK;
1247 }
1248
1249 typedef struct {
1250     task_t header;
1251     nsChannelBSC *bsc;
1252 } stop_request_task_t;
1253
1254 static void stop_request_proc(task_t *_task)
1255 {
1256     stop_request_task_t *task = (stop_request_task_t*)_task;
1257
1258     TRACE("(%p)\n", task->bsc);
1259
1260     list_remove(&task->bsc->bsc.entry);
1261     list_init(&task->bsc->bsc.entry);
1262     on_stop_nsrequest(task->bsc, S_OK);
1263     IBindStatusCallback_Release(&task->bsc->bsc.IBindStatusCallback_iface);
1264 }
1265
1266 static HRESULT async_stop_request(nsChannelBSC *This)
1267 {
1268     stop_request_task_t *task;
1269
1270     task = heap_alloc(sizeof(*task));
1271     if(!task)
1272         return E_OUTOFMEMORY;
1273
1274     IBindStatusCallback_AddRef(&This->bsc.IBindStatusCallback_iface);
1275     task->bsc = This;
1276     push_task(&task->header, stop_request_proc, This->bsc.doc->basedoc.doc_obj->basedoc.task_magic);
1277     return S_OK;
1278 }
1279
1280 static void handle_navigation_error(nsChannelBSC *This, DWORD result)
1281 {
1282     HTMLDocumentObj *doc;
1283     IOleCommandTarget *olecmd;
1284     BOOL is_error_url;
1285     SAFEARRAY *sa;
1286     SAFEARRAYBOUND bound;
1287     VARIANT var, varOut;
1288     LONG ind;
1289     BSTR url, unk;
1290     HRESULT hres;
1291
1292     if(!This->window)
1293         return;
1294
1295     doc = This->window->doc_obj;
1296     if(!doc || !doc->doc_object_service || !doc->client)
1297         return;
1298
1299     hres = IDocObjectService_IsErrorUrl(doc->doc_object_service,
1300             This->window->url, &is_error_url);
1301     if(FAILED(hres) || is_error_url)
1302         return;
1303
1304     hres = IOleClientSite_QueryInterface(doc->client,
1305             &IID_IOleCommandTarget, (void**)&olecmd);
1306     if(FAILED(hres))
1307         return;
1308
1309     bound.lLbound = 0;
1310     bound.cElements = 8;
1311     sa = SafeArrayCreate(VT_VARIANT, 1, &bound);
1312     if(!sa) {
1313         IOleCommandTarget_Release(olecmd);
1314         return;
1315     }
1316
1317     ind = 0;
1318     V_VT(&var) = VT_I4;
1319     V_I4(&var) = result;
1320     SafeArrayPutElement(sa, &ind, &var);
1321
1322     ind = 1;
1323     V_VT(&var) = VT_BSTR;
1324     url = SysAllocString(This->window->url);
1325     V_BSTR(&var) = url;
1326     SafeArrayPutElement(sa, &ind, &var);
1327
1328     ind = 3;
1329     V_VT(&var) = VT_UNKNOWN;
1330     V_UNKNOWN(&var) = (IUnknown*)&This->window->IHTMLWindow2_iface;
1331     SafeArrayPutElement(sa, &ind, &var);
1332
1333     /* FIXME: what are the following fields for? */
1334     ind = 2;
1335     V_VT(&var) = VT_UNKNOWN;
1336     V_UNKNOWN(&var) = NULL;
1337     SafeArrayPutElement(sa, &ind, &var);
1338
1339     ind = 4;
1340     V_VT(&var) = VT_BOOL;
1341     V_BOOL(&var) = FALSE;
1342     SafeArrayPutElement(sa, &ind, &var);
1343
1344     ind = 5;
1345     V_VT(&var) = VT_BOOL;
1346     V_BOOL(&var) = FALSE;
1347     SafeArrayPutElement(sa, &ind, &var);
1348
1349     ind = 6;
1350     V_VT(&var) = VT_BSTR;
1351     unk = SysAllocString(NULL);
1352     V_BSTR(&var) = unk;
1353     SafeArrayPutElement(sa, &ind, &var);
1354
1355     ind = 7;
1356     V_VT(&var) = VT_UNKNOWN;
1357     V_UNKNOWN(&var) = NULL;
1358     SafeArrayPutElement(sa, &ind, &var);
1359
1360     V_VT(&var) = VT_ARRAY;
1361     V_ARRAY(&var) = sa;
1362     V_VT(&varOut) = VT_BOOL;
1363     V_BOOL(&varOut) = VARIANT_TRUE;
1364     IOleCommandTarget_Exec(olecmd, &CGID_DocHostCmdPriv, 1, 0, &var, FAILED(hres)?NULL:&varOut);
1365
1366     SysFreeString(url);
1367     SysFreeString(unk);
1368     SafeArrayDestroy(sa);
1369     IOleCommandTarget_Release(olecmd);
1370 }
1371
1372 static HRESULT nsChannelBSC_stop_binding(BSCallback *bsc, HRESULT result)
1373 {
1374     nsChannelBSC *This = nsChannelBSC_from_BSCallback(bsc);
1375
1376     if(FAILED(result))
1377         handle_navigation_error(This, result);
1378     else if(This->window) {
1379         result = async_stop_request(This);
1380         if(SUCCEEDED(result))
1381            return S_OK;
1382     }
1383
1384     on_stop_nsrequest(This, result);
1385     return S_OK;
1386 }
1387
1388 static HRESULT nsChannelBSC_read_data(BSCallback *bsc, IStream *stream)
1389 {
1390     nsChannelBSC *This = nsChannelBSC_from_BSCallback(bsc);
1391
1392     return read_stream_data(This, stream);
1393 }
1394
1395 static HRESULT handle_redirect(nsChannelBSC *This, const WCHAR *new_url)
1396 {
1397     nsRedirectCallback *callback;
1398     nsIChannelEventSink *sink;
1399     nsChannel *new_channel;
1400     nsresult nsres;
1401     HRESULT hres;
1402
1403     TRACE("(%p)->(%s)\n", This, debugstr_w(new_url));
1404
1405     if(!This->nschannel || !This->nschannel->notif_callback)
1406         return S_OK;
1407
1408     nsres = nsIInterfaceRequestor_GetInterface(This->nschannel->notif_callback, &IID_nsIChannelEventSink, (void**)&sink);
1409     if(NS_FAILED(nsres))
1410         return S_OK;
1411
1412     hres = create_redirect_nschannel(new_url, This->nschannel, &new_channel);
1413     if(SUCCEEDED(hres)) {
1414         hres = create_redirect_callback(new_channel, This, &callback);
1415         nsIChannel_Release(&new_channel->nsIHttpChannel_iface);
1416     }
1417
1418     if(SUCCEEDED(hres)) {
1419         nsres = nsIChannelEventSink_AsyncOnChannelRedirect(sink, (nsIChannel*)&This->nschannel->nsIHttpChannel_iface,
1420                 (nsIChannel*)&callback->nschannel->nsIHttpChannel_iface, REDIRECT_TEMPORARY, /* FIXME */
1421                 &callback->nsIAsyncVerifyRedirectCallback_iface);
1422
1423         if(NS_FAILED(nsres))
1424             FIXME("AsyncOnChannelRedirect failed: %08x\n", hres);
1425         else if(This->nschannel != callback->nschannel)
1426             FIXME("nschannel not updated\n");
1427
1428         nsIAsyncVerifyRedirectCallback_Release(&callback->nsIAsyncVerifyRedirectCallback_iface);
1429     }
1430
1431     nsIChannelEventSink_Release(sink);
1432     return hres;
1433 }
1434
1435 static HRESULT nsChannelBSC_on_progress(BSCallback *bsc, ULONG status_code, LPCWSTR status_text)
1436 {
1437     nsChannelBSC *This = nsChannelBSC_from_BSCallback(bsc);
1438
1439     switch(status_code) {
1440     case BINDSTATUS_MIMETYPEAVAILABLE:
1441         if(!This->nschannel)
1442             return S_OK;
1443
1444         heap_free(This->nschannel->content_type);
1445         This->nschannel->content_type = heap_strdupWtoA(status_text);
1446         break;
1447     case BINDSTATUS_REDIRECTING:
1448         return handle_redirect(This, status_text);
1449     case BINDSTATUS_BEGINDOWNLOADDATA: {
1450         IWinInetHttpInfo *http_info;
1451         DWORD status, size = sizeof(DWORD);
1452         HRESULT hres;
1453
1454         if(!This->bsc.binding)
1455             break;
1456
1457         hres = IBinding_QueryInterface(This->bsc.binding, &IID_IWinInetHttpInfo, (void**)&http_info);
1458         if(FAILED(hres))
1459             break;
1460
1461         hres = IWinInetHttpInfo_QueryInfo(http_info,
1462                 HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, &status, &size, NULL, NULL);
1463         IWinInetHttpInfo_Release(http_info);
1464         if(FAILED(hres) || status == HTTP_STATUS_OK)
1465             break;
1466
1467         handle_navigation_error(This, status);
1468     }
1469     }
1470
1471     return S_OK;
1472 }
1473
1474 static HRESULT nsChannelBSC_on_response(BSCallback *bsc, DWORD response_code,
1475         LPCWSTR response_headers)
1476 {
1477     nsChannelBSC *This = nsChannelBSC_from_BSCallback(bsc);
1478     HRESULT hres;
1479
1480     This->nschannel->response_status = response_code;
1481
1482     if(response_headers) {
1483         const WCHAR *headers;
1484
1485         headers = strchrW(response_headers, '\r');
1486         if(headers && headers[1] == '\n') {
1487             headers += 2;
1488             hres = parse_headers(headers, &This->nschannel->response_headers);
1489             if(FAILED(hres)) {
1490                 WARN("parsing headers failed: %08x\n", hres);
1491                 return hres;
1492             }
1493         }
1494     }
1495
1496     return S_OK;
1497 }
1498
1499 static HRESULT nsChannelBSC_beginning_transaction(BSCallback *bsc, WCHAR **additional_headers)
1500 {
1501     nsChannelBSC *This = nsChannelBSC_from_BSCallback(bsc);
1502     http_header_t *iter;
1503     DWORD len = 0;
1504     WCHAR *ptr;
1505
1506     static const WCHAR content_lengthW[] =
1507         {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0};
1508
1509     if(!This->nschannel)
1510         return S_FALSE;
1511
1512     LIST_FOR_EACH_ENTRY(iter, &This->nschannel->request_headers, http_header_t, entry) {
1513         if(strcmpW(iter->header, content_lengthW))
1514             len += strlenW(iter->header) + 2 /* ": " */ + strlenW(iter->data) + 2 /* "\r\n" */;
1515     }
1516
1517     if(!len)
1518         return S_OK;
1519
1520     *additional_headers = ptr = CoTaskMemAlloc((len+1)*sizeof(WCHAR));
1521     if(!ptr)
1522         return E_OUTOFMEMORY;
1523
1524     LIST_FOR_EACH_ENTRY(iter, &This->nschannel->request_headers, http_header_t, entry) {
1525         if(!strcmpW(iter->header, content_lengthW))
1526             continue;
1527
1528         len = strlenW(iter->header);
1529         memcpy(ptr, iter->header, len*sizeof(WCHAR));
1530         ptr += len;
1531
1532         *ptr++ = ':';
1533         *ptr++ = ' ';
1534
1535         len = strlenW(iter->data);
1536         memcpy(ptr, iter->data, len*sizeof(WCHAR));
1537         ptr += len;
1538
1539         *ptr++ = '\r';
1540         *ptr++ = '\n';
1541     }
1542
1543     *ptr = 0;
1544
1545     return S_OK;
1546 }
1547
1548 static const BSCallbackVtbl nsChannelBSCVtbl = {
1549     nsChannelBSC_destroy,
1550     nsChannelBSC_init_bindinfo,
1551     nsChannelBSC_start_binding,
1552     nsChannelBSC_stop_binding,
1553     nsChannelBSC_read_data,
1554     nsChannelBSC_on_progress,
1555     nsChannelBSC_on_response,
1556     nsChannelBSC_beginning_transaction
1557 };
1558
1559 HRESULT create_channelbsc(IMoniker *mon, WCHAR *headers, BYTE *post_data, DWORD post_data_size, nsChannelBSC **retval)
1560 {
1561     nsChannelBSC *ret;
1562
1563     ret = heap_alloc_zero(sizeof(*ret));
1564     if(!ret)
1565         return E_OUTOFMEMORY;
1566
1567     init_bscallback(&ret->bsc, &nsChannelBSCVtbl, mon, BINDF_ASYNCHRONOUS | BINDF_ASYNCSTORAGE | BINDF_PULLDATA);
1568
1569     if(headers) {
1570         ret->bsc.headers = heap_strdupW(headers);
1571         if(!ret->bsc.headers) {
1572             IBindStatusCallback_Release(&ret->bsc.IBindStatusCallback_iface);
1573             return E_OUTOFMEMORY;
1574         }
1575     }
1576
1577     if(post_data) {
1578         ret->bsc.post_data = GlobalAlloc(0, post_data_size);
1579         if(!ret->bsc.post_data) {
1580             heap_free(ret->bsc.headers);
1581             IBindStatusCallback_Release(&ret->bsc.IBindStatusCallback_iface);
1582             return E_OUTOFMEMORY;
1583         }
1584
1585         memcpy(ret->bsc.post_data, post_data, post_data_size);
1586         ret->bsc.post_data_len = post_data_size;
1587     }
1588
1589     *retval = ret;
1590     return S_OK;
1591 }
1592
1593 void set_window_bscallback(HTMLWindow *window, nsChannelBSC *callback)
1594 {
1595     if(window->bscallback) {
1596         if(window->bscallback->bsc.binding)
1597             IBinding_Abort(window->bscallback->bsc.binding);
1598         window->bscallback->bsc.doc = NULL;
1599         window->bscallback->window = NULL;
1600         IBindStatusCallback_Release(&window->bscallback->bsc.IBindStatusCallback_iface);
1601     }
1602
1603     window->bscallback = callback;
1604
1605     if(callback) {
1606         callback->window = window;
1607         IBindStatusCallback_AddRef(&callback->bsc.IBindStatusCallback_iface);
1608         callback->bsc.doc = window->doc;
1609     }
1610 }
1611
1612 typedef struct {
1613     task_t header;
1614     HTMLWindow *window;
1615     nsChannelBSC *bscallback;
1616 } start_doc_binding_task_t;
1617
1618 static void start_doc_binding_proc(task_t *_task)
1619 {
1620     start_doc_binding_task_t *task = (start_doc_binding_task_t*)_task;
1621
1622     start_binding(task->window, NULL, (BSCallback*)task->bscallback, NULL);
1623     IBindStatusCallback_Release(&task->bscallback->bsc.IBindStatusCallback_iface);
1624 }
1625
1626 HRESULT async_start_doc_binding(HTMLWindow *window, nsChannelBSC *bscallback)
1627 {
1628     start_doc_binding_task_t *task;
1629
1630     task = heap_alloc(sizeof(start_doc_binding_task_t));
1631     if(!task)
1632         return E_OUTOFMEMORY;
1633
1634     task->window = window;
1635     task->bscallback = bscallback;
1636     IBindStatusCallback_AddRef(&bscallback->bsc.IBindStatusCallback_iface);
1637
1638     push_task(&task->header, start_doc_binding_proc, window->task_magic);
1639     return S_OK;
1640 }
1641
1642 void abort_document_bindings(HTMLDocumentNode *doc)
1643 {
1644     BSCallback *iter, *next;
1645
1646     LIST_FOR_EACH_ENTRY_SAFE(iter, next, &doc->bindings, BSCallback, entry) {
1647         if(iter->doc)
1648             remove_target_tasks(iter->doc->basedoc.task_magic);
1649
1650         if(iter->binding)
1651             IBinding_Abort(iter->binding);
1652         else {
1653             list_remove(&iter->entry);
1654             list_init(&iter->entry);
1655             iter->vtbl->stop_binding(iter, S_OK);
1656         }
1657
1658         iter->doc = NULL;
1659     }
1660 }
1661
1662 HRESULT channelbsc_load_stream(nsChannelBSC *bscallback, IStream *stream)
1663 {
1664     HRESULT hres = S_OK;
1665
1666     if(!bscallback->nschannel) {
1667         ERR("NULL nschannel\n");
1668         return E_FAIL;
1669     }
1670
1671     bscallback->nschannel->content_type = heap_strdupA("text/html");
1672     if(!bscallback->nschannel->content_type)
1673         return E_OUTOFMEMORY;
1674
1675     list_add_head(&bscallback->bsc.doc->bindings, &bscallback->bsc.entry);
1676     if(stream)
1677         hres = read_stream_data(bscallback, stream);
1678     if(SUCCEEDED(hres))
1679         hres = async_stop_request(bscallback);
1680     if(FAILED(hres))
1681         IBindStatusCallback_OnStopBinding(&bscallback->bsc.IBindStatusCallback_iface, hres,
1682                 ERROR_SUCCESS);
1683
1684     return hres;
1685 }
1686
1687 void channelbsc_set_channel(nsChannelBSC *This, nsChannel *channel, nsIStreamListener *listener, nsISupports *context)
1688 {
1689     nsIChannel_AddRef(&channel->nsIHttpChannel_iface);
1690     This->nschannel = channel;
1691
1692     nsIStreamListener_AddRef(listener);
1693     This->nslistener = listener;
1694
1695     if(context) {
1696         nsISupports_AddRef(context);
1697         This->nscontext = context;
1698     }
1699
1700     if(This->bsc.headers) {
1701         HRESULT hres;
1702
1703         hres = parse_headers(This->bsc.headers, &channel->request_headers);
1704         heap_free(This->bsc.headers);
1705         This->bsc.headers = NULL;
1706         if(FAILED(hres))
1707             WARN("parse_headers failed: %08x\n", hres);
1708     }
1709 }
1710
1711 HRESULT hlink_frame_navigate(HTMLDocument *doc, LPCWSTR url, nsChannel *nschannel, DWORD hlnf, BOOL *cancel)
1712 {
1713     IHlinkFrame *hlink_frame;
1714     nsChannelBSC *callback;
1715     IServiceProvider *sp;
1716     IBindCtx *bindctx;
1717     IMoniker *mon;
1718     IHlink *hlink;
1719     HRESULT hres;
1720
1721     *cancel = FALSE;
1722
1723     hres = IOleClientSite_QueryInterface(doc->doc_obj->client, &IID_IServiceProvider,
1724             (void**)&sp);
1725     if(FAILED(hres))
1726         return S_OK;
1727
1728     hres = IServiceProvider_QueryService(sp, &IID_IHlinkFrame, &IID_IHlinkFrame,
1729             (void**)&hlink_frame);
1730     IServiceProvider_Release(sp);
1731     if(FAILED(hres))
1732         return S_OK;
1733
1734     hres = create_channelbsc(NULL, NULL, NULL, 0, &callback);
1735     if(FAILED(hres)) {
1736         IHlinkFrame_Release(hlink_frame);
1737         return hres;
1738     }
1739
1740     if(nschannel)
1741         read_post_data_stream(callback, nschannel);
1742
1743     hres = CreateAsyncBindCtx(0, &callback->bsc.IBindStatusCallback_iface, NULL, &bindctx);
1744     if(SUCCEEDED(hres))
1745         hres = CoCreateInstance(&CLSID_StdHlink, NULL, CLSCTX_INPROC_SERVER,
1746                 &IID_IHlink, (LPVOID*)&hlink);
1747
1748     if(SUCCEEDED(hres))
1749         hres = CreateURLMoniker(NULL, url, &mon);
1750
1751     if(SUCCEEDED(hres)) {
1752         IHlink_SetMonikerReference(hlink, HLINKSETF_TARGET, mon, NULL);
1753
1754         if(hlnf & HLNF_OPENINNEWWINDOW) {
1755             static const WCHAR wszBlank[] = {'_','b','l','a','n','k',0};
1756             IHlink_SetTargetFrameName(hlink, wszBlank); /* FIXME */
1757         }
1758
1759         hres = IHlinkFrame_Navigate(hlink_frame, hlnf, bindctx,
1760                 &callback->bsc.IBindStatusCallback_iface, hlink);
1761         IMoniker_Release(mon);
1762         *cancel = hres == S_OK;
1763         hres = S_OK;
1764     }
1765
1766     IHlinkFrame_Release(hlink_frame);
1767     IBindCtx_Release(bindctx);
1768     IBindStatusCallback_Release(&callback->bsc.IBindStatusCallback_iface);
1769     return hres;
1770 }
1771
1772 HRESULT navigate_url(HTMLWindow *window, const WCHAR *new_url, const WCHAR *base_url)
1773 {
1774     WCHAR url[INTERNET_MAX_URL_LENGTH];
1775     nsWineURI *uri;
1776     HRESULT hres;
1777
1778     if(!new_url) {
1779         *url = 0;
1780     }else if(base_url) {
1781         DWORD len = 0;
1782
1783         hres = CoInternetCombineUrl(base_url, new_url, URL_ESCAPE_SPACES_ONLY|URL_DONT_ESCAPE_EXTRA_INFO,
1784                 url, sizeof(url)/sizeof(WCHAR), &len, 0);
1785         if(FAILED(hres))
1786             return hres;
1787     }else {
1788         strcpyW(url, new_url);
1789     }
1790
1791     if(window->doc_obj && window->doc_obj->hostui) {
1792         OLECHAR *translated_url = NULL;
1793
1794         hres = IDocHostUIHandler_TranslateUrl(window->doc_obj->hostui, 0, url,
1795                 &translated_url);
1796         if(hres == S_OK) {
1797             TRACE("%08x %s -> %s\n", hres, debugstr_w(url), debugstr_w(translated_url));
1798             strcpyW(url, translated_url);
1799             CoTaskMemFree(translated_url);
1800         }
1801     }
1802
1803     if(window->doc_obj && window == window->doc_obj->basedoc.window) {
1804         BOOL cancel;
1805
1806         hres = hlink_frame_navigate(&window->doc->basedoc, url, NULL, 0, &cancel);
1807         if(FAILED(hres))
1808             return hres;
1809
1810         if(cancel) {
1811             TRACE("Navigation handled by hlink frame\n");
1812             return S_OK;
1813         }
1814     }
1815
1816     hres = create_doc_uri(window, url, &uri);
1817     if(FAILED(hres))
1818         return hres;
1819
1820     hres = load_nsuri(window, uri, NULL, LOAD_FLAGS_NONE);
1821     nsISupports_Release((nsISupports*)uri);
1822     return hres;
1823 }