navigate.c 76 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
 */

#include <stdarg.h>
20
#include <assert.h>
21 22 23 24 25 26 27

#define COBJMACROS
#define NONAMELESSUNION

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

#include "wine/debug.h"

#include "mshtml_private.h"
40
#include "htmlscript.h"
41
#include "binding.h"
42 43 44 45

WINE_DEFAULT_DEBUG_CHANNEL(mshtml);

#define CONTENT_LENGTH "Content-Length"
46
#define UTF8_STR "utf-8"
47
#define UTF16_STR "utf-16"
48

49
struct nsProtocolStream {
50
    nsIInputStream nsIInputStream_iface;
51 52 53 54 55

    LONG ref;

    char buf[1024];
    DWORD buf_size;
56
};
57

58 59 60 61
static inline nsProtocolStream *impl_from_nsIInputStream(nsIInputStream *iface)
{
    return CONTAINING_RECORD(iface, nsProtocolStream, nsIInputStream_iface);
}
62 63

static nsresult NSAPI nsInputStream_QueryInterface(nsIInputStream *iface, nsIIDRef riid,
64
        void **result)
65
{
66
    nsProtocolStream *This = impl_from_nsIInputStream(iface);
67 68 69 70 71

    *result = NULL;

    if(IsEqualGUID(&IID_nsISupports, riid)) {
        TRACE("(%p)->(IID_nsISupports %p)\n", This, result);
72
        *result  = &This->nsIInputStream_iface;
73 74
    }else if(IsEqualGUID(&IID_nsIInputStream, riid)) {
        TRACE("(%p)->(IID_nsIInputStream %p)\n", This, result);
75
        *result  = &This->nsIInputStream_iface;
76 77 78
    }

    if(*result) {
79
        nsIInputStream_AddRef(&This->nsIInputStream_iface);
80 81 82 83 84 85 86 87 88
        return NS_OK;
    }

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

static nsrefcnt NSAPI nsInputStream_AddRef(nsIInputStream *iface)
{
89
    nsProtocolStream *This = impl_from_nsIInputStream(iface);
90 91
    LONG ref = InterlockedIncrement(&This->ref);

92
    TRACE("(%p) ref=%d\n", This, ref);
93 94 95 96 97 98 99

    return ref;
}


static nsrefcnt NSAPI nsInputStream_Release(nsIInputStream *iface)
{
100
    nsProtocolStream *This = impl_from_nsIInputStream(iface);
101 102
    LONG ref = InterlockedDecrement(&This->ref);

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

    if(!ref)
106
        heap_free(This);
107 108 109 110 111 112

    return ref;
}

static nsresult NSAPI nsInputStream_Close(nsIInputStream *iface)
{
113
    nsProtocolStream *This = impl_from_nsIInputStream(iface);
114 115 116 117
    FIXME("(%p)\n", This);
    return NS_ERROR_NOT_IMPLEMENTED;
}

118
static nsresult NSAPI nsInputStream_Available(nsIInputStream *iface, UINT64 *_retval)
119
{
120
    nsProtocolStream *This = impl_from_nsIInputStream(iface);
121 122 123 124
    FIXME("(%p)->(%p)\n", This, _retval);
    return NS_ERROR_NOT_IMPLEMENTED;
}

125 126
static nsresult NSAPI nsInputStream_Read(nsIInputStream *iface, char *aBuf, UINT32 aCount,
                                         UINT32 *_retval)
127
{
128
    nsProtocolStream *This = impl_from_nsIInputStream(iface);
129
    DWORD read = aCount;
130

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

133 134
    if(read > This->buf_size)
        read = This->buf_size;
135

136 137 138 139 140 141
    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;
    }
142

143
    *_retval = read;
144
    return NS_OK;
145 146 147
}

static nsresult NSAPI nsInputStream_ReadSegments(nsIInputStream *iface,
148 149
        nsresult (WINAPI *aWriter)(nsIInputStream*,void*,const char*,UINT32,UINT32,UINT32*),
        void *aClousure, UINT32 aCount, UINT32 *_retval)
150
{
151
    nsProtocolStream *This = impl_from_nsIInputStream(iface);
152
    UINT32 written = 0;
153 154
    nsresult nsres;

155
    TRACE("(%p)->(%p %p %d %p)\n", This, aWriter, aClousure, aCount, _retval);
156 157 158 159

    if(!This->buf_size)
        return S_OK;

160 161
    if(aCount > This->buf_size)
        aCount = This->buf_size;
162

163
    nsres = aWriter(&This->nsIInputStream_iface, aClousure, This->buf, 0, aCount, &written);
164
    if(NS_FAILED(nsres))
165
        TRACE("aWriter failed: %08x\n", nsres);
166 167
    else if(written != This->buf_size)
        FIXME("written %d != buf_size %d\n", written, This->buf_size);
168 169 170

    This->buf_size -= written; 

171
    *_retval = written;
172 173 174
    return nsres;
}

175
static nsresult NSAPI nsInputStream_IsNonBlocking(nsIInputStream *iface, cpp_bool *_retval)
176
{
177
    nsProtocolStream *This = impl_from_nsIInputStream(iface);
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
    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
};

193
static nsProtocolStream *create_nsprotocol_stream(void)
194
{
195 196 197 198 199
    nsProtocolStream *ret;

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

201
    ret->nsIInputStream_iface.lpVtbl = &nsInputStreamVtbl;
202 203 204 205 206 207
    ret->ref = 1;
    ret->buf_size = 0;

    return ret;
}

208 209
static void release_request_data(request_data_t *request_data)
{
210 211
    if(request_data->post_stream)
        nsIInputStream_Release(request_data->post_stream);
212 213 214 215 216
    heap_free(request_data->headers);
    if(request_data->post_data)
        GlobalFree(request_data->post_data);
}

217 218 219 220
static inline BSCallback *impl_from_IBindStatusCallback(IBindStatusCallback *iface)
{
    return CONTAINING_RECORD(iface, BSCallback, IBindStatusCallback_iface);
}
221 222 223 224

static HRESULT WINAPI BindStatusCallback_QueryInterface(IBindStatusCallback *iface,
        REFIID riid, void **ppv)
{
225
    BSCallback *This = impl_from_IBindStatusCallback(iface);
226 227 228 229

    *ppv = NULL;
    if(IsEqualGUID(&IID_IUnknown, riid)) {
        TRACE("(%p)->(IID_IUnknown, %p)\n", This, ppv);
230
        *ppv = &This->IBindStatusCallback_iface;
231 232
    }else if(IsEqualGUID(&IID_IBindStatusCallback, riid)) {
        TRACE("(%p)->(IID_IBindStatusCallback, %p)\n", This, ppv);
233
        *ppv = &This->IBindStatusCallback_iface;
234 235
    }else if(IsEqualGUID(&IID_IServiceProvider, riid)) {
        TRACE("(%p)->(IID_IServiceProvider %p)\n", This, ppv);
236
        *ppv = &This->IServiceProvider_iface;
237 238
    }else if(IsEqualGUID(&IID_IHttpNegotiate, riid)) {
        TRACE("(%p)->(IID_IHttpNegotiate %p)\n", This, ppv);
239
        *ppv = &This->IHttpNegotiate2_iface;
240 241
    }else if(IsEqualGUID(&IID_IHttpNegotiate2, riid)) {
        TRACE("(%p)->(IID_IHttpNegotiate2 %p)\n", This, ppv);
242
        *ppv = &This->IHttpNegotiate2_iface;
243 244
    }else if(IsEqualGUID(&IID_IInternetBindInfo, riid)) {
        TRACE("(%p)->(IID_IInternetBindInfo %p)\n", This, ppv);
245
        *ppv = &This->IInternetBindInfo_iface;
246 247 248
    }else if(IsEqualGUID(&IID_IBindCallbackRedirect, riid)) {
        TRACE("(%p)->(IID_IBindCallbackRedirect %p)\n", This, ppv);
        *ppv = &This->IBindCallbackRedirect_iface;
249 250 251
    }

    if(*ppv) {
252
        IBindStatusCallback_AddRef(&This->IBindStatusCallback_iface);
253 254 255 256 257 258 259 260 261
        return S_OK;
    }

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

static ULONG WINAPI BindStatusCallback_AddRef(IBindStatusCallback *iface)
{
262
    BSCallback *This = impl_from_IBindStatusCallback(iface);
263 264
    LONG ref = InterlockedIncrement(&This->ref);

265
    TRACE("(%p) ref = %d\n", This, ref);
266 267 268 269 270 271

    return ref;
}

static ULONG WINAPI BindStatusCallback_Release(IBindStatusCallback *iface)
{
272
    BSCallback *This = impl_from_IBindStatusCallback(iface);
273 274
    LONG ref = InterlockedDecrement(&This->ref);

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

    if(!ref) {
278
        release_request_data(&This->request_data);
279 280
        if(This->mon)
            IMoniker_Release(This->mon);
281 282
        if(This->binding)
            IBinding_Release(This->binding);
283
        list_remove(&This->entry);
284
        list_init(&This->entry);
285 286

        This->vtbl->destroy(This);
287 288 289 290 291 292 293 294
    }

    return ref;
}

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

297
    TRACE("(%p)->(%d %p)\n", This, dwReserved, pbind);
298 299 300 301

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

302 303
    if(This->window)
        list_add_head(&This->window->bindings, &This->entry);
304

305
    return This->vtbl->start_binding(This);
306 307 308 309
}

static HRESULT WINAPI BindStatusCallback_GetPriority(IBindStatusCallback *iface, LONG *pnPriority)
{
310
    BSCallback *This = impl_from_IBindStatusCallback(iface);
311 312 313 314 315 316
    FIXME("(%p)->(%p)\n", This, pnPriority);
    return E_NOTIMPL;
}

