DXR will be turned off on Tuesday, December 29th. It will redirect to Searchfox.
See the announcement on Discourse.

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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* 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
 * 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 "nsUnknownDecoder.h"
#include "nsIPipe.h"
#include "nsIInputStream.h"
#include "nsIInputStream.h"
#include "nsIOutputStream.h"
#include "nsMimeTypes.h"
#include "nsIPrefBranch.h"

#include "nsCRT.h"
#include "nsCRT.h"

#include "nsIMIMEService.h"

#include "nsIDivertableChannel.h"
#include "nsIViewSourceChannel.h"
#include "nsIViewSourceChannel.h"
#include "nsIHttpChannel.h"
#include "nsIForcePendingChannel.h"
#include "nsIEncodedChannel.h"
#include "nsIURI.h"
#include "nsStringStream.h"
#include "nsStringStream.h"
#include "nsNetCID.h"
#include "nsNetUtil.h"

#include <algorithm>
#include <algorithm>

#define MAX_BUFFER_SIZE 512u

NS_IMPL_ISUPPORTS(nsUnknownDecoder::ConvertedStreamListener, nsIStreamListener,
                  nsIRequestObserver)
                  nsIRequestObserver)

nsUnknownDecoder::ConvertedStreamListener::ConvertedStreamListener(
    nsUnknownDecoder* aDecoder) {
  mDecoder = aDecoder;
  mDecoder = aDecoder;
}

nsresult nsUnknownDecoder::ConvertedStreamListener::AppendDataToString(
    nsIInputStream* inputStream, void* closure, const char* rawSegment,
    uint32_t toOffset, uint32_t count, uint32_t* writeCount) {
    uint32_t toOffset, uint32_t count, uint32_t* writeCount) {
  nsCString* decodedData = static_cast<nsCString*>(closure);
  decodedData->Append(rawSegment, count);
  *writeCount = count;
  return NS_OK;
}
}

NS_IMETHODIMP
nsUnknownDecoder::ConvertedStreamListener::OnStartRequest(nsIRequest* request) {
  return NS_OK;
}
}

NS_IMETHODIMP
nsUnknownDecoder::ConvertedStreamListener::OnDataAvailable(
    nsIRequest* request, nsIInputStream* stream, uint64_t offset,
    uint32_t count) {
    uint32_t count) {
  uint32_t read;
  nsAutoCString decodedData;
  {
    MutexAutoLock lock(mDecoder->mMutex);
    decodedData = mDecoder->mDecodedData;
    decodedData = mDecoder->mDecodedData;
  }
  nsresult rv =
      stream->ReadSegments(AppendDataToString, &decodedData, count, &read);
  if (NS_FAILED(rv)) {
  if (NS_FAILED(rv)) {
    return rv;
  }
  MutexAutoLock lock(mDecoder->mMutex);
  mDecoder->mDecodedData = decodedData;
  return NS_OK;
  return NS_OK;
}

NS_IMETHODIMP
nsUnknownDecoder::ConvertedStreamListener::OnStopRequest(nsIRequest* request,
                                                         nsresult status) {
                                                         nsresult status) {
  return NS_OK;
}

nsUnknownDecoder::nsUnknownDecoder()
    : mBuffer(nullptr),
    : mBuffer(nullptr),
      mBufferLen(0),
      mRequireHTMLsuffix(false),
      mMutex("nsUnknownDecoder"),
      mDecodedData("") {
  nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
  nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
  if (prefs) {
    bool val;
    if (NS_SUCCEEDED(prefs->GetBoolPref("security.requireHTMLsuffix", &val)))
      mRequireHTMLsuffix = val;
  }
  }
}

nsUnknownDecoder::~nsUnknownDecoder() {
  if (mBuffer) {
    delete[] mBuffer;
    mBuffer = nullptr;
  }
  }
}

// ----
//
// nsISupports implementation...
// nsISupports implementation...
//
// ----

NS_IMPL_ADDREF(nsUnknownDecoder)
NS_IMPL_RELEASE(nsUnknownDecoder)
NS_IMPL_RELEASE(nsUnknownDecoder)

NS_INTERFACE_MAP_BEGIN(nsUnknownDecoder)
  NS_INTERFACE_MAP_ENTRY(nsIStreamConverter)
  NS_INTERFACE_MAP_ENTRY(nsIStreamListener)
  NS_INTERFACE_MAP_ENTRY(nsIRequestObserver)
  NS_INTERFACE_MAP_ENTRY(nsIRequestObserver)
  NS_INTERFACE_MAP_ENTRY(nsIContentSniffer)
  NS_INTERFACE_MAP_ENTRY(nsIThreadRetargetableStreamListener)
  NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIStreamListener)
NS_INTERFACE_MAP_END


// ----
//
// nsIStreamConverter methods...
//
// ----

NS_IMETHODIMP
NS_IMETHODIMP
nsUnknownDecoder::Convert(nsIInputStream* aFromStream, const char* aFromType,
                          const char* aToType, nsISupports* aCtxt,
                          nsIInputStream** aResultStream) {
  return NS_ERROR_NOT_IMPLEMENTED;
}
}

NS_IMETHODIMP
nsUnknownDecoder::AsyncConvertData(const char* aFromType, const char* aToType,
                                   nsIStreamListener* aListener,
                                   nsISupports* aCtxt) {
                                   nsISupports* aCtxt) {
  NS_ASSERTION(aListener && aFromType && aToType,
               "null pointer passed into multi mixed converter");
  // hook up our final listener. this guy gets the various On*() calls we want
  // to throw at him.
  //

  MutexAutoLock lock(mMutex);
  mNextListener = aListener;
  mNextListener = aListener;
  return (aListener) ? NS_OK : NS_ERROR_FAILURE;
}

NS_IMETHODIMP
nsUnknownDecoder::GetConvertedType(const nsACString& aFromType,
                                   nsIChannel* aChannel, nsACString& aToType) {
  return NS_ERROR_NOT_IMPLEMENTED;
  return NS_ERROR_NOT_IMPLEMENTED;
}

// ----
//
// nsIStreamListener methods...
// nsIStreamListener methods...
//
// ----

NS_IMETHODIMP
nsUnknownDecoder::OnDataAvailable(nsIRequest* request, nsIInputStream* aStream,
nsUnknownDecoder::OnDataAvailable(nsIRequest* request, nsIInputStream* aStream,
                                  uint64_t aSourceOffset, uint32_t aCount) {
  nsresult rv = NS_OK;

  bool contentTypeEmpty;
  {
  {
    MutexAutoLock lock(mMutex);
    if (!mNextListener) return NS_ERROR_FAILURE;

    contentTypeEmpty = mContentType.IsEmpty();
  }
  }

  if (contentTypeEmpty) {
    uint32_t count, len;

    // If the buffer has not been allocated by now, just fail...
    if (!mBuffer) return NS_ERROR_OUT_OF_MEMORY;

    //
    // Determine how much of the stream should be read to fill up the
    // Determine how much of the stream should be read to fill up the
    // sniffer buffer...
    //
    if (mBufferLen + aCount >= MAX_BUFFER_SIZE) {
      count = MAX_BUFFER_SIZE - mBufferLen;
    } else {
    } else {
      count = aCount;
    }

    // Read the data into the buffer...
    rv = aStream->Read((mBuffer + mBufferLen), count, &len);
    rv = aStream->Read((mBuffer + mBufferLen), count, &len);
    if (NS_FAILED(rv)) return rv;

    mBufferLen += len;
    aCount -= len;


    if (aCount) {
      //
      // Adjust the source offset...  The call to FireListenerNotifications(...)
      // will make the first OnDataAvailable(...) call with an offset of 0.
      // So, this offset needs to be adjusted to reflect that...
      // So, this offset needs to be adjusted to reflect that...
      //
      aSourceOffset += mBufferLen;

      DetermineContentType(request);

      rv = FireListenerNotifications(request, nullptr);
    }
    }
  }

  // Must not fire ODA again if it failed once
  if (aCount && NS_SUCCEEDED(rv)) {
#ifdef DEBUG
#ifdef DEBUG
    {
      MutexAutoLock lock(mMutex);
      NS_ASSERTION(!mContentType.IsEmpty(),
                   "Content type should be known by now.");
    }
    }
#endif

    nsCOMPtr<nsIDivertableChannel> divertable = do_QueryInterface(request);
    if (divertable) {
      bool diverting;
      bool diverting;
      divertable->GetDivertingToParent(&diverting);
      if (diverting) {
        // The channel is diverted to the parent do not send any more data here.
        return rv;
      }
      }
    }

    nsCOMPtr<nsIStreamListener> listener;
    {
      MutexAutoLock lock(mMutex);
      MutexAutoLock lock(mMutex);
      listener = mNextListener;
    }
    rv = listener->OnDataAvailable(request, aStream, aSourceOffset, aCount);
  }


  return rv;
}

// ----
// ----
//
// nsIRequestObserver methods...
//
// ----


NS_IMETHODIMP
nsUnknownDecoder::OnStartRequest(nsIRequest* request) {
  nsresult rv = NS_OK;

  {
  {
    MutexAutoLock lock(mMutex);
    if (!mNextListener) return NS_ERROR_FAILURE;
  }

  // Allocate the sniffer buffer...
  // Allocate the sniffer buffer...
  if (NS_SUCCEEDED(rv) && !mBuffer) {
    mBuffer = new char[MAX_BUFFER_SIZE];

    if (!mBuffer) {
      rv = NS_ERROR_OUT_OF_MEMORY;
      rv = NS_ERROR_OUT_OF_MEMORY;
    }
  }

  nsCOMPtr<nsIDivertableChannel> divertable = do_QueryInterface(request);
  if (divertable) {
  if (divertable) {
    divertable->UnknownDecoderInvolvedKeepData();
  }


  // Do not pass the OnStartRequest on to the next listener (yet)...
  // Do not pass the OnStartRequest on to the next listener (yet)...
  return rv;
}


NS_IMETHODIMP
nsUnknownDecoder::OnStopRequest(nsIRequest* request, nsresult aStatus) {
  nsresult rv = NS_OK;

  bool contentTypeEmpty;
  bool contentTypeEmpty;
  {
    MutexAutoLock lock(mMutex);
    if (!mNextListener) return NS_ERROR_FAILURE;

    contentTypeEmpty = mContentType.IsEmpty();
    contentTypeEmpty = mContentType.IsEmpty();
  }

  //
  // The total amount of data is less than the size of the sniffer buffer.
  // Analyze the buffer now...
  // Analyze the buffer now...
  //
  if (contentTypeEmpty) {
    DetermineContentType(request);

    /*
    /*
     * In Case we did Sniff Unknown Content with XTCO: nosniff enabled,
     * add an Telemetry-Entry whether the sniffed content is able to
     * execute Script.
     */
    nsCOMPtr<nsIChannel> channel = do_QueryInterface(request);
    nsCOMPtr<nsIChannel> channel = do_QueryInterface(request);
    if (channel) {
      nsCOMPtr<nsILoadInfo> loadInfo = channel->LoadInfo();
      if (loadInfo->GetSkipContentSniffing()) {
        if (mContentType.EqualsLiteral("text/html") ||
            mContentType.EqualsLiteral("text/xml") ||
            mContentType.EqualsLiteral("text/xml") ||
            mContentType.EqualsLiteral("aplication/pdf")) {
          Telemetry::AccumulateCategorical(
              mozilla::Telemetry::LABELS_XCTO_NOSNIFF_TOPLEVEL_NAV_EXCEPTIONS::
                  ExceptionScriptable);
        } else {
        } else {
          Telemetry::AccumulateCategorical(
              mozilla::Telemetry::LABELS_XCTO_NOSNIFF_TOPLEVEL_NAV_EXCEPTIONS::
                  Exception);
        }
      }
      }
    }

    // Make sure channel listeners see channel as pending while we call
    // OnStartRequest/OnDataAvailable, even though the underlying channel
    // has already hit OnStopRequest.
    // has already hit OnStopRequest.
    nsCOMPtr<nsIForcePendingChannel> forcePendingChannel =
        do_QueryInterface(request);
    if (forcePendingChannel) {
      forcePendingChannel->ForcePending(true);
    }
    }

    rv = FireListenerNotifications(request, nullptr);

    if (NS_FAILED(rv)) {
    if (NS_FAILED(rv)) {
      aStatus = rv;
    }

    // now we need to set pending state to false before calling OnStopRequest
    if (forcePendingChannel) {
      forcePendingChannel->ForcePending(false);
      forcePendingChannel->ForcePending(false);
    }
  }

  nsCOMPtr<nsIStreamListener> listener;
  {
  {
    MutexAutoLock lock(mMutex);
    listener = mNextListener;
    mNextListener = nullptr;
  }
  rv = listener->OnStopRequest(request, aStatus);
  rv = listener->OnStopRequest(request, aStatus);

  return rv;
}

// ----
// ----
//
// nsIContentSniffer methods...
//
// ----
// ----
NS_IMETHODIMP
nsUnknownDecoder::GetMIMETypeFromContent(nsIRequest* aRequest,
                                         const uint8_t* aData, uint32_t aLength,
                                         nsACString& type) {
  // This is only used by sniffer, therefore we do not need to lock anything
  // This is only used by sniffer, therefore we do not need to lock anything
  // here.
  nsCOMPtr<nsIChannel> channel(do_QueryInterface(aRequest));
  if (channel) {
    nsCOMPtr<nsILoadInfo> loadInfo = channel->LoadInfo();
    if (loadInfo->GetSkipContentSniffing()) {
    if (loadInfo->GetSkipContentSniffing()) {
      return NS_ERROR_NOT_AVAILABLE;
    }
  }

  mBuffer = const_cast<char*>(reinterpret_cast<const char*>(aData));
  mBufferLen = aLength;
  DetermineContentType(aRequest);
  DetermineContentType(aRequest);
  mBuffer = nullptr;
  mBufferLen = 0;
  type.Assign(mContentType);
  type.Assign(mContentType);
  mContentType.Truncate();
  mContentType.Truncate();
  return type.IsEmpty() ? NS_ERROR_NOT_AVAILABLE : NS_OK;
}


// Actual sniffing code

bool nsUnknownDecoder::AllowSniffing(nsIRequest* aRequest) {
  if (!mRequireHTMLsuffix) {
    return true;
    return true;
  }

  nsCOMPtr<nsIChannel> channel = do_QueryInterface(aRequest);
  if (!channel) {
    NS_ERROR("QI failed");
    NS_ERROR("QI failed");
    return false;
  }

  nsCOMPtr<nsIURI> uri;
  if (NS_FAILED(channel->GetURI(getter_AddRefs(uri))) || !uri) {
  if (NS_FAILED(channel->GetURI(getter_AddRefs(uri))) || !uri) {
    return false;
  }

  nsCOMPtr<nsILoadInfo> loadInfo = channel->LoadInfo();
  if (loadInfo->GetSkipContentSniffing()) {
  if (loadInfo->GetSkipContentSniffing()) {
    return false;
  }

  return !uri->SchemeIs("file");
  return !uri->SchemeIs("file");
}

/**
 * This is the array of sniffer entries that depend on "magic numbers"
 * in the file.  Each entry has either a type associated with it (set
 * these with the SNIFFER_ENTRY macro) or a function to be executed
 * these with the SNIFFER_ENTRY macro) or a function to be executed
 * (set these with the SNIFFER_ENTRY_WITH_FUNC macro).  The function
 * should take a single nsIRequest* and returns bool -- true if
 * it sets mContentType, false otherwise
 */
nsUnknownDecoder::nsSnifferEntry nsUnknownDecoder::sSnifferEntries[] = {
nsUnknownDecoder::nsSnifferEntry nsUnknownDecoder::sSnifferEntries[] = {
    SNIFFER_ENTRY("%PDF-", APPLICATION_PDF),

    SNIFFER_ENTRY("%!PS-Adobe-", APPLICATION_POSTSCRIPT),

    // Files that start with mailbox delimiters let's provisionally call
    // Files that start with mailbox delimiters let's provisionally call
    // text/plain
    SNIFFER_ENTRY("From", TEXT_PLAIN), SNIFFER_ENTRY(">From", TEXT_PLAIN),

    // If the buffer begins with "#!" or "%!" then it is a script of
    // some sort...  "Scripts" can include arbitrary data to be passed
    // some sort...  "Scripts" can include arbitrary data to be passed
    // to an interpreter, so we need to decide whether we can call this
    // text or whether it's data.
    SNIFFER_ENTRY_WITH_FUNC("#!", &nsUnknownDecoder::LastDitchSniff),

    // XXXbz should (and can) we also include the various ways that <?xml can
    // XXXbz should (and can) we also include the various ways that <?xml can
    // appear as UTF-16 and such?  See http://www.w3.org/TR/REC-xml#sec-guessing
    SNIFFER_ENTRY_WITH_FUNC("<?xml", &nsUnknownDecoder::SniffForXML)};

uint32_t nsUnknownDecoder::sSnifferEntryNum =
uint32_t nsUnknownDecoder::sSnifferEntryNum =
    sizeof(nsUnknownDecoder::sSnifferEntries) /
    sizeof(nsUnknownDecoder::nsSnifferEntry);

void nsUnknownDecoder::DetermineContentType(nsIRequest* aRequest) {
  {
  {
    MutexAutoLock lock(mMutex);
    NS_ASSERTION(mContentType.IsEmpty(), "Content type is already known.");
    if (!mContentType.IsEmpty()) return;
  }

  nsCOMPtr<nsIChannel> channel(do_QueryInterface(aRequest));
  if (channel) {
  if (channel) {
    nsCOMPtr<nsILoadInfo> loadInfo = channel->LoadInfo();
    if (loadInfo->GetSkipContentSniffing()) {
      /*
       * If we did not get a useful Content-Type from the server
       * but also have sniffing disabled, just determine whether
       * but also have sniffing disabled, just determine whether
       * to use text/plain or octetstream and log an error to the Console
       */
      LastDitchSniff(aRequest);

      nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(aRequest));
      nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(aRequest));
      if (httpChannel) {
        nsAutoCString type;
        httpChannel->GetContentType(type);
        nsCOMPtr<nsIURI> requestUri;
        httpChannel->GetURI(getter_AddRefs(requestUri));
        httpChannel->GetURI(getter_AddRefs(requestUri));
        nsAutoCString spec;
        requestUri->GetSpec(spec);
        if (spec.Length() > 50) {
          spec.Truncate(50);
          spec.AppendLiteral("...");
          spec.AppendLiteral("...");
        }
        httpChannel->LogMimeTypeMismatch(
            NS_LITERAL_CSTRING("XTCOWithMIMEValueMissing"), false,
            NS_ConvertUTF8toUTF16(spec),
            NS_ConvertUTF8toUTF16(spec),
            // Type is not used in the Error Message but required
            NS_ConvertUTF8toUTF16(type));
      }
      return;
    }
  }
  }

  const char* testData = mBuffer;
  uint32_t testDataLen = mBufferLen;
  // Check if data are compressed.
  nsAutoCString decodedData;

  if (channel) {
  if (channel) {
    // ConvertEncodedData is always called only on a single thread for each
    // instance of an object.
    nsresult rv = ConvertEncodedData(aRequest, mBuffer, mBufferLen);
    if (NS_SUCCEEDED(rv)) {
      MutexAutoLock lock(mMutex);
      MutexAutoLock lock(mMutex);
      decodedData = mDecodedData;
    }
    if (!decodedData.IsEmpty()) {
      testData = decodedData.get();
      testDataLen = std::min(decodedData.Length(), MAX_BUFFER_SIZE);
      testDataLen = std::min(decodedData.Length(), MAX_BUFFER_SIZE);
    }
  }

  // First, run through all the types we can detect reliably based on
  // magic numbers
  // magic numbers
  uint32_t i;
  for (i = 0; i < sSnifferEntryNum; ++i) {
    if (testDataLen >= sSnifferEntries[i].mByteLen &&  // enough data
        memcmp(testData, sSnifferEntries[i].mBytes,
               sSnifferEntries[i].mByteLen) == 0) {  // and type matches
               sSnifferEntries[i].mByteLen) == 0) {  // and type matches
      NS_ASSERTION(
          sSnifferEntries[i].mMimeType ||
              sSnifferEntries[i].mContentTypeSniffer,
          "Must have either a type string or a function to set the type");
          "Must have either a type string or a function to set the type");
      NS_ASSERTION(!sSnifferEntries[i].mMimeType ||
                       !sSnifferEntries[i].mContentTypeSniffer,
                   "Both a type string and a type sniffing function set;"
                   "Both a type string and a type sniffing function set;"
                   " using type string");
      if (sSnifferEntries[i].mMimeType) {
        MutexAutoLock lock(mMutex);
        mContentType = sSnifferEntries[i].mMimeType;
        NS_ASSERTION(!mContentType.IsEmpty(),
        NS_ASSERTION(!mContentType.IsEmpty(),
                     "Content type should be known by now.");
        return;
      }
      if ((this->*(sSnifferEntries[i].mContentTypeSniffer))(aRequest)) {
#ifdef DEBUG
#ifdef DEBUG
        MutexAutoLock lock(mMutex);
        NS_ASSERTION(!mContentType.IsEmpty(),
                     "Content type should be known by now.");
#endif
        return;
        return;
      }
    }
  }

  nsAutoCString sniffedType;
  nsAutoCString sniffedType;
  NS_SniffContent(NS_DATA_SNIFFER_CATEGORY, aRequest, (const uint8_t*)testData,
                  testDataLen, sniffedType);
  {
    MutexAutoLock lock(mMutex);
    mContentType = sniffedType;
    if (!mContentType.IsEmpty()) {
      return;
      return;
    }
  }

  if (SniffForHTML(aRequest)) {
#ifdef DEBUG
#ifdef DEBUG
    MutexAutoLock lock(mMutex);
    NS_ASSERTION(!mContentType.IsEmpty(),
    NS_ASSERTION(!mContentType.IsEmpty(),
                 "Content type should be known by now.");
#endif
    return;
  }


  // We don't know what this is yet.  Before we just give up, try
  // the URI from the request.
  if (SniffURI(aRequest)) {
#ifdef DEBUG
    MutexAutoLock lock(mMutex);
    MutexAutoLock lock(mMutex);
    NS_ASSERTION(!mContentType.IsEmpty(),
                 "Content type should be known by now.");
#endif
    return;
  }
  }

  LastDitchSniff(aRequest);
#ifdef DEBUG
  MutexAutoLock lock(mMutex);
  NS_ASSERTION(!mContentType.IsEmpty(), "Content type should be known by now.");
  NS_ASSERTION(!mContentType.IsEmpty(), "Content type should be known by now.");
#endif
}


bool nsUnknownDecoder::SniffForHTML(nsIRequest* aRequest) {
bool nsUnknownDecoder::SniffForHTML(nsIRequest* aRequest) {
  /*
   * To prevent a possible attack, we will not consider this to be
   * html content if it comes from the local file system and our prefs
   * html content if it comes from the local file system and our prefs
   * are set right
   */
  if (!AllowSniffing(aRequest)) {
    return false;
  }
  }

  MutexAutoLock lock(mMutex);

  // Now look for HTML.
  const char* str;
  const char* end;
  const char* end;
  if (mDecodedData.IsEmpty()) {
    str = mBuffer;
    end = mBuffer + mBufferLen;
  } else {
    str = mDecodedData.get();
    str = mDecodedData.get();
    end = mDecodedData.get() + std::min(mDecodedData.Length(), MAX_BUFFER_SIZE);
  }

  // skip leading whitespace
  // skip leading whitespace
  while (str != end && nsCRT::IsAsciiSpace(*str)) {
    ++str;
  }

  // did we find something like a start tag?
  // did we find something like a start tag?
  if (str == end || *str != '<' || ++str == end) {
    return false;
  }

  // If we seem to be SGML or XML and we got down here, just pretend we're HTML
  // If we seem to be SGML or XML and we got down here, just pretend we're HTML
  if (*str == '!' || *str == '?') {
    mContentType = TEXT_HTML;
    return true;
  }


  uint32_t bufSize = end - str;
  // We use sizeof(_tagstr) below because that's the length of _tagstr
  // with the one char " " or ">" appended.
#define MATCHES_TAG(_tagstr)                                  \
  (bufSize >= sizeof(_tagstr) &&                              \
  (bufSize >= sizeof(_tagstr) &&                              \
   (PL_strncasecmp(str, _tagstr " ", sizeof(_tagstr)) == 0 || \
    PL_strncasecmp(str, _tagstr ">", sizeof(_tagstr)) == 0))

  if (MATCHES_TAG("html") || MATCHES_TAG("frameset") || MATCHES_TAG("body") ||
      MATCHES_TAG("head") || MATCHES_TAG("script") || MATCHES_TAG("iframe") ||
      MATCHES_TAG("a") || MATCHES_TAG("img") || MATCHES_TAG("table") ||
      MATCHES_TAG("title") || MATCHES_TAG("link") || MATCHES_TAG("base") ||
      MATCHES_TAG("title") || MATCHES_TAG("link") || MATCHES_TAG("base") ||
      MATCHES_TAG("style") || MATCHES_TAG("div") || MATCHES_TAG("p") ||
      MATCHES_TAG("font") || MATCHES_TAG("applet") || MATCHES_TAG("meta") ||
      MATCHES_TAG("center") || MATCHES_TAG("form") || MATCHES_TAG("isindex") ||
      MATCHES_TAG("h1") || MATCHES_TAG("h2") || MATCHES_TAG("h3") ||
      MATCHES_TAG("h4") || MATCHES_TAG("h5") || MATCHES_TAG("h6") ||
      MATCHES_TAG("h4") || MATCHES_TAG("h5") || MATCHES_TAG("h6") ||
      MATCHES_TAG("b") || MATCHES_TAG("pre")) {
    mContentType = TEXT_HTML;
    return true;
  }


#undef MATCHES_TAG

  return false;
}


bool nsUnknownDecoder::SniffForXML(nsIRequest* aRequest) {
  // Just like HTML, this should be able to be shut off.
  if (!AllowSniffing(aRequest)) {
  if (!AllowSniffing(aRequest)) {
    return false;
  }

  // First see whether we can glean anything from the uri...
  if (!SniffURI(aRequest)) {
  if (!SniffURI(aRequest)) {
    // Oh well; just generic XML will have to do
    MutexAutoLock lock(mMutex);
    mContentType = TEXT_XML;
  }


  return true;
}

bool nsUnknownDecoder::SniffURI(nsIRequest* aRequest) {
bool nsUnknownDecoder::SniffURI(nsIRequest* aRequest) {
  nsCOMPtr<nsIChannel> channel(do_QueryInterface(aRequest));
  nsCOMPtr<nsILoadInfo> loadInfo = channel->LoadInfo();
  if (loadInfo->GetSkipContentSniffing()) {
    return false;
  }
  }
  nsCOMPtr<nsIMIMEService> mimeService(do_GetService("@mozilla.org/mime;1"));
  if (mimeService) {
    nsCOMPtr<nsIChannel> channel = do_QueryInterface(aRequest);
    if (channel) {
      nsCOMPtr<nsIURI> uri;
      nsCOMPtr<nsIURI> uri;
      nsresult result = channel->GetURI(getter_AddRefs(uri));
      if (NS_SUCCEEDED(result) && uri) {
        nsAutoCString type;
        result = mimeService->GetTypeFromURI(uri, type);
        if (NS_SUCCEEDED(result)) {
        if (NS_SUCCEEDED(result)) {
          MutexAutoLock lock(mMutex);
          mContentType = type;
          return true;
        }
      }
      }
    }
  }

  return false;
}
}

// This macro is based on RFC 2046 Section 4.1.2.  Treat any char 0-31
// except the 9-13 range (\t, \n, \v, \f, \r) and char 27 (used by
// encodings like Shift_JIS) as non-text
#define IS_TEXT_CHAR(ch) \
#define IS_TEXT_CHAR(ch) \
  (((unsigned char)(ch)) > 31 || (9 <= (ch) && (ch) <= 13) || (ch) == 27)

bool nsUnknownDecoder::LastDitchSniff(nsIRequest* aRequest) {
  // All we can do now is try to guess whether this is text/plain or
  // application/octet-stream
  // application/octet-stream

  MutexAutoLock lock(mMutex);

  const char* testData;
  uint32_t testDataLen;
  uint32_t testDataLen;
  if (mDecodedData.IsEmpty()) {
    testData = mBuffer;
    // Since some legacy text files end with 0x1A, reading the entire buffer
    // will lead misdetection.
    testDataLen = std::min<uint32_t>(mBufferLen, MAX_BUFFER_SIZE);
    testDataLen = std::min<uint32_t>(mBufferLen, MAX_BUFFER_SIZE);
  } else {
    testData = mDecodedData.get();
    testDataLen = std::min(mDecodedData.Length(), MAX_BUFFER_SIZE);
  }


  // First, check for a BOM.  If we see one, assume this is text/plain
  // in whatever encoding.  If there is a BOM _and_ text we will
  // always have at least 4 bytes in the buffer (since the 2-byte BOMs
  // are for 2-byte encodings and the UTF-8 BOM is 3 bytes).
  // are for 2-byte encodings and the UTF-8 BOM is 3 bytes).
  if (testDataLen >= 4) {
    const unsigned char* buf = (const unsigned char*)testData;
    if ((buf[0] == 0xFE && buf[1] == 0xFF) ||  // UTF-16, Big Endian
        (buf[0] == 0xFF && buf[1] == 0xFE) ||  // UTF-16 or UCS-4, Little Endian
        (buf[0] == 0xFF && buf[1] == 0xFE) ||  // UTF-16 or UCS-4, Little Endian
        (buf[0] == 0xEF && buf[1] == 0xBB && buf[2] == 0xBF) ||  // UTF-8
        (buf[0] == 0 && buf[1] == 0 && buf[2] == 0xFE &&
         buf[3] == 0xFF)) {  // UCS-4, Big Endian

      mContentType = TEXT_PLAIN;
      mContentType = TEXT_PLAIN;
      return true;
    }
  }

  // Now see whether the buffer has any non-text chars.  If not, then let's
  // Now see whether the buffer has any non-text chars.  If not, then let's
  // just call it text/plain...
  //
  uint32_t i;
  for (i = 0; i < testDataLen && IS_TEXT_CHAR(testData[i]); i++) {
  }
  }

  if (i == testDataLen) {
    mContentType = TEXT_PLAIN;
  } else {
    mContentType = APPLICATION_OCTET_STREAM;
  }


  return true;
}

nsresult nsUnknownDecoder::FireListenerNotifications(nsIRequest* request,
                                                     nsISupports* aCtxt) {
                                                     nsISupports* aCtxt) {
  nsresult rv = NS_OK;

  nsCOMPtr<nsIStreamListener> listener;
  nsAutoCString contentType;
  {
  {
    MutexAutoLock lock(mMutex);
    if (!mNextListener) return NS_ERROR_FAILURE;


    listener = mNextListener;
    contentType = mContentType;
  }

  if (!contentType.IsEmpty()) {
  if (!contentType.IsEmpty()) {
    nsCOMPtr<nsIViewSourceChannel> viewSourceChannel =
        do_QueryInterface(request);
    if (viewSourceChannel) {
      rv = viewSourceChannel->SetOriginalContentType(contentType);
    } else {
    } else {
      nsCOMPtr<nsIChannel> channel = do_QueryInterface(request, &rv);
      if (NS_SUCCEEDED(rv)) {
        // Set the new content type on the channel...
        rv = channel->SetContentType(contentType);
        rv = channel->SetContentType(contentType);
      }
    }

    NS_ASSERTION(NS_SUCCEEDED(rv), "Unable to set content type on channel!");


    if (NS_FAILED(rv)) {
      // Cancel the request to make sure it has the correct status if
      // mNextListener looks at it.
      request->Cancel(rv);
      listener->OnStartRequest(request);
      listener->OnStartRequest(request);

      nsCOMPtr<nsIDivertableChannel> divertable = do_QueryInterface(request);
      if (divertable) {
        rv = divertable->UnknownDecoderInvolvedOnStartRequestCalled();
      }
      }

      return rv;
    }
  }


  // Fire the OnStartRequest(...)
  rv = listener->OnStartRequest(request);

  nsCOMPtr<nsIDivertableChannel> divertable = do_QueryInterface(request);
  if (divertable) {
    rv = divertable->UnknownDecoderInvolvedOnStartRequestCalled();
    rv = divertable->UnknownDecoderInvolvedOnStartRequestCalled();
    bool diverting;
    divertable->GetDivertingToParent(&diverting);
    if (diverting) {
      // The channel is diverted to the parent do not send any more data here.
      return rv;
      return rv;
    }
  }

  if (NS_SUCCEEDED(rv)) {
  if (NS_SUCCEEDED(rv)) {
    // install stream converter if required
    nsCOMPtr<nsIEncodedChannel> encodedChannel = do_QueryInterface(request);
    if (encodedChannel) {
      nsCOMPtr<nsIStreamListener> listenerNew;
      rv = encodedChannel->DoApplyContentConversions(
      rv = encodedChannel->DoApplyContentConversions(
          listener, getter_AddRefs(listenerNew), aCtxt);
      if (NS_SUCCEEDED(rv) && listenerNew) {
        MutexAutoLock lock(mMutex);
        mNextListener = listenerNew;
        listener = listenerNew;
        listener = listenerNew;
      }
    }
  }

  if (!mBuffer) return NS_ERROR_OUT_OF_MEMORY;
  if (!mBuffer) return NS_ERROR_OUT_OF_MEMORY;

  // If the request was canceled, then we need to treat that equivalently
  // to an error returned by OnStartRequest.
  if (NS_SUCCEEDED(rv)) request->GetStatus(&rv);


  // Fire the first OnDataAvailable for the data that was read from the
  // stream into the sniffer buffer...
  if (NS_SUCCEEDED(rv) && (mBufferLen > 0)) {
    uint32_t len = 0;
    nsCOMPtr<nsIInputStream> in;
    nsCOMPtr<nsIInputStream> in;
    nsCOMPtr<nsIOutputStream> out;
    nsCOMPtr<nsIOutputStream> out;

    // Create a pipe and fill it with the data from the sniffer buffer.
    rv = NS_NewPipe(getter_AddRefs(in), getter_AddRefs(out), MAX_BUFFER_SIZE,
                    MAX_BUFFER_SIZE);


    if (NS_SUCCEEDED(rv)) {
      rv = out->Write(mBuffer, mBufferLen, &len);
      if (NS_SUCCEEDED(rv)) {
        if (len == mBufferLen) {
          rv = listener->OnDataAvailable(request, in, 0, len);
          rv = listener->OnDataAvailable(request, in, 0, len);
        } else {
          NS_ERROR("Unable to write all the data into the pipe.");
          rv = NS_ERROR_FAILURE;
        }
      }
      }
    }
  }

  delete[] mBuffer;
  mBuffer = nullptr;
  mBufferLen = 0;


  return rv;
}

nsresult nsUnknownDecoder::ConvertEncodedData(nsIRequest* request,
                                              const char* data,
                                              const char* data,
                                              uint32_t length) {
  nsresult rv = NS_OK;

  {
    MutexAutoLock lock(mMutex);
    MutexAutoLock lock(mMutex);
    mDecodedData = "";
  }
  nsCOMPtr<nsIEncodedChannel> encodedChannel(do_QueryInterface(request));
  if (encodedChannel) {
    RefPtr<ConvertedStreamListener> strListener =
    RefPtr<ConvertedStreamListener> strListener =
        new ConvertedStreamListener(this);

    nsCOMPtr<nsIStreamListener> listener;
    rv = encodedChannel->DoApplyContentConversions(
    rv = encodedChannel->DoApplyContentConversions(
        strListener, getter_AddRefs(listener), nullptr);

    if (NS_FAILED(rv)) {
      return rv;
    }
    }

    if (listener) {
      listener->OnStartRequest(request);

      if (length) {
      if (length) {
        nsCOMPtr<nsIStringInputStream> rawStream =
            do_CreateInstance(NS_STRINGINPUTSTREAM_CONTRACTID);
        if (!rawStream) return NS_ERROR_FAILURE;

        rv = rawStream->SetData((const char*)data, length);
        rv = rawStream->SetData((const char*)data, length);
        NS_ENSURE_SUCCESS(rv, rv);

        rv = listener->OnDataAvailable(request, rawStream, 0, length);
        NS_ENSURE_SUCCESS(rv, rv);
      }

      listener->OnStopRequest(request, NS_OK);
    }
  }
  }
  return rv;
}

//
// nsIThreadRetargetableStreamListener methods
// nsIThreadRetargetableStreamListener methods
//
NS_IMETHODIMP
nsUnknownDecoder::CheckListenerChain() {
  nsCOMPtr<nsIThreadRetargetableStreamListener> listener;
  {
  {
    MutexAutoLock lock(mMutex);
    listener = do_QueryInterface(mNextListener);
    listener = do_QueryInterface(mNextListener);
  }
  if (!listener) {
    return NS_ERROR_NO_INTERFACE;
  }
  }

  return listener->CheckListenerChain();
}

void nsBinaryDetector::DetermineContentType(nsIRequest* aRequest) {
void nsBinaryDetector::DetermineContentType(nsIRequest* aRequest) {
  nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(aRequest);
  if (!httpChannel) {
    return;
  }


  nsCOMPtr<nsILoadInfo> loadInfo = httpChannel->LoadInfo();
  if (loadInfo->GetSkipContentSniffing()) {
    LastDitchSniff(aRequest);
    return;
  }
  }
  // It's an HTTP channel.  Check for the text/plain mess
  nsAutoCString contentTypeHdr;
  Unused << httpChannel->GetResponseHeader(NS_LITERAL_CSTRING("Content-Type"),
                                           contentTypeHdr);
  nsAutoCString contentType;
  nsAutoCString contentType;
  httpChannel->GetContentType(contentType);

  // Make sure to do a case-sensitive exact match comparison here.  Apache
  // 1.x just sends text/plain for "unknown", while Apache 2.x sends
  // text/plain with a ISO-8859-1 charset.  Debian's Apache version, just to
  // text/plain with a ISO-8859-1 charset.  Debian's Apache version, just to
  // be different, sends text/plain with iso-8859-1 charset.  For extra fun,
  // FC7, RHEL4, and Ubuntu Feisty send charset=UTF-8.  Don't do general
  // case-insensitive comparison, since we really want to apply this crap as
  // rarely as we can.
  if (!contentType.EqualsLiteral("text/plain") ||
  if (!contentType.EqualsLiteral("text/plain") ||
      (!contentTypeHdr.EqualsLiteral("text/plain") &&
       !contentTypeHdr.EqualsLiteral("text/plain; charset=ISO-8859-1") &&
       !contentTypeHdr.EqualsLiteral("text/plain; charset=ISO-8859-1") &&
       !contentTypeHdr.EqualsLiteral("text/plain; charset=iso-8859-1") &&
       !contentTypeHdr.EqualsLiteral("text/plain; charset=UTF-8"))) {
    return;
  }


  // Check whether we have content-encoding.  If we do, don't try to
  // detect the type.
  // XXXbz we could improve this by doing a local decompress if we
  // wanted, I'm sure.
  nsAutoCString contentEncoding;
  nsAutoCString contentEncoding;
  Unused << httpChannel->GetResponseHeader(
      NS_LITERAL_CSTRING("Content-Encoding"), contentEncoding);
  if (!contentEncoding.IsEmpty()) {
    return;
  }
  }

  LastDitchSniff(aRequest);
  MutexAutoLock lock(mMutex);
  if (mContentType.EqualsLiteral(APPLICATION_OCTET_STREAM)) {
    // We want to guess at it instead
    mContentType = APPLICATION_GUESS_FROM_EXT;
  } else {
    // Let the text/plain type we already have be, so that other content
    // sniffers can also get a shot at this data.
    mContentType.Truncate();
  }
  }
}