EmbedPromptService.cpp 29.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#define LOG_COMPONENT "EmbedPromptService"
#include "mozilla/embedlite/EmbedLog.h"

#include "EmbedPromptService.h"

#include "nsStringGlue.h"
#include "nsIAuthPrompt.h"
#include "nsISupportsImpl.h"
14
#include "nsThreadUtils.h"
15
#include "nsIDOMWindowUtils.h"
16
#include "nsIThread.h"
17 18 19 20 21 22 23 24 25 26 27 28 29
#include "nsIInterfaceRequestorUtils.h"
#include "nsIInterfaceRequestor.h"
#include "nsIURI.h"
#include "nsServiceManagerUtils.h"
#include "nsILoadContext.h"
#include "nsIAuthInformation.h"
#include "nsICancelable.h"
#include "nsIAuthPromptCallback.h"
#include "nsIIOService.h"
#include "nsNetCID.h"
#include "nsIProtocolHandler.h"
#include "nsIDOMWindow.h"
#include "nsIEmbedLiteJSON.h"
30
#include "nsIObserverService.h"
31
#include "nsIWindowWatcher.h"
32 33 34 35
#include "nsILoginManager.h"
#include "nsILoginInfo.h"
#include "nsComponentManagerUtils.h"
#include "nsMemory.h"
36 37 38 39 40

// Prompt Factory Implementation

using namespace mozilla::embedlite;

41 42 43 44 45 46 47 48 49 50 51 52
EmbedPromptOuterObserver::EmbedPromptOuterObserver(IDestroyNotification* aNotifier, nsIDOMWindow* aWin)
  : mNotifier(aNotifier)
  , mWin(aWin)
{
    mService = do_GetService(NS_OBSERVERSERVICE_CONTRACTID);
    if (mService) {
        mService->AddObserver(this, "outer-window-destroyed", false);
    }
}

void EmbedPromptOuterObserver::OnDestroy()
{
Tatiana Meshkova's avatar
Tatiana Meshkova committed
53 54 55
    if (mService) {
        mService->RemoveObserver(this, "outer-window-destroyed");
    }
56 57 58 59 60 61 62
}

EmbedPromptOuterObserver::~EmbedPromptOuterObserver()
{
    OnDestroy();
}

63
NS_IMPL_ISUPPORTS(EmbedPromptOuterObserver, nsIObserver, nsISupportsWeakReference)
64 65 66 67

NS_IMETHODIMP
EmbedPromptOuterObserver::Observe(nsISupports *aSubject,
                                  const char *aTopic,
68
                                  const char16_t *aData)
69 70 71
{
    if (!strcmp(aTopic, "outer-window-destroyed")) {
        OnDestroy();
Tatiana Meshkova's avatar
Tatiana Meshkova committed
72 73 74
        if (mNotifier) {
            mNotifier->OnDestroyNotification();
        }
75 76 77 78
    }
    return NS_OK;
}

79 80 81 82 83 84 85 86
EmbedPromptFactory::EmbedPromptFactory()
{
}

EmbedPromptFactory::~EmbedPromptFactory()
{
}

87
NS_IMPL_ISUPPORTS(EmbedPromptFactory, nsIPromptFactory)
88 89 90 91 92


NS_IMETHODIMP
EmbedPromptFactory::GetPrompt(nsIDOMWindow* aParent, const nsIID& iid, void **result)
{
93 94 95 96 97 98 99 100 101 102 103
    nsCOMPtr<nsIDOMWindow> parent(aParent);
    if (!parent) { // if no parent provided, consult the window watcher:
        nsresult rv;
        nsCOMPtr<nsIWindowWatcher> wwatcher = do_GetService(NS_WINDOWWATCHER_CONTRACTID, &rv);
        NS_ENSURE_SUCCESS(rv, rv);
        wwatcher->GetActiveWindow(getter_AddRefs(parent));
        if (!parent) {
            return NS_ERROR_FAILURE;
        }
    }

104 105
    if (iid.Equals(NS_GET_IID(nsIAuthPrompt)) ||
        iid.Equals(NS_GET_IID(nsIAuthPrompt2))) {
106
        nsRefPtr<EmbedAuthPromptService> service = new EmbedAuthPromptService(parent);
107
        *result = service.forget().take();
108
    } else if (iid.Equals(NS_GET_IID(nsIPrompt))) {
109
        nsRefPtr<EmbedPromptService> service = new EmbedPromptService(parent);
110
        *result = service.forget().take();
111 112 113 114 115 116 117 118 119 120 121 122
    }

    return NS_OK;
}

// Prompt Service Implementation