static HRESULT WINAPI BindStatusCallback_OnLowResource(IBindStatusCallback *iface, DWORD reserved)
{
317
    BSCallback *This = impl_from_IBindStatusCallback(iface);
318
    FIXME("(%p)->(%d)\n", This, reserved);
319 320 321 322 323 324
    return E_NOTIMPL;
}

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

327
    TRACE("%p)->(%u %u %u %s)\n", This, ulProgress, ulProgressMax, ulStatusCode,
328
            debugstr_w(szStatusText));
329

330
    return This->vtbl->on_progress(This, ulStatusCode, szStatusText);
331 332 333 334 335
}

static HRESULT WINAPI BindStatusCallback_OnStopBinding(IBindStatusCallback *iface,
        HRESULT hresult, LPCWSTR szError)
{
336
    BSCallback *This = impl_from_IBindStatusCallback(iface);
337
    HRESULT hres;
338

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

341 342
    /* NOTE: IE7 calls GetBindResult here */

343 344
    hres = This->vtbl->stop_binding(This, hresult);

345 346 347 348
    if(This->binding) {
        IBinding_Release(This->binding);
        This->binding = NULL;
    }
349

350 351 352 353 354
    if(This->mon) {
        IMoniker_Release(This->mon);
        This->mon = NULL;
    }

355
    list_remove(&This->entry);
356
    list_init(&This->entry);
357
    This->window = NULL;
358

359
    return hres;
360 361 362 363 364
}

static HRESULT WINAPI BindStatusCallback_GetBindInfo(IBindStatusCallback *iface,
        DWORD *grfBINDF, BINDINFO *pbindinfo)
{
365
    BSCallback *This = impl_from_IBindStatusCallback(iface);
366 367 368 369
    DWORD size;

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

370 371 372 373 374 375 376 377 378 379
    if(!This->bindinfo_ready) {
        HRESULT hres;

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

        This->bindinfo_ready = TRUE;
    }

380
    *grfBINDF = This->bindf;
381 382 383 384 385

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

386
    pbindinfo->cbstgmedData = This->request_data.post_data_len;
387
    pbindinfo->dwCodePage = CP_UTF8;
388
    pbindinfo->dwOptions = This->bindinfo_options;
389

390
    if(This->request_data.post_data_len) {
391 392 393
        pbindinfo->dwBindVerb = BINDVERB_POST;

        pbindinfo->stgmedData.tymed = TYMED_HGLOBAL;
394
        pbindinfo->stgmedData.u.hGlobal = This->request_data.post_data;
395 396
        pbindinfo->stgmedData.pUnkForRelease = (IUnknown*)&This->IBindStatusCallback_iface;
        IBindStatusCallback_AddRef(&This->IBindStatusCallback_iface);
397 398 399 400 401 402 403 404
    }

    return S_OK;
}

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

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

409
    return This->vtbl->read_data(This, pstgmed->u.pstm);
410 411 412 413 414
}

static HRESULT WINAPI BindStatusCallback_OnObjectAvailable(IBindStatusCallback *iface,
        REFIID riid, IUnknown *punk)
{
415
    BSCallback *This = impl_from_IBindStatusCallback(iface);
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
    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
};

434 435 436 437
static inline BSCallback *impl_from_IHttpNegotiate2(IHttpNegotiate2 *iface)
{
    return CONTAINING_RECORD(iface, BSCallback, IHttpNegotiate2_iface);
}
438 439 440 441

static HRESULT WINAPI HttpNegotiate_QueryInterface(IHttpNegotiate2 *iface,
                                                   REFIID riid, void **ppv)
{
442 443
    BSCallback *This = impl_from_IHttpNegotiate2(iface);
    return IBindStatusCallback_QueryInterface(&This->IBindStatusCallback_iface, riid, ppv);
444 445 446 447
}

static ULONG WINAPI HttpNegotiate_AddRef(IHttpNegotiate2 *iface)
{
448 449
    BSCallback *This = impl_from_IHttpNegotiate2(iface);
    return IBindStatusCallback_AddRef(&This->IBindStatusCallback_iface);
450 451 452 453
}

static ULONG WINAPI HttpNegotiate_Release(IHttpNegotiate2 *iface)
{
454 455
    BSCallback *This = impl_from_IHttpNegotiate2(iface);
    return IBindStatusCallback_Release(&This->IBindStatusCallback_iface);
456 457 458 459 460
}

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

464
    TRACE("(%p)->(%s %s %d %p)\n", This, debugstr_w(szURL), debugstr_w(szHeaders),
465 466
          dwReserved, pszAdditionalHeaders);

467 468 469 470 471 472
    *pszAdditionalHeaders = NULL;

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

473
    if(This->request_data.headers) {
474
        DWORD size;
475

476
        size = (lstrlenW(This->request_data.headers)+1)*sizeof(WCHAR);
477 478 479
        *pszAdditionalHeaders = CoTaskMemAlloc(size);
        if(!*pszAdditionalHeaders)
            return E_OUTOFMEMORY;
480
        memcpy(*pszAdditionalHeaders, This->request_data.headers, size);
481
    }
482 483 484 485 486 487 488

    return S_OK;
}

static HRESULT WINAPI HttpNegotiate_OnResponse(IHttpNegotiate2 *iface, DWORD dwResponseCode,
        LPCWSTR szResponseHeaders, LPCWSTR szRequestHeaders, LPWSTR *pszAdditionalRequestHeaders)
{
489
    BSCallback *This = impl_from_IHttpNegotiate2(iface);
490 491

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

494
    return This->vtbl->on_response(This, dwResponseCode, szResponseHeaders);
495 496 497 498 499
}

static HRESULT WINAPI HttpNegotiate_GetRootSecurityId(IHttpNegotiate2 *iface,
        BYTE *pbSecurityId, DWORD *pcbSecurityId, DWORD_PTR dwReserved)
{
500
    BSCallback *This = impl_from_IHttpNegotiate2(iface);
501 502
    TRACE("(%p)->(%p %p %ld)\n", This, pbSecurityId, pcbSecurityId, dwReserved);
    return E_NOTIMPL; /* FIXME */
503 504 505 506 507 508 509 510 511 512 513
}

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

514 515 516 517
static inline BSCallback *impl_from_IInternetBindInfo(IInternetBindInfo *iface)
{
    return CONTAINING_RECORD(iface, BSCallback, IInternetBindInfo_iface);
}
518 519 520 521

static HRESULT WINAPI InternetBindInfo_QueryInterface(IInternetBindInfo *iface,
                                                      REFIID riid, void **ppv)
{
522 523
    BSCallback *This = impl_from_IInternetBindInfo(iface);
    return IBindStatusCallback_QueryInterface(&This->IBindStatusCallback_iface, riid, ppv);
524 525 526 527
}

static ULONG WINAPI InternetBindInfo_AddRef(IInternetBindInfo *iface)
{
528 529
    BSCallback *This = impl_from_IInternetBindInfo(iface);
    return IBindStatusCallback_AddRef(&This->IBindStatusCallback_iface);
530 531 532 533
}

static ULONG WINAPI InternetBindInfo_Release(IInternetBindInfo *iface)
{
534 535
    BSCallback *This = impl_from_IInternetBindInfo(iface);
    return IBindStatusCallback_Release(&This->IBindStatusCallback_iface);
536 537 538 539 540
}

static HRESULT WINAPI InternetBindInfo_GetBindInfo(IInternetBindInfo *iface,
                                                   DWORD *grfBINDF, BINDINFO *pbindinfo)
{
541
    BSCallback *This = impl_from_IInternetBindInfo(iface);
542 543 544 545 546 547 548
    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)
{
549
    BSCallback *This = impl_from_IInternetBindInfo(iface);
550
    FIXME("(%p)->(%u %p %u %p)\n", This, ulStringType, ppwzStr, cEl, pcElFetched);
551 552 553 554 555 556 557 558 559 560 561
    return E_NOTIMPL;
}

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

562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
static inline BSCallback *impl_from_IBindCallbackRedirect(IBindCallbackRedirect *iface)
{
    return CONTAINING_RECORD(iface, BSCallback, IBindCallbackRedirect_iface);
}

static HRESULT WINAPI BindCallbackRedirect_QueryInterface(IBindCallbackRedirect *iface, REFIID riid, void **ppv)
{
    BSCallback *This = impl_from_IBindCallbackRedirect(iface);
    return IBindStatusCallback_QueryInterface(&This->IBindStatusCallback_iface, riid, ppv);
}

static ULONG WINAPI BindCallbackRedirect_AddRef(IBindCallbackRedirect *iface)
{
    BSCallback *This = impl_from_IBindCallbackRedirect(iface);
    return IBindStatusCallback_AddRef(&This->IBindStatusCallback_iface);
}

static ULONG WINAPI BindCallbackRedirect_Release(IBindCallbackRedirect *iface)
{
    BSCallback *This = impl_from_IBindCallbackRedirect(iface);
    return IBindStatusCallback_Release(&This->IBindStatusCallback_iface);
}

static HRESULT WINAPI BindCallbackRedirect_Redirect(IBindCallbackRedirect *iface, const WCHAR *url, VARIANT_BOOL *vbCancel)
{
    BSCallback *This = impl_from_IBindCallbackRedirect(iface);
588
    GeckoBrowser *browser;
589 590 591 592 593 594
    BOOL cancel = FALSE;
    BSTR frame_name = NULL;
    HRESULT hres = S_OK;

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

595 596 597
    if(This->window && This->window->base.outer_window && (browser = This->window->base.outer_window->browser)
       && browser->doc->doc_object_service) {
        if(is_main_content_window(This->window->base.outer_window)) {
598 599 600 601 602
            hres = IHTMLWindow2_get_name(&This->window->base.IHTMLWindow2_iface, &frame_name);
            if(FAILED(hres))
                return hres;
        }

603
        hres = IDocObjectService_FireBeforeNavigate2(browser->doc->doc_object_service, NULL, url, 0x40,
604 605 606 607
                                                     frame_name, NULL, 0, NULL, TRUE, &cancel);
        SysFreeString(frame_name);
    }

608
    *vbCancel = variant_bool(cancel);
609 610 611 612 613 614 615 616 617 618
    return hres;
}

