navigate.c 67.7 KB
Newer Older
1
/*
2
 * Copyright 2006-2010 Jacek Caban for CodeWeavers
3 4 5 6 7 8 9 10 11 12 13 14 15
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * 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 20 21
 */

#include "config.h"

#include <stdarg.h>
22
#include <assert.h>
23 24 25 26 27 28 29 30

#define COBJMACROS
#define NONAMELESSUNION
#define NONAMELESSSTRUCT

#include "windef.h"
#include "winbase.h"
#include "winuser.h"
31
#include "winreg.h"
32
#include "ole2.h"
33
#include "hlguids.h"
34
#include "shlguid.h"
35 36
#include "wininet.h"
#include "shlwapi.h"
37 38
#include "htiface.h"
#include "shdeprecated.h"
39 40 41 42

#include "wine/debug.h"

#include "mshtml_private.h"
43
#include "htmlscript.h"
44
#include "binding.h"
45 46 47 48

WINE_DEFAULT_DEBUG_CHANNEL(mshtml);

#define CONTENT_LENGTH "Content-Length"
49
#define UTF8_STR "utf-8"
50
#define UTF16_STR "utf-16"
51

52
static const WCHAR emptyW[] = {0};
53
static const WCHAR text_htmlW[] = {'t','e','x','t','/','h','t','m','l',0};
54

55 56 57 58 59 60
enum {
    BOM_NONE,
    BOM_UTF8,
    BOM_UTF16
};

61
struct nsProtocolStream {
62
    nsIInputStream nsIInputStream_iface;
63 64 65 66 67

    LONG ref;

    char buf[1024];
    DWORD buf_size;
68
};
69

70
struct BSCallbackVtbl {
71
    void (*destroy)(BSCallback*);
72
    HRESULT (*init_bindinfo)(BSCallback*);
73 74 75 76
    HRESULT (*start_binding)(BSCallback*);
    HRESULT (*stop_binding)(BSCallback*,HRESULT);
    HRESULT (*read_data)(BSCallback*,IStream*);
    HRESULT (*on_progress)(BSCallback*,ULONG,LPCWSTR);
77
    HRESULT (*on_response)(BSCallback*,DWORD,LPCWSTR);
78
    HRESULT (*beginning_transaction)(BSCallback*,WCHAR**);
79 80
};

81 82 83 84
static inline nsProtocolStream *impl_from_nsIInputStream(nsIInputStream *iface)
{
    return CONTAINING_RECORD(iface, nsProtocolStream, nsIInputStream_iface);
}
85 86

static nsresult NSAPI nsInputStream_QueryInterface(nsIInputStream *iface, nsIIDRef riid,
87
        void **result)
88
{
89
    nsProtocolStream *This = impl_from_nsIInputStream(iface);
90 91 92 93 94

    *result = NULL;

    if(IsEqualGUID(&IID_nsISupports, riid)) {
        TRACE("(%p)->(IID_nsISupports %p)\n", This, result);
95
        *result  = &This->nsIInputStream_iface;
96 97
    }else if(IsEqualGUID(&IID_nsIInputStream, riid)) {
        TRACE("(%p)->(IID_nsIInputStream %p)\n", This, result);
98
        *result  = &This->nsIInputStream_iface;
99 100 101
    }

    if(*result) {
102
        nsIInputStream_AddRef(&This->nsIInputStream_iface);
103 104 105 106 107 108 109 110 111
        return NS_OK;
    }

    WARN("unsupported interface %s\n", debugstr_guid(riid));
    return NS_NOINTERFACE;
}

static nsrefcnt NSAPI nsInputStream_AddRef(nsIInputStream *iface)
{
112
    nsProtocolStream *This = impl_from_nsIInputStream(iface);
113 114
    LONG ref = InterlockedIncrement(&This->ref);

115
    TRACE("(%p) ref=%d\n", This, ref);
116 117 118 119 120 121 122

    return ref;
}


static nsrefcnt NSAPI nsInputStream_Release(nsIInputStream *iface)
{
123
    nsProtocolStream *This = impl_from_nsIInputStream(iface);
124 125
    LONG ref = InterlockedDecrement(&This->ref);

126
    TRACE("(%p) ref=%d\n", This, ref);
127 128

    if(!ref)
129
        heap_free(This);
130 131 132 133 134 135

    return ref;
}

static nsresult NSAPI nsInputStream_Close(nsIInputStream *iface)
{
136
    nsProtocolStream *This = impl_from_nsIInputStream(iface);
137 138 139 140
    FIXME("(%p)\n", This);
    return NS_ERROR_NOT_IMPLEMENTED;
}

141
static nsresult NSAPI nsInputStream_Available(nsIInputStream *iface, UINT64 *_retval)
142
{
143
    nsProtocolStream *This = impl_from_nsIInputStream(iface);
144 145 146 147
    FIXME("(%p)->(%p)\n", This, _retval);
    return NS_ERROR_NOT_IMPLEMENTED;
}

148 149
static nsresult NSAPI nsInputStream_Read(nsIInputStream *iface, char *aBuf, UINT32 aCount,
                                         UINT32 *_retval)
150
{
151
    nsProtocolStream *This = impl_from_nsIInputStream(iface);
152
    DWORD read = aCount;
153

154
    TRACE("(%p)->(%p %d %p)\n", This, aBuf, aCount, _retval);
155

156 157
    if(read > This->buf_size)
        read = This->buf_size;
158

159 160 161 162 163 164
    if(read) {
        memcpy(aBuf, This->buf, read);
        if(read < This->buf_size)
            memmove(This->buf, This->buf+read, This->buf_size-read);
        This->buf_size -= read;
    }
165

166
    *_retval = read;
167
    return NS_OK;
168 169 170
}

static nsresult NSAPI nsInputStream_ReadSegments(nsIInputStream *iface,
171 172
        nsresult (WINAPI *aWriter)(nsIInputStream*,void*,const char*,UINT32,UINT32,UINT32*),
        void *aClousure, UINT32 aCount, UINT32 *_retval)
173
{
174
    nsProtocolStream *This = impl_from_nsIInputStream(iface);
175
    UINT32 written = 0;
176 177
    nsresult nsres;

178
    TRACE("(%p)->(%p %p %d %p)\n", This, aWriter, aClousure, aCount, _retval);
179 180 181 182

    if(!This->buf_size)
        return S_OK;

183 184
    if(aCount > This->buf_size)
        aCount = This->buf_size;
185

186
    nsres = aWriter(&This->nsIInputStream_iface, aClousure, This->buf, 0, aCount, &written);
187
    if(NS_FAILED(nsres))
188 189 190
        TRACE("aWritter failed: %08x\n", nsres);
    else if(written != This->buf_size)
        FIXME("written %d != buf_size %d\n", written, This->buf_size);
191 192 193

    This->buf_size -= written; 

194
    *_retval = written;
195 196 197
    return nsres;
}

198
static nsresult NSAPI nsInputStream_IsNonBlocking(nsIInputStream *iface, cpp_bool *_retval)
199
{
200
    nsProtocolStream *This = impl_from_nsIInputStream(iface);
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
    FIXME("(%p)->(%p)\n", This, _retval);
    return NS_ERROR_NOT_IMPLEMENTED;
}

static const nsIInputStreamVtbl nsInputStreamVtbl = {
    nsInputStream_QueryInterface,
    nsInputStream_AddRef,
    nsInputStream_Release,
    nsInputStream_Close,
    nsInputStream_Available,
    nsInputStream_Read,
    nsInputStream_ReadSegments,
    nsInputStream_IsNonBlocking
};

216
static nsProtocolStream *create_nsprotocol_stream(void)
217
{
218 219 220 221 222
    nsProtocolStream *ret;

    ret = heap_alloc(sizeof(nsProtocolStream));
    if(!ret)
        return NULL;
223

224
    ret->nsIInputStream_iface.lpVtbl = &nsInputStreamVtbl;
225 226 227 228 229 230
    ret->ref = 1;
    ret->buf_size = 0;

    return ret;
}

231 232 233 234
static inline BSCallback *impl_from_IBindStatusCallback(IBindStatusCallback *iface)
{
    return CONTAINING_RECORD(iface, BSCallback, IBindStatusCallback_iface);
}
235 236 237 238

static HRESULT WINAPI BindStatusCallback_QueryInterface(IBindStatusCallback *iface,
        REFIID riid, void **ppv)
{
239
    BSCallback *This = impl_from_IBindStatusCallback(iface);
240 241 242 243

    *ppv = NULL;
    if(IsEqualGUID(&IID_IUnknown, riid)) {
        TRACE("(%p)->(IID_IUnknown, %p)\n", This, ppv);
244
        *ppv = &This->IBindStatusCallback_iface;
245 246
    }else if(IsEqualGUID(&IID_IBindStatusCallback, riid)) {
        TRACE("(%p)->(IID_IBindStatusCallback, %p)\n", This, ppv);
247
        *ppv = &This->IBindStatusCallback_iface;
248 249
    }else if(IsEqualGUID(&IID_IServiceProvider, riid)) {
        TRACE("(%p)->(IID_IServiceProvider %p)\n", This, ppv);
250
        *ppv = &This->IServiceProvider_iface;
251 252
    }else if(IsEqualGUID(&IID_IHttpNegotiate, riid)) {
        TRACE("(%p)->(IID_IHttpNegotiate %p)\n", This, ppv);
253
        *ppv = &This->IHttpNegotiate2_iface;
254 255
    }else if(IsEqualGUID(&IID_IHttpNegotiate2, riid)) {
        TRACE("(%p)->(IID_IHttpNegotiate2 %p)\n", This, ppv);
256
        *ppv = &This->IHttpNegotiate2_iface;
257 258
    }else if(IsEqualGUID(&IID_IInternetBindInfo, riid)) {
        TRACE("(%p)->(IID_IInternetBindInfo %p)\n", This, ppv);
259
        *ppv = &This->IInternetBindInfo_iface;
260 261 262
    }

    if(*ppv) {
263
        IBindStatusCallback_AddRef(&This->IBindStatusCallback_iface);
264 265 266 267 268 269 270 271 272
        return S_OK;
    }

    TRACE("Unsupported riid = %s\n", debugstr_guid(riid));
    return E_NOINTERFACE;
}

static ULONG WINAPI BindStatusCallback_AddRef(IBindStatusCallback *iface)
{
273
    BSCallback *This = impl_from_IBindStatusCallback(iface);
274 275
    LONG ref = InterlockedIncrement(&This->ref);

276
    TRACE("(%p) ref = %d\n", This, ref);
277 278 279 280 281 282

    return ref;
}

static ULONG WINAPI BindStatusCallback_Release(IBindStatusCallback *iface)
{
283
    BSCallback *This = impl_from_IBindStatusCallback(iface);
284 285
    LONG ref = InterlockedDecrement(&This->ref);

286
    TRACE("(%p) ref = %d\n", This, ref);
287 288 289 290

    if(!ref) {
        if(This->post_data)
            GlobalFree(This->post_data);
291 292
        if(This->mon)
            IMoniker_Release(This->mon);
293 294
        if(This->binding)
            IBinding_Release(This->binding);
295
        list_remove(&This->entry);
296
        list_init(&This->entry);
297
        heap_free(This->headers);
298 299

        This->vtbl->destroy(This);
300 301 302 303 304 305 306 307
    }

    return ref;
}