EmbedPromptService::EmbedPromptService(nsIDOMWindow* aWin)
  : mWin(aWin)
  , mModalDepth(0)
{
    mService = do_GetService("@mozilla.org/embedlite-app-service;1");
123 124 125 126 127 128 129
    mOuterService = new EmbedPromptOuterObserver(this, aWin);
}

void
EmbedPromptService::OnDestroyNotification()
{
    CancelResponse();
130 131 132 133
}

EmbedPromptService::~EmbedPromptService()
{
Tatiana Meshkova's avatar
Tatiana Meshkova committed
134 135 136
    if (mOuterService) {
        mOuterService->OnDestroy();
    }
137 138
}

139
NS_IMPL_ISUPPORTS(EmbedPromptService, nsIPrompt, nsIEmbedMessageListener)
140 141

NS_IMETHODIMP
142 143
EmbedPromptService::Alert(const char16_t* aDialogTitle, 
                          const char16_t* aDialogText)
144 145 146 147 148
{
    AlertCheck(aDialogTitle, aDialogText, nullptr, nullptr);
    return NS_OK;
}

149 150 151 152 153 154 155 156 157
void
EmbedPromptService::CancelResponse()
{
    std::map<uint32_t, EmbedPromptResponse>::iterator it;
    for (it = mResponseMap.begin(); it != mResponseMap.end(); it++) {
        mModalDepth--;
    }
}

158
NS_IMETHODIMP
159
EmbedPromptService::OnMessageReceived(const char* messageName, const char16_t* message)
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
{
    nsCOMPtr<nsIEmbedLiteJSON> json = do_GetService("@mozilla.org/embedlite-json;1");
    nsCOMPtr<nsIPropertyBag2> root;
    NS_ENSURE_SUCCESS(json->ParseJSON(nsDependentString(message), getter_AddRefs(root)), NS_ERROR_FAILURE);

    uint32_t winid = 0;
    root->GetPropertyAsUint32(NS_LITERAL_STRING("winid"), &winid);

    std::map<uint32_t, EmbedPromptResponse>::iterator it =
        mResponseMap.find(winid);
    if (it == mResponseMap.end())
        return NS_ERROR_FAILURE;
    EmbedPromptResponse& response = it->second;

    nsString promptValue;
    root->GetPropertyAsAString(NS_LITERAL_STRING("promptvalue"), response.promptvalue);
    root->GetPropertyAsBool(NS_LITERAL_STRING("accepted"), &response.accepted);
    root->GetPropertyAsBool(NS_LITERAL_STRING("checkvalue"), &response.checkvalue);

    mModalDepth--;

    return NS_OK;
}

184 185 186 187 188
uint32_t
EmbedPromptService::CheckWinID()
{
    uint32_t winid = 0;
    mService->GetIDByWindow(mWin, &winid);
Tatiana Meshkova's avatar
Tatiana Meshkova committed
189
    if (!winid && mOuterService) {
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
        mOuterService->OnDestroy();
        mOuterService = nullptr;
    }
    return winid;
}

uint32_t
EmbedAuthPromptService::CheckWinID()
{
    uint32_t winid = 0;
    mService->GetIDByWindow(mWin, &winid);
    if (!winid) {
        mOuterService->OnDestroy();
        mOuterService = nullptr;
    }
    return winid;
}


209
NS_IMETHODIMP
210 211 212
EmbedPromptService::AlertCheck(const char16_t* aDialogTitle,
                               const char16_t* aDialogText,
                               const char16_t* aCheckMsg, bool* aCheckValue)
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
{
    uint32_t winid;
    mService->GetIDByWindow(mWin, &winid);

    nsString sendString;
    // Just simple property bag support still
    nsCOMPtr<nsIEmbedLiteJSON> json = do_GetService("@mozilla.org/embedlite-json;1");
    nsCOMPtr<nsIWritablePropertyBag2> root;
    json->CreateObject(getter_AddRefs(root));
    root->SetPropertyAsAString(NS_LITERAL_STRING("title"), nsDependentString(aDialogTitle));
    root->SetPropertyAsAString(NS_LITERAL_STRING("text"), nsDependentString(aDialogText));
    root->SetPropertyAsUint32(NS_LITERAL_STRING("winid"), winid);
    if (aCheckMsg && aCheckValue) {
        root->SetPropertyAsAString(NS_LITERAL_STRING("checkmsg"), nsDependentString(aCheckMsg));
        root->SetPropertyAsBool(NS_LITERAL_STRING("checkmsgval"), *aCheckValue);
    }
    json->CreateJSON(root, sendString);

    mResponseMap[winid] = EmbedPromptResponse();

    mService->SendAsyncMessage(winid, NS_LITERAL_STRING("embed:alert").get(), sendString.get());
    mService->AddMessageListener("alertresponse", this);

    nsresult rv(NS_OK);

    mService->EnterSecureJSContext();

    nsCOMPtr<nsIDOMWindowUtils> utils = do_GetInterface(mWin);
    NS_ENSURE_TRUE(utils, NS_ERROR_FAILURE);

243
    rv = utils->EnterModalState();
244 245 246 247 248 249 250 251

    mModalDepth++;
    int origModalDepth = mModalDepth;
    nsCOMPtr<nsIThread> thread;
    NS_GetCurrentThread(getter_AddRefs(thread));
    while (mModalDepth == origModalDepth && NS_SUCCEEDED(rv)) {
        bool processedEvent;
        rv = thread->ProcessNextEvent(true, &processedEvent);
252
        if (NS_SUCCEEDED(rv) && (!processedEvent || !CheckWinID())) {
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
            rv = NS_ERROR_UNEXPECTED;
        }
    }
    mService->RemoveMessageListener("alertresponse", this);

    std::map<uint32_t, EmbedPromptResponse>::iterator it = mResponseMap.find(winid);
    if (it == mResponseMap.end()) {
        return NS_ERROR_UNEXPECTED;
    }

    if (!it->second.accepted) {
        NS_WARNING("Alert not accepted");
    }

    if (aCheckValue) {
        *aCheckValue = it->second.checkvalue;
    }

    mResponseMap.erase(it);

273
    rv = utils->LeaveModalState();
274 275 276 277 278 279 280

    mService->LeaveSecureJSContext();

    return NS_OK;
}