static const IBindCallbackRedirectVtbl BindCallbackRedirectVtbl = {
    BindCallbackRedirect_QueryInterface,
    BindCallbackRedirect_AddRef,
    BindCallbackRedirect_Release,
    BindCallbackRedirect_Redirect
};

619 620 621 622
static inline BSCallback *impl_from_IServiceProvider(IServiceProvider *iface)
{
    return CONTAINING_RECORD(iface, BSCallback, IServiceProvider_iface);
}
623 624 625 626

static HRESULT WINAPI BSCServiceProvider_QueryInterface(IServiceProvider *iface,
                                                        REFIID riid, void **ppv)
{
627
    BSCallback *This = impl_from_IServiceProvider(iface);
628
    return IBindStatusCallback_QueryInterface(&This->IBindStatusCallback_iface, riid, ppv);
629 630 631 632
}

static ULONG WINAPI BSCServiceProvider_AddRef(IServiceProvider *iface)
{
633
    BSCallback *This = impl_from_IServiceProvider(iface);
634
    return IBindStatusCallback_AddRef(&This->IBindStatusCallback_iface);
635 636 637 638
}

static ULONG WINAPI BSCServiceProvider_Release(IServiceProvider *iface)
{
639
    BSCallback *This = impl_from_IServiceProvider(iface);
640
    return IBindStatusCallback_Release(&This->IBindStatusCallback_iface);
641 642 643 644 645
}

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

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

650 651
    if(This->window && IsEqualGUID(guidService, &IID_IWindowForBindingUI))
        return IServiceProvider_QueryService(&This->window->base.IServiceProvider_iface, guidService, riid, ppv);
652
    return E_NOINTERFACE;
653 654 655 656 657 658 659 660 661
}

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

662
void init_bscallback(BSCallback *This, const BSCallbackVtbl *vtbl, IMoniker *mon, DWORD bindf)
663
{
664
    This->IBindStatusCallback_iface.lpVtbl = &BindStatusCallbackVtbl;
665
    This->IServiceProvider_iface.lpVtbl = &ServiceProviderVtbl;
666 667
    This->IHttpNegotiate2_iface.lpVtbl = &HttpNegotiate2Vtbl;
    This->IInternetBindInfo_iface.lpVtbl = &InternetBindInfoVtbl;
668
    This->IBindCallbackRedirect_iface.lpVtbl = &BindCallbackRedirectVtbl;
669 670 671
    This->vtbl = vtbl;
    This->ref = 1;
    This->bindf = bindf;
672
    This->bindinfo_options = BINDINFO_OPTIONS_USE_IE_ENCODING;
673
    This->bom = BOM_NONE;
674

675
    list_init(&This->entry);
676

677 678
    if(mon)
        IMoniker_AddRef(mon);
679
    This->mon = mon;
680 681
}

682
HRESULT read_stream(BSCallback *This, IStream *stream, void *buf, DWORD size, DWORD *ret_size)
683
{
684 685
    DWORD read_size = 0, skip=0;
    BYTE *data = buf;
686 687 688
    HRESULT hres;

    hres = IStream_Read(stream, buf, size, &read_size);
689

690
    if(!This->read && This->bom == BOM_NONE) {
691 692 693 694 695 696 697 698 699 700 701 702 703 704
        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);
        }
    }

705
    This->read += read_size;
706
    *ret_size = read_size;
707 708 709
    return hres;
}

710 711 712 713 714 715 716
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','='};

717
    ptr = wcschr(value, ';');
718 719 720 721
    if(!ptr)
        return;

    ptr++;
722
    while(*ptr && iswspace(*ptr))
723 724
        ptr++;

725 726
    len = lstrlenW(value);
    if(ptr + ARRAY_SIZE(charsetW) < value+len && !wcsnicmp(ptr, charsetW, ARRAY_SIZE(charsetW))) {
727 728 729 730 731
        size_t charset_len, lena;
        nsACString charset_str;
        const WCHAR *charset;
        char *charseta;

732
        ptr += ARRAY_SIZE(charsetW);
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760

        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)));
    }
}

761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
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;
}

794 795 796 797 798 799 800 801 802 803
static HRESULT process_response_headers(nsChannelBSC *This, const WCHAR *headers)
{
    http_header_t *iter;
    HRESULT hres;

    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) {
804
        if(!wcsicmp(iter->header, L"content-type"))
805 806 807 808 809 810
            parse_content_type(This, iter->data);
    }

    return S_OK;
}

811 812 813 814 815 816 817 818 819 820 821 822 823 824 825
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);
826 827
    if(!len) {
        heap_free(buf);
828
        return;
829
    }
830

831
    ptr = wcschr(buf, '\r');
832 833 834 835 836 837 838 839
    if(ptr && ptr[1] == '\n') {
        ptr += 2;
        process_response_headers(This, ptr);
    }

    heap_free(buf);
}

840
HRESULT start_binding(HTMLInnerWindow *inner_window, BSCallback *bscallback, IBindCtx *bctx)
841 842 843 844
{
    IStream *str = NULL;
    HRESULT hres;

845
    TRACE("(%p %p %p)\n", inner_window, bscallback, bctx);
846

847
    bscallback->window = inner_window;
848 849 850

    /* NOTE: IE7 calls IsSystemMoniker here*/

851
    if(bctx) {
852 853 854
        hres = RegisterBindStatusCallback(bctx, &bscallback->IBindStatusCallback_iface, NULL, 0);
        if(SUCCEEDED(hres))
            IBindCtx_AddRef(bctx);
855
    }else {
856
        hres = CreateAsyncBindCtx(0, &bscallback->IBindStatusCallback_iface, NULL, &bctx);
857 858 859
    }

    if(FAILED(hres)) {
860
        bscallback->window = NULL;
861
        return hres;
862 863
    }

864
    hres = IMoniker_BindToStorage(bscallback->mon, bctx, NULL, &IID_IStream, (void**)&str);
865 866
    IBindCtx_Release(bctx);
    if(FAILED(hres)) {
867
        WARN("BindToStorage failed: %08x\n", hres);
868
        bscallback->window = NULL;
869 870 871 872 873 874 875 876
        return hres;
    }

    if(str)
        IStream_Release(str);

    return S_OK;
}
877

878 879
static HRESULT read_post_data_stream(nsIInputStream *stream, BOOL contains_headers, struct list *headers_list,
        request_data_t *request_data)
880
{
881
    nsISeekableStream *seekable_stream;
882
    UINT64 available = 0;
883
    UINT32 data_len = 0;
884 885 886 887
    char *data, *post_data;
    nsresult nsres;
    HRESULT hres = S_OK;

888
    if(!stream)
889 890
        return S_OK;

891
    nsres =  nsIInputStream_Available(stream, &available);
892 893 894
    if(NS_FAILED(nsres))
        return E_FAIL;

895
    post_data = data = GlobalAlloc(0, available+1);
896 897 898
    if(!data)
        return E_OUTOFMEMORY;

899
    nsres = nsIInputStream_Read(stream, data, available, &data_len);
900 901 902 903 904
    if(NS_FAILED(nsres)) {
        GlobalFree(data);
        return E_FAIL;
    }

905
    if(contains_headers) {
906
        if(data_len >= 2 && data[0] == '\r' && data[1] == '\n') {
907 908 909 910 911
            post_data = data+2;
            data_len -= 2;
        }else {
            WCHAR *headers;
            DWORD size;
912 913 914 915 916
            char *ptr;

            post_data += data_len;
            for(ptr = data; ptr+4 < data+data_len; ptr++) {
                if(!memcmp(ptr, "\r\n\r\n", 4)) {
917 918
                    ptr += 2;
                    post_data = ptr+2;
919 920 921
                    break;
                }
            }
922 923 924

            data_len -= post_data-data;

925
            size = MultiByteToWideChar(CP_ACP, 0, data, ptr-data, NULL, 0);
926 927
            headers = heap_alloc((size+1)*sizeof(WCHAR));
            if(headers) {
928
                MultiByteToWideChar(CP_ACP, 0, data, ptr-data, headers, size);
929
                headers[size] = 0;
930 931
                if(headers_list)
                    hres = parse_headers(headers, headers_list);
932
                if(SUCCEEDED(hres))
933
                    request_data->headers = headers;
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
                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;

953
        new_data = GlobalAlloc(0, data_len+1);
954 955 956 957 958 959 960 961
        if(new_data)
            memcpy(new_data, post_data, data_len);
        GlobalFree(data);
        if(!new_data)
            return E_OUTOFMEMORY;
        post_data = new_data;
    }

962 963
    if(post_data)
        post_data[data_len] = 0;
964 965
    request_data->post_data = post_data;
    request_data->post_data_len = data_len;
966 967 968 969 970 971 972 973 974 975 976

    nsres = nsIInputStream_QueryInterface(stream, &IID_nsISeekableStream, (void**)&seekable_stream);
    assert(nsres == NS_OK);

    nsres = nsISeekableStream_Seek(seekable_stream, NS_SEEK_SET, 0);
    assert(nsres == NS_OK);

    nsISeekableStream_Release(seekable_stream);

    nsIInputStream_AddRef(stream);
    request_data->post_stream = stream;
977
    TRACE("post_data = %s\n", debugstr_an(request_data->post_data, request_data->post_data_len));
978 979 980
    return S_OK;
}

981
static HRESULT on_start_nsrequest(nsChannelBSC *This)
982 983 984
{
    nsresult nsres;

985 986
    This->nschannel->binding = This;

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

    nsres = nsIStreamListener_OnStartRequest(This->nslistener,
992
            (nsIRequest*)&This->nschannel->nsIHttpChannel_iface, This->nscontext);
993
    if(NS_FAILED(nsres)) {
994
        FIXME("OnStartRequest failed: %08x\n", nsres);
995 996 997
        return E_FAIL;
    }

998
    if(This->is_doc_channel) {
999 1000
        HRESULT hres;

1001 1002
        if(!This->bsc.window)
            return E_ABORT; /* Binding aborted in OnStartRequest call. */
1003 1004 1005 1006 1007 1008
        hres = update_window_doc(This->bsc.window);
        if(FAILED(hres))
            return hres;

        if(This->bsc.binding)
            process_document_response_headers(This->bsc.window->doc, This->bsc.binding);
1009 1010
        if(This->bsc.window->base.outer_window->readystate != READYSTATE_LOADING)
            set_ready_state(This->bsc.window->base.outer_window, READYSTATE_LOADING);
1011 1012 1013
    }

    return S_OK;
1014 1015
}

1016
static void on_stop_nsrequest(nsChannelBSC *This, HRESULT result)
1017
{
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
    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;
    }
1030

1031 1032
    if(This->nslistener) {
        nsres = nsIStreamListener_OnStopRequest(This->nslistener,
1033 1034
                 (nsIRequest*)&This->nschannel->nsIHttpChannel_iface, This->nscontext,
                 request_result);
1035
        if(NS_FAILED(nsres))
Andrew Eikum's avatar
Andrew Eikum committed
1036
            WARN("OnStopRequest failed: %08x\n", nsres);
1037 1038
    }

1039 1040 1041 1042 1043 1044 1045 1046 1047
    if(This->nschannel) {
        if(This->nschannel->load_group) {
            nsres = nsILoadGroup_RemoveRequest(This->nschannel->load_group,
                    (nsIRequest*)&This->nschannel->nsIHttpChannel_iface, NULL, request_result);
            if(NS_FAILED(nsres))
                ERR("RemoveRequest failed: %08x\n", nsres);
        }
        if(This->nschannel->binding == This)
            This->nschannel->binding = NULL;
1048
    }
1049 1050
}

1051 1052
static HRESULT read_stream_data(nsChannelBSC *This, IStream *stream)
{
1053
    DWORD read;
1054 1055 1056
    nsresult nsres;
    HRESULT hres;

1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
    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);
            }
        }
    }