static HRESULT WINAPI BindStatusCallback_OnStartBinding(IBindStatusCallback *iface,
        DWORD dwReserved, IBinding *pbind)
{
308
    BSCallback *This = impl_from_IBindStatusCallback(iface);
309

310
    TRACE("(%p)->(%d %p)\n", This, dwReserved, pbind);
311 312 313 314

    IBinding_AddRef(pbind);
    This->binding = pbind;

315 316
    if(This->window)
        list_add_head(&This->window->bindings, &This->entry);
317

318
    return This->vtbl->start_binding(This);
319 320 321 322
}

static HRESULT WINAPI BindStatusCallback_GetPriority(IBindStatusCallback *iface, LONG *pnPriority)
{
323
    BSCallback *This = impl_from_IBindStatusCallback(iface);
324 325 326 327 328 329
    FIXME("(%p)->(%p)\n", This, pnPriority);
    return E_NOTIMPL;
}

static HRESULT WINAPI BindStatusCallback_OnLowResource(IBindStatusCallback *iface, DWORD reserved)
{
330
    BSCallback *This = impl_from_IBindStatusCallback(iface);
331
    FIXME("(%p)->(%d)\n", This, reserved);
332 333 334 335 336 337
    return E_NOTIMPL;
}

static HRESULT WINAPI BindStatusCallback_OnProgress(IBindStatusCallback *iface, ULONG ulProgress,
        ULONG ulProgressMax, ULONG ulStatusCode, LPCWSTR szStatusText)
{
338
    BSCallback *This = impl_from_IBindStatusCallback(iface);
339

340
    TRACE("%p)->(%u %u %u %s)\n", This, ulProgress, ulProgressMax, ulStatusCode,
341
            debugstr_w(szStatusText));
342

343
    return This->vtbl->on_progress(This, ulStatusCode, szStatusText);
344 345 346 347 348
}

static HRESULT WINAPI BindStatusCallback_OnStopBinding(IBindStatusCallback *iface,
        HRESULT hresult, LPCWSTR szError)
{
349
    BSCallback *This = impl_from_IBindStatusCallback(iface);
350
    HRESULT hres;
351

352
    TRACE("(%p)->(%08x %s)\n", This, hresult, debugstr_w(szError));
353

354 355
    /* NOTE: IE7 calls GetBindResult here */

356 357
    hres = This->vtbl->stop_binding(This, hresult);

358 359 360 361
    if(This->binding) {
        IBinding_Release(This->binding);
        This->binding = NULL;
    }
362

363
    list_remove(&This->entry);
364
    list_init(&This->entry);
365
    This->window = NULL;
366

367
    return hres;
368 369 370 371 372
}

static HRESULT WINAPI BindStatusCallback_GetBindInfo(IBindStatusCallback *iface,
        DWORD *grfBINDF, BINDINFO *pbindinfo)
{
373
    BSCallback *This = impl_from_IBindStatusCallback(iface);
374 375 376 377
    DWORD size;

    TRACE("(%p)->(%p %p)\n", This, grfBINDF, pbindinfo);

378 379 380 381 382 383 384 385 386 387
    if(!This->bindinfo_ready) {
        HRESULT hres;

        hres = This->vtbl->init_bindinfo(This);
        if(FAILED(hres))
            return hres;

        This->bindinfo_ready = TRUE;
    }

388
    *grfBINDF = This->bindf;
389 390 391 392 393

    size = pbindinfo->cbSize;
    memset(pbindinfo, 0, size);
    pbindinfo->cbSize = size;

394
    pbindinfo->cbstgmedData = This->post_data_len;
395
    pbindinfo->dwCodePage = CP_UTF8;
396
    pbindinfo->dwOptions = 0x80000;
397 398 399 400 401 402

    if(This->post_data) {
        pbindinfo->dwBindVerb = BINDVERB_POST;

        pbindinfo->stgmedData.tymed = TYMED_HGLOBAL;
        pbindinfo->stgmedData.u.hGlobal = This->post_data;
403 404
        pbindinfo->stgmedData.pUnkForRelease = (IUnknown*)&This->IBindStatusCallback_iface;
        IBindStatusCallback_AddRef(&This->IBindStatusCallback_iface);
405 406 407 408 409 410 411 412
    }

    return S_OK;
}

static HRESULT WINAPI BindStatusCallback_OnDataAvailable(IBindStatusCallback *iface,
        DWORD grfBSCF, DWORD dwSize, FORMATETC *pformatetc, STGMEDIUM *pstgmed)
{
413
    BSCallback *This = impl_from_IBindStatusCallback(iface);
414

415
    TRACE("(%p)->(%08x %d %p %p)\n", This, grfBSCF, dwSize, pformatetc, pstgmed);
416

417
    return This->vtbl->read_data(This, pstgmed->u.pstm);
418 419 420 421 422
}

static HRESULT WINAPI BindStatusCallback_OnObjectAvailable(IBindStatusCallback *iface,
        REFIID riid, IUnknown *punk)
{
423
    BSCallback *This = impl_from_IBindStatusCallback(iface);
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
    FIXME("(%p)->(%s %p)\n", This, debugstr_guid(riid), punk);
    return E_NOTIMPL;
}

static const IBindStatusCallbackVtbl BindStatusCallbackVtbl = {
    BindStatusCallback_QueryInterface,
    BindStatusCallback_AddRef,
    BindStatusCallback_Release,
    BindStatusCallback_OnStartBinding,
    BindStatusCallback_GetPriority,
    BindStatusCallback_OnLowResource,
    BindStatusCallback_OnProgress,
    BindStatusCallback_OnStopBinding,
    BindStatusCallback_GetBindInfo,
    BindStatusCallback_OnDataAvailable,
    BindStatusCallback_OnObjectAvailable
};

442 443 444 445
static inline BSCallback *impl_from_IHttpNegotiate2(IHttpNegotiate2 *iface)
{
    return CONTAINING_RECORD(iface, BSCallback, IHttpNegotiate2_iface);
}
446 447 448 449

static HRESULT WINAPI HttpNegotiate_QueryInterface(IHttpNegotiate2 *iface,
                                                   REFIID riid, void **ppv)
{
450 451
    BSCallback *This = impl_from_IHttpNegotiate2(iface);
    return IBindStatusCallback_QueryInterface(&This->IBindStatusCallback_iface, riid, ppv);
452 453 454 455
}

static ULONG WINAPI HttpNegotiate_AddRef(IHttpNegotiate2 *iface)
{
456 457
    BSCallback *This = impl_from_IHttpNegotiate2(iface);
    return IBindStatusCallback_AddRef(&This->IBindStatusCallback_iface);
458 459 460 461
}

static ULONG WINAPI HttpNegotiate_Release(IHttpNegotiate2 *iface)
{
462 463
    BSCallback *This = impl_from_IHttpNegotiate2(iface);
    return IBindStatusCallback_Release(&This->IBindStatusCallback_iface);
464 465 466 467 468
}

static HRESULT WINAPI HttpNegotiate_BeginningTransaction(IHttpNegotiate2 *iface,
        LPCWSTR szURL, LPCWSTR szHeaders, DWORD dwReserved, LPWSTR *pszAdditionalHeaders)
{
469
    BSCallback *This = impl_from_IHttpNegotiate2(iface);
470
    HRESULT hres;
471

472
    TRACE("(%p)->(%s %s %d %p)\n", This, debugstr_w(szURL), debugstr_w(szHeaders),
473 474
          dwReserved, pszAdditionalHeaders);

475 476 477 478 479 480 481 482
    *pszAdditionalHeaders = NULL;

    hres = This->vtbl->beginning_transaction(This, pszAdditionalHeaders);
    if(hres != S_FALSE)
        return hres;

    if(This->headers) {
        DWORD size;
483

484 485 486 487 488 489
        size = (strlenW(This->headers)+1)*sizeof(WCHAR);
        *pszAdditionalHeaders = CoTaskMemAlloc(size);
        if(!*pszAdditionalHeaders)
            return E_OUTOFMEMORY;
        memcpy(*pszAdditionalHeaders, This->headers, size);
    }
490 491 492 493 494 495 496

    return S_OK;
}

static HRESULT WINAPI HttpNegotiate_OnResponse(IHttpNegotiate2 *iface, DWORD dwResponseCode,
        LPCWSTR szResponseHeaders, LPCWSTR szRequestHeaders, LPWSTR *pszAdditionalRequestHeaders)
{
497
    BSCallback *This = impl_from_IHttpNegotiate2(iface);
498 499

    TRACE("(%p)->(%d %s %s %p)\n", This, dwResponseCode, debugstr_w(szResponseHeaders),
500
          debugstr_w(szRequestHeaders), pszAdditionalRequestHeaders);
501

502
    return This->vtbl->on_response(This, dwResponseCode, szResponseHeaders);
503 504 505 506 507
}

static HRESULT WINAPI HttpNegotiate_GetRootSecurityId(IHttpNegotiate2 *iface,
        BYTE *pbSecurityId, DWORD *pcbSecurityId, DWORD_PTR dwReserved)
{
508
    BSCallback *This = impl_from_IHttpNegotiate2(iface);
509 510 511 512 513 514 515 516 517 518 519 520 521
    FIXME("(%p)->(%p %p %ld)\n", This, pbSecurityId, pcbSecurityId, dwReserved);
    return E_NOTIMPL;
}

static const IHttpNegotiate2Vtbl HttpNegotiate2Vtbl = {
    HttpNegotiate_QueryInterface,
    HttpNegotiate_AddRef,
    HttpNegotiate_Release,
    HttpNegotiate_BeginningTransaction,
    HttpNegotiate_OnResponse,
    HttpNegotiate_GetRootSecurityId
};

522 523 524 525
static inline BSCallback *impl_from_IInternetBindInfo(IInternetBindInfo *iface)
{
    return CONTAINING_RECORD(iface, BSCallback, IInternetBindInfo_iface);
}
526 527 528 529

static HRESULT WINAPI InternetBindInfo_QueryInterface(IInternetBindInfo *iface,
                                                      REFIID riid, void **ppv)
{
530 531
    BSCallback *This = impl_from_IInternetBindInfo(iface);
    return IBindStatusCallback_QueryInterface(&This->IBindStatusCallback_iface, riid, ppv);
532 533 534 535
}

static ULONG WINAPI InternetBindInfo_AddRef(IInternetBindInfo *iface)
{
536 537
    BSCallback *This = impl_from_IInternetBindInfo(iface);
    return IBindStatusCallback_AddRef(&This->IBindStatusCallback_iface);
538 539 540 541
}

static ULONG WINAPI InternetBindInfo_Release(IInternetBindInfo *iface)
{
542 543
    BSCallback *This = impl_from_IInternetBindInfo(iface);
    return IBindStatusCallback_Release(&This->IBindStatusCallback_iface);
544 545 546 547 548
}

static HRESULT WINAPI InternetBindInfo_GetBindInfo(IInternetBindInfo *iface,
                                                   DWORD *grfBINDF, BINDINFO *pbindinfo)
{
549
    BSCallback *This = impl_from_IInternetBindInfo(iface);
550 551 552 553 554 555 556
    FIXME("(%p)->(%p %p)\n", This, grfBINDF, pbindinfo);
    return E_NOTIMPL;
}

static HRESULT WINAPI InternetBindInfo_GetBindString(IInternetBindInfo *iface,
        ULONG ulStringType, LPOLESTR *ppwzStr, ULONG cEl, ULONG *pcElFetched)
{
557
    BSCallback *This = impl_from_IInternetBindInfo(iface);
558
    FIXME("(%p)->(%u %p %u %p)\n", This, ulStringType, ppwzStr, cEl, pcElFetched);
559 560 561 562 563 564 565 566 567 568 569
    return E_NOTIMPL;
}