NS_IMETHODIMP
281 282
EmbedPromptService::Confirm(const char16_t* aDialogTitle,
                            const char16_t* aDialogText, bool* aConfirm)
283 284 285 286 287 288 289
{
    ConfirmCheck(aDialogTitle,
                 aDialogText, nullptr, nullptr, aConfirm);
    return NS_OK;
}

NS_IMETHODIMP
290 291 292
EmbedPromptService::ConfirmCheck(const char16_t* aDialogTitle,
                                 const char16_t* aDialogText,
                                 const char16_t* aCheckMsg,
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
                                 bool* aCheckValue, bool* aConfirm)
{
    uint32_t winid;
    mService->GetIDByWindow(mWin, &winid);

    nsString sendString;
    // Just simple property bag support still
    nsCOMPtr<nsIEmbedLiteJSON> json = do_GetService("@mozilla.org/embedlite-json;1");
    nsCOMPtr<nsIWritablePropertyBag2> root;
    json->CreateObject(getter_AddRefs(root));
    root->SetPropertyAsAString(NS_LITERAL_STRING("title"), nsDependentString(aDialogTitle));
    root->SetPropertyAsAString(NS_LITERAL_STRING("text"), nsDependentString(aDialogText));
    root->SetPropertyAsUint32(NS_LITERAL_STRING("winid"), winid);
    if (aCheckMsg && aCheckValue) {
        root->SetPropertyAsAString(NS_LITERAL_STRING("checkmsg"), nsDependentString(aCheckMsg));
        root->SetPropertyAsBool(NS_LITERAL_STRING("checkmsgval"), *aCheckValue);
    }
    if (aConfirm) {
        root->SetPropertyAsBool(NS_LITERAL_STRING("confirmval"), *aConfirm);
    }

    json->CreateJSON(root, sendString);

    mResponseMap[winid] = EmbedPromptResponse();

    mService->SendAsyncMessage(winid, NS_LITERAL_STRING("embed:confirm").get(), sendString.get());
    mService->AddMessageListener("confirmresponse", this);

    nsresult rv(NS_OK);

    mService->EnterSecureJSContext();

    nsCOMPtr<nsIDOMWindowUtils> utils = do_GetInterface(mWin);
    NS_ENSURE_TRUE(utils, NS_ERROR_FAILURE);

328
    rv = utils->EnterModalState();
329 330 331 332 333 334 335 336

    mModalDepth++;
    int origModalDepth = mModalDepth;
    nsCOMPtr<nsIThread> thread;
    NS_GetCurrentThread(getter_AddRefs(thread));
    while (mModalDepth == origModalDepth && NS_SUCCEEDED(rv)) {
        bool processedEvent;
        rv = thread->ProcessNextEvent(true, &processedEvent);
337
        if (NS_SUCCEEDED(rv) && (!processedEvent || !CheckWinID())) {
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
            rv = NS_ERROR_UNEXPECTED;
        }
    }
    mService->RemoveMessageListener("confirmresponse", this);

    std::map<uint32_t, EmbedPromptResponse>::iterator it = mResponseMap.find(winid);
    if (it == mResponseMap.end()) {
        return NS_ERROR_UNEXPECTED;
    }

    if (!it->second.accepted) {
        NS_WARNING("Alert not accepted");
    }

    if (aCheckValue) {
        *aCheckValue = it->second.checkvalue;
    }

    if (aConfirm) {
        *aConfirm = it->second.accepted;
    }

    mResponseMap.erase(it);

362
    rv = utils->LeaveModalState();
363 364 365 366 367 368 369

    mService->LeaveSecureJSContext();

    return NS_OK;
}