1070 1071 1072
    if(!This->nschannel)
        return S_OK;

1073 1074 1075 1076
    if(!This->nslistener) {
        BYTE buf[1024];

        do {
1077
            hres = read_stream(&This->bsc, stream, buf, sizeof(buf), &read);
1078 1079 1080 1081 1082
        }while(hres == S_OK && read);

        return S_OK;
    }

1083
    if(!This->nsstream) {
1084
        This->nsstream = create_nsprotocol_stream();
1085 1086 1087
        if(!This->nsstream)
            return E_OUTOFMEMORY;
    }
1088 1089

    do {
1090
        BOOL first_read = !This->bsc.read;
1091 1092

        hres = read_stream(&This->bsc, stream, This->nsstream->buf+This->nsstream->buf_size,
1093 1094
                sizeof(This->nsstream->buf)-This->nsstream->buf_size, &read);
        if(!read)
1095 1096
            break;

1097
        This->nsstream->buf_size += read;
1098

1099
        if(first_read) {
1100 1101
            switch(This->bsc.bom) {
            case BOM_UTF8:
1102
                This->nschannel->charset = heap_strdupA(UTF8_STR);
1103 1104 1105
                break;
            case BOM_UTF16:
                This->nschannel->charset = heap_strdupA(UTF16_STR);
1106 1107
            case BOM_NONE:
                /* FIXME: Get charset from HTTP headers */;
1108
            }
1109

1110 1111 1112
            if(!This->nschannel->content_type) {
                WCHAR *mime;

1113
                hres = FindMimeFromData(NULL, NULL, This->nsstream->buf, This->nsstream->buf_size,
1114
                        This->is_doc_channel ? L"text/html" : NULL, 0, &mime, 0);
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
                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;
            }

1126 1127 1128
            hres = on_start_nsrequest(This);
            if(FAILED(hres))
                return hres;
1129 1130 1131
        }

        nsres = nsIStreamListener_OnDataAvailable(This->nslistener,
1132
                (nsIRequest*)&This->nschannel->nsIHttpChannel_iface, This->nscontext,
1133
                &This->nsstream->nsIInputStream_iface, This->bsc.read-This->nsstream->buf_size,
1134 1135 1136 1137
                This->nsstream->buf_size);
        if(NS_FAILED(nsres))
            ERR("OnDataAvailable failed: %08x\n", nsres);

1138 1139 1140 1141
        if(This->nsstream->buf_size == sizeof(This->nsstream->buf)) {
            ERR("buffer is full\n");
            break;
        }
1142 1143 1144 1145 1146
    }while(hres == S_OK);

    return S_OK;
}

1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
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)) {
1167
        TRACE("(%p)->(IID_nsISupports %p)\n", This, result);
1168 1169 1170 1171 1172 1173
        *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;
1174
        WARN("unimplemented iface %s\n", debugstr_guid(riid));
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
        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);
1201
        nsIHttpChannel_Release(&This->nschannel->nsIHttpChannel_iface);
1202 1203 1204 1205 1206 1207
        heap_free(This);
    }

    return ref;
}

1208
static nsresult NSAPI nsAsyncVerifyRedirectCallback_OnRedirectVerifyCallback(nsIAsyncVerifyRedirectCallback *iface, nsresult result)
1209 1210
{
    nsRedirectCallback *This = impl_from_nsIAsyncVerifyRedirectCallback(iface);
1211 1212
    nsChannel *old_nschannel;
    nsresult nsres;
1213 1214 1215

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

1216
    old_nschannel = This->bsc->nschannel;
1217
    nsIHttpChannel_AddRef(&This->nschannel->nsIHttpChannel_iface);
1218 1219 1220 1221 1222 1223 1224 1225 1226
    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);
    }

1227
    if(This->bsc->is_doc_channel && This->bsc->bsc.window && This->bsc->bsc.window->base.outer_window) {
1228 1229 1230
        IUri *uri = nsuri_get_uri(This->nschannel->uri);

        if(uri) {
1231
            set_current_uri(This->bsc->bsc.window->base.outer_window, uri);
1232 1233 1234 1235 1236 1237
            IUri_Release(uri);
        }else {
            WARN("Could not get IUri from nsWineURI\n");
        }
    }

1238
    if(old_nschannel) {
1239 1240 1241 1242 1243 1244
        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);
        }
1245 1246 1247
        nsIHttpChannel_Release(&old_nschannel->nsIHttpChannel_iface);
    }

1248 1249 1250 1251 1252 1253 1254
    return NS_OK;
}

static const nsIAsyncVerifyRedirectCallbackVtbl nsAsyncVerifyRedirectCallbackVtbl = {
    nsAsyncVerifyRedirectCallback_QueryInterface,
    nsAsyncVerifyRedirectCallback_AddRef,
    nsAsyncVerifyRedirectCallback_Release,
1255
    nsAsyncVerifyRedirectCallback_OnRedirectVerifyCallback
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
};

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;

1269
    nsIHttpChannel_AddRef(&nschannel->nsIHttpChannel_iface);
1270 1271 1272 1273 1274 1275 1276 1277 1278
    callback->nschannel = nschannel;

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

    *ret = callback;
    return S_OK;
}

1279 1280 1281 1282
static inline nsChannelBSC *nsChannelBSC_from_BSCallback(BSCallback *iface)
{
    return CONTAINING_RECORD(iface, nsChannelBSC, bsc);
}
1283 1284 1285

static void nsChannelBSC_destroy(BSCallback *bsc)
{
1286
    nsChannelBSC *This = nsChannelBSC_from_BSCallback(bsc);
1287

1288 1289 1290
    if(This->nschannel) {
        if(This->nschannel->binding == This)
            This->nschannel->binding = NULL;
1291
        nsIHttpChannel_Release(&This->nschannel->nsIHttpChannel_iface);
1292
    }
1293 1294 1295 1296 1297
    if(This->nslistener)
        nsIStreamListener_Release(This->nslistener);
    if(This->nscontext)
        nsISupports_Release(This->nscontext);
    if(This->nsstream)
1298
        nsIInputStream_Release(&This->nsstream->nsIInputStream_iface);
1299 1300 1301 1302 1303
    heap_free(This);
}

static HRESULT nsChannelBSC_start_binding(BSCallback *bsc)
{
1304
    nsChannelBSC *This = nsChannelBSC_from_BSCallback(bsc);
1305

1306 1307
    if(This->is_doc_channel)
        This->bsc.window->base.outer_window->base.inner_window->doc->skip_mutation_notif = FALSE;
1308

1309 1310 1311
    return S_OK;
}

1312 1313
static HRESULT nsChannelBSC_init_bindinfo(BSCallback *bsc)
{
1314
    nsChannelBSC *This = nsChannelBSC_from_BSCallback(bsc);
1315
    nsChannel *nschannel = This->nschannel;
1316
    GeckoBrowser *browser;
1317
    HRESULT hres;
1318

1319
    if(This->is_doc_channel && This->bsc.window && This->bsc.window->base.outer_window
1320 1321
       && (browser = This->bsc.window->base.outer_window->browser)) {
        if(browser->doc->hostinfo.dwFlags & DOCHOSTUIFLAG_ENABLE_REDIRECT_NOTIFICATION)
1322 1323 1324
            This->bsc.bindinfo_options |= BINDINFO_OPTIONS_DISABLEAUTOREDIRECTS;
    }

1325 1326 1327
    if(nschannel && nschannel->post_data_stream) {
        hres = read_post_data_stream(nschannel->post_data_stream, nschannel->post_data_contains_headers,
                &nschannel->request_headers, &This->bsc.request_data);
1328 1329
        if(FAILED(hres))
            return hres;
1330 1331 1332 1333 1334
    }

    return S_OK;
}

1335 1336 1337 1338 1339 1340
typedef struct {
    task_t header;
    nsChannelBSC *bsc;
} stop_request_task_t;