static const IInternetBindInfoVtbl InternetBindInfoVtbl = {
    InternetBindInfo_QueryInterface,
    InternetBindInfo_AddRef,
    InternetBindInfo_Release,
    InternetBindInfo_GetBindInfo,
    InternetBindInfo_GetBindString
};

570 571 572 573
static inline BSCallback *impl_from_IServiceProvider(IServiceProvider *iface)
{
    return CONTAINING_RECORD(iface, BSCallback, IServiceProvider_iface);
}
574 575 576 577

static HRESULT WINAPI BSCServiceProvider_QueryInterface(IServiceProvider *iface,
                                                        REFIID riid, void **ppv)
{
578
    BSCallback *This = impl_from_IServiceProvider(iface);
579
    return IBindStatusCallback_QueryInterface(&This->IBindStatusCallback_iface, riid, ppv);
580 581 582 583
}

static ULONG WINAPI BSCServiceProvider_AddRef(IServiceProvider *iface)
{
584
    BSCallback *This = impl_from_IServiceProvider(iface);
585
    return IBindStatusCallback_AddRef(&This->IBindStatusCallback_iface);
586 587 588 589
}

static ULONG WINAPI BSCServiceProvider_Release(IServiceProvider *iface)
{
590
    BSCallback *This = impl_from_IServiceProvider(iface);
591
    return IBindStatusCallback_Release(&This->IBindStatusCallback_iface);
592 593 594 595 596
}

static HRESULT WINAPI BSCServiceProvider_QueryService(IServiceProvider *iface,
        REFGUID guidService, REFIID riid, void **ppv)
{
597
    BSCallback *This = impl_from_IServiceProvider(iface);
598

599
    TRACE("(%p)->(%s %s %p)\n", This, debugstr_guid(guidService), debugstr_guid(riid), ppv);
600

601 602
    if(This->window && IsEqualGUID(guidService, &IID_IWindowForBindingUI))
        return IServiceProvider_QueryService(&This->window->base.IServiceProvider_iface, guidService, riid, ppv);
603
    return E_NOINTERFACE;
604 605 606 607 608 609 610 611 612
}

static const IServiceProviderVtbl ServiceProviderVtbl = {
    BSCServiceProvider_QueryInterface,
    BSCServiceProvider_AddRef,
    BSCServiceProvider_Release,
    BSCServiceProvider_QueryService
};

613
static void init_bscallback(BSCallback *This, const BSCallbackVtbl *vtbl, IMoniker *mon, DWORD bindf)
614
{
615
    This->IBindStatusCallback_iface.lpVtbl = &BindStatusCallbackVtbl;
616
    This->IServiceProvider_iface.lpVtbl = &ServiceProviderVtbl;
617 618
    This->IHttpNegotiate2_iface.lpVtbl = &HttpNegotiate2Vtbl;
    This->IInternetBindInfo_iface.lpVtbl = &InternetBindInfoVtbl;
619 620 621
    This->vtbl = vtbl;
    This->ref = 1;
    This->bindf = bindf;
622
    This->bom = BOM_NONE;
623

624
    list_init(&This->entry);
625

626 627
    if(mon)
        IMoniker_AddRef(mon);
628
    This->mon = mon;
629 630
}

631 632
static HRESULT read_stream(BSCallback *This, IStream *stream, void *buf, DWORD size, DWORD *ret_size)
{
633 634
    DWORD read_size = 0, skip=0;
    BYTE *data = buf;
635 636 637
    HRESULT hres;

    hres = IStream_Read(stream, buf, size, &read_size);
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655

    if(!This->readed && This->bom == BOM_NONE) {
        if(read_size >= 2 && data[0] == 0xff && data[1] == 0xfe) {
            This->bom = BOM_UTF16;
            skip = 2;
        }else if(read_size >= 3 && data[0] == 0xef && data[1] == 0xbb && data[2] == 0xbf) {
            This->bom = BOM_UTF8;
            skip = 3;
        }
        if(skip) {
            read_size -= skip;
            if(read_size)
                memmove(data, data+skip, read_size);
        }
    }

    This->readed += read_size;
    *ret_size = read_size;
656 657 658
    return hres;
}

659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
static void parse_content_type(nsChannelBSC *This, const WCHAR *value)
{
    const WCHAR *ptr;
    size_t len;

    static const WCHAR charsetW[] = {'c','h','a','r','s','e','t','='};

    ptr = strchrW(value, ';');
    if(!ptr)
        return;

    ptr++;
    while(*ptr && isspaceW(*ptr))
        ptr++;

    len = strlenW(value);
    if(ptr + sizeof(charsetW)/sizeof(WCHAR) < value+len && !memicmpW(ptr, charsetW, sizeof(charsetW)/sizeof(WCHAR))) {
        size_t charset_len, lena;
        nsACString charset_str;
        const WCHAR *charset;
        char *charseta;

        ptr += sizeof(charsetW)/sizeof(WCHAR);

        if(*ptr == '\'') {
            FIXME("Quoted value\n");
            return;
        }else {
            charset = ptr;
            while(*ptr && *ptr != ',')
                ptr++;
            charset_len = ptr-charset;
        }

        lena = WideCharToMultiByte(CP_ACP, 0, charset, charset_len, NULL, 0, NULL, NULL);
        charseta = heap_alloc(lena+1);
        if(!charseta)
            return;

        WideCharToMultiByte(CP_ACP, 0, charset, charset_len, charseta, lena, NULL, NULL);
        charseta[lena] = 0;

        nsACString_InitDepend(&charset_str, charseta);
        nsIHttpChannel_SetContentCharset(&This->nschannel->nsIHttpChannel_iface, &charset_str);
        nsACString_Finish(&charset_str);
        heap_free(charseta);
    }else {
        FIXME("unhandled: %s\n", debugstr_wn(ptr, len - (ptr-value)));
    }
}

710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
static HRESULT parse_headers(const WCHAR *headers, struct list *headers_list)
{
    const WCHAR *header, *header_end, *colon, *value;
    HRESULT hres;

    header = headers;
    while(*header) {
        if(header[0] == '\r' && header[1] == '\n' && !header[2])
            break;
        for(colon = header; *colon && *colon != ':' && *colon != '\r'; colon++);
        if(*colon != ':')
            return E_FAIL;

        value = colon+1;
        while(*value == ' ')
            value++;
        if(!*value)
            return E_FAIL;

        for(header_end = value+1; *header_end && *header_end != '\r'; header_end++);

        hres = set_http_header(headers_list, header, colon-header, value, header_end-value);
        if(FAILED(hres))
            return hres;

        header = header_end;
        if(header[0] == '\r' && header[1] == '\n')
            header += 2;
    }

    return S_OK;
}

743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
static HRESULT process_response_headers(nsChannelBSC *This, const WCHAR *headers)
{
    http_header_t *iter;
    HRESULT hres;

    static const WCHAR content_typeW[] = {'c','o','n','t','e','n','t','-','t','y','p','e',0};

    hres = parse_headers(headers, &This->nschannel->response_headers);
    if(FAILED(hres))
        return hres;

    LIST_FOR_EACH_ENTRY(iter, &This->nschannel->response_headers, http_header_t, entry) {
        if(!strcmpiW(iter->header, content_typeW))
            parse_content_type(This, iter->data);
    }

    return S_OK;
}

762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
static void query_http_info(nsChannelBSC *This, IWinInetHttpInfo *wininet_info)
{
    const WCHAR *ptr;
    DWORD len = 0;
    WCHAR *buf;

    IWinInetHttpInfo_QueryInfo(wininet_info, HTTP_QUERY_RAW_HEADERS_CRLF, NULL, &len, NULL, NULL);
    if(!len)
        return;

    buf = heap_alloc(len);
    if(!buf)
        return;

    IWinInetHttpInfo_QueryInfo(wininet_info, HTTP_QUERY_RAW_HEADERS_CRLF, buf, &len, NULL, NULL);
777 778
    if(!len) {
        heap_free(buf);
779
        return;
780
    }
781 782 783 784 785 786 787 788 789 790

    ptr = strchrW(buf, '\r');
    if(ptr && ptr[1] == '\n') {
        ptr += 2;
        process_response_headers(This, ptr);
    }

    heap_free(buf);
}

791
HRESULT start_binding(HTMLInnerWindow *inner_window, BSCallback *bscallback, IBindCtx *bctx)
792 793 794 795
{
    IStream *str = NULL;
    HRESULT hres;

796
    TRACE("(%p %p %p)\n", inner_window, bscallback, bctx);
797

798
    bscallback->window = inner_window;
799 800 801

    /* NOTE: IE7 calls IsSystemMoniker here*/

802
    if(bctx) {
803 804 805
        hres = RegisterBindStatusCallback(bctx, &bscallback->IBindStatusCallback_iface, NULL, 0);
        if(SUCCEEDED(hres))
            IBindCtx_AddRef(bctx);
806
    }else {
807
        hres = CreateAsyncBindCtx(0, &bscallback->IBindStatusCallback_iface, NULL, &bctx);
808 809 810 811 812
    }

    if(FAILED(hres)) {
        bscallback->vtbl->stop_binding(bscallback, hres);
        return hres;
813 814
    }

815
    hres = IMoniker_BindToStorage(bscallback->mon, bctx, NULL, &IID_IStream, (void**)&str);
816 817
    IBindCtx_Release(bctx);
    if(FAILED(hres)) {
818
        WARN("BindToStorage failed: %08x\n", hres);
819
        bscallback->vtbl->stop_binding(bscallback, hres);
820 821 822 823 824 825
        return hres;
    }

    if(str)
        IStream_Release(str);

826 827
    IMoniker_Release(bscallback->mon);
    bscallback->mon = NULL;
828

829 830
    return S_OK;
}
831

832 833 834 835
typedef struct {
    BSCallback bsc;

    DWORD size;
836
    char *buf;
837 838 839
    HRESULT hres;
} BufferBSC;

840 841 842 843
static inline BufferBSC *BufferBSC_from_BSCallback(BSCallback *iface)
{
    return CONTAINING_RECORD(iface, BufferBSC, bsc);
}
844 845 846

static void BufferBSC_destroy(BSCallback *bsc)
{
847
    BufferBSC *This = BufferBSC_from_BSCallback(bsc);
848 849 850 851 852

    heap_free(This->buf);
    heap_free(This);
}

853 854 855 856 857
static HRESULT BufferBSC_init_bindinfo(BSCallback *bsc)
{
    return S_OK;
}

858 859 860 861 862 863 864
static HRESULT BufferBSC_start_binding(BSCallback *bsc)
{
    return S_OK;
}

static HRESULT BufferBSC_stop_binding(BSCallback *bsc, HRESULT result)
{
865
    BufferBSC *This = BufferBSC_from_BSCallback(bsc);
866 867 868 869 870 871 872 873 874 875 876 877 878 879

    This->hres = result;

    if(FAILED(result)) {
        heap_free(This->buf);
        This->buf = NULL;
        This->size = 0;
    }

    return S_OK;
}

static HRESULT BufferBSC_read_data(BSCallback *bsc, IStream *stream)
{
880
    BufferBSC *This = BufferBSC_from_BSCallback(bsc);
881 882 883 884
    DWORD readed;
    HRESULT hres;

    if(!This->buf) {
885 886 887
        This->buf = heap_alloc(128);
        if(!This->buf)
            return E_OUTOFMEMORY;
888 889 890 891
        This->size = 128;
    }

    do {
892
        if(This->bsc.readed >= This->size) {
893 894 895 896
            This->size <<= 1;
            This->buf = heap_realloc(This->buf, This->size);
        }

897
        hres = read_stream(&This->bsc, stream, This->buf+This->bsc.readed, This->size-This->bsc.readed, &readed);
898 899 900 901 902 903 904 905 906 907
    }while(hres == S_OK);

    return S_OK;
}

