DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (c68fe15a81fc)

VCS Links

Line Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 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 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 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 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 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 424 425 426 427 428 429 430 431 432 433 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 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 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 577 578 579 580 581 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 646 647 648 649 650 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 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 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 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 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 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set sw=2 ts=8 et tw=80 : */

/* This Source Code Form is subject to the terms of the Mozilla Public
/* 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/. */

#include "mozilla/net/FTPChannelParent.h"
#include "nsStringStream.h"
#include "nsStringStream.h"
#include "mozilla/net/ChannelEventQueue.h"
#include "mozilla/dom/BrowserParent.h"
#include "nsFTPChannel.h"
#include "nsNetCID.h"
#include "nsNetUtil.h"
#include "nsNetUtil.h"
#include "nsQueryObject.h"
#include "nsFtpProtocolHandler.h"
#include "nsIAuthPrompt.h"
#include "nsIAuthPromptProvider.h"
#include "nsIHttpChannelInternal.h"
#include "nsISecureBrowserUI.h"
#include "nsISecureBrowserUI.h"
#include "nsIForcePendingChannel.h"
#include "mozilla/ipc/IPCStreamUtils.h"
#include "mozilla/ipc/URIUtils.h"
#include "mozilla/Unused.h"
#include "SerializedLoadContext.h"
#include "SerializedLoadContext.h"
#include "mozilla/ipc/BackgroundUtils.h"
#include "mozilla/LoadInfo.h"
#include "mozilla/LoadInfo.h"
#include "mozilla/dom/ContentParent.h"

using namespace mozilla::dom;
using namespace mozilla::ipc;


#undef LOG
#define LOG(args) MOZ_LOG(gFTPLog, mozilla::LogLevel::Debug, args)

namespace mozilla {
namespace net {
namespace net {

FTPChannelParent::FTPChannelParent(dom::BrowserParent* aIframeEmbedding,
                                   nsILoadContext* aLoadContext,
                                   PBOverrideStatus aOverrideStatus)
    : mIPCClosed(false),
    : mIPCClosed(false),
      mLoadContext(aLoadContext),
      mPBOverride(aOverrideStatus),
      mStatus(NS_OK),
      mDivertingFromChild(false),
      mDivertedOnStartRequest(false),
      mDivertedOnStartRequest(false),
      mSuspendedForDiversion(false),
      mBrowserParent(aIframeEmbedding),
      mUseUTF8(false) {
  nsIProtocolHandler* handler;
  CallGetService(NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX "ftp", &handler);
  CallGetService(NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX "ftp", &handler);
  MOZ_ASSERT(handler, "no ftp handler");

  mEventQ = new ChannelEventQueue(static_cast<nsIParentChannel*>(this));
}


FTPChannelParent::~FTPChannelParent() { gFtpHandler->Release(); }

void FTPChannelParent::ActorDestroy(ActorDestroyReason why) {
  // We may still have refcount>0 if the channel hasn't called OnStopRequest
  // yet, but we must not send any more msgs to child.
  // yet, but we must not send any more msgs to child.
  mIPCClosed = true;
}

//-----------------------------------------------------------------------------
// FTPChannelParent::nsISupports
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------

NS_IMPL_ISUPPORTS(FTPChannelParent, nsIStreamListener, nsIParentChannel,
                  nsIInterfaceRequestor, nsIRequestObserver,
                  nsIChannelEventSink, nsIFTPChannelParentInternal)


//-----------------------------------------------------------------------------
// FTPChannelParent::PFTPChannelParent
//-----------------------------------------------------------------------------


//-----------------------------------------------------------------------------
// FTPChannelParent methods
//-----------------------------------------------------------------------------

bool FTPChannelParent::Init(const FTPChannelCreationArgs& aArgs) {
bool FTPChannelParent::Init(const FTPChannelCreationArgs& aArgs) {
  switch (aArgs.type()) {
    case FTPChannelCreationArgs::TFTPChannelOpenArgs: {
      const FTPChannelOpenArgs& a = aArgs.get_FTPChannelOpenArgs();
      return DoAsyncOpen(a.uri(), a.startPos(), a.entityID(), a.uploadStream(),
                         a.loadInfo(), a.loadFlags());
                         a.loadInfo(), a.loadFlags());
    }
    case FTPChannelCreationArgs::TFTPChannelConnectArgs: {
      const FTPChannelConnectArgs& cArgs = aArgs.get_FTPChannelConnectArgs();
      return ConnectChannel(cArgs.channelId());
    }
    }
    default:
      MOZ_ASSERT_UNREACHABLE("unknown open type");
      return false;
  }
}
}

bool FTPChannelParent::DoAsyncOpen(const URIParams& aURI,
                                   const uint64_t& aStartPos,
                                   const nsCString& aEntityID,
                                   const Maybe<IPCStream>& aUploadStream,
                                   const Maybe<LoadInfoArgs>& aLoadInfoArgs,
                                   const Maybe<LoadInfoArgs>& aLoadInfoArgs,
                                   const uint32_t& aLoadFlags) {
  nsresult rv;

  nsCOMPtr<nsIURI> uri = DeserializeURI(aURI);
  if (!uri) return false;
  if (!uri) return false;

#ifdef DEBUG
  LOG(("FTPChannelParent DoAsyncOpen [this=%p uri=%s]\n", this,
       uri->GetSpecOrDefault().get()));
#endif
#endif

  nsCOMPtr<nsIIOService> ios(do_GetIOService(&rv));
  if (NS_FAILED(rv)) {
    return SendFailedAsyncOpen(rv);
  }
  }

  nsCOMPtr<nsILoadInfo> loadInfo;
  rv = mozilla::ipc::LoadInfoArgsToLoadInfo(aLoadInfoArgs,
                                            getter_AddRefs(loadInfo));
                                            getter_AddRefs(loadInfo));
  if (NS_FAILED(rv)) {
    return SendFailedAsyncOpen(rv);
  }

  OriginAttributes attrs;
  OriginAttributes attrs;
  rv = loadInfo->GetOriginAttributes(&attrs);
  if (NS_FAILED(rv)) {
    return SendFailedAsyncOpen(rv);
  }


  nsCOMPtr<nsIChannel> chan;
  rv = NS_NewChannelInternal(getter_AddRefs(chan), uri, loadInfo, nullptr,
                             nullptr, nullptr, aLoadFlags, ios);

  if (NS_FAILED(rv)) return SendFailedAsyncOpen(rv);


  mChannel = chan;

  // later on mChannel may become an HTTP channel (we'll be redirected to one
  // if we're using a proxy), but for now this is safe
  nsFtpChannel* ftpChan = static_cast<nsFtpChannel*>(mChannel.get());

  if (mPBOverride != kPBOverride_Unset) {
  if (mPBOverride != kPBOverride_Unset) {
    ftpChan->SetPrivate(mPBOverride == kPBOverride_Private ? true : false);
  }
  rv = ftpChan->SetNotificationCallbacks(this);
  if (NS_FAILED(rv)) return SendFailedAsyncOpen(rv);


  nsCOMPtr<nsIInputStream> upload = DeserializeIPCStream(aUploadStream);
  if (upload) {
    // contentType and contentLength are ignored
    rv = ftpChan->SetUploadStream(upload, EmptyCString(), 0);
    if (NS_FAILED(rv)) return SendFailedAsyncOpen(rv);
    if (NS_FAILED(rv)) return SendFailedAsyncOpen(rv);
  }

  rv = ftpChan->ResumeAt(aStartPos, aEntityID);
  if (NS_FAILED(rv)) return SendFailedAsyncOpen(rv);


  rv = ftpChan->AsyncOpen(this);

  if (NS_FAILED(rv)) return SendFailedAsyncOpen(rv);

  return true;
  return true;
}

bool FTPChannelParent::ConnectChannel(const uint32_t& channelId) {
  nsresult rv;

  LOG(("Looking for a registered channel [this=%p, id=%d]", this, channelId));

  nsCOMPtr<nsIChannel> channel;
  rv = NS_LinkRedirectChannels(channelId, this, getter_AddRefs(channel));
  if (NS_SUCCEEDED(rv)) mChannel = channel;
  if (NS_SUCCEEDED(rv)) mChannel = channel;

  LOG(("  found channel %p, rv=%08" PRIx32, mChannel.get(),
       static_cast<uint32_t>(rv)));

  return true;
  return true;
}

mozilla::ipc::IPCResult FTPChannelParent::RecvCancel(const nsresult& status) {
  if (mChannel) mChannel->Cancel(status);


  return IPC_OK();
}

mozilla::ipc::IPCResult FTPChannelParent::RecvSuspend() {
  if (mChannel) {
    mChannel->Suspend();
  }
  }
  return IPC_OK();
}

mozilla::ipc::IPCResult FTPChannelParent::RecvResume() {
  if (mChannel) {
  if (mChannel) {
    mChannel->Resume();
  }
  return IPC_OK();
}


class FTPDivertDataAvailableEvent : public MainThreadChannelEvent {
 public:
  FTPDivertDataAvailableEvent(FTPChannelParent* aParent, const nsCString& data,
                              const uint64_t& offset, const uint32_t& count)
      : mParent(aParent), mData(data), mOffset(offset), mCount(count) {}
      : mParent(aParent), mData(data), mOffset(offset), mCount(count) {}

  void Run() override {
    mParent->DivertOnDataAvailable(mData, mOffset, mCount);
  }

 private:
  FTPChannelParent* mParent;
  nsCString mData;
  uint64_t mOffset;
  uint64_t mOffset;
  uint32_t mCount;
};

mozilla::ipc::IPCResult FTPChannelParent::RecvDivertOnDataAvailable(
    const nsCString& data, const uint64_t& offset, const uint32_t& count) {
    const nsCString& data, const uint64_t& offset, const uint32_t& count) {
  if (NS_WARN_IF(!mDivertingFromChild)) {
    MOZ_ASSERT(mDivertingFromChild,
               "Cannot RecvDivertOnDataAvailable if diverting is not set!");
    FailDiversion(NS_ERROR_UNEXPECTED);
    return IPC_FAIL_NO_REASON(this);
    return IPC_FAIL_NO_REASON(this);
  }

  // Drop OnDataAvailables if the parent was canceled already.
  if (NS_FAILED(mStatus)) {
    return IPC_OK();
    return IPC_OK();
  }

  mEventQ->RunOrEnqueue(
      new FTPDivertDataAvailableEvent(this, data, offset, count));
  return IPC_OK();
}


void FTPChannelParent::DivertOnDataAvailable(const nsCString& data,
                                             const uint64_t& offset,
                                             const uint32_t& count) {
  LOG(("FTPChannelParent::DivertOnDataAvailable [this=%p]\n", this));


  if (NS_WARN_IF(!mDivertingFromChild)) {
    MOZ_ASSERT(mDivertingFromChild,
               "Cannot DivertOnDataAvailable if diverting is not set!");
    FailDiversion(NS_ERROR_UNEXPECTED);
    return;
  }


  // Drop OnDataAvailables if the parent was canceled already.
  if (NS_FAILED(mStatus)) {
    return;
  }


  nsCOMPtr<nsIInputStream> stringStream;
  nsresult rv =
      NS_NewByteInputStream(getter_AddRefs(stringStream),
                            MakeSpan(data).To(count), NS_ASSIGNMENT_DEPEND);
  if (NS_FAILED(rv)) {
  if (NS_FAILED(rv)) {
    if (mChannel) {
      mChannel->Cancel(rv);
    }
    mStatus = rv;
    return;
    return;
  }

  AutoEventEnqueuer ensureSerialDispatch(mEventQ);

  rv = OnDataAvailable(mChannel, stringStream, offset, count);
  rv = OnDataAvailable(mChannel, stringStream, offset, count);

  stringStream->Close();
  if (NS_FAILED(rv)) {
    if (mChannel) {
      mChannel->Cancel(rv);
      mChannel->Cancel(rv);
    }
    mStatus = rv;
  }
}


class FTPDivertStopRequestEvent : public MainThreadChannelEvent {
 public:
  FTPDivertStopRequestEvent(FTPChannelParent* aParent,
                            const nsresult& statusCode)
      : mParent(aParent), mStatusCode(statusCode) {}

  void Run() override { mParent->DivertOnStopRequest(mStatusCode); }
  void Run() override { mParent->DivertOnStopRequest(mStatusCode); }

 private:
  FTPChannelParent* mParent;
  nsresult mStatusCode;
  nsresult mStatusCode;
};

mozilla::ipc::IPCResult FTPChannelParent::RecvDivertOnStopRequest(
    const nsresult& statusCode) {
    const nsresult& statusCode) {
  if (NS_WARN_IF(!mDivertingFromChild)) {
    MOZ_ASSERT(mDivertingFromChild,
               "Cannot RecvDivertOnStopRequest if diverting is not set!");
    FailDiversion(NS_ERROR_UNEXPECTED);
    return IPC_FAIL_NO_REASON(this);
    return IPC_FAIL_NO_REASON(this);
  }

  mEventQ->RunOrEnqueue(new FTPDivertStopRequestEvent(this, statusCode));
  return IPC_OK();
}
}

void FTPChannelParent::DivertOnStopRequest(const nsresult& statusCode) {
  LOG(("FTPChannelParent::DivertOnStopRequest [this=%p]\n", this));

  if (NS_WARN_IF(!mDivertingFromChild)) {
  if (NS_WARN_IF(!mDivertingFromChild)) {
    MOZ_ASSERT(mDivertingFromChild,
               "Cannot DivertOnStopRequest if diverting is not set!");
    FailDiversion(NS_ERROR_UNEXPECTED);
    return;
  }
  }

  // Honor the channel's status even if the underlying transaction completed.
  nsresult status = NS_FAILED(mStatus) ? mStatus : statusCode;

  // Reset fake pending status in case OnStopRequest has already been called.
  // Reset fake pending status in case OnStopRequest has already been called.
  if (mChannel) {
    nsCOMPtr<nsIForcePendingChannel> forcePendingIChan =
        do_QueryInterface(mChannel);
    if (forcePendingIChan) {
      forcePendingIChan->ForcePending(false);
    }
  }
  }

  AutoEventEnqueuer ensureSerialDispatch(mEventQ);
  OnStopRequest(mChannel, status);
}


class FTPDivertCompleteEvent : public MainThreadChannelEvent {
 public:
  explicit FTPDivertCompleteEvent(FTPChannelParent* aParent)
      : mParent(aParent) {}


  void Run() override { mParent->DivertComplete(); }

 private:
  FTPChannelParent* mParent;
  FTPChannelParent* mParent;
};

mozilla::ipc::IPCResult FTPChannelParent::RecvDivertComplete() {
  if (NS_WARN_IF(!mDivertingFromChild)) {
    MOZ_ASSERT(mDivertingFromChild,
    MOZ_ASSERT(mDivertingFromChild,
               "Cannot RecvDivertComplete if diverting is not set!");
    FailDiversion(NS_ERROR_UNEXPECTED);
    return IPC_FAIL_NO_REASON(this);
  }


  mEventQ->RunOrEnqueue(new FTPDivertCompleteEvent(this));
  return IPC_OK();
}

void FTPChannelParent::DivertComplete() {
void FTPChannelParent::DivertComplete() {
  LOG(("FTPChannelParent::DivertComplete [this=%p]\n", this));

  if (NS_WARN_IF(!mDivertingFromChild)) {
    MOZ_ASSERT(mDivertingFromChild,
               "Cannot DivertComplete if diverting is not set!");
               "Cannot DivertComplete if diverting is not set!");
    FailDiversion(NS_ERROR_UNEXPECTED);
    FailDiversion(NS_ERROR_UNEXPECTED);
    return;
  }

  nsresult rv = ResumeForDiversion();
  if (NS_WARN_IF(NS_FAILED(rv))) {
  if (NS_WARN_IF(NS_FAILED(rv))) {
    FailDiversion(NS_ERROR_UNEXPECTED);
  }
}

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// FTPChannelParent::nsIRequestObserver
//-----------------------------------------------------------------------------

NS_IMETHODIMP
FTPChannelParent::OnStartRequest(nsIRequest* aRequest) {
FTPChannelParent::OnStartRequest(nsIRequest* aRequest) {
  LOG(("FTPChannelParent::OnStartRequest [this=%p]\n", this));

  if (mDivertingFromChild) {
    MOZ_RELEASE_ASSERT(mDivertToListener,
                       "Cannot divert if listener is unset!");
                       "Cannot divert if listener is unset!");
    return mDivertToListener->OnStartRequest(aRequest);
  }

  nsCOMPtr<nsIChannel> chan = do_QueryInterface(aRequest);
  nsCOMPtr<nsIChannel> chan = do_QueryInterface(aRequest);
  MOZ_ASSERT(chan);
  NS_ENSURE_TRUE(chan, NS_ERROR_UNEXPECTED);

  // Send down any permissions which are relevant to this URL if we are
  // performing a document load.
  // performing a document load.
  if (!mIPCClosed) {
    PContentParent* pcp = Manager()->Manager();
    MOZ_ASSERT(pcp, "We should have a manager if our IPC isn't closed");
    DebugOnly<nsresult> rv =
        static_cast<ContentParent*>(pcp)->AboutToLoadHttpFtpDocumentForChild(
        static_cast<ContentParent*>(pcp)->AboutToLoadHttpFtpDocumentForChild(
            chan);
    MOZ_ASSERT(NS_SUCCEEDED(rv));
  }

  int64_t contentLength;
  chan->GetContentLength(&contentLength);
  nsCString contentType;
  chan->GetContentType(contentType);
  chan->GetContentType(contentType);
  nsresult channelStatus = NS_OK;
  chan->GetStatus(&channelStatus);

  nsCString entityID;
  nsCOMPtr<nsIResumableChannel> resChan = do_QueryInterface(aRequest);
  MOZ_ASSERT(
      resChan);  // both FTP and HTTP should implement nsIResumableChannel
      resChan);  // both FTP and HTTP should implement nsIResumableChannel
  if (resChan) {
    resChan->GetEntityID(entityID);
  }

  PRTime lastModified = 0;
  PRTime lastModified = 0;
  nsCOMPtr<nsIFTPChannel> ftpChan = do_QueryInterface(aRequest);
  if (ftpChan) {
    ftpChan->GetLastModifiedTime(&lastModified);
  }
  nsCOMPtr<nsIHttpChannelInternal> httpChan = do_QueryInterface(aRequest);
  nsCOMPtr<nsIHttpChannelInternal> httpChan = do_QueryInterface(aRequest);
  if (httpChan) {
    Unused << httpChan->GetLastModifiedTime(&lastModified);
  }

  URIParams uriparam;
  URIParams uriparam;
  nsCOMPtr<nsIURI> uri;
  chan->GetURI(getter_AddRefs(uri));
  SerializeURI(uri, uriparam);

  if (mIPCClosed ||
  if (mIPCClosed ||
      !SendOnStartRequest(channelStatus, contentLength, contentType,
                          lastModified, entityID, uriparam)) {
    return NS_ERROR_UNEXPECTED;
  }

  return NS_OK;
}

NS_IMETHODIMP
NS_IMETHODIMP
FTPChannelParent::OnStopRequest(nsIRequest* aRequest, nsresult aStatusCode) {
  LOG(("FTPChannelParent::OnStopRequest: [this=%p status=%" PRIu32 "]\n", this,
       static_cast<uint32_t>(aStatusCode)));

  if (mDivertingFromChild) {
    MOZ_RELEASE_ASSERT(mDivertToListener,
    MOZ_RELEASE_ASSERT(mDivertToListener,
                       "Cannot divert if listener is unset!");
    return mDivertToListener->OnStopRequest(aRequest, aStatusCode);
  }

  if (mIPCClosed || !SendOnStopRequest(aStatusCode, mErrorMsg, mUseUTF8)) {
  if (mIPCClosed || !SendOnStopRequest(aStatusCode, mErrorMsg, mUseUTF8)) {
    return NS_ERROR_UNEXPECTED;
  }

  return NS_OK;
}

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// FTPChannelParent::nsIStreamListener
//-----------------------------------------------------------------------------

NS_IMETHODIMP
FTPChannelParent::OnDataAvailable(nsIRequest* aRequest,
FTPChannelParent::OnDataAvailable(nsIRequest* aRequest,
                                  nsIInputStream* aInputStream,
                                  uint64_t aOffset, uint32_t aCount) {
  LOG(("FTPChannelParent::OnDataAvailable [this=%p]\n", this));

  if (mDivertingFromChild) {
  if (mDivertingFromChild) {
    MOZ_RELEASE_ASSERT(mDivertToListener,
                       "Cannot divert if listener is unset!");
    return mDivertToListener->OnDataAvailable(aRequest, aInputStream, aOffset,
                                              aCount);
  }
  }

  nsCString data;
  nsresult rv = NS_ReadInputStreamToString(aInputStream, data, aCount);
  if (NS_FAILED(rv)) return rv;
  if (NS_FAILED(rv)) return rv;

  nsresult channelStatus = NS_OK;
  mChannel->GetStatus(&channelStatus);

  if (mIPCClosed || !SendOnDataAvailable(channelStatus, data, aOffset, aCount))
  if (mIPCClosed || !SendOnDataAvailable(channelStatus, data, aOffset, aCount))
    return NS_ERROR_UNEXPECTED;

  return NS_OK;
}


//-----------------------------------------------------------------------------
// FTPChannelParent::nsIParentChannel
//-----------------------------------------------------------------------------

NS_IMETHODIMP
NS_IMETHODIMP
FTPChannelParent::SetParentListener(ParentChannelListener* aListener) {
  // Do not need ptr to ParentChannelListener.
  return NS_OK;
}

NS_IMETHODIMP
FTPChannelParent::NotifyClassificationFlags(uint32_t aClassificationFlags,
FTPChannelParent::NotifyClassificationFlags(uint32_t aClassificationFlags,
                                            bool aIsThirdParty) {
  // One day, this should probably be filled in.
  return NS_OK;
}


NS_IMETHODIMP
FTPChannelParent::NotifyFlashPluginStateChanged(
    nsIHttpChannel::FlashPluginState aState) {
  // One day, this should probably be filled in.
  return NS_OK;
  return NS_OK;
}

NS_IMETHODIMP
FTPChannelParent::SetClassifierMatchedInfo(const nsACString& aList,
                                           const nsACString& aProvider,
                                           const nsACString& aProvider,
                                           const nsACString& aFullHash) {
  // One day, this should probably be filled in.
  return NS_OK;
}
}

NS_IMETHODIMP
FTPChannelParent::SetClassifierMatchedTrackingInfo(
    const nsACString& aLists, const nsACString& aFullHashes) {
  // One day, this should probably be filled in.
  // One day, this should probably be filled in.
  return NS_OK;
}

NS_IMETHODIMP
FTPChannelParent::Delete() {
FTPChannelParent::Delete() {
  if (mIPCClosed || !SendDeleteSelf()) return NS_ERROR_UNEXPECTED;

  return NS_OK;
}


//-----------------------------------------------------------------------------
// FTPChannelParent::nsIInterfaceRequestor
//-----------------------------------------------------------------------------

NS_IMETHODIMP
NS_IMETHODIMP
FTPChannelParent::GetInterface(const nsIID& uuid, void** result) {
  if (uuid.Equals(NS_GET_IID(nsIAuthPromptProvider)) ||
      uuid.Equals(NS_GET_IID(nsISecureBrowserUI))) {
      uuid.Equals(NS_GET_IID(nsISecureBrowserUI))) {
    if (mBrowserParent) {
    if (mBrowserParent) {
      return mBrowserParent->QueryInterface(uuid, result);
    }
  } else if (uuid.Equals(NS_GET_IID(nsIAuthPrompt)) ||
  } else if (uuid.Equals(NS_GET_IID(nsIAuthPrompt)) ||
             uuid.Equals(NS_GET_IID(nsIAuthPrompt2))) {
    nsCOMPtr<nsIAuthPromptProvider> provider(do_QueryObject(mBrowserParent));
    if (provider) {
      nsresult rv = provider->GetAuthPrompt(
          nsIAuthPromptProvider::PROMPT_NORMAL, uuid, result);
          nsIAuthPromptProvider::PROMPT_NORMAL, uuid, result);
      if (NS_FAILED(rv)) {
        return NS_ERROR_NO_INTERFACE;
      }
      return NS_OK;
    }
    }
  }

  // Only support nsILoadContext if child channel's callbacks did too
  if (uuid.Equals(NS_GET_IID(nsILoadContext)) && mLoadContext) {
    nsCOMPtr<nsILoadContext> copy = mLoadContext;
    nsCOMPtr<nsILoadContext> copy = mLoadContext;
    copy.forget(result);
    return NS_OK;
  }
  }


  return QueryInterface(uuid, result);
}


nsresult FTPChannelParent::ResumeChannelInternalIfPossible() {
  nsCOMPtr<nsIChannelWithDivertableParentListener> chan =
      do_QueryInterface(mChannel);
  if (chan) {
    return chan->ResumeInternal();
    return chan->ResumeInternal();
  }
  return mChannel->Resume();
}

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// FTPChannelParent::ADivertableParentChannel
//-----------------------------------------------------------------------------
nsresult FTPChannelParent::SuspendForDiversion() {
  MOZ_ASSERT(mChannel);
  if (NS_WARN_IF(mDivertingFromChild)) {
  if (NS_WARN_IF(mDivertingFromChild)) {
    MOZ_ASSERT(!mDivertingFromChild, "Already suspended for diversion!");
    return NS_ERROR_UNEXPECTED;
  }

  // MessageDiversionStarted call will suspend mEventQ as many times as the
  // MessageDiversionStarted call will suspend mEventQ as many times as the
  // channel has been suspended, so that channel and this queue are in sync.
  nsCOMPtr<nsIChannelWithDivertableParentListener> chan =
      do_QueryInterface(mChannel);
  if (chan) {
    chan->MessageDiversionStarted(this);
  }


  // We need to suspend only nsHttp/FTPChannel (i.e. we should not suspend
  // mEventQ). Therefore we call mChannel->SuspendInternal() and not
  // mChannel->Suspend().
  // We are suspending only nsHttp/FTPChannel here because we want to stop
  // OnDataAvailable until diversion is over. At the same time we should
  // OnDataAvailable until diversion is over. At the same time we should
  // send the diverted OnDataAvailable-s to the listeners and not queue them
  // in mEventQ.
  // Try suspending the channel. Allow it to fail, since OnStopRequest may have
  // been called and thus the channel may not be pending.
  nsresult rv;
  nsresult rv;
  if (chan) {
    rv = chan->SuspendInternal();
  } else {
  } else {
    rv = mChannel->Suspend();
    rv = mChannel->Suspend();
  }

  MOZ_ASSERT(NS_SUCCEEDED(rv) || rv == NS_ERROR_NOT_AVAILABLE);
  MOZ_ASSERT(NS_SUCCEEDED(rv) || rv == NS_ERROR_NOT_AVAILABLE);
  mSuspendedForDiversion = NS_SUCCEEDED(rv);

  // Once this is set, no more OnStart/OnData/OnStop callbacks should be sent
  // to the child.
  mDivertingFromChild = true;
  mDivertingFromChild = true;

  return NS_OK;
}

/* private, supporting function for ADivertableParentChannel */
/* private, supporting function for ADivertableParentChannel */
nsresult FTPChannelParent::ResumeForDiversion() {
  MOZ_ASSERT(mChannel);
  MOZ_ASSERT(mDivertToListener);
  if (NS_WARN_IF(!mDivertingFromChild)) {
    MOZ_ASSERT(mDivertingFromChild,
    MOZ_ASSERT(mDivertingFromChild,
               "Cannot ResumeForDiversion if not diverting!");
    return NS_ERROR_UNEXPECTED;
  }

  nsCOMPtr<nsIChannelWithDivertableParentListener> chan =
  nsCOMPtr<nsIChannelWithDivertableParentListener> chan =
      do_QueryInterface(mChannel);
  if (chan) {
    chan->MessageDiversionStop();
  }


  if (mSuspendedForDiversion) {
    nsresult rv = ResumeChannelInternalIfPossible();
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return rv;
    }
    }
    mSuspendedForDiversion = false;
  }

  // Delete() will tear down IPDL, but ref from underlying nsFTPChannel will
  // keep us alive if there's more data to be delivered to listener.
  // keep us alive if there's more data to be delivered to listener.
  if (NS_WARN_IF(NS_FAILED(Delete()))) {
    return NS_ERROR_UNEXPECTED;
  }
  return NS_OK;
}
}

nsresult FTPChannelParent::SuspendMessageDiversion() {
  // This only need to suspend message queue.
  mEventQ->Suspend();
  return NS_OK;
}


nsresult FTPChannelParent::ResumeMessageDiversion() {
  // This only need to resumes message queue.
  mEventQ->Resume();
  return NS_OK;
}
}

nsresult FTPChannelParent::CancelDiversion() {
  // Only HTTP channels can have child-process-sourced-data that's long-lived
  // so this isn't currently relevant for FTP channels and there is nothing to
  // so this isn't currently relevant for FTP channels and there is nothing to
  // do.
  return NS_OK;
}

void FTPChannelParent::DivertTo(nsIStreamListener* aListener) {
void FTPChannelParent::DivertTo(nsIStreamListener* aListener) {
  MOZ_ASSERT(aListener);
  if (NS_WARN_IF(!mDivertingFromChild)) {
    MOZ_ASSERT(mDivertingFromChild,
               "Cannot DivertTo new listener if diverting is not set!");
    return;
    return;
  }

  if (NS_WARN_IF(mIPCClosed || !SendFlushedForDiversion())) {
    FailDiversion(NS_ERROR_UNEXPECTED);
    return;
  }


  mDivertToListener = aListener;

  // Call OnStartRequest and SendDivertMessages asynchronously to avoid
  // reentering client context.
  NS_DispatchToCurrentThread(
  NS_DispatchToCurrentThread(
      NewRunnableMethod("net::FTPChannelParent::StartDiversion", this,
                        &FTPChannelParent::StartDiversion));
}

void FTPChannelParent::StartDiversion() {
void FTPChannelParent::StartDiversion() {
  if (NS_WARN_IF(!mDivertingFromChild)) {
    MOZ_ASSERT(mDivertingFromChild,
               "Cannot StartDiversion if diverting is not set!");
    return;
  }
  }

  // Fake pending status in case OnStopRequest has already been called.
  if (mChannel) {
    nsCOMPtr<nsIForcePendingChannel> forcePendingIChan =
        do_QueryInterface(mChannel);
    if (forcePendingIChan) {
      forcePendingIChan->ForcePending(true);
      forcePendingIChan->ForcePending(true);
    }
  }

  {
    AutoEventEnqueuer ensureSerialDispatch(mEventQ);
    AutoEventEnqueuer ensureSerialDispatch(mEventQ);
    // Call OnStartRequest for the "DivertTo" listener.
    nsresult rv = OnStartRequest(mChannel);
    if (NS_FAILED(rv)) {
      if (mChannel) {
        mChannel->Cancel(rv);
        mChannel->Cancel(rv);
      }
      mStatus = rv;
      return;
    }
  }
  }

  // After OnStartRequest has been called, tell FTPChannelChild to divert the
  // OnDataAvailables and OnStopRequest to this FTPChannelParent.
  if (NS_WARN_IF(mIPCClosed || !SendDivertMessages())) {
    FailDiversion(NS_ERROR_UNEXPECTED);
    return;
  }
  }
}

class FTPFailDiversionEvent : public Runnable {
 public:
  FTPFailDiversionEvent(FTPChannelParent* aChannelParent, nsresult aErrorCode)
  FTPFailDiversionEvent(FTPChannelParent* aChannelParent, nsresult aErrorCode)
      : Runnable("net::FTPFailDiversionEvent"),
        mChannelParent(aChannelParent),
        mErrorCode(aErrorCode) {
    MOZ_RELEASE_ASSERT(aChannelParent);
    MOZ_RELEASE_ASSERT(NS_FAILED(aErrorCode));
    MOZ_RELEASE_ASSERT(NS_FAILED(aErrorCode));
  }
  NS_IMETHOD Run() override {
    mChannelParent->NotifyDiversionFailed(mErrorCode);
    return NS_OK;
  }
  }

 private:
  RefPtr<FTPChannelParent> mChannelParent;
  nsresult mErrorCode;
};
};

void FTPChannelParent::FailDiversion(nsresult aErrorCode) {
  MOZ_RELEASE_ASSERT(NS_FAILED(aErrorCode));
  MOZ_RELEASE_ASSERT(mDivertingFromChild);
  MOZ_RELEASE_ASSERT(mDivertToListener);
  MOZ_RELEASE_ASSERT(mDivertToListener);
  MOZ_RELEASE_ASSERT(mChannel);

  NS_DispatchToCurrentThread(new FTPFailDiversionEvent(this, aErrorCode));
}


void FTPChannelParent::NotifyDiversionFailed(nsresult aErrorCode) {
  MOZ_RELEASE_ASSERT(NS_FAILED(aErrorCode));
  MOZ_RELEASE_ASSERT(mDivertingFromChild);
  MOZ_RELEASE_ASSERT(mDivertToListener);
  MOZ_RELEASE_ASSERT(mChannel);
  MOZ_RELEASE_ASSERT(mChannel);

  mChannel->Cancel(aErrorCode);
  nsCOMPtr<nsIForcePendingChannel> forcePendingIChan =
      do_QueryInterface(mChannel);
  if (forcePendingIChan) {
  if (forcePendingIChan) {
    forcePendingIChan->ForcePending(false);
  }

  bool isPending = false;
  nsresult rv = mChannel->IsPending(&isPending);
  MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv));


  // Resume only we suspended earlier.
  if (mSuspendedForDiversion) {
    ResumeChannelInternalIfPossible();
  }
  // Channel has already sent OnStartRequest to the child, so ensure that we
  // Channel has already sent OnStartRequest to the child, so ensure that we
  // call it here if it hasn't already been called.
  if (!mDivertedOnStartRequest) {
    nsCOMPtr<nsIForcePendingChannel> forcePendingIChan =
        do_QueryInterface(mChannel);
    if (forcePendingIChan) {
    if (forcePendingIChan) {
      forcePendingIChan->ForcePending(true);
    }
    mDivertToListener->OnStartRequest(mChannel);

    if (forcePendingIChan) {
      forcePendingIChan->ForcePending(false);
    }
  }
  // If the channel is pending, it will call OnStopRequest itself; otherwise, do
  // If the channel is pending, it will call OnStopRequest itself; otherwise, do
  // it here.
  if (!isPending) {
    mDivertToListener->OnStopRequest(mChannel, aErrorCode);
  }
  mDivertToListener = nullptr;
  mDivertToListener = nullptr;
  mChannel = nullptr;

  if (!mIPCClosed) {
    Unused << SendDeleteSelf();
  }
  }
}

//-----------------------------------------------------------------------------
// FTPChannelParent::nsIChannelEventSink
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------

NS_IMETHODIMP
FTPChannelParent::AsyncOnChannelRedirect(
    nsIChannel* oldChannel, nsIChannel* newChannel, uint32_t redirectFlags,
    nsIAsyncVerifyRedirectCallback* callback) {
    nsIAsyncVerifyRedirectCallback* callback) {
  nsCOMPtr<nsIFTPChannel> ftpChan = do_QueryInterface(newChannel);
  if (!ftpChan) {
    // when FTP is set to use HTTP proxying, we wind up getting redirected to an
    // HTTP channel.
    nsCOMPtr<nsIHttpChannel> httpChan = do_QueryInterface(newChannel);
    nsCOMPtr<nsIHttpChannel> httpChan = do_QueryInterface(newChannel);
    if (!httpChan) return NS_ERROR_UNEXPECTED;
  }
  mChannel = newChannel;
  callback->OnRedirectVerifyCallback(NS_OK);
  return NS_OK;
  return NS_OK;
}

NS_IMETHODIMP
FTPChannelParent::SetErrorMsg(const char* aMsg, bool aUseUTF8) {
  mErrorMsg = aMsg;
  mErrorMsg = aMsg;
  mUseUTF8 = aUseUTF8;
  return NS_OK;
}

//---------------------
//---------------------
}  // namespace net
}  // namespace mozilla