static void stop_request_proc(task_t *_task)
1341
{
1342
    stop_request_task_t *task = (stop_request_task_t*)_task;
1343

1344
    TRACE("(%p)\n", task->bsc);
1345

1346 1347
    list_remove(&task->bsc->bsc.entry);
    list_init(&task->bsc->bsc.entry);
1348
    on_stop_nsrequest(task->bsc, S_OK);
1349 1350 1351 1352 1353 1354
}

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

1355
    IBindStatusCallback_Release(&task->bsc->bsc.IBindStatusCallback_iface);
1356
    heap_free(task);
1357
}
1358

1359 1360 1361 1362
static HRESULT async_stop_request(nsChannelBSC *This)
{
    stop_request_task_t *task;

1363
    if(!This->bsc.read) {
1364 1365 1366 1367
        TRACE("No data read, calling OnStartRequest\n");
        on_start_nsrequest(This);
    }

1368 1369 1370 1371
    task = heap_alloc(sizeof(*task));
    if(!task)
        return E_OUTOFMEMORY;

1372
    IBindStatusCallback_AddRef(&This->bsc.IBindStatusCallback_iface);
1373
    task->bsc = This;
1374

1375
    return push_task(&task->header, stop_request_proc, stop_request_task_destr, This->bsc.window->task_magic);
1376 1377
}

1378 1379
static void handle_navigation_error(nsChannelBSC *This, DWORD result)
{
1380
    HTMLOuterWindow *outer_window;
1381 1382 1383 1384 1385 1386
    HTMLDocumentObj *doc;
    BOOL is_error_url;
    SAFEARRAY *sa;
    SAFEARRAYBOUND bound;
    VARIANT var, varOut;
    LONG ind;
1387
    BSTR unk;
1388 1389
    HRESULT hres;

1390 1391
    if(!This->is_doc_channel || !This->bsc.window || !This->bsc.window->base.outer_window
       || !This->bsc.window->base.outer_window->browser)
1392 1393
        return;

1394
    outer_window = This->bsc.window->base.outer_window;
1395 1396
    doc = outer_window->browser->doc;
    if(!doc->doc_object_service || !doc->client)
1397 1398 1399
        return;

    hres = IDocObjectService_IsErrorUrl(doc->doc_object_service,
1400
            outer_window->url, &is_error_url);
1401 1402 1403
    if(FAILED(hres) || is_error_url)
        return;

1404
    if(!doc->client_cmdtrg)
1405 1406 1407 1408 1409
        return;

    bound.lLbound = 0;
    bound.cElements = 8;
    sa = SafeArrayCreate(VT_VARIANT, 1, &bound);
1410
    if(!sa)
1411 1412 1413 1414 1415 1416 1417 1418 1419
        return;

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

    ind = 1;
    V_VT(&var) = VT_BSTR;
1420
    V_BSTR(&var) = outer_window->url;
1421 1422 1423 1424
    SafeArrayPutElement(sa, &ind, &var);

    ind = 3;
    V_VT(&var) = VT_UNKNOWN;
1425
    V_UNKNOWN(&var) = (IUnknown*)&outer_window->base.IHTMLWindow2_iface;
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458
    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;
1459
    IOleCommandTarget_Exec(doc->client_cmdtrg, &CGID_DocHostCmdPriv, 1, 0, &var, FAILED(hres)?NULL:&varOut);
1460 1461 1462 1463 1464

    SysFreeString(unk);
    SafeArrayDestroy(sa);
}

1465 1466
static HRESULT nsChannelBSC_stop_binding(BSCallback *bsc, HRESULT result)
{
1467
    nsChannelBSC *This = nsChannelBSC_from_BSCallback(bsc);
1468

1469
    if(result != E_ABORT && This->is_doc_channel && This->bsc.window) {
1470 1471
        if(FAILED(result))
            handle_navigation_error(This, result);
1472
        else if(This->nschannel) {
1473 1474 1475 1476
            result = async_stop_request(This);
            if(SUCCEEDED(result))
                return S_OK;
        }
1477 1478
    }

1479
    on_stop_nsrequest(This, result);
1480 1481 1482 1483 1484
    return S_OK;
}

static HRESULT nsChannelBSC_read_data(BSCallback *bsc, IStream *stream)
{
1485
    nsChannelBSC *This = nsChannelBSC_from_BSCallback(bsc);
1486 1487 1488 1489

    return read_stream_data(This, stream);
}

1490 1491 1492 1493 1494
static HRESULT handle_redirect(nsChannelBSC *This, const WCHAR *new_url)
{
    nsRedirectCallback *callback;
    nsIChannelEventSink *sink;
    nsChannel *new_channel;
1495
    IMoniker *mon;
1496 1497 1498 1499 1500
    nsresult nsres;
    HRESULT hres;

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

1501 1502 1503 1504 1505 1506
    hres = CreateURLMoniker(NULL, new_url, &mon);
    if(FAILED(hres))
        return hres;
    IMoniker_Release(This->bsc.mon);
    This->bsc.mon = mon;

1507 1508 1509 1510 1511 1512 1513 1514 1515
    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)) {
1516 1517
        TRACE("%p %p->%p\n", This, This->nschannel, new_channel);

1518
        hres = create_redirect_callback(new_channel, This, &callback);
1519
        nsIHttpChannel_Release(&new_channel->nsIHttpChannel_iface);
1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530
    }

    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");
1531 1532

        nsIAsyncVerifyRedirectCallback_Release(&callback->nsIAsyncVerifyRedirectCallback_iface);
1533 1534 1535 1536 1537 1538
    }

    nsIChannelEventSink_Release(sink);
    return hres;
}

1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
static BOOL is_supported_doc_mime(const WCHAR *mime)
{
    char *nscat, *mimea;
    BOOL ret;

    mimea = heap_strdupWtoA(mime);
    if(!mimea)
        return FALSE;

    nscat = get_nscategory_entry("Gecko-Content-Viewers", mimea);

    ret = nscat != NULL && !strcmp(nscat, "@mozilla.org/content/document-loader-factory;1");

    heap_free(mimea);
    nsfree(nscat);
    return ret;
}

1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
static IUri *get_moniker_uri(IMoniker *mon)
{
    IUriContainer *uri_container;
    IUri *ret = NULL;
    HRESULT hres;

    hres = IMoniker_QueryInterface(mon, &IID_IUriContainer, (void**)&uri_container);
    if(SUCCEEDED(hres)) {
        hres = IUriContainer_GetIUri(uri_container, &ret);
        IUriContainer_Release(uri_container);
        if(FAILED(hres))
            return NULL;
    }else {
        FIXME("No IUriContainer\n");
    }

    return ret;
}

static void handle_extern_mime_navigation(nsChannelBSC *This)
{
1578
    IWebBrowserPriv2IE9 *webbrowser_priv;
1579 1580 1581 1582 1583 1584 1585
    IOleCommandTarget *cmdtrg;
    HTMLDocumentObj *doc_obj;
    IBindCtx *bind_ctx;
    IUri *uri;
    VARIANT flags;
    HRESULT hres;

1586
    if(!This->bsc.window || !This->bsc.window->base.outer_window || !This->bsc.window->base.outer_window->browser)
1587 1588
        return;

1589
    doc_obj = This->bsc.window->base.outer_window->browser->doc;
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618

    hres = IOleClientSite_QueryInterface(doc_obj->client, &IID_IOleCommandTarget, (void**)&cmdtrg);
    if(SUCCEEDED(hres)) {
        IOleCommandTarget_Exec(cmdtrg, &CGID_ShellDocView, 62, 0, NULL, NULL);
        IOleCommandTarget_Release(cmdtrg);
    }

    set_document_navigation(doc_obj, FALSE);

    if(!doc_obj->webbrowser) {
        FIXME("unimplemented in non-webbrowser mode\n");
        return;
    }

    uri = get_moniker_uri(This->bsc.mon);
    if(!uri)
        return;

    hres = CreateBindCtx(0, &bind_ctx);
    if(FAILED(hres)) {
        IUri_Release(uri);
        return;
    }

    V_VT(&flags) = VT_I4;
    V_I4(&flags) = navHyperlink;

    hres = IUnknown_QueryInterface(doc_obj->webbrowser, &IID_IWebBrowserPriv2IE8, (void**)&webbrowser_priv);
    if(SUCCEEDED(hres)) {
1619 1620
        hres = IWebBrowserPriv2IE9_NavigateWithBindCtx2(webbrowser_priv, uri, &flags, NULL, NULL, NULL, bind_ctx, NULL, 0);
        IWebBrowserPriv2IE9_Release(webbrowser_priv);
1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
    }else {
        IWebBrowserPriv *webbrowser_priv_old;
        VARIANT uriv;

        hres = IUnknown_QueryInterface(doc_obj->webbrowser, &IID_IWebBrowserPriv, (void**)&webbrowser_priv_old);
        if(SUCCEEDED(hres)) {
            V_VT(&uriv) = VT_BSTR;
            IUri_GetDisplayUri(uri, &V_BSTR(&uriv));

            hres = IWebBrowserPriv_NavigateWithBindCtx(webbrowser_priv_old, &uriv, &flags, NULL, NULL, NULL, bind_ctx, NULL);

            SysFreeString(V_BSTR(&uriv));
            IWebBrowserPriv_Release(webbrowser_priv_old);
        }
    }

    IUri_Release(uri);
}

1640 1641
static HRESULT nsChannelBSC_on_progress(BSCallback *bsc, ULONG status_code, LPCWSTR status_text)
{
1642
    nsChannelBSC *This = nsChannelBSC_from_BSCallback(bsc);
1643 1644

    switch(status_code) {
1645
    case BINDSTATUS_MIMETYPEAVAILABLE:
1646 1647 1648
        if(This->is_doc_channel && !is_supported_doc_mime(status_text)) {
            FIXME("External MIME: %s\n", debugstr_w(status_text));

1649 1650
            handle_extern_mime_navigation(This);

1651 1652 1653
            This->nschannel = NULL;
        }

1654 1655 1656
        if(!This->nschannel)
            return S_OK;

1657 1658
        heap_free(This->nschannel->content_type);
        This->nschannel->content_type = heap_strdupWtoA(status_text);
1659 1660
        break;
    case BINDSTATUS_REDIRECTING:
1661
        return handle_redirect(This, status_text);
1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681
    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);
    }