static HRESULT BufferBSC_on_progress(BSCallback *bsc, ULONG status_code, LPCWSTR status_text)
{
    return S_OK;
}

908 909
static HRESULT BufferBSC_on_response(BSCallback *bsc, DWORD response_code,
        LPCWSTR response_headers)
910 911 912 913
{
    return S_OK;
}

914 915 916 917 918
static HRESULT BufferBSC_beginning_transaction(BSCallback *bsc, WCHAR **additional_headers)
{
    return S_FALSE;
}

919 920
static const BSCallbackVtbl BufferBSCVtbl = {
    BufferBSC_destroy,
921
    BufferBSC_init_bindinfo,
922 923 924 925
    BufferBSC_start_binding,
    BufferBSC_stop_binding,
    BufferBSC_read_data,
    BufferBSC_on_progress,
926 927
    BufferBSC_on_response,
    BufferBSC_beginning_transaction
928 929 930
};


931
HRESULT bind_mon_to_wstr(HTMLInnerWindow *window, IMoniker *mon, WCHAR **ret)
932
{
933
    BufferBSC *bsc;
934
    int cp = CP_ACP;
935
    WCHAR *text;
936 937
    HRESULT hres;

938 939 940 941 942 943 944
    bsc = heap_alloc_zero(sizeof(*bsc));
    if(!bsc)
        return E_OUTOFMEMORY;

    init_bscallback(&bsc->bsc, &BufferBSCVtbl, mon, 0);
    bsc->hres = E_FAIL;

945
    hres = start_binding(window, &bsc->bsc, NULL);
946
    if(SUCCEEDED(hres))
947
        hres = bsc->hres;
948 949 950
    if(FAILED(hres)) {
        IBindStatusCallback_Release(&bsc->bsc.IBindStatusCallback_iface);
        return hres;
951 952
    }

953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988
    if(!bsc->bsc.readed) {
        *ret = NULL;
        return S_OK;
    }

    switch(bsc->bsc.bom) {
    case BOM_UTF16:
        if(bsc->bsc.readed % sizeof(WCHAR)) {
            FIXME("The buffer is not a valid utf16 string\n");
            hres = E_FAIL;
            break;
        }

        text = heap_alloc(bsc->bsc.readed+sizeof(WCHAR));
        if(!text) {
            hres = E_OUTOFMEMORY;
            break;
        }

        memcpy(text, bsc->buf, bsc->bsc.readed);
        text[bsc->bsc.readed/sizeof(WCHAR)] = 0;
        break;

    case BOM_UTF8:
        cp = CP_UTF8;
        /* fallthrough */
    default: {
        DWORD len;

        len = MultiByteToWideChar(cp, 0, bsc->buf, bsc->bsc.readed, NULL, 0);
        text = heap_alloc((len+1)*sizeof(WCHAR));
        if(!text) {
            hres = E_OUTOFMEMORY;
            break;
        }

989 990 991
        MultiByteToWideChar(CP_ACP, 0, bsc->buf, bsc->bsc.readed, text, len);
        text[len] = 0;
    }
992 993
    }

994
    IBindStatusCallback_Release(&bsc->bsc.IBindStatusCallback_iface);
995 996
    if(FAILED(hres))
        return hres;
997

998 999
    *ret = text;
    return S_OK;
1000 1001
}

1002 1003
static HRESULT read_post_data_stream(nsChannelBSC *This, nsChannel *nschannel)
{
1004
    UINT64 available = 0;
1005
    UINT32 data_len = 0;
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
    char *data, *post_data;
    nsresult nsres;
    HRESULT hres = S_OK;

    if(!nschannel->post_data_stream)
        return S_OK;

    nsres =  nsIInputStream_Available(nschannel->post_data_stream, &available);
    if(NS_FAILED(nsres))
        return E_FAIL;

1017
    post_data = data = GlobalAlloc(0, available);
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
    if(!data)
        return E_OUTOFMEMORY;

    nsres = nsIInputStream_Read(nschannel->post_data_stream, data, available, &data_len);
    if(NS_FAILED(nsres)) {
        GlobalFree(data);
        return E_FAIL;
    }

    if(nschannel->post_data_contains_headers) {
1028
        if(data_len >= 2 && data[0] == '\r' && data[1] == '\n') {
1029 1030 1031 1032 1033
            post_data = data+2;
            data_len -= 2;
        }else {
            WCHAR *headers;
            DWORD size;
1034 1035 1036 1037 1038 1039 1040 1041 1042
            char *ptr;

            post_data += data_len;
            for(ptr = data; ptr+4 < data+data_len; ptr++) {
                if(!memcmp(ptr, "\r\n\r\n", 4)) {
                    post_data = ptr+4;
                    break;
                }
            }
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087

            data_len -= post_data-data;

            size = MultiByteToWideChar(CP_ACP, 0, data, post_data-data, NULL, 0);
            headers = heap_alloc((size+1)*sizeof(WCHAR));
            if(headers) {
                MultiByteToWideChar(CP_ACP, 0, data, post_data-data, headers, size);
                headers[size] = 0;
                hres = parse_headers(headers , &nschannel->request_headers);
                if(SUCCEEDED(hres))
                    This->bsc.headers = headers;
                else
                    heap_free(headers);
            }else {
                hres = E_OUTOFMEMORY;
            }
        }
    }

    if(FAILED(hres)) {
        GlobalFree(data);
        return hres;
    }

    if(!data_len) {
        GlobalFree(data);
        post_data = NULL;
    }else if(post_data != data) {
        char *new_data;

        new_data = GlobalAlloc(0, data_len);
        if(new_data)
            memcpy(new_data, post_data, data_len);
        GlobalFree(data);
        if(!new_data)
            return E_OUTOFMEMORY;
        post_data = new_data;
    }

    This->bsc.post_data = post_data;
    This->bsc.post_data_len = data_len;
    TRACE("post_data = %s\n", debugstr_a(This->bsc.post_data));
    return S_OK;
}

1088
static HRESULT on_start_nsrequest(nsChannelBSC *This)
1089 1090 1091 1092 1093 1094 1095 1096
{
    nsresult nsres;

    /* FIXME: it's needed for http connections from BindToObject. */
    if(!This->nschannel->response_status)
        This->nschannel->response_status = 200;

    nsres = nsIStreamListener_OnStartRequest(This->nslistener,
1097
            (nsIRequest*)&This->nschannel->nsIHttpChannel_iface, This->nscontext);
1098
    if(NS_FAILED(nsres)) {
1099
        FIXME("OnStartRequest failed: %08x\n", nsres);
1100 1101 1102
        return E_FAIL;
    }

1103
    if(This->is_doc_channel) {
1104
        update_window_doc(This->bsc.window);
1105 1106
        if(This->bsc.window->base.outer_window->readystate != READYSTATE_LOADING)
            set_ready_state(This->bsc.window->base.outer_window, READYSTATE_LOADING);
1107 1108 1109
    }

    return S_OK;
1110 1111
}

1112
static void on_stop_nsrequest(nsChannelBSC *This, HRESULT result)
1113
{
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
    nsresult nsres, request_result;

    switch(result) {
    case S_OK:
        request_result = NS_OK;
        break;
    case E_ABORT:
        request_result = NS_BINDING_ABORTED;
        break;
    default:
        request_result = NS_ERROR_FAILURE;
    }
1126

1127 1128
    if(This->nslistener) {
        nsres = nsIStreamListener_OnStopRequest(This->nslistener,
1129 1130
                 (nsIRequest*)&This->nschannel->nsIHttpChannel_iface, This->nscontext,
                 request_result);
1131
        if(NS_FAILED(nsres))
Andrew Eikum's avatar
Andrew Eikum committed
1132
            WARN("OnStopRequest failed: %08x\n", nsres);
1133 1134 1135 1136
    }

    if(This->nschannel->load_group) {
        nsres = nsILoadGroup_RemoveRequest(This->nschannel->load_group,
1137
                (nsIRequest*)&This->nschannel->nsIHttpChannel_iface, NULL, request_result);
1138 1139 1140
        if(NS_FAILED(nsres))
            ERR("RemoveRequest failed: %08x\n", nsres);
    }
1141 1142
}

1143 1144
static HRESULT read_stream_data(nsChannelBSC *This, IStream *stream)
{
1145
    DWORD read;
1146 1147 1148
    nsresult nsres;
    HRESULT hres;

1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
    if(!This->response_processed) {
        IWinInetHttpInfo *wininet_info;

        This->response_processed = TRUE;
        if(This->bsc.binding) {
            hres = IBinding_QueryInterface(This->bsc.binding, &IID_IWinInetHttpInfo, (void**)&wininet_info);
            if(SUCCEEDED(hres)) {
                query_http_info(This, wininet_info);
                IWinInetHttpInfo_Release(wininet_info);
            }
        }
    }

1162 1163 1164 1165
    if(!This->nslistener) {
        BYTE buf[1024];

        do {
1166
            hres = read_stream(&This->bsc, stream, buf, sizeof(buf), &read);
1167 1168 1169 1170 1171
        }while(hres == S_OK && read);

        return S_OK;
    }

1172
    if(!This->nsstream) {
1173
        This->nsstream = create_nsprotocol_stream();
1174 1175 1176
        if(!This->nsstream)
            return E_OUTOFMEMORY;
    }
1177 1178

    do {
1179 1180 1181
        BOOL first_read = !This->bsc.readed;

        hres = read_stream(&This->bsc, stream, This->nsstream->buf+This->nsstream->buf_size,
1182 1183
                sizeof(This->nsstream->buf)-This->nsstream->buf_size, &read);
        if(!read)
1184 1185
            break;

1186
        This->nsstream->buf_size += read;
1187

1188
        if(first_read) {
1189 1190
            switch(This->bsc.bom) {
            case BOM_UTF8:
1191
                This->nschannel->charset = heap_strdupA(UTF8_STR);
1192 1193 1194 1195
                break;
            case BOM_UTF16:
                This->nschannel->charset = heap_strdupA(UTF16_STR);
            }
1196

1197 1198 1199
            if(!This->nschannel->content_type) {
                WCHAR *mime;

1200
                hres = FindMimeFromData(NULL, NULL, This->nsstream->buf, This->nsstream->buf_size,
1201
                        This->is_doc_channel ? text_htmlW : NULL, 0, &mime, 0);
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
                if(FAILED(hres))
                    return hres;

                TRACE("Found MIME %s\n", debugstr_w(mime));

                This->nschannel->content_type = heap_strdupWtoA(mime);
                CoTaskMemFree(mime);
                if(!This->nschannel->content_type)
                    return E_OUTOFMEMORY;
            }

1213
            on_start_nsrequest(This);
1214 1215 1216
        }

        nsres = nsIStreamListener_OnDataAvailable(This->nslistener,
1217
                (nsIRequest*)&This->nschannel->nsIHttpChannel_iface, This->nscontext,
1218
                &This->nsstream->nsIInputStream_iface, This->bsc.readed-This->nsstream->buf_size,
1219 1220 1221 1222
                This->nsstream->buf_size);
        if(NS_FAILED(nsres))
            ERR("OnDataAvailable failed: %08x\n", nsres);

1223 1224 1225 1226
        if(This->nsstream->buf_size == sizeof(This->nsstream->buf)) {
            ERR("buffer is full\n");
            break;
        }
1227 1228 1229 1230 1231
    }while(hres == S_OK);

    return S_OK;
}