NS_IMETHODIMP
370 371
EmbedPromptService::ConfirmEx(const char16_t* aDialogTitle,
                              const char16_t* aDialogText,
372
                              PRUint32 aButtonFlags,
373 374 375 376
                              const char16_t* aButton0Title,
                              const char16_t* aButton1Title,
                              const char16_t* aButton2Title,
                              const char16_t* aCheckMsg, bool* aCheckValue,
377 378 379 380 381 382 383
                              PRInt32* aRetVal)
{
//    LOGNI();
    return NS_OK;
}

NS_IMETHODIMP
384 385 386
EmbedPromptService::Prompt(const char16_t* aDialogTitle,
                           const char16_t* aDialogText, char16_t** aValue,
                           const char16_t* aCheckMsg, bool* aCheckValue,
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
                           bool* aConfirm)
{
    uint32_t winid;
    mService->GetIDByWindow(mWin, &winid);

    nsString sendString;
    // Just simple property bag support still
    nsCOMPtr<nsIEmbedLiteJSON> json = do_GetService("@mozilla.org/embedlite-json;1");
    nsCOMPtr<nsIWritablePropertyBag2> root;
    json->CreateObject(getter_AddRefs(root));
    root->SetPropertyAsAString(NS_LITERAL_STRING("title"), nsDependentString(aDialogTitle));
    root->SetPropertyAsAString(NS_LITERAL_STRING("text"), nsDependentString(aDialogText));
    root->SetPropertyAsUint32(NS_LITERAL_STRING("winid"), winid);
    if (aCheckMsg && aCheckValue) {
        root->SetPropertyAsAString(NS_LITERAL_STRING("checkmsg"), nsDependentString(aCheckMsg));
        root->SetPropertyAsBool(NS_LITERAL_STRING("checkmsgval"), *aCheckValue);
    }
    if (aConfirm) {
        root->SetPropertyAsBool(NS_LITERAL_STRING("confirmval"), *aConfirm);
    }
    if (aValue) {
        root->SetPropertyAsAString(NS_LITERAL_STRING("defaultValue"), nsDependentString(*aValue));
    }
    json->CreateJSON(root, sendString);

    mResponseMap[winid] = EmbedPromptResponse();

    mService->SendAsyncMessage(winid, NS_LITERAL_STRING("embed:prompt").get(), sendString.get());
    mService->AddMessageListener("promptresponse", this);

    nsresult rv(NS_OK);

    mService->EnterSecureJSContext();

    nsCOMPtr<nsIDOMWindowUtils> utils = do_GetInterface(mWin);
    NS_ENSURE_TRUE(utils, NS_ERROR_FAILURE);

424
    rv = utils->EnterModalState();
425 426 427 428 429 430 431 432

    mModalDepth++;
    int origModalDepth = mModalDepth;
    nsCOMPtr<nsIThread> thread;
    NS_GetCurrentThread(getter_AddRefs(thread));
    while (mModalDepth == origModalDepth && NS_SUCCEEDED(rv)) {
        bool processedEvent;
        rv = thread->ProcessNextEvent(true, &processedEvent);
433
        if (NS_SUCCEEDED(rv) && (!processedEvent || !CheckWinID())) {
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
            rv = NS_ERROR_UNEXPECTED;
        }
    }
    mService->RemoveMessageListener("promptresponse", this);

    std::map<uint32_t, EmbedPromptResponse>::iterator it = mResponseMap.find(winid);
    if (it == mResponseMap.end()) {
        return NS_ERROR_UNEXPECTED;
    }

    if (!it->second.accepted) {
        NS_WARNING("Alert not accepted");
    }

    if (aCheckValue) {
        *aCheckValue = it->second.checkvalue;
    }

    if (aValue) {
        if (*aValue)
            NS_Free(*aValue);
       *aValue = ToNewUnicode(it->second.promptvalue);
    }

    if (aConfirm) {
        *aConfirm = it->second.accepted;
    }

    mResponseMap.erase(it);

464
    rv = utils->LeaveModalState();
465 466 467 468 469 470 471

    mService->LeaveSecureJSContext();

    return NS_OK;
}

NS_IMETHODIMP
472 473 474 475 476
EmbedPromptService::PromptUsernameAndPassword(const char16_t* aDialogTitle,
                                              const char16_t* aDialogText,
                                              char16_t** aUsername,
                                              char16_t** aPassword,
                                              const char16_t* aCheckMsg,
477 478 479 480 481 482 483 484
                                              bool* aCheckValue,
                                              bool* aConfirm)
{
//    LOGNI();
    return NS_OK;
}