1682 1683 1684 1685 1686
    }

    return S_OK;
}

1687 1688
static HRESULT process_response_status_text(const WCHAR *header, const WCHAR *header_end, char **status_text)
{
1689
    header = wcschr(header + 1, ' ');
1690 1691
    if(!header || header >= header_end)
        return E_FAIL;
1692
    header = wcschr(header + 1, ' ');
1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704
    if(!header || header >= header_end)
        return E_FAIL;
    ++header;

    *status_text = heap_strndupWtoU(header, header_end - header);

    if(!*status_text)
        return E_OUTOFMEMORY;

    return S_OK;
}

1705 1706
static HRESULT nsChannelBSC_on_response(BSCallback *bsc, DWORD response_code,
        LPCWSTR response_headers)
1707
{
1708
    nsChannelBSC *This = nsChannelBSC_from_BSCallback(bsc);
1709
    char *str;
1710
    HRESULT hres;
1711

1712
    This->response_processed = TRUE;
1713
    This->nschannel->response_status = response_code;
1714 1715

    if(response_headers) {
1716 1717
        const WCHAR *headers;

1718
        headers = wcschr(response_headers, '\r');
1719 1720 1721 1722 1723 1724 1725 1726 1727
        hres = process_response_status_text(response_headers, headers, &str);
        if(FAILED(hres)) {
            WARN("parsing headers failed: %08x\n", hres);
            return hres;
        }

        heap_free(This->nschannel->response_status_text);
        This->nschannel->response_status_text = str;

1728 1729
        if(headers && headers[1] == '\n') {
            headers += 2;
1730
            hres = process_response_headers(This, headers);
1731 1732
            if(FAILED(hres)) {
                WARN("parsing headers failed: %08x\n", hres);
1733
                return hres;
1734
            }
1735 1736 1737
        }
    }

1738 1739 1740
    return S_OK;
}

1741 1742
static HRESULT nsChannelBSC_beginning_transaction(BSCallback *bsc, WCHAR **additional_headers)
{
1743
    nsChannelBSC *This = nsChannelBSC_from_BSCallback(bsc);
1744 1745 1746 1747 1748 1749 1750 1751
    http_header_t *iter;
    DWORD len = 0;
    WCHAR *ptr;

    if(!This->nschannel)
        return S_FALSE;

    LIST_FOR_EACH_ENTRY(iter, &This->nschannel->request_headers, http_header_t, entry) {
1752
        if(wcscmp(iter->header, L"Content-Length"))
1753
            len += lstrlenW(iter->header) + 2 /* ": " */ + lstrlenW(iter->data) + 2 /* "\r\n" */;
1754 1755 1756 1757 1758 1759 1760 1761 1762 1763
    }

    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) {
1764
        if(!wcscmp(iter->header, L"Content-Length"))
1765 1766
            continue;

1767
        len = lstrlenW(iter->header);
1768 1769 1770 1771 1772 1773
        memcpy(ptr, iter->header, len*sizeof(WCHAR));
        ptr += len;

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

1774
        len = lstrlenW(iter->data);
1775 1776 1777 1778 1779 1780 1781 1782 1783 1784
        memcpy(ptr, iter->data, len*sizeof(WCHAR));
        ptr += len;

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

    *ptr = 0;

    return S_OK;
1785 1786
}

1787 1788
static const BSCallbackVtbl nsChannelBSCVtbl = {
    nsChannelBSC_destroy,
1789
    nsChannelBSC_init_bindinfo,
1790 1791 1792 1793
    nsChannelBSC_start_binding,
    nsChannelBSC_stop_binding,
    nsChannelBSC_read_data,
    nsChannelBSC_on_progress,
1794 1795
    nsChannelBSC_on_response,
    nsChannelBSC_beginning_transaction
1796 1797
};

1798 1799
HRESULT create_channelbsc(IMoniker *mon, const WCHAR *headers, BYTE *post_data, DWORD post_data_size,
        BOOL is_doc_binding, nsChannelBSC **retval)
1800
{
1801
    nsChannelBSC *ret;
1802
    DWORD bindf;
1803 1804 1805 1806

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

1808 1809 1810 1811 1812
    bindf = BINDF_ASYNCHRONOUS | BINDF_ASYNCSTORAGE | BINDF_PULLDATA;
    if(post_data_size)
        bindf |= BINDF_FORMS_SUBMIT | BINDF_PRAGMA_NO_CACHE | BINDF_HYPERLINK | BINDF_GETNEWESTVERSION;

    init_bscallback(&ret->bsc, &nsChannelBSCVtbl, mon, bindf);
1813
    ret->is_doc_channel = is_doc_binding;
1814

1815
    if(headers) {
1816 1817
        ret->bsc.request_data.headers = heap_strdupW(headers);
        if(!ret->bsc.request_data.headers) {
1818
            IBindStatusCallback_Release(&ret->bsc.IBindStatusCallback_iface);
1819 1820 1821 1822 1823
            return E_OUTOFMEMORY;
        }
    }

    if(post_data) {
1824
        ret->bsc.request_data.post_data = GlobalAlloc(0, post_data_size+1);
1825 1826
        if(!ret->bsc.request_data.post_data) {
            release_request_data(&ret->bsc.request_data);
1827
            IBindStatusCallback_Release(&ret->bsc.IBindStatusCallback_iface);
1828 1829 1830
            return E_OUTOFMEMORY;
        }

1831
        memcpy(ret->bsc.request_data.post_data, post_data, post_data_size);
1832
        ((BYTE*)ret->bsc.request_data.post_data)[post_data_size] = 0;
1833
        ret->bsc.request_data.post_data_len = post_data_size;
1834 1835
    }

1836
    TRACE("created %p\n", ret);
1837 1838
    *retval = ret;
    return S_OK;
1839 1840
}

1841 1842
typedef struct {
    task_t header;
1843
    HTMLOuterWindow *window;
1844
    HTMLInnerWindow *pending_window;
1845 1846 1847 1848 1849 1850
} 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;

1851
    set_current_mon(task->window, task->pending_window->bscallback->bsc.mon, BINDING_NAVIGATED);
1852
    start_binding(task->pending_window, &task->pending_window->bscallback->bsc, NULL);
1853 1854 1855 1856 1857 1858
}

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

1859
    IHTMLWindow2_Release(&task->pending_window->base.IHTMLWindow2_iface);
1860
    heap_free(task);
1861 1862
}

1863
HRESULT async_start_doc_binding(HTMLOuterWindow *window, HTMLInnerWindow *pending_window)
1864 1865 1866
{
    start_doc_binding_task_t *task;

1867
    TRACE("%p\n", pending_window);
1868

1869 1870 1871 1872 1873
    task = heap_alloc(sizeof(start_doc_binding_task_t));
    if(!task)
        return E_OUTOFMEMORY;

    task->window = window;
1874 1875
    task->pending_window = pending_window;
    IHTMLWindow2_AddRef(&pending_window->base.IHTMLWindow2_iface);
1876

1877
    return push_task(&task->header, start_doc_binding_proc, start_doc_binding_task_destr, pending_window->task_magic);
1878 1879
}

1880
void abort_window_bindings(HTMLInnerWindow *window)
1881
{
1882 1883
    BSCallback *iter;

1884 1885
    remove_target_tasks(window->task_magic);

1886 1887
    while(!list_empty(&window->bindings)) {
        iter = LIST_ENTRY(window->bindings.next, BSCallback, entry);
1888

1889 1890
        TRACE("Aborting %p\n", iter);

1891 1892
        IBindStatusCallback_AddRef(&iter->IBindStatusCallback_iface);

1893 1894
        if(iter->binding)
            IBinding_Abort(iter->binding);
1895
        else
1896
            iter->vtbl->stop_binding(iter, E_ABORT);
1897

1898
        iter->window = NULL;
1899 1900 1901 1902 1903 1904 1905 1906 1907
        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;
1908
    }
1909 1910 1911 1912 1913

    if(window->mon) {
        IMoniker_Release(window->mon);
        window->mon = NULL;
    }
1914
}
1915

1916
HRESULT channelbsc_load_stream(HTMLInnerWindow *pending_window, IMoniker *mon, IStream *stream)
1917
{
1918
    nsChannelBSC *bscallback = pending_window->bscallback;
1919
    HRESULT hres = S_OK;
1920

1921 1922 1923 1924
    if(!bscallback->nschannel) {
        ERR("NULL nschannel\n");
        return E_FAIL;
    }
1925

1926 1927 1928
    bscallback->nschannel->content_type = heap_strdupA("text/html");
    if(!bscallback->nschannel->content_type)
        return E_OUTOFMEMORY;
1929

1930 1931
    set_current_mon(pending_window->base.outer_window, mon, 0);

1932
    bscallback->bsc.window = pending_window;
1933 1934 1935 1936 1937
    if(stream)
        hres = read_stream_data(bscallback, stream);
    if(SUCCEEDED(hres))
        hres = async_stop_request(bscallback);
    if(FAILED(hres))
1938
        IBindStatusCallback_OnStopBinding(&bscallback->bsc.IBindStatusCallback_iface, hres, NULL);
1939 1940 1941

    return hres;
}
1942