1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
typedef struct {
    nsIAsyncVerifyRedirectCallback nsIAsyncVerifyRedirectCallback_iface;

    LONG ref;

    nsChannel *nschannel;
    nsChannelBSC *bsc;
} nsRedirectCallback;

static nsRedirectCallback *impl_from_nsIAsyncVerifyRedirectCallback(nsIAsyncVerifyRedirectCallback *iface)
{
    return CONTAINING_RECORD(iface, nsRedirectCallback, nsIAsyncVerifyRedirectCallback_iface);
}

static nsresult NSAPI nsAsyncVerifyRedirectCallback_QueryInterface(nsIAsyncVerifyRedirectCallback *iface,
        nsIIDRef riid, void **result)
{
    nsRedirectCallback *This = impl_from_nsIAsyncVerifyRedirectCallback(iface);

    if(IsEqualGUID(&IID_nsISupports, riid)) {
1252
        TRACE("(%p)->(IID_nsISupports %p)\n", This, result);
1253 1254 1255 1256 1257 1258
        *result = &This->nsIAsyncVerifyRedirectCallback_iface;
    }else if(IsEqualGUID(&IID_nsIAsyncVerifyRedirectCallback, riid)) {
        TRACE("(%p)->(IID_nsIAsyncVerifyRedirectCallback %p)\n", This, result);
        *result = &This->nsIAsyncVerifyRedirectCallback_iface;
    }else {
        *result = NULL;
1259
        WARN("unimplemented iface %s\n", debugstr_guid(riid));
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
        return NS_NOINTERFACE;
    }

    nsISupports_AddRef((nsISupports*)*result);
    return NS_OK;
}

static nsrefcnt NSAPI nsAsyncVerifyRedirectCallback_AddRef(nsIAsyncVerifyRedirectCallback *iface)
{
    nsRedirectCallback *This = impl_from_nsIAsyncVerifyRedirectCallback(iface);
    LONG ref = InterlockedIncrement(&This->ref);

    TRACE("(%p) ref=%d\n", This, ref);

    return ref;
}

static nsrefcnt NSAPI nsAsyncVerifyRedirectCallback_Release(nsIAsyncVerifyRedirectCallback *iface)
{
    nsRedirectCallback *This = impl_from_nsIAsyncVerifyRedirectCallback(iface);
    LONG ref = InterlockedDecrement(&This->ref);

    TRACE("(%p) ref=%d\n", This, ref);

    if(!ref) {
        IBindStatusCallback_Release(&This->bsc->bsc.IBindStatusCallback_iface);
1286
        nsIHttpChannel_Release(&This->nschannel->nsIHttpChannel_iface);
1287 1288 1289 1290 1291 1292 1293 1294 1295
        heap_free(This);
    }

    return ref;
}

static nsresult NSAPI nsAsyncVerifyRedirectCallback_AsyncOnChannelRedirect(nsIAsyncVerifyRedirectCallback *iface, nsresult result)
{
    nsRedirectCallback *This = impl_from_nsIAsyncVerifyRedirectCallback(iface);
1296 1297
    nsChannel *old_nschannel;
    nsresult nsres;
1298 1299 1300

    TRACE("(%p)->(%08x)\n", This, result);

1301
    old_nschannel = This->bsc->nschannel;
1302
    nsIHttpChannel_AddRef(&This->nschannel->nsIHttpChannel_iface);
1303 1304 1305 1306 1307 1308 1309 1310 1311
    This->bsc->nschannel = This->nschannel;

    if(This->nschannel->load_group) {
        nsres = nsILoadGroup_AddRequest(This->nschannel->load_group, (nsIRequest*)&This->nschannel->nsIHttpChannel_iface,
                NULL);
        if(NS_FAILED(nsres))
            ERR("AddRequest failed: %08x\n", nsres);
    }

1312
    if(This->bsc->is_doc_channel) {
1313 1314 1315
        IUri *uri = nsuri_get_uri(This->nschannel->uri);

        if(uri) {
1316
            set_current_uri(This->bsc->bsc.window->base.outer_window, uri);
1317 1318 1319 1320 1321 1322
            IUri_Release(uri);
        }else {
            WARN("Could not get IUri from nsWineURI\n");
        }
    }

1323
    if(old_nschannel) {
1324 1325 1326 1327 1328 1329
        if(old_nschannel->load_group) {
            nsres = nsILoadGroup_RemoveRequest(old_nschannel->load_group,
                    (nsIRequest*)&old_nschannel->nsIHttpChannel_iface, NULL, NS_OK);
            if(NS_FAILED(nsres))
                ERR("RemoveRequest failed: %08x\n", nsres);
        }
1330 1331 1332
        nsIHttpChannel_Release(&old_nschannel->nsIHttpChannel_iface);
    }

1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
    return NS_OK;
}

static const nsIAsyncVerifyRedirectCallbackVtbl nsAsyncVerifyRedirectCallbackVtbl = {
    nsAsyncVerifyRedirectCallback_QueryInterface,
    nsAsyncVerifyRedirectCallback_AddRef,
    nsAsyncVerifyRedirectCallback_Release,
    nsAsyncVerifyRedirectCallback_AsyncOnChannelRedirect
};

static HRESULT create_redirect_callback(nsChannel *nschannel, nsChannelBSC *bsc, nsRedirectCallback **ret)
{
    nsRedirectCallback *callback;

    callback = heap_alloc(sizeof(*callback));
    if(!callback)
        return E_OUTOFMEMORY;

    callback->nsIAsyncVerifyRedirectCallback_iface.lpVtbl = &nsAsyncVerifyRedirectCallbackVtbl;
    callback->ref = 1;

1354
    nsIHttpChannel_AddRef(&nschannel->nsIHttpChannel_iface);
1355 1356 1357 1358 1359 1360 1361 1362 1363
    callback->nschannel = nschannel;

    IBindStatusCallback_AddRef(&bsc->bsc.IBindStatusCallback_iface);
    callback->bsc = bsc;

    *ret = callback;
    return S_OK;
}

1364 1365 1366 1367
static inline nsChannelBSC *nsChannelBSC_from_BSCallback(BSCallback *iface)
{
    return CONTAINING_RECORD(iface, nsChannelBSC, bsc);
}
1368 1369 1370

static void nsChannelBSC_destroy(BSCallback *bsc)
{
1371
    nsChannelBSC *This = nsChannelBSC_from_BSCallback(bsc);
1372 1373

    if(This->nschannel)
1374
        nsIHttpChannel_Release(&This->nschannel->nsIHttpChannel_iface);
1375 1376 1377 1378 1379
    if(This->nslistener)
        nsIStreamListener_Release(This->nslistener);
    if(This->nscontext)
        nsISupports_Release(This->nscontext);
    if(This->nsstream)
1380
        nsIInputStream_Release(&This->nsstream->nsIInputStream_iface);
1381 1382 1383 1384 1385
    heap_free(This);
}

static HRESULT nsChannelBSC_start_binding(BSCallback *bsc)
{
1386
    nsChannelBSC *This = nsChannelBSC_from_BSCallback(bsc);
1387

1388 1389
    if(This->is_doc_channel)
        This->bsc.window->base.outer_window->base.inner_window->doc->skip_mutation_notif = FALSE;
1390

1391 1392 1393
    return S_OK;
}

1394 1395
static HRESULT nsChannelBSC_init_bindinfo(BSCallback *bsc)
{
1396
    nsChannelBSC *This = nsChannelBSC_from_BSCallback(bsc);
1397
    HRESULT hres;
1398 1399

    if(This->nschannel && This->nschannel->post_data_stream) {
1400
        hres = read_post_data_stream(This, This->nschannel);
1401 1402
        if(FAILED(hres))
            return hres;
1403 1404 1405 1406 1407
    }

    return S_OK;
}

1408 1409 1410 1411 1412 1413
typedef struct {
    task_t header;
    nsChannelBSC *bsc;
} stop_request_task_t;

static void stop_request_proc(task_t *_task)
1414
{
1415
    stop_request_task_t *task = (stop_request_task_t*)_task;
1416

1417
    TRACE("(%p)\n", task->bsc);
1418

1419 1420
    list_remove(&task->bsc->bsc.entry);
    list_init(&task->bsc->bsc.entry);
1421
    on_stop_nsrequest(task->bsc, S_OK);
1422 1423 1424 1425 1426 1427
}

static void stop_request_task_destr(task_t *_task)
{
    stop_request_task_t *task = (stop_request_task_t*)_task;

1428
    IBindStatusCallback_Release(&task->bsc->bsc.IBindStatusCallback_iface);
1429
    heap_free(task);
1430
}
1431

1432 1433 1434 1435
static HRESULT async_stop_request(nsChannelBSC *This)
{
    stop_request_task_t *task;

1436 1437 1438 1439 1440
    if(!This->bsc.readed) {
        TRACE("No data read, calling OnStartRequest\n");
        on_start_nsrequest(This);
    }

1441 1442 1443 1444
    task = heap_alloc(sizeof(*task));
    if(!task)
        return E_OUTOFMEMORY;

1445
    IBindStatusCallback_AddRef(&This->bsc.IBindStatusCallback_iface);
1446
    task->bsc = This;
1447

1448
    return push_task(&task->header, stop_request_proc, stop_request_task_destr, This->bsc.window->task_magic);
1449 1450
}

1451 1452
static void handle_navigation_error(nsChannelBSC *This, DWORD result)
{
1453
    HTMLOuterWindow *outer_window;
1454 1455 1456 1457 1458 1459
    HTMLDocumentObj *doc;
    BOOL is_error_url;
    SAFEARRAY *sa;
    SAFEARRAYBOUND bound;
    VARIANT var, varOut;
    LONG ind;
1460
    BSTR unk;
1461 1462
    HRESULT hres;

1463
    if(!This->is_doc_channel || !This->bsc.window)
1464 1465
        return;

1466 1467 1468
    outer_window = This->bsc.window->base.outer_window;

    doc = outer_window->doc_obj;
1469 1470 1471 1472
    if(!doc || !doc->doc_object_service || !doc->client)
        return;

    hres = IDocObjectService_IsErrorUrl(doc->doc_object_service,
1473
            outer_window->url, &is_error_url);
1474 1475 1476
    if(FAILED(hres) || is_error_url)
        return;

1477
    if(!doc->client_cmdtrg)
1478 1479 1480 1481 1482
        return;

    bound.lLbound = 0;
    bound.cElements = 8;
    sa = SafeArrayCreate(VT_VARIANT, 1, &bound);
1483
    if(!sa)
1484 1485 1486 1487 1488 1489 1490 1491 1492
        return;

    ind = 0;
    V_VT(&var) = VT_I4;
    V_I4(&var) = result;
    SafeArrayPutElement(sa, &ind, &var);

    ind = 1;
    V_VT(&var) = VT_BSTR;
1493
    V_BSTR(&var) = outer_window->url;
1494 1495 1496 1497
    SafeArrayPutElement(sa, &ind, &var);

    ind = 3;
    V_VT(&var) = VT_UNKNOWN;
1498
    V_UNKNOWN(&var) = (IUnknown*)&outer_window->base.IHTMLWindow2_iface;
1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531
    SafeArrayPutElement(sa, &ind, &var);

    /* FIXME: what are the following fields for? */
    ind = 2;
    V_VT(&var) = VT_UNKNOWN;
    V_UNKNOWN(&var) = NULL;
    SafeArrayPutElement(sa, &ind, &var);

    ind = 4;
    V_VT(&var) = VT_BOOL;
    V_BOOL(&var) = FALSE;
    SafeArrayPutElement(sa, &ind, &var);

    ind = 5;
    V_VT(&var) = VT_BOOL;
    V_BOOL(&var) = FALSE;
    SafeArrayPutElement(sa, &ind, &var);

    ind = 6;
    V_VT(&var) = VT_BSTR;
    unk = SysAllocString(NULL);
    V_BSTR(&var) = unk;
    SafeArrayPutElement(sa, &ind, &var);

    ind = 7;
    V_VT(&var) = VT_UNKNOWN;
    V_UNKNOWN(&var) = NULL;
    SafeArrayPutElement(sa, &ind, &var);

    V_VT(&var) = VT_ARRAY;
    V_ARRAY(&var) = sa;
    V_VT(&varOut) = VT_BOOL;
    V_BOOL(&varOut) = VARIANT_TRUE;
1532
    IOleCommandTarget_Exec(doc->client_cmdtrg, &CGID_DocHostCmdPriv, 1, 0, &var, FAILED(hres)?NULL:&varOut);
1533 1534 1535 1536 1537

    SysFreeString(unk);
    SafeArrayDestroy(sa);
}