NS_IMETHODIMP
485 486 487 488
EmbedPromptService::PromptPassword(const char16_t* aDialogTitle,
                                   const char16_t* aDialogText,
                                   char16_t** aPassword,
                                   const char16_t* aCheckMsg,
489 490 491 492 493 494 495
                                   bool* aCheckValue, bool* aConfirm)
{
//    LOGNI();
    return NS_OK;
}

NS_IMETHODIMP
496 497 498
EmbedPromptService::Select(const char16_t* aDialogTitle,
                           const char16_t* aDialogText, PRUint32 aCount,
                           const char16_t** aSelectList, PRInt32* outSelection,
499 500 501 502 503 504 505 506 507 508 509 510 511
                           bool* aConfirm)
{
//    LOGNI();
    return NS_OK;
}


// Prompt Auth Implementation

EmbedAuthPromptService::EmbedAuthPromptService(nsIDOMWindow* aWin)
  : mWin(aWin)
{
    mService = do_GetService("@mozilla.org/embedlite-app-service;1");
512
    mOuterService = new EmbedPromptOuterObserver(this, mWin);
513 514 515 516
}

EmbedAuthPromptService::~EmbedAuthPromptService()
{
Tatiana Meshkova's avatar
Tatiana Meshkova committed
517 518 519
    if (mOuterService) {
        mOuterService->OnDestroy();
    }
520 521
}

522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
void
EmbedAuthPromptService::CancelResponse()
{
    std::map<uint32_t, EmbedPromptResponse>::iterator it;
    for (it = mResponseMap.begin(); it != mResponseMap.end(); it++) {
        mModalDepth--;
    }
}

void
EmbedAuthPromptService::OnDestroyNotification()
{
    CancelResponse();
}

537
NS_IMPL_ISUPPORTS(EmbedAuthPromptService, nsIAuthPrompt2, nsIEmbedMessageListener)
538 539 540 541 542 543 544 545 546 547 548

NS_IMETHODIMP
EmbedAuthPromptService::PromptAuth(nsIChannel* aChannel,
                                   uint32_t level,
                                   nsIAuthInformation* authInfo,
                                   bool *_retval)
{
//    LOGNI();
    return NS_OK;
}

549
class nsAuthCancelableConsumer final : public nsICancelable
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
{
public:
    NS_DECL_ISUPPORTS

    nsAuthCancelableConsumer(nsIAuthPromptCallback* aCallback,
                             nsISupports *aContext)
        : mCallback(aCallback)
        , mContext(aContext)
    {
        NS_ASSERTION(mCallback, "null callback");
    }

    NS_IMETHOD Cancel(nsresult reason)
    {
        NS_ENSURE_ARG(NS_FAILED(reason));

        // If we've already called DoCallback then, nothing more to do.
        if (mCallback) {
            mCallback->OnAuthCancelled(mContext, false);
        }
        mCallback = nullptr;
        mContext = nullptr;
        return NS_OK;
    }

    nsCOMPtr<nsIAuthPromptCallback> mCallback;
    nsCOMPtr<nsISupports> mContext;
577 578
private:
    virtual ~nsAuthCancelableConsumer() {}
579 580
};

581
NS_IMPL_ISUPPORTS(nsAuthCancelableConsumer, nsICancelable);
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645

static nsCString getFormattedHostname(nsIURI* uri)
{
    nsCString scheme;
    uri->GetScheme(scheme);
    nsCString host;
    uri->GetHost(host);
    nsCString hostname(scheme);
    hostname.AppendLiteral("://");
    hostname.Append(host);

    // If the URI explicitly specified a port, only include it when
    // it's not the default. (We never want "http://foo.com:80")
    int32_t port = -1;
    uri->GetPort(&port);
    if (port != -1) {
        int32_t handlerPort = -1;
        nsCOMPtr<nsIIOService> ioService = do_GetService(NS_IOSERVICE_CONTRACTID);
        if (ioService) {
            nsCOMPtr<nsIProtocolHandler> handler;
            ioService->GetProtocolHandler(scheme.get(), getter_AddRefs(handler));
            if (handler) {
                handler->GetDefaultPort(&handlerPort);
            }
        }
        if (port != handlerPort) {
            hostname.AppendLiteral(":");
            hostname.AppendInt(port);
        }
    }
    return hostname;
}

static nsresult
getAuthTarget(nsIChannel* aChannel, nsIAuthInformation *authInfo, nsCString& hostname, nsCString& realm)
{
    nsresult rv;
    nsCOMPtr<nsIURI> uri;
    rv = aChannel->GetURI(getter_AddRefs(uri));
    NS_ENSURE_SUCCESS(rv, rv);
    hostname = getFormattedHostname(uri);
    // If a HTTP WWW-Authenticate header specified a realm, that value
    // will be available here. If it wasn't set or wasn't HTTP, we'll use
    // the formatted hostname instead.
    nsString ut16realm;
    if (NS_FAILED(authInfo->GetRealm(ut16realm)) || ut16realm.IsEmpty()) {
        realm = hostname;
    } else {
        realm = NS_ConvertUTF16toUTF8(ut16realm);
    }
    return NS_OK;
}

class EmbedAuthRunnable : public nsIRunnable
{
public:
    NS_DECL_ISUPPORTS

    EmbedAuthRunnable(EmbedAsyncAuthPrompt* aPrompt)
      : mPrompt(aPrompt)
    {
    }
    NS_IMETHOD Run();
    EmbedAsyncAuthPrompt* mPrompt;
646 647
private:
    virtual ~EmbedAuthRunnable() {}
648 649
};

650
NS_IMPL_ISUPPORTS(EmbedAuthRunnable, nsIRunnable)
651 652 653 654 655 656 657 658 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

NS_IMETHODIMP
EmbedAuthRunnable::Run()
{
    mPrompt->mService->DoSendAsyncPrompt(mPrompt);
    delete mPrompt;
    mPrompt = nullptr;
    return NS_OK;
}

NS_IMETHODIMP
EmbedAuthPromptService::AsyncPromptAuth(nsIChannel* aChannel,
                                        nsIAuthPromptCallback* aCallback,
                                        nsISupports *aContext, uint32_t level,
                                        nsIAuthInformation *authInfo,
                                        nsICancelable * *_retval)
{
    // The cases that we don't support now.
    nsresult rv;
    uint32_t authInfoFlags;
    rv = authInfo->GetFlags(&authInfoFlags);
    NS_ENSURE_SUCCESS(rv, rv);
    if ((authInfoFlags & nsIAuthInformation::AUTH_PROXY) &&
        (authInfoFlags & nsIAuthInformation::ONLY_PASSWORD)) {
        NS_ERROR("Not Implemented");
        return NS_ERROR_FAILURE;
    }

    nsCOMPtr<nsAuthCancelableConsumer> consumer = new nsAuthCancelableConsumer(aCallback, aContext);

    nsCString hostname, httpRealm;
    NS_ENSURE_SUCCESS(getAuthTarget(aChannel, authInfo, hostname, httpRealm), NS_ERROR_FAILURE);

    nsCString hashKey;
    hashKey.AppendInt(level);
    hashKey.AppendLiteral("|");
    hashKey.Append(hostname);
    hashKey.AppendLiteral("|");
    hashKey.Append(httpRealm);
//    hashKey.AppendPrintf("%u|%s|%s", level, hostname.get(), httpRealm.get());
    LOGT("host:%s, realm:%s, hash:%s", hostname.get(), httpRealm.get(), hashKey.get());
    EmbedAsyncAuthPrompt* asyncPrompt = asyncPrompts[hashKey.get()];
    if (asyncPrompt) {
        asyncPrompt->consumers.AppendElement(consumer);
695
        *_retval = consumer.forget().take();
696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
        return NS_OK;
    }
    asyncPrompt = new EmbedAsyncAuthPrompt(consumer, aChannel, authInfo, level, false);
    asyncPrompt->mWin = mWin;
    asyncPrompt->mHashKey = hashKey;
    asyncPrompt->mService = this;
    asyncPrompts[hashKey.get()] = asyncPrompt;
    DoAsyncPrompt();
    return NS_OK;
}

nsresult
EmbedAuthPromptService::DoSendAsyncPrompt(EmbedAsyncAuthPrompt* mPrompt)
{
    if (!mPrompt->mWin) {
        return NS_ERROR_FAILURE;
    }
    nsCString hostname, httpRealm;
    NS_ENSURE_SUCCESS(getAuthTarget(mPrompt->mChannel, mPrompt->mAuthInfo, hostname, httpRealm), NS_ERROR_FAILURE);
    nsString username;
716
    nsString password;
717 718 719 720 721 722 723
    nsresult rv;
    uint32_t authInfoFlags;
    rv = mPrompt->mAuthInfo->GetFlags(&authInfoFlags);
    NS_ENSURE_SUCCESS(rv, rv);
    bool isOnlyPassword = !!(authInfoFlags & nsIAuthInformation::ONLY_PASSWORD);
    mPrompt->mAuthInfo->GetUsername(username);

724 725 726 727 728 729 730 731 732 733
    nsCOMPtr<nsILoginManager> loginMgr = do_GetService("@mozilla.org/login-manager;1");
    uint32_t loginCount;
    nsILoginInfo **logins;
    loginMgr->FindLogins(&loginCount, NS_ConvertUTF8toUTF16(hostname),
                         nsString(), NS_ConvertUTF8toUTF16(httpRealm), &logins);
    for (uint32_t loginIndex = 0; loginIndex < loginCount; ++loginIndex) {
        logins[loginIndex]->GetUsername(username);
        logins[loginIndex]->GetPassword(password);
        NS_RELEASE(logins[loginIndex]);
    }
734
    free(logins);
735

736 737 738 739 740 741 742 743 744 745 746 747 748
    uint32_t winid;
    mService->GetIDByWindow(mPrompt->mWin, &winid);

    nsString sendString;
    // Just simple property bag support still
    nsCOMPtr<nsIEmbedLiteJSON> json = do_GetService("@mozilla.org/embedlite-json;1");
    nsCOMPtr<nsIWritablePropertyBag2> root;
    json->CreateObject(getter_AddRefs(root));
    root->SetPropertyAsACString(NS_LITERAL_STRING("title"), httpRealm);
    root->SetPropertyAsACString(NS_LITERAL_STRING("text"), hostname);
    root->SetPropertyAsUint32(NS_LITERAL_STRING("winid"), winid);
    root->SetPropertyAsBool(NS_LITERAL_STRING("passwordOnly"), isOnlyPassword);
    root->SetPropertyAsAString(NS_LITERAL_STRING("defaultValue"), username);
749 750
    root->SetPropertyAsAString(NS_LITERAL_STRING("storedUsername"), username);
    root->SetPropertyAsAString(NS_LITERAL_STRING("storedPassword"), password);
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765

    json->CreateJSON(root, sendString);

    mResponseMap[winid] = EmbedPromptResponse();

    mService->SendAsyncMessage(winid, NS_LITERAL_STRING("embed:auth").get(), sendString.get());
    mService->AddMessageListener("authresponse", this);

    mModalDepth++;
    int origModalDepth = mModalDepth;
    nsCOMPtr<nsIThread> thread;
    NS_GetCurrentThread(getter_AddRefs(thread));
    while (mModalDepth == origModalDepth && NS_SUCCEEDED(rv)) {
        bool processedEvent;
        rv = thread->ProcessNextEvent(true, &processedEvent);
766
        if (NS_SUCCEEDED(rv) && (!processedEvent || !CheckWinID())) {
767 768 769 770 771 772 773 774 775 776 777 778
            rv = NS_ERROR_UNEXPECTED;
        }
    }
    mService->RemoveMessageListener("authresponse", this);

    std::map<uint32_t, EmbedPromptResponse>::iterator it = mResponseMap.find(winid);
    if (it == mResponseMap.end()) {
        return NS_ERROR_UNEXPECTED;
    }

    if (!it->second.accepted) {
        NS_WARNING("Alert not accepted");
779 780 781 782 783 784 785 786 787
    } else if (!(username.Equals(it->second.username) && password.Equals(it->second.password)) &&
               !it->second.dontsave) {
        // remove old credentials
        loginMgr->FindLogins(&loginCount, NS_ConvertUTF8toUTF16(hostname),
                             nsString(), NS_ConvertUTF8toUTF16(httpRealm), &logins);
        for (uint32_t loginIndex = 0; loginIndex < loginCount; ++loginIndex) {
            loginMgr->RemoveLogin(logins[loginIndex]);
            NS_RELEASE(logins[loginIndex]);
        }
788
        free(logins);
789 790 791 792 793 794 795 796 797 798
        // store credentials to DB
        nsCOMPtr<nsILoginInfo> loginInfo = do_CreateInstance("@mozilla.org/login-manager/loginInfo;1" , &rv);
        NS_ENSURE_SUCCESS(rv, rv);
        loginInfo->SetHostname(NS_ConvertUTF8toUTF16(hostname));
        loginInfo->SetHttpRealm(NS_ConvertUTF8toUTF16(httpRealm));
        loginInfo->SetUsername(it->second.username);
        loginInfo->SetPassword(it->second.password);
        loginInfo->SetUsernameField(nsString());
        loginInfo->SetPasswordField(nsString());
        loginMgr->AddLogin(loginInfo);
799 800 801 802 803 804 805 806 807 808
    }

    DoResponseAsyncPrompt(mPrompt, it->second.accepted, it->second.username, it->second.password);

    mResponseMap.erase(it);

    return NS_OK;
}

NS_IMETHODIMP
809
EmbedAuthPromptService::OnMessageReceived(const char* messageName, const char16_t* message)
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825
{
    nsCOMPtr<nsIEmbedLiteJSON> json = do_GetService("@mozilla.org/embedlite-json;1");
    nsCOMPtr<nsIPropertyBag2> root;
    NS_ENSURE_SUCCESS(json->ParseJSON(nsDependentString(message), getter_AddRefs(root)), NS_ERROR_FAILURE);

    uint32_t winid = 0;
    root->GetPropertyAsUint32(NS_LITERAL_STRING("winid"), &winid);

    std::map<uint32_t, EmbedPromptResponse>::iterator it =
        mResponseMap.find(winid);
    if (it == mResponseMap.end())
        return NS_ERROR_FAILURE;
    EmbedPromptResponse& response = it->second;

    nsString promptValue;
    root->GetPropertyAsBool(NS_LITERAL_STRING("accepted"), &response.accepted);
826
    root->GetPropertyAsBool(NS_LITERAL_STRING("dontsave"), &response.dontsave);
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
    root->GetPropertyAsAString(NS_LITERAL_STRING("username"), response.username);
    root->GetPropertyAsAString(NS_LITERAL_STRING("password"), response.password);

    mModalDepth--;

    return NS_OK;
}

void
EmbedAuthPromptService::DoAsyncPrompt()
{
    // Find the key of a prompt whose browser element parent does not have
    // async prompt in progress.
    nsCString hashKey;
    std::map<std::string, EmbedAsyncAuthPrompt*>::iterator it;
    for (it = asyncPrompts.begin(); it != asyncPrompts.end(); it++) {
        EmbedAsyncAuthPrompt* asyncPrompt = it->second;
        if (asyncPrompt) {
            if (!asyncPrompt || !asyncPromptInProgress[asyncPrompt->mWin]) {
                hashKey = it->first.c_str();
                break;
            }
        }
    }
    // Didn't find an available prompt, so just return.
    if (hashKey.IsEmpty()) {
        return;
    }

    EmbedAsyncAuthPrompt* asyncPrompt = asyncPrompts[hashKey.get()];
    nsCString hostname, httpRealm;
    NS_ENSURE_SUCCESS(getAuthTarget(asyncPrompt->mChannel, asyncPrompt->mAuthInfo, hostname, httpRealm), );
    if (asyncPrompt->mWin) {
        asyncPromptInProgress[asyncPrompt->mWin] = true;
    }
    asyncPrompt->mInProgress = true;
    nsCOMPtr<nsIRunnable> runnable = new EmbedAuthRunnable(asyncPrompt);
    nsCOMPtr<nsIThread> thread;
    NS_GetCurrentThread(getter_AddRefs(thread));
    if (NS_FAILED(thread->Dispatch(runnable, nsIThread::DISPATCH_NORMAL))) {
        NS_WARNING("Dispatching EmbedAuthRunnable failed.");
    }
}

void
EmbedAuthPromptService::DoResponseAsyncPrompt(EmbedAsyncAuthPrompt* prompt,
                                              const bool& confirmed,
                                              const nsString& username,
                                              const nsString& password)
{
    nsresult rv;
    asyncPrompts.erase(prompt->mHashKey.get());
    prompt->mInProgress = false;
    if (prompt->mWin) {
        asyncPromptInProgress.erase(prompt->mWin);
    }
    // Fill authentication information with username and password provided
    // by user.
    uint32_t flags;
    rv = prompt->mAuthInfo->GetFlags(&flags);
    NS_ENSURE_SUCCESS(rv, );
    if (!username.IsEmpty()) {
        if (flags & nsIAuthInformation::NEED_DOMAIN) {
            // Domain is separated from username by a backslash
            int idx = username.Find("\\");
            if (idx == -1) {
                prompt->mAuthInfo->SetUsername(username);
            } else {
                prompt->mAuthInfo->SetDomain(nsDependentSubstring(username, 0, idx));
                prompt->mAuthInfo->SetUsername(nsDependentSubstring(username, idx + 1));
            }
        } else {
            prompt->mAuthInfo->SetUsername(username);
        }
    }

    if (!password.IsEmpty()) {
        prompt->mAuthInfo->SetPassword(password);
    }

    for (unsigned int i = 0; i < prompt->consumers.Length(); i++) {
908
        nsRefPtr<nsAuthCancelableConsumer> consumer = static_cast<nsAuthCancelableConsumer*>(prompt->consumers[i].get());
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
        if (!consumer->mCallback) {
            // Not having a callback means that consumer didn't provide it
            // or canceled the notification.
            continue;
        }
        if (confirmed) {
            // printf("Ok, calling onAuthAvailable to finish auth.\n");
            consumer->mCallback->OnAuthAvailable(consumer->mContext, prompt->mAuthInfo);
        } else {
            // printf("Cancelled, calling onAuthCancelled to finish auth.\n");
            consumer->mCallback->OnAuthCancelled(consumer->mContext, true);
        }
    }

    // Process the next prompt, if one is pending.
    DoAsyncPrompt();
}