1943
void channelbsc_set_channel(nsChannelBSC *This, nsChannel *channel, nsIStreamListener *listener, nsISupports *context)
1944
{
1945
    nsIHttpChannel_AddRef(&channel->nsIHttpChannel_iface);
1946 1947 1948 1949 1950 1951 1952 1953 1954
    This->nschannel = channel;

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

    if(context) {
        nsISupports_AddRef(context);
        This->nscontext = context;
    }
1955

1956
    if(This->bsc.request_data.headers) {
1957 1958
        HRESULT hres;

1959 1960 1961
        hres = parse_headers(This->bsc.request_data.headers, &channel->request_headers);
        heap_free(This->bsc.request_data.headers);
        This->bsc.request_data.headers = NULL;
1962 1963 1964
        if(FAILED(hres))
            WARN("parse_headers failed: %08x\n", hres);
    }
1965
}
1966

1967 1968
typedef struct {
    task_t header;
1969
    HTMLOuterWindow *window;
1970 1971 1972 1973 1974 1975
    IUri *uri;
} navigate_javascript_task_t;

static void navigate_javascript_proc(task_t *_task)
{
    navigate_javascript_task_t *task = (navigate_javascript_task_t*)_task;
1976
    HTMLOuterWindow *window = task->window;
1977 1978 1979 1980 1981 1982 1983 1984 1985 1986
    VARIANT v;
    BSTR code;
    HRESULT hres;

    task->window->readystate = READYSTATE_COMPLETE;

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

1987 1988 1989 1990 1991 1992
    hres = UrlUnescapeW(code, NULL, NULL, URL_UNESCAPE_INPLACE);
    if(FAILED(hres)) {
        SysFreeString(code);
        return;
    }

1993
    set_download_state(window->browser->doc, 1);
1994 1995

    V_VT(&v) = VT_EMPTY;
1996
    hres = exec_script(window->base.inner_window, code, L"jscript", &v);
1997 1998 1999 2000 2001 2002
    SysFreeString(code);
    if(SUCCEEDED(hres) && V_VT(&v) != VT_EMPTY) {
        FIXME("javascirpt URL returned %s\n", debugstr_variant(&v));
        VariantClear(&v);
    }

2003 2004
    if(window->browser->doc->view_sink)
        IAdviseSink_OnViewChange(window->browser->doc->view_sink, DVASPECT_CONTENT, -1);
2005

2006
    set_download_state(window->browser->doc, 0);
2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018
}

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;
2019
    HTMLOuterWindow *window;
2020
    nsChannelBSC *bscallback;
2021
    DWORD flags;
2022
    IMoniker *mon;
2023
    IUri *uri;
2024 2025 2026 2027 2028 2029 2030
} navigate_task_t;

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

2031
    hres = set_moniker(task->window, task->mon, task->uri, NULL, task->bscallback, TRUE);
2032
    if(SUCCEEDED(hres)) {
2033
        set_current_mon(task->window, task->bscallback->bsc.mon, task->flags);
2034
        set_current_uri(task->window, task->uri);
2035 2036
        start_binding(task->window->pending_window, &task->bscallback->bsc, NULL);
    }
2037 2038 2039 2040 2041 2042
}

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

2043
    IBindStatusCallback_Release(&task->bscallback->bsc.IBindStatusCallback_iface);
2044
    IMoniker_Release(task->mon);
2045
    IUri_Release(task->uri);
2046 2047 2048
    heap_free(task);
}

2049
static HRESULT navigate_fragment(HTMLOuterWindow *window, IUri *uri)
2050 2051 2052
{
    nsIDOMLocation *nslocation;
    nsAString nsfrag_str;
2053
    WCHAR *selector;
2054 2055 2056
    BSTR frag;
    nsresult nsres;
    HRESULT hres;
2057
    static const WCHAR selector_formatW[] = L"a[id=\"%s\"]";
2058

2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074
    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);
2075
    if(NS_FAILED(nsres))
2076
        ERR("SetHash failed: %08x\n", nsres);
2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087

    /*
     * 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;

2088
        swprintf(selector, ARRAY_SIZE(selector_formatW)+SysStringLen(frag), selector_formatW, frag);
2089 2090
        nsAString_InitDepend(&selector_str, selector);
        /* NOTE: Gecko doesn't set result to NULL if there is no match, so nselem must be initialized */
2091
        nsres = nsIDOMHTMLDocument_QuerySelector(window->base.inner_window->doc->nsdoc, &selector_str, &nselem);
2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103
        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);
            }
        }
2104 2105
    }

2106 2107
    SysFreeString(frag);

2108 2109 2110
    if(window->browser->doc->doc_object_service) {
        IDocObjectService_FireNavigateComplete2(window->browser->doc->doc_object_service, &window->base.IHTMLWindow2_iface, 0x10);
        IDocObjectService_FireDocumentComplete(window->browser->doc->doc_object_service, &window->base.IHTMLWindow2_iface, 0);
2111 2112 2113 2114 2115 2116

    }

    return S_OK;
}

2117
HRESULT super_navigate(HTMLOuterWindow *window, IUri *uri, DWORD flags, const WCHAR *headers, BYTE *post_data, DWORD post_data_size)
2118 2119
{
    nsChannelBSC *bsc;
2120
    IUri *uri_nofrag;
2121 2122 2123 2124
    IMoniker *mon;
    DWORD scheme;
    HRESULT hres;

2125 2126 2127 2128
    uri_nofrag = get_uri_nofrag(uri);
    if(!uri_nofrag)
        return E_FAIL;

2129
    if(window->browser->doc->client && !(flags & BINDING_REFRESH)) {
2130 2131
        IOleCommandTarget *cmdtrg;

2132
        hres = IOleClientSite_QueryInterface(window->browser->doc->client, &IID_IOleCommandTarget, (void**)&cmdtrg);
2133 2134 2135 2136
        if(SUCCEEDED(hres)) {
            VARIANT in, out;
            BSTR url_str;

2137
            hres = IUri_GetDisplayUri(uri_nofrag, &url_str);
2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151
            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);
            }
        }
    }

2152
    if(!(flags & BINDING_NOFRAG) && window->uri_nofrag && !post_data_size) {
2153 2154 2155 2156 2157 2158 2159 2160
        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);
        }
2161 2162
    }

2163 2164
    hres = CreateURLMonikerEx2(NULL, uri_nofrag, &mon, URL_MK_UNIFORM);
    IUri_Release(uri_nofrag);
2165 2166 2167 2168 2169 2170
    if(FAILED(hres))
        return hres;

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

2171
    hres = create_channelbsc(mon, headers, post_data, post_data_size, TRUE, &bsc);
2172 2173 2174 2175 2176
    if(FAILED(hres)) {
        IMoniker_Release(mon);
        return hres;
    }

2177
    prepare_for_binding(&window->browser->doc->basedoc, mon, flags);
2178 2179

    hres = IUri_GetScheme(uri, &scheme);
2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192
    if(SUCCEEDED(hres) && scheme == URL_SCHEME_JAVASCRIPT) {
        navigate_javascript_task_t *task;

        IBindStatusCallback_Release(&bsc->bsc.IBindStatusCallback_iface);
        IMoniker_Release(mon);

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

        /* Why silently? */
        window->readystate = READYSTATE_COMPLETE;
        if(!(flags & BINDING_FROMHIST))
2193
            call_docview_84(window->browser->doc);
2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205

        IUri_AddRef(uri);
        task->window = window;
        task->uri = uri;
        hres = push_task(&task->header, navigate_javascript_proc, navigate_javascript_task_destr, window->task_magic);
    }else if(flags & BINDING_SUBMIT) {
        hres = set_moniker(window, mon, uri, NULL, bsc, TRUE);
        if(SUCCEEDED(hres))
            hres = start_binding(window->pending_window, &bsc->bsc, NULL);
        IBindStatusCallback_Release(&bsc->bsc.IBindStatusCallback_iface);
        IMoniker_Release(mon);
    }else {
2206 2207 2208 2209
        navigate_task_t *task;

        task = heap_alloc(sizeof(*task));
        if(!task) {
2210
            IBindStatusCallback_Release(&bsc->bsc.IBindStatusCallback_iface);
2211 2212 2213 2214
            IMoniker_Release(mon);
            return E_OUTOFMEMORY;
        }

2215 2216
        /* Silently and repeated when real loading starts? */
        window->readystate = READYSTATE_LOADING;
2217
        if(!(flags & (BINDING_FROMHIST|BINDING_REFRESH)))
2218
            call_docview_84(window->browser->doc);
2219

2220 2221
        task->window = window;
        task->bscallback = bsc;
2222
        task->flags = flags;
2223
        task->mon = mon;
2224 2225 2226

        IUri_AddRef(uri);
        task->uri = uri;
2227
        hres = push_task(&task->header, navigate_proc, navigate_task_destr, window->task_magic);
2228 2229
    }

2230
    return hres;
2231 2232
}

2233
HRESULT navigate_new_window(HTMLOuterWindow *window, IUri *uri, const WCHAR *name, request_data_t *request_data, IHTMLWindow2 **ret)
2234
{
2235 2236
    INewWindowManager *new_window_mgr;
    BSTR display_uri, context_url;
2237 2238 2239 2240 2241 2242
    IWebBrowser2 *web_browser;
    IHTMLWindow2 *new_window;
    IBindCtx *bind_ctx;
    nsChannelBSC *bsc;
    HRESULT hres;

2243 2244 2245 2246 2247
    if(!window->browser)
        return E_UNEXPECTED;

    if (window->browser->doc->client) {
        hres = do_query_service((IUnknown*)window->browser->doc->client, &SID_SNewWindowManager,
2248 2249 2250 2251 2252 2253
                                &IID_INewWindowManager, (void**)&new_window_mgr);
        if (FAILED(hres)) {
            FIXME("No INewWindowManager\n");
            return hres;
        }

2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264
        hres = IUri_GetDisplayUri(window->uri_nofrag, &context_url);
        if(FAILED(hres))
            return hres;

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

        hres = INewWindowManager_EvaluateNewWindow(new_window_mgr, display_uri, name, context_url,
2265 2266
                NULL, FALSE, window->browser->doc->has_popup ? 0 : NWMF_FIRST, 0);
        window->browser->doc->has_popup = TRUE;
2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277
        SysFreeString(display_uri);
        SysFreeString(context_url);
        INewWindowManager_Release(new_window_mgr);
        if(FAILED(hres)) {
            if(ret)
                *ret = NULL;
            return S_OK;
        }
    }


2278 2279 2280 2281 2282 2283
    if(request_data)
        hres = create_channelbsc(NULL, request_data->headers,
                request_data->post_data, request_data->post_data_len, FALSE,
                &bsc);
    else
        hres = create_channelbsc(NULL, NULL, NULL, 0, FALSE, &bsc);
2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297
    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;

2298
        hres = IWebBrowser2_QueryInterface(web_browser, &IID_ITargetFramePriv2, (void**)&target_frame_priv);
2299 2300 2301
        if(SUCCEEDED(hres)) {
            hres = ITargetFramePriv2_AggregatedNavigation2(target_frame_priv,
                    HLNF_DISABLEWINDOWRESTRICTIONS|HLNF_OPENINNEWWINDOW, bind_ctx, &bsc->bsc.IBindStatusCallback_iface,
2302
                    name, uri, L"");
2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323
            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);

2324 2325 2326 2327
    if(ret)
        *ret = new_window;
    else
        IHTMLWindow2_Release(new_window);
2328 2329 2330
    return S_OK;
}

2331
HRESULT hlink_frame_navigate(HTMLDocument *doc, LPCWSTR url, nsChannel *nschannel, DWORD hlnf, BOOL *cancel)
2332
{
2333
    IHlinkFrame *hlink_frame;
2334
    nsChannelBSC *callback;
2335 2336 2337
    IBindCtx *bindctx;
    IMoniker *mon;
    IHlink *hlink;
2338 2339
    HRESULT hres;

2340 2341
    *cancel = FALSE;

2342
    hres = do_query_service((IUnknown*)doc->doc_obj->client, &IID_IHlinkFrame, &IID_IHlinkFrame,
2343 2344
            (void**)&hlink_frame);
    if(FAILED(hres))
2345
        return S_OK;
2346

2347
    hres = create_channelbsc(NULL, NULL, NULL, 0, FALSE, &callback);
2348 2349 2350 2351
    if(FAILED(hres)) {
        IHlinkFrame_Release(hlink_frame);
        return hres;
    }
2352

2353
    if(nschannel)
2354 2355
        read_post_data_stream(nschannel->post_data_stream, nschannel->post_data_contains_headers,
                &nschannel->request_headers, &callback->bsc.request_data);
2356

2357
    hres = CreateAsyncBindCtx(0, &callback->bsc.IBindStatusCallback_iface, NULL, &bindctx);
2358
    if(SUCCEEDED(hres))
2359
       hres = CoCreateInstance(&CLSID_StdHlink, NULL, CLSCTX_INPROC_SERVER,
2360
                &IID_IHlink, (LPVOID*)&hlink);
2361

2362 2363
    if(SUCCEEDED(hres))
        hres = CreateURLMoniker(NULL, url, &mon);
2364

2365
    if(SUCCEEDED(hres)) {
2366
        IHlink_SetMonikerReference(hlink, HLINKSETF_TARGET, mon, NULL);
2367 2368

        if(hlnf & HLNF_OPENINNEWWINDOW) {
2369
            IHlink_SetTargetFrameName(hlink, L"_blank"); /* FIXME */
2370 2371
        }

2372 2373
        hres = IHlinkFrame_Navigate(hlink_frame, hlnf, bindctx,
                &callback->bsc.IBindStatusCallback_iface, hlink);
2374
        IMoniker_Release(mon);
2375 2376
        *cancel = hres == S_OK;
        hres = S_OK;
2377 2378
    }

2379
    IHlinkFrame_Release(hlink_frame);
2380
    IBindCtx_Release(bindctx);
2381
    IBindStatusCallback_Release(&callback->bsc.IBindStatusCallback_iface);
2382
    return hres;
2383
}
2384

2385 2386
static HRESULT navigate_uri(HTMLOuterWindow *window, IUri *uri, const WCHAR *display_uri, const request_data_t *request_data,
        DWORD flags)
2387
{
2388
    nsWineURI *nsuri;
2389 2390
    HRESULT hres;

2391 2392
    TRACE("%s\n", debugstr_w(display_uri));

2393 2394 2395 2396
    if(!window->browser)
        return E_UNEXPECTED;

    if(window->browser->doc->webbrowser) {
2397 2398 2399 2400
        DWORD post_data_len = request_data ? request_data->post_data_len : 0;
        void *post_data = post_data_len ? request_data->post_data : NULL;
        const WCHAR *headers = request_data ? request_data->headers : NULL;

2401
        if(!(flags & BINDING_REFRESH)) {
2402
            BSTR frame_name = NULL;
2403
            BOOL cancel = FALSE;
2404

2405
            if(!is_main_content_window(window)) {
2406 2407 2408 2409 2410
                hres = IHTMLWindow2_get_name(&window->base.IHTMLWindow2_iface, &frame_name);
                if(FAILED(hres))
                    return hres;
            }

2411
            hres = IDocObjectService_FireBeforeNavigate2(window->browser->doc->doc_object_service, NULL, display_uri, 0x40,
2412 2413
                    frame_name, post_data, post_data_len ? post_data_len+1 : 0, headers, TRUE, &cancel);
            SysFreeString(frame_name);
2414 2415 2416 2417
            if(SUCCEEDED(hres) && cancel) {
                TRACE("Navigation canceled\n");
                return S_OK;
            }
2418 2419
        }

2420
        if(is_main_content_window(window))
2421
            return super_navigate(window, uri, flags, headers, post_data, post_data_len);
2422 2423
    }

2424
    if(is_main_content_window(window)) {
2425 2426
        BOOL cancel;

2427
        hres = hlink_frame_navigate(&window->base.inner_window->doc->basedoc, display_uri, NULL, 0, &cancel);
2428 2429 2430 2431 2432
        if(FAILED(hres))
            return hres;

        if(cancel) {
            TRACE("Navigation handled by hlink frame\n");
2433
            return S_OK;
2434
        }
2435
    }
2436

2437
    hres = create_doc_uri(uri, &nsuri);
2438 2439 2440
    if(FAILED(hres))
        return hres;

2441
    hres = load_nsuri(window, nsuri, request_data ? request_data->post_stream : NULL, NULL, LOAD_FLAGS_NONE);
2442 2443 2444 2445
    nsISupports_Release((nsISupports*)nsuri);
    return hres;
}

2446 2447 2448 2449 2450 2451 2452 2453 2454
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;

2455
    hres = navigate_uri(window, uri, display_uri, NULL, flags);
2456 2457 2458 2459
    SysFreeString(display_uri);
    return hres;
}

2460
static HRESULT translate_uri(HTMLOuterWindow *window, IUri *orig_uri, BSTR *ret_display_uri, IUri **ret_uri)
2461
{
2462
    IUri *uri = NULL;
2463 2464 2465
    BSTR display_uri;
    HRESULT hres;

2466
    hres = IUri_GetDisplayUri(orig_uri, &display_uri);
2467
    if(FAILED(hres))
2468 2469
        return hres;

2470
    if(window->browser->doc->hostui) {
2471 2472
        OLECHAR *translated_url = NULL;

2473
        hres = IDocHostUIHandler_TranslateUrl(window->browser->doc->hostui, 0, display_uri,
2474
                &translated_url);
2475
        if(hres == S_OK && translated_url) {
2476 2477
            TRACE("%08x %s -> %s\n", hres, debugstr_w(display_uri), debugstr_w(translated_url));
            SysFreeString(display_uri);
2478
            hres = create_uri(translated_url, 0, &uri);
2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490
            CoTaskMemFree(translated_url);
            if(FAILED(hres))
                return hres;

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

2491 2492 2493 2494 2495 2496 2497 2498 2499 2500
    if(!uri) {
        IUri_AddRef(orig_uri);
        uri = orig_uri;
    }

    *ret_display_uri = display_uri;
    *ret_uri = uri;
    return S_OK;
}

2501
HRESULT submit_form(HTMLOuterWindow *window, const WCHAR *target, IUri *submit_uri, nsIInputStream *post_stream)
2502 2503 2504 2505 2506 2507 2508 2509
{
    request_data_t request_data = {NULL};
    HRESULT hres;

    hres = read_post_data_stream(post_stream, TRUE, NULL, &request_data);
    if(FAILED(hres))
        return hres;

2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526
    if(window) {
        IUri *uri;
        BSTR display_uri;

        window->readystate_locked++;

        hres = translate_uri(window, submit_uri, &display_uri, &uri);
        if(SUCCEEDED(hres)) {
            hres = navigate_uri(window, uri, display_uri, &request_data, BINDING_NAVIGATED|BINDING_SUBMIT);
            IUri_Release(uri);
            SysFreeString(display_uri);
        }

        window->readystate_locked--;
    }else
        hres = navigate_new_window(window, submit_uri, target, &request_data, NULL);

2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548
    release_request_data(&request_data);
    return hres;
}

HRESULT navigate_url(HTMLOuterWindow *window, const WCHAR *new_url, IUri *base_uri, DWORD flags)
{
    IUri *uri, *nav_uri;
    BSTR display_uri;
    HRESULT hres;

    if(new_url && base_uri)
        hres = CoInternetCombineUrlEx(base_uri, new_url, URL_ESCAPE_SPACES_ONLY|URL_DONT_ESCAPE_EXTRA_INFO,
                &nav_uri, 0);
    else
        hres = create_uri(new_url, 0, &nav_uri);
    if(FAILED(hres))
        return hres;

    hres = translate_uri(window, nav_uri, &display_uri, &uri);
    IUri_Release(nav_uri);
    if(FAILED(hres))
        return hres;
2549

2550
    hres = navigate_uri(window, uri, display_uri, NULL, flags);
2551 2552
    IUri_Release(uri);
    SysFreeString(display_uri);
2553
    return hres;
2554
}