1538 1539
static HRESULT nsChannelBSC_stop_binding(BSCallback *bsc, HRESULT result)
{
1540
    nsChannelBSC *This = nsChannelBSC_from_BSCallback(bsc);
1541

1542 1543 1544
    if(result != E_ABORT) {
        if(FAILED(result))
            handle_navigation_error(This, result);
1545
        else if(This->is_doc_channel) {
1546 1547 1548 1549
            result = async_stop_request(This);
            if(SUCCEEDED(result))
                return S_OK;
        }
1550 1551
    }

1552
    on_stop_nsrequest(This, result);
1553 1554 1555 1556 1557
    return S_OK;
}

static HRESULT nsChannelBSC_read_data(BSCallback *bsc, IStream *stream)
{
1558
    nsChannelBSC *This = nsChannelBSC_from_BSCallback(bsc);
1559 1560 1561 1562

    return read_stream_data(This, stream);
}

1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581
static HRESULT handle_redirect(nsChannelBSC *This, const WCHAR *new_url)
{
    nsRedirectCallback *callback;
    nsIChannelEventSink *sink;
    nsChannel *new_channel;
    nsresult nsres;
    HRESULT hres;

    TRACE("(%p)->(%s)\n", This, debugstr_w(new_url));

    if(!This->nschannel || !This->nschannel->notif_callback)
        return S_OK;

    nsres = nsIInterfaceRequestor_GetInterface(This->nschannel->notif_callback, &IID_nsIChannelEventSink, (void**)&sink);
    if(NS_FAILED(nsres))
        return S_OK;

    hres = create_redirect_nschannel(new_url, This->nschannel, &new_channel);
    if(SUCCEEDED(hres)) {
1582 1583
        TRACE("%p %p->%p\n", This, This->nschannel, new_channel);

1584
        hres = create_redirect_callback(new_channel, This, &callback);
1585
        nsIHttpChannel_Release(&new_channel->nsIHttpChannel_iface);
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596
    }

    if(SUCCEEDED(hres)) {
        nsres = nsIChannelEventSink_AsyncOnChannelRedirect(sink, (nsIChannel*)&This->nschannel->nsIHttpChannel_iface,
                (nsIChannel*)&callback->nschannel->nsIHttpChannel_iface, REDIRECT_TEMPORARY, /* FIXME */
                &callback->nsIAsyncVerifyRedirectCallback_iface);

        if(NS_FAILED(nsres))
            FIXME("AsyncOnChannelRedirect failed: %08x\n", hres);
        else if(This->nschannel != callback->nschannel)
            FIXME("nschannel not updated\n");
1597 1598

        nsIAsyncVerifyRedirectCallback_Release(&callback->nsIAsyncVerifyRedirectCallback_iface);
1599 1600 1601 1602 1603 1604
    }

    nsIChannelEventSink_Release(sink);
    return hres;
}

1605 1606
static HRESULT nsChannelBSC_on_progress(BSCallback *bsc, ULONG status_code, LPCWSTR status_text)
{
1607
    nsChannelBSC *This = nsChannelBSC_from_BSCallback(bsc);
1608 1609

    switch(status_code) {
1610
    case BINDSTATUS_MIMETYPEAVAILABLE:
1611 1612 1613
        if(!This->nschannel)
            return S_OK;

1614 1615
        heap_free(This->nschannel->content_type);
        This->nschannel->content_type = heap_strdupWtoA(status_text);
1616 1617
        break;
    case BINDSTATUS_REDIRECTING:
1618
        return handle_redirect(This, status_text);
1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638
    case BINDSTATUS_BEGINDOWNLOADDATA: {
        IWinInetHttpInfo *http_info;
        DWORD status, size = sizeof(DWORD);
        HRESULT hres;

        if(!This->bsc.binding)
            break;

        hres = IBinding_QueryInterface(This->bsc.binding, &IID_IWinInetHttpInfo, (void**)&http_info);
        if(FAILED(hres))
            break;

        hres = IWinInetHttpInfo_QueryInfo(http_info,
                HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, &status, &size, NULL, NULL);
        IWinInetHttpInfo_Release(http_info);
        if(FAILED(hres) || status == HTTP_STATUS_OK)
            break;

        handle_navigation_error(This, status);
    }
1639 1640 1641 1642 1643
    }

    return S_OK;
}

1644 1645
static HRESULT nsChannelBSC_on_response(BSCallback *bsc, DWORD response_code,
        LPCWSTR response_headers)
1646
{
1647
    nsChannelBSC *This = nsChannelBSC_from_BSCallback(bsc);
1648
    HRESULT hres;
1649

1650
    This->response_processed = TRUE;
1651
    This->nschannel->response_status = response_code;
1652 1653

    if(response_headers) {
1654 1655 1656 1657 1658
        const WCHAR *headers;

        headers = strchrW(response_headers, '\r');
        if(headers && headers[1] == '\n') {
            headers += 2;
1659
            hres = process_response_headers(This, headers);
1660 1661
            if(FAILED(hres)) {
                WARN("parsing headers failed: %08x\n", hres);
1662
                return hres;
1663
            }
1664 1665 1666
        }
    }

1667 1668 1669
    return S_OK;
}

1670 1671
static HRESULT nsChannelBSC_beginning_transaction(BSCallback *bsc, WCHAR **additional_headers)
{
1672
    nsChannelBSC *This = nsChannelBSC_from_BSCallback(bsc);
1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716
    http_header_t *iter;
    DWORD len = 0;
    WCHAR *ptr;

    static const WCHAR content_lengthW[] =
        {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0};

    if(!This->nschannel)
        return S_FALSE;

    LIST_FOR_EACH_ENTRY(iter, &This->nschannel->request_headers, http_header_t, entry) {
        if(strcmpW(iter->header, content_lengthW))
            len += strlenW(iter->header) + 2 /* ": " */ + strlenW(iter->data) + 2 /* "\r\n" */;
    }

    if(!len)
        return S_OK;

    *additional_headers = ptr = CoTaskMemAlloc((len+1)*sizeof(WCHAR));
    if(!ptr)
        return E_OUTOFMEMORY;

    LIST_FOR_EACH_ENTRY(iter, &This->nschannel->request_headers, http_header_t, entry) {
        if(!strcmpW(iter->header, content_lengthW))
            continue;

        len = strlenW(iter->header);
        memcpy(ptr, iter->header, len*sizeof(WCHAR));
        ptr += len;

        *ptr++ = ':';
        *ptr++ = ' ';

        len = strlenW(iter->data);
        memcpy(ptr, iter->data, len*sizeof(WCHAR));
        ptr += len;

        *ptr++ = '\r';
        *ptr++ = '\n';
    }

    *ptr = 0;

    return S_OK;
1717 1718
}

1719 1720
static const BSCallbackVtbl nsChannelBSCVtbl = {
    nsChannelBSC_destroy,
1721
    nsChannelBSC_init_bindinfo,
1722 1723 1724 1725
    nsChannelBSC_start_binding,
    nsChannelBSC_stop_binding,
    nsChannelBSC_read_data,
    nsChannelBSC_on_progress,
1726 1727
    nsChannelBSC_on_response,
    nsChannelBSC_beginning_transaction
1728 1729
};

1730 1731
HRESULT create_channelbsc(IMoniker *mon, const WCHAR *headers, BYTE *post_data, DWORD post_data_size,
        BOOL is_doc_binding, nsChannelBSC **retval)
1732
{
1733 1734 1735 1736 1737
    nsChannelBSC *ret;

    ret = heap_alloc_zero(sizeof(*ret));
    if(!ret)
        return E_OUTOFMEMORY;
1738 1739

    init_bscallback(&ret->bsc, &nsChannelBSCVtbl, mon, BINDF_ASYNCHRONOUS | BINDF_ASYNCSTORAGE | BINDF_PULLDATA);
1740
    ret->is_doc_channel = is_doc_binding;
1741

1742 1743 1744
    if(headers) {
        ret->bsc.headers = heap_strdupW(headers);
        if(!ret->bsc.headers) {
1745
            IBindStatusCallback_Release(&ret->bsc.IBindStatusCallback_iface);
1746 1747 1748 1749 1750 1751
            return E_OUTOFMEMORY;
        }
    }

    if(post_data) {
        ret->bsc.post_data = GlobalAlloc(0, post_data_size);
1752 1753
        if(!ret->bsc.post_data) {
            heap_free(ret->bsc.headers);
1754
            IBindStatusCallback_Release(&ret->bsc.IBindStatusCallback_iface);
1755 1756 1757 1758 1759 1760 1761 1762 1763
            return E_OUTOFMEMORY;
        }

        memcpy(ret->bsc.post_data, post_data, post_data_size);
        ret->bsc.post_data_len = post_data_size;
    }

    *retval = ret;
    return S_OK;
1764 1765
}

1766 1767
typedef struct {
    task_t header;
1768
    HTMLOuterWindow *window;
1769
    HTMLInnerWindow *pending_window;
1770 1771 1772 1773 1774 1775
} start_doc_binding_task_t;

static void start_doc_binding_proc(task_t *_task)
{
    start_doc_binding_task_t *task = (start_doc_binding_task_t*)_task;

1776
    set_current_mon(task->window, task->pending_window->bscallback->bsc.mon, BINDING_NAVIGATED);
1777
    start_binding(task->pending_window, &task->pending_window->bscallback->bsc, NULL);
1778 1779 1780 1781 1782 1783
}

static void start_doc_binding_task_destr(task_t *_task)
{
    start_doc_binding_task_t *task = (start_doc_binding_task_t*)_task;

1784
    IHTMLWindow2_Release(&task->pending_window->base.IHTMLWindow2_iface);
1785
    heap_free(task);
1786 1787
}

1788
HRESULT async_start_doc_binding(HTMLOuterWindow *window, HTMLInnerWindow *pending_window)
1789 1790 1791
{
    start_doc_binding_task_t *task;

1792
    TRACE("%p\n", pending_window);
1793

1794 1795 1796 1797 1798
    task = heap_alloc(sizeof(start_doc_binding_task_t));
    if(!task)
        return E_OUTOFMEMORY;

    task->window = window;
1799 1800
    task->pending_window = pending_window;
    IHTMLWindow2_AddRef(&pending_window->base.IHTMLWindow2_iface);
1801

1802
    return push_task(&task->header, start_doc_binding_proc, start_doc_binding_task_destr, pending_window->task_magic);
1803 1804
}

1805
void abort_window_bindings(HTMLInnerWindow *window)
1806
{
1807 1808
    BSCallback *iter;

1809 1810
    remove_target_tasks(window->task_magic);

1811 1812
    while(!list_empty(&window->bindings)) {
        iter = LIST_ENTRY(window->bindings.next, BSCallback, entry);
1813

1814 1815
        TRACE("Aborting %p\n", iter);

1816 1817
        IBindStatusCallback_AddRef(&iter->IBindStatusCallback_iface);

1818 1819
        if(iter->binding)
            IBinding_Abort(iter->binding);
1820
        else
1821
            iter->vtbl->stop_binding(iter, E_ABORT);
1822

1823
        iter->window = NULL;
1824 1825 1826 1827 1828 1829 1830 1831 1832
        list_remove(&iter->entry);
        list_init(&iter->entry);

        IBindStatusCallback_Release(&iter->IBindStatusCallback_iface);
    }

    if(window->bscallback) {
        IBindStatusCallback_Release(&window->bscallback->bsc.IBindStatusCallback_iface);
        window->bscallback = NULL;
1833
    }
1834 1835 1836 1837 1838

    if(window->mon) {
        IMoniker_Release(window->mon);
        window->mon = NULL;
    }
1839
}
1840

1841
HRESULT channelbsc_load_stream(HTMLInnerWindow *pending_window, IStream *stream)
1842
{
1843
    nsChannelBSC *bscallback = pending_window->bscallback;
1844
    HRESULT hres = S_OK;
1845

1846 1847 1848 1849
    if(!bscallback->nschannel) {
        ERR("NULL nschannel\n");
        return E_FAIL;
    }
1850

1851 1852 1853
    bscallback->nschannel->content_type = heap_strdupA("text/html");
    if(!bscallback->nschannel->content_type)
        return E_OUTOFMEMORY;
1854

1855
    bscallback->bsc.window = pending_window;
1856 1857 1858 1859 1860
    if(stream)
        hres = read_stream_data(bscallback, stream);
    if(SUCCEEDED(hres))
        hres = async_stop_request(bscallback);
    if(FAILED(hres))
1861 1862
        IBindStatusCallback_OnStopBinding(&bscallback->bsc.IBindStatusCallback_iface, hres,
                ERROR_SUCCESS);
1863 1864 1865

    return hres;
}
1866

1867
void channelbsc_set_channel(nsChannelBSC *This, nsChannel *channel, nsIStreamListener *listener, nsISupports *context)
1868
{
1869
    nsIHttpChannel_AddRef(&channel->nsIHttpChannel_iface);
1870 1871 1872 1873 1874 1875 1876 1877 1878
    This->nschannel = channel;

    nsIStreamListener_AddRef(listener);
    This->nslistener = listener;

    if(context) {
        nsISupports_AddRef(context);
        This->nscontext = context;
    }
1879 1880 1881 1882 1883 1884 1885 1886 1887 1888

    if(This->bsc.headers) {
        HRESULT hres;

        hres = parse_headers(This->bsc.headers, &channel->request_headers);
        heap_free(This->bsc.headers);
        This->bsc.headers = NULL;
        if(FAILED(hres))
            WARN("parse_headers failed: %08x\n", hres);
    }
1889
}
1890

1891 1892
typedef struct {
    task_t header;
1893
    HTMLOuterWindow *window;
1894 1895 1896 1897 1898 1899
    IUri *uri;
} navigate_javascript_task_t;

static void navigate_javascript_proc(task_t *_task)
{
    navigate_javascript_task_t *task = (navigate_javascript_task_t*)_task;
1900
    HTMLOuterWindow *window = task->window;
1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912
    VARIANT v;
    BSTR code;
    HRESULT hres;

    static const WCHAR jscriptW[] = {'j','s','c','r','i','p','t',0};

    task->window->readystate = READYSTATE_COMPLETE;

    hres = IUri_GetPath(task->uri, &code);
    if(FAILED(hres))
        return;

1913 1914 1915 1916 1917 1918
    hres = UrlUnescapeW(code, NULL, NULL, URL_UNESCAPE_INPLACE);
    if(FAILED(hres)) {
        SysFreeString(code);
        return;
    }

1919 1920 1921
    set_download_state(window->doc_obj, 1);

    V_VT(&v) = VT_EMPTY;
1922
    hres = exec_script(window->base.inner_window, code, jscriptW, &v);
1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944
    SysFreeString(code);
    if(SUCCEEDED(hres) && V_VT(&v) != VT_EMPTY) {
        FIXME("javascirpt URL returned %s\n", debugstr_variant(&v));
        VariantClear(&v);
    }

    if(window->doc_obj->view_sink)
        IAdviseSink_OnViewChange(window->doc_obj->view_sink, DVASPECT_CONTENT, -1);

    set_download_state(window->doc_obj, 0);
}

static void navigate_javascript_task_destr(task_t *_task)
{
    navigate_javascript_task_t *task = (navigate_javascript_task_t*)_task;

    IUri_Release(task->uri);
    heap_free(task);
}

typedef struct {
    task_t header;
1945
    HTMLOuterWindow *window;
1946
    nsChannelBSC *bscallback;
1947
    DWORD flags;
1948
    IMoniker *mon;
1949
    IUri *uri;
1950 1951 1952 1953 1954 1955 1956
} navigate_task_t;

static void navigate_proc(task_t *_task)
{
    navigate_task_t *task = (navigate_task_t*)_task;
    HRESULT hres;

1957
    hres = set_moniker(&task->window->doc_obj->basedoc, task->mon, task->uri, NULL, task->bscallback, TRUE);
1958
    if(SUCCEEDED(hres)) {
1959
        set_current_mon(task->window, task->bscallback->bsc.mon, task->flags);
1960
        set_current_uri(task->window, task->uri);
1961 1962
        start_binding(task->window->pending_window, &task->bscallback->bsc, NULL);
    }
1963 1964 1965 1966 1967 1968
}

static void navigate_task_destr(task_t *_task)
{
    navigate_task_t *task = (navigate_task_t*)_task;

1969
    IBindStatusCallback_Release(&task->bscallback->bsc.IBindStatusCallback_iface);
1970
    IMoniker_Release(task->mon);
1971
    IUri_Release(task->uri);
1972 1973 1974
    heap_free(task);
}

1975
static HRESULT navigate_fragment(HTMLOuterWindow *window, IUri *uri)
1976 1977 1978
{
    nsIDOMLocation *nslocation;
    nsAString nsfrag_str;
1979
    WCHAR *selector;
1980 1981 1982 1983
    BSTR frag;
    nsresult nsres;
    HRESULT hres;

1984 1985
    const WCHAR selector_formatW[] = {'a','[','i','d','=','"','%','s','"',']',0};

1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001
    set_current_uri(window, uri);

    nsres = nsIDOMWindow_GetLocation(window->nswindow, &nslocation);
    if(FAILED(nsres) || !nslocation)
        return E_FAIL;

    hres = IUri_GetFragment(uri, &frag);
    if(FAILED(hres)) {
        nsIDOMLocation_Release(nslocation);
        return hres;
    }

    nsAString_InitDepend(&nsfrag_str, frag);
    nsres = nsIDOMLocation_SetHash(nslocation, &nsfrag_str);
    nsAString_Finish(&nsfrag_str);
    nsIDOMLocation_Release(nslocation);
2002
    if(NS_FAILED(nsres))
2003
        ERR("SetHash failed: %08x\n", nsres);
2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017

    /*
     * IE supports scrolling to anchor elements with "#hash" ids (note that '#' is part of the id),
     * while Gecko scrolls only to elements with "hash" ids. We scroll the page ourselves if
     * a[id="#hash"] element can be found.
     */
    selector = heap_alloc(sizeof(selector_formatW)+SysStringLen(frag)*sizeof(WCHAR));
    if(selector) {
        nsIDOMElement *nselem = NULL;
        nsAString selector_str;

        sprintfW(selector, selector_formatW, frag);
        nsAString_InitDepend(&selector_str, selector);
        /* NOTE: Gecko doesn't set result to NULL if there is no match, so nselem must be initialized */
2018
        nsres = nsIDOMNodeSelector_QuerySelector(window->base.inner_window->doc->nsnode_selector, &selector_str, &nselem);
2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030
        nsAString_Finish(&selector_str);
        heap_free(selector);
        if(NS_SUCCEEDED(nsres) && nselem) {
            nsIDOMHTMLElement *html_elem;

            nsres = nsIDOMElement_QueryInterface(nselem, &IID_nsIDOMHTMLElement, (void**)&html_elem);
            nsIDOMElement_Release(nselem);
            if(NS_SUCCEEDED(nsres)) {
                nsIDOMHTMLElement_ScrollIntoView(html_elem, TRUE, 1);
                nsIDOMHTMLElement_Release(html_elem);
            }
        }
2031 2032
    }

2033 2034
    SysFreeString(frag);

2035
    if(window->doc_obj->doc_object_service) {
2036 2037
        IDocObjectService_FireNavigateComplete2(window->doc_obj->doc_object_service, &window->base.IHTMLWindow2_iface, 0x10);
        IDocObjectService_FireDocumentComplete(window->doc_obj->doc_object_service, &window->base.IHTMLWindow2_iface, 0);
2038 2039 2040 2041 2042 2043

    }

    return S_OK;
}

2044
HRESULT super_navigate(HTMLOuterWindow *window, IUri *uri, DWORD flags, const WCHAR *headers, BYTE *post_data, DWORD post_data_size)
2045 2046
{
    nsChannelBSC *bsc;
2047
    IUri *uri_nofrag;
2048 2049 2050 2051
    IMoniker *mon;
    DWORD scheme;
    HRESULT hres;

2052 2053 2054 2055
    uri_nofrag = get_uri_nofrag(uri);
    if(!uri_nofrag)
        return E_FAIL;

2056
    if(window->doc_obj->client && !(flags & BINDING_REFRESH)) {
2057 2058 2059 2060 2061 2062 2063
        IOleCommandTarget *cmdtrg;

        hres = IOleClientSite_QueryInterface(window->doc_obj->client, &IID_IOleCommandTarget, (void**)&cmdtrg);
        if(SUCCEEDED(hres)) {
            VARIANT in, out;
            BSTR url_str;

2064
            hres = IUri_GetDisplayUri(uri_nofrag, &url_str);
2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078
            if(SUCCEEDED(hres)) {
                V_VT(&in) = VT_BSTR;
                V_BSTR(&in) = url_str;
                V_VT(&out) = VT_BOOL;
                V_BOOL(&out) = VARIANT_TRUE;
                hres = IOleCommandTarget_Exec(cmdtrg, &CGID_ShellDocView, 67, 0, &in, &out);
                IOleCommandTarget_Release(cmdtrg);
                if(SUCCEEDED(hres))
                    VariantClear(&out);
                SysFreeString(url_str);
            }
        }
    }

2079
    if(!(flags & BINDING_REFRESH) && window->uri_nofrag && !post_data_size) {
2080 2081 2082 2083 2084 2085 2086 2087
        BOOL eq;

        hres = IUri_IsEqual(uri_nofrag, window->uri_nofrag, &eq);
        if(SUCCEEDED(hres) && eq) {
            IUri_Release(uri_nofrag);
            TRACE("fragment navigate\n");
            return navigate_fragment(window, uri);
        }
2088 2089
    }

2090 2091
    hres = CreateURLMonikerEx2(NULL, uri_nofrag, &mon, URL_MK_UNIFORM);
    IUri_Release(uri_nofrag);
2092 2093 2094 2095 2096 2097
    if(FAILED(hres))
        return hres;

    /* FIXME: Why not set_ready_state? */
    window->readystate = READYSTATE_UNINITIALIZED;

2098
    hres = create_channelbsc(mon, headers, post_data, post_data_size, TRUE, &bsc);
2099 2100 2101 2102 2103
    if(FAILED(hres)) {
        IMoniker_Release(mon);
        return hres;
    }

2104
    prepare_for_binding(&window->doc_obj->basedoc, mon, flags);
2105 2106

    hres = IUri_GetScheme(uri, &scheme);
2107
    if(SUCCEEDED(hres) && scheme != URL_SCHEME_JAVASCRIPT) {
2108 2109 2110 2111
        navigate_task_t *task;

        task = heap_alloc(sizeof(*task));
        if(!task) {
2112
            IBindStatusCallback_Release(&bsc->bsc.IBindStatusCallback_iface);
2113 2114 2115 2116
            IMoniker_Release(mon);
            return E_OUTOFMEMORY;
        }

2117 2118
        /* Silently and repeated when real loading starts? */
        window->readystate = READYSTATE_LOADING;
2119
        if(!(flags & (BINDING_FROMHIST|BINDING_REFRESH)))
2120
            call_docview_84(window->doc_obj);
2121

2122 2123
        task->window = window;
        task->bscallback = bsc;
2124
        task->flags = flags;
2125
        task->mon = mon;
2126 2127 2128

        IUri_AddRef(uri);
        task->uri = uri;
2129
        hres = push_task(&task->header, navigate_proc, navigate_task_destr, window->task_magic);
2130 2131 2132
    }else {
        navigate_javascript_task_t *task;

2133
        IBindStatusCallback_Release(&bsc->bsc.IBindStatusCallback_iface);
2134 2135 2136 2137 2138 2139
        IMoniker_Release(mon);

        task = heap_alloc(sizeof(*task));
        if(!task)
            return E_OUTOFMEMORY;

2140 2141
        /* Why silently? */
        window->readystate = READYSTATE_COMPLETE;
2142 2143
        if(!(flags & BINDING_FROMHIST))
            call_docview_84(window->doc_obj);
2144

2145 2146 2147
        IUri_AddRef(uri);
        task->window = window;
        task->uri = uri;
2148
        hres = push_task(&task->header, navigate_javascript_proc, navigate_javascript_task_destr, window->task_magic);
2149 2150
    }

2151
    return hres;
2152 2153
}

2154
HRESULT navigate_new_window(HTMLOuterWindow *window, IUri *uri, const WCHAR *name, IHTMLWindow2 **ret)
2155 2156 2157 2158 2159 2160 2161
{
    IWebBrowser2 *web_browser;
    IHTMLWindow2 *new_window;
    IBindCtx *bind_ctx;
    nsChannelBSC *bsc;
    HRESULT hres;

2162
    hres = create_channelbsc(NULL, NULL, NULL, 0, FALSE, &bsc);
2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176
    if(FAILED(hres))
        return hres;

    hres = CreateAsyncBindCtx(0, &bsc->bsc.IBindStatusCallback_iface, NULL, &bind_ctx);
    if(FAILED(hres)) {
        IBindStatusCallback_Release(&bsc->bsc.IBindStatusCallback_iface);
        return hres;
    }

    hres = CoCreateInstance(&CLSID_InternetExplorer, NULL, CLSCTX_LOCAL_SERVER,
            &IID_IWebBrowser2, (void**)&web_browser);
    if(SUCCEEDED(hres)) {
        ITargetFramePriv2 *target_frame_priv;

2177
        hres = IWebBrowser2_QueryInterface(web_browser, &IID_ITargetFramePriv2, (void**)&target_frame_priv);
2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202
        if(SUCCEEDED(hres)) {
            hres = ITargetFramePriv2_AggregatedNavigation2(target_frame_priv,
                    HLNF_DISABLEWINDOWRESTRICTIONS|HLNF_OPENINNEWWINDOW, bind_ctx, &bsc->bsc.IBindStatusCallback_iface,
                    name, uri, emptyW);
            ITargetFramePriv2_Release(target_frame_priv);

            if(SUCCEEDED(hres))
                hres = do_query_service((IUnknown*)web_browser, &SID_SHTMLWindow, &IID_IHTMLWindow2, (void**)&new_window);
        }
        if(FAILED(hres)) {
            IWebBrowser2_Quit(web_browser);
            IWebBrowser2_Release(web_browser);
        }
    }else {
        WARN("Could not create InternetExplorer instance: %08x\n", hres);
    }

    IBindStatusCallback_Release(&bsc->bsc.IBindStatusCallback_iface);
    IBindCtx_Release(bind_ctx);
    if(FAILED(hres))
        return hres;

    IWebBrowser2_put_Visible(web_browser, VARIANT_TRUE);
    IWebBrowser2_Release(web_browser);

2203 2204 2205 2206
    if(ret)
        *ret = new_window;
    else
        IHTMLWindow2_Release(new_window);
2207 2208 2209
    return S_OK;
}

2210
HRESULT hlink_frame_navigate(HTMLDocument *doc, LPCWSTR url, nsChannel *nschannel, DWORD hlnf, BOOL *cancel)
2211
{
2212
    IHlinkFrame *hlink_frame;
2213
    nsChannelBSC *callback;
2214 2215 2216
    IBindCtx *bindctx;
    IMoniker *mon;
    IHlink *hlink;
2217 2218
    HRESULT hres;

2219 2220
    *cancel = FALSE;

2221
    hres = do_query_service((IUnknown*)doc->doc_obj->client, &IID_IHlinkFrame, &IID_IHlinkFrame,
2222 2223
            (void**)&hlink_frame);
    if(FAILED(hres))
2224
        return S_OK;
2225

2226
    hres = create_channelbsc(NULL, NULL, NULL, 0, FALSE, &callback);
2227 2228 2229 2230
    if(FAILED(hres)) {
        IHlinkFrame_Release(hlink_frame);
        return hres;
    }
2231

2232 2233
    if(nschannel)
        read_post_data_stream(callback, nschannel);
2234

2235
    hres = CreateAsyncBindCtx(0, &callback->bsc.IBindStatusCallback_iface, NULL, &bindctx);
2236
    if(SUCCEEDED(hres))
2237
       hres = CoCreateInstance(&CLSID_StdHlink, NULL, CLSCTX_INPROC_SERVER,
2238
                &IID_IHlink, (LPVOID*)&hlink);
2239

2240 2241
    if(SUCCEEDED(hres))
        hres = CreateURLMoniker(NULL, url, &mon);
2242

2243
    if(SUCCEEDED(hres)) {
2244
        IHlink_SetMonikerReference(hlink, HLINKSETF_TARGET, mon, NULL);
2245 2246 2247 2248 2249 2250

        if(hlnf & HLNF_OPENINNEWWINDOW) {
            static const WCHAR wszBlank[] = {'_','b','l','a','n','k',0};
            IHlink_SetTargetFrameName(hlink, wszBlank); /* FIXME */
        }

2251 2252
        hres = IHlinkFrame_Navigate(hlink_frame, hlnf, bindctx,
                &callback->bsc.IBindStatusCallback_iface, hlink);
2253
        IMoniker_Release(mon);
2254 2255
        *cancel = hres == S_OK;
        hres = S_OK;
2256 2257
    }

2258
    IHlinkFrame_Release(hlink_frame);
2259
    IBindCtx_Release(bindctx);
2260
    IBindStatusCallback_Release(&callback->bsc.IBindStatusCallback_iface);
2261
    return hres;
2262
}
2263

2264
static HRESULT navigate_uri(HTMLOuterWindow *window, IUri *uri, const WCHAR *display_uri, DWORD flags)
2265
{
2266
    nsWineURI *nsuri;
2267 2268
    HRESULT hres;

2269 2270
    TRACE("%s\n", debugstr_w(display_uri));

2271
    if(window->doc_obj && window->doc_obj->webbrowser && window == window->doc_obj->basedoc.window) {
2272 2273
        if(!(flags & BINDING_REFRESH)) {
            BOOL cancel = FALSE;
2274

2275 2276 2277 2278 2279 2280
            hres = IDocObjectService_FireBeforeNavigate2(window->doc_obj->doc_object_service, NULL, display_uri, 0x40,
                    NULL, NULL, 0, NULL, TRUE, &cancel);
            if(SUCCEEDED(hres) && cancel) {
                TRACE("Navigation canceled\n");
                return S_OK;
            }
2281 2282
        }

2283
        return super_navigate(window, uri, flags, NULL, NULL, 0);
2284 2285
    }

2286
    if(window->doc_obj && window == window->doc_obj->basedoc.window) {
2287 2288
        BOOL cancel;

2289
        hres = hlink_frame_navigate(&window->base.inner_window->doc->basedoc, display_uri, NULL, 0, &cancel);
2290 2291 2292 2293 2294
        if(FAILED(hres))
            return hres;

        if(cancel) {
            TRACE("Navigation handled by hlink frame\n");
2295
            return S_OK;
2296
        }
2297
    }
2298

2299
    hres = create_doc_uri(window, uri, &nsuri);
2300 2301 2302 2303 2304 2305 2306 2307
    if(FAILED(hres))
        return hres;

    hres = load_nsuri(window, nsuri, NULL, LOAD_FLAGS_NONE);
    nsISupports_Release((nsISupports*)nsuri);
    return hres;
}

2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321
HRESULT load_uri(HTMLOuterWindow *window, IUri *uri, DWORD flags)
{
    BSTR display_uri;
    HRESULT hres;

    hres = IUri_GetDisplayUri(uri, &display_uri);
    if(FAILED(hres))
        return hres;

    hres = navigate_uri(window, uri, display_uri, flags);
    SysFreeString(display_uri);
    return hres;
}

2322
HRESULT navigate_url(HTMLOuterWindow *window, const WCHAR *new_url, IUri *base_uri, DWORD flags)
2323 2324 2325 2326 2327 2328 2329 2330 2331
{
    BSTR display_uri;
    IUri *uri;
    HRESULT hres;

    if(new_url && base_uri)
        hres = CoInternetCombineUrlEx(base_uri, new_url, URL_ESCAPE_SPACES_ONLY|URL_DONT_ESCAPE_EXTRA_INFO,
                &uri, 0);
    else
2332
        hres = create_uri(new_url, 0, &uri);
2333
    if(FAILED(hres))
2334 2335
        return hres;

2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350
    hres = IUri_GetDisplayUri(uri, &display_uri);
    if(FAILED(hres)) {
        IUri_Release(uri);
        return hres;
    }

    if(window->doc_obj && window->doc_obj->hostui) {
        OLECHAR *translated_url = NULL;

        hres = IDocHostUIHandler_TranslateUrl(window->doc_obj->hostui, 0, display_uri,
                &translated_url);
        if(hres == S_OK) {
            TRACE("%08x %s -> %s\n", hres, debugstr_w(display_uri), debugstr_w(translated_url));
            SysFreeString(display_uri);
            IUri_Release(uri);
2351
            hres = create_uri(translated_url, 0, &uri);
2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363
            CoTaskMemFree(translated_url);
            if(FAILED(hres))
                return hres;

            hres = IUri_GetDisplayUri(uri, &display_uri);
            if(FAILED(hres)) {
                IUri_Release(uri);
                return hres;
            }
        }
    }

2364
    hres = navigate_uri(window, uri, display_uri, flags);
2365 2366 2367

    IUri_Release(uri);
    SysFreeString(display_uri);
2368
    return hres;
2369
}