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.

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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* 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 "DataTransferItemList.h"

#include "nsContentUtils.h"
#include "nsIGlobalObject.h"
#include "nsIClipboard.h"
#include "nsIScriptObjectPrincipal.h"
#include "nsIScriptGlobalObject.h"
#include "nsIScriptContext.h"
#include "nsISupportsPrimitives.h"
#include "nsQueryObject.h"
#include "nsVariant.h"
#include "mozilla/ContentEvents.h"
#include "mozilla/EventForwards.h"
#include "mozilla/storage/Variant.h"
#include "mozilla/dom/DataTransferItemListBinding.h"

namespace mozilla {
namespace dom {

NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE(DataTransferItemList, mDataTransfer,
                                      mItems, mIndexedItems, mFiles)
NS_IMPL_CYCLE_COLLECTING_ADDREF(DataTransferItemList)
NS_IMPL_CYCLE_COLLECTING_RELEASE(DataTransferItemList)

NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(DataTransferItemList)
  NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
  NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END

JSObject* DataTransferItemList::WrapObject(JSContext* aCx,
                                           JS::Handle<JSObject*> aGivenProto) {
  return DataTransferItemList_Binding::Wrap(aCx, this, aGivenProto);
}

already_AddRefed<DataTransferItemList> DataTransferItemList::Clone(
    DataTransfer* aDataTransfer) const {
  RefPtr<DataTransferItemList> list = new DataTransferItemList(aDataTransfer);

  // We need to clone the mItems and mIndexedItems lists while keeping the same
  // correspondences between the mIndexedItems and mItems lists (namely, if an
  // item is in mIndexedItems, and mItems it must have the same new identity)

  // First, we copy over indexedItems, and clone every entry. Then, we go over
  // mItems. For every entry, we use its mIndex property to locate it in
  // mIndexedItems on the original DataTransferItemList, and then copy over the
  // reference from the same index pair on the new DataTransferItemList

  list->mIndexedItems.SetLength(mIndexedItems.Length());
  list->mItems.SetLength(mItems.Length());

  // Copy over mIndexedItems, cloning every entry
  for (uint32_t i = 0; i < mIndexedItems.Length(); i++) {
    const nsTArray<RefPtr<DataTransferItem>>& items = mIndexedItems[i];
    nsTArray<RefPtr<DataTransferItem>>& newItems = list->mIndexedItems[i];
    newItems.SetLength(items.Length());
    for (uint32_t j = 0; j < items.Length(); j++) {
      newItems[j] = items[j]->Clone(aDataTransfer);
    }
  }

  // Copy over mItems, getting the actual entries from mIndexedItems
  for (uint32_t i = 0; i < mItems.Length(); i++) {
    uint32_t index = mItems[i]->Index();
    MOZ_ASSERT(index < mIndexedItems.Length());
    uint32_t subIndex = mIndexedItems[index].IndexOf(mItems[i]);

    // Copy over the reference
    list->mItems[i] = list->mIndexedItems[index][subIndex];
  }

  return list.forget();
}

void DataTransferItemList::Remove(uint32_t aIndex,
                                  nsIPrincipal& aSubjectPrincipal,
                                  ErrorResult& aRv) {
  if (mDataTransfer->IsReadOnly()) {
    aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
    return;
  }

  if (aIndex >= Length()) {
    return;
  }

  ClearDataHelper(mItems[aIndex], aIndex, -1, aSubjectPrincipal, aRv);
}

DataTransferItem* DataTransferItemList::IndexedGetter(uint32_t aIndex,
                                                      bool& aFound) const {
  if (aIndex >= mItems.Length()) {
    aFound = false;
    return nullptr;
  }

  MOZ_ASSERT(mItems[aIndex]);
  aFound = true;
  return mItems[aIndex];
}

uint32_t DataTransferItemList::MozItemCount() const {
  uint32_t length = mIndexedItems.Length();
  // XXX: Compat hack - Index 0 always exists due to changes in internals, but
  // if it is empty, scripts using the moz* APIs should see it as not existing.
  if (length == 1 && mIndexedItems[0].IsEmpty()) {
    return 0;
  }
  return length;
}

void DataTransferItemList::Clear(nsIPrincipal& aSubjectPrincipal,
                                 ErrorResult& aRv) {
  if (NS_WARN_IF(mDataTransfer->IsReadOnly())) {
    return;
  }

  uint32_t count = Length();
  for (uint32_t i = 0; i < count; i++) {
    // We always remove the last item first, to avoid moving items around in
    // memory as much
    Remove(Length() - 1, aSubjectPrincipal, aRv);
    ENSURE_SUCCESS_VOID(aRv);
  }

  MOZ_ASSERT(Length() == 0);
}

DataTransferItem* DataTransferItemList::Add(const nsAString& aData,
                                            const nsAString& aType,
                                            nsIPrincipal& aSubjectPrincipal,
                                            ErrorResult& aRv) {
  if (NS_WARN_IF(mDataTransfer->IsReadOnly())) {
    return nullptr;
  }

  RefPtr<nsVariantCC> data(new nsVariantCC());
  data->SetAsAString(aData);

  nsAutoString format;
  mDataTransfer->GetRealFormat(aType, format);

  if (!DataTransfer::PrincipalMaySetData(format, data, &aSubjectPrincipal)) {
    aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
    return nullptr;
  }

  // We add the textual data to index 0. We set aInsertOnly to true, as we don't
  // want to update an existing entry if it is already present, as per the spec.
  RefPtr<DataTransferItem> item =
      SetDataWithPrincipal(format, data, 0, &aSubjectPrincipal,
                           /* aInsertOnly = */ true,
                           /* aHidden = */ false, aRv);
  if (NS_WARN_IF(aRv.Failed())) {
    return nullptr;
  }
  MOZ_ASSERT(item->Kind() != DataTransferItem::KIND_FILE);

  return item;
}

DataTransferItem* DataTransferItemList::Add(File& aData,
                                            nsIPrincipal& aSubjectPrincipal,
                                            ErrorResult& aRv) {
  if (mDataTransfer->IsReadOnly()) {
    return nullptr;
  }

  nsCOMPtr<nsISupports> supports = do_QueryObject(&aData);
  nsCOMPtr<nsIWritableVariant> data = new nsVariantCC();
  data->SetAsISupports(supports);

  nsAutoString type;
  aData.GetType(type);

  if (!DataTransfer::PrincipalMaySetData(type, data, &aSubjectPrincipal)) {
    aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
    return nullptr;
  }

  // We need to add this as a new item, as multiple files can't exist in the
  // same item in the Moz DataTransfer layout. It will be appended at the end of
  // the internal specced layout.
  uint32_t index = mIndexedItems.Length();
  RefPtr<DataTransferItem> item =
      SetDataWithPrincipal(type, data, index, &aSubjectPrincipal,
                           /* aInsertOnly = */ true,
                           /* aHidden = */ false, aRv);
  if (NS_WARN_IF(aRv.Failed())) {
    return nullptr;
  }
  MOZ_ASSERT(item->Kind() == DataTransferItem::KIND_FILE);

  return item;
}

already_AddRefed<FileList> DataTransferItemList::Files(
    nsIPrincipal* aPrincipal) {
  // The DataTransfer can hold data with varying principals, coming from
  // different windows. This means that permissions checks need to be made when
  // accessing data from the DataTransfer. With the accessor methods, this is
  // checked by DataTransferItem::Data(), however with files, we keep a cached
  // live copy of the files list for spec compliance.
  //
  // A DataTransfer is only exposed to one webpage, and chrome code. The chrome
  // code should be able to see all files on the DataTransfer, while the webpage
  // should only be able to see the files it can see. As chrome code doesn't
  // need as strict spec compliance as web visible code, we generate a new
  // FileList object every time you access the Files list from chrome code, but
  // re-use the cached one when accessing from non-chrome code.
  //
  // It is not legal to expose an identical DataTransfer object is to multiple
  // different principals without using the `Clone` method or similar to copy it
  // first. If that happens, this method will assert, and return nullptr in
  // release builds. If this functionality is required in the future, a more
  // advanced caching mechanism for the FileList objects will be required.
  RefPtr<FileList> files;
  if (nsContentUtils::IsSystemPrincipal(aPrincipal)) {
    files = new FileList(mDataTransfer);
    GenerateFiles(files, aPrincipal);
    return files.forget();
  }

  if (!mFiles) {
    mFiles = new FileList(mDataTransfer);
    mFilesPrincipal = aPrincipal;
    RegenerateFiles();
  }

  if (!aPrincipal->Subsumes(mFilesPrincipal)) {
    MOZ_ASSERT(false,
               "This DataTransfer should only be accessed by the system "
               "and a single principal");
    return nullptr;
  }

  files = mFiles;
  return files.forget();
}

void DataTransferItemList::MozRemoveByTypeAt(const nsAString& aType,
                                             uint32_t aIndex,
                                             nsIPrincipal& aSubjectPrincipal,
                                             ErrorResult& aRv) {
  if (NS_WARN_IF(mDataTransfer->IsReadOnly() ||
                 aIndex >= mIndexedItems.Length())) {
    return;
  }

  bool removeAll = aType.IsEmpty();

  nsTArray<RefPtr<DataTransferItem>>& items = mIndexedItems[aIndex];
  uint32_t count = items.Length();
  // We remove the last item of the list repeatedly - that way we don't
  // have to worry about modifying the loop iterator
  if (removeAll) {
    for (uint32_t i = 0; i < count; ++i) {
      uint32_t index = items.Length() - 1;
      MOZ_ASSERT(index == count - i - 1);

      ClearDataHelper(items[index], -1, index, aSubjectPrincipal, aRv);
      if (NS_WARN_IF(aRv.Failed())) {
        return;
      }
    }

    // items is no longer a valid reference, as removing the last element from
    // it via ClearDataHelper invalidated it. so we can't MOZ_ASSERT that the
    // length is now 0.
    return;
  }

  for (uint32_t i = 0; i < count; ++i) {
    // NOTE: As this is a moz-prefixed API, it works based on internal types.
    nsAutoString type;
    items[i]->GetInternalType(type);
    if (type == aType) {
      ClearDataHelper(items[i], -1, i, aSubjectPrincipal, aRv);
      return;
    }
  }
}

DataTransferItem* DataTransferItemList::MozItemByTypeAt(const nsAString& aType,
                                                        uint32_t aIndex) {
  if (NS_WARN_IF(aIndex >= mIndexedItems.Length())) {
    return nullptr;
  }

  uint32_t count = mIndexedItems[aIndex].Length();
  for (uint32_t i = 0; i < count; i++) {
    RefPtr<DataTransferItem> item = mIndexedItems[aIndex][i];
    // NOTE: As this is a moz-prefixed API it works on internal types
    nsString type;
    item->GetInternalType(type);
    if (type.Equals(aType)) {
      return item;
    }
  }

  return nullptr;
}

already_AddRefed<DataTransferItem> DataTransferItemList::SetDataWithPrincipal(
    const nsAString& aType, nsIVariant* aData, uint32_t aIndex,
    nsIPrincipal* aPrincipal, bool aInsertOnly, bool aHidden,
    ErrorResult& aRv) {
  if (aIndex < mIndexedItems.Length()) {
    nsTArray<RefPtr<DataTransferItem>>& items = mIndexedItems[aIndex];
    uint32_t count = items.Length();
    for (uint32_t i = 0; i < count; i++) {
      RefPtr<DataTransferItem> item = items[i];
      nsString type;
      item->GetInternalType(type);
      if (type.Equals(aType)) {
        if (NS_WARN_IF(aInsertOnly)) {
          aRv.Throw(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
          return nullptr;
        }

        // don't allow replacing data that has a stronger principal
        bool subsumes;
        if (NS_WARN_IF(item->Principal() && aPrincipal &&
                       (NS_FAILED(aPrincipal->Subsumes(item->Principal(),
                                                       &subsumes)) ||
                        !subsumes))) {
          aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
          return nullptr;
        }
        item->SetPrincipal(aPrincipal);

        DataTransferItem::eKind oldKind = item->Kind();
        item->SetData(aData);

        mDataTransfer->TypesListMayHaveChanged();

        if (aIndex != 0) {
          // If the item changes from being a file to not a file or vice-versa,
          // its presence in the mItems array may need to change.
          if (item->Kind() == DataTransferItem::KIND_FILE &&
              oldKind != DataTransferItem::KIND_FILE) {
            // not file => file
            mItems.AppendElement(item);
          } else if (item->Kind() != DataTransferItem::KIND_FILE &&
                     oldKind == DataTransferItem::KIND_FILE) {
            // file => not file
            mItems.RemoveElement(item);
          }
        }

        // Regenerate the Files array if we have modified a file's status
        if (item->Kind() == DataTransferItem::KIND_FILE ||
            oldKind == DataTransferItem::KIND_FILE) {
          RegenerateFiles();
        }

        return item.forget();
      }
    }
  } else {
    // Make sure that we aren't adding past the end of the mIndexedItems array.
    // XXX Should this be a MOZ_ASSERT instead?
    aIndex = mIndexedItems.Length();
  }

  // Add the new item
  RefPtr<DataTransferItem> item =
      AppendNewItem(aIndex, aType, aData, aPrincipal, aHidden);

  if (item->Kind() == DataTransferItem::KIND_FILE) {
    RegenerateFiles();
  }

  return item.forget();
}

DataTransferItem* DataTransferItemList::AppendNewItem(uint32_t aIndex,
                                                      const nsAString& aType,
                                                      nsIVariant* aData,
                                                      nsIPrincipal* aPrincipal,
                                                      bool aHidden) {
  if (mIndexedItems.Length() <= aIndex) {
    MOZ_ASSERT(mIndexedItems.Length() == aIndex);
    mIndexedItems.AppendElement();
  }
  RefPtr<DataTransferItem> item = new DataTransferItem(mDataTransfer, aType);
  item->SetIndex(aIndex);
  item->SetPrincipal(aPrincipal);
  item->SetData(aData);
  item->SetChromeOnly(aHidden);

  mIndexedItems[aIndex].AppendElement(item);

  // We only want to add the item to the main mItems list if the index we are
  // adding to is 0, or the item we are adding is a file. If we add an item
  // which is not a file to a non-zero index, invariants could be broken.
  // (namely the invariant that there are not 2 non-file entries in the items
  // array with the same type).
  //
  // We also want to update our DataTransfer's type list any time we're adding a
  // KIND_FILE item, or an item at index 0.
  if (item->Kind() == DataTransferItem::KIND_FILE || aIndex == 0) {
    if (!aHidden) {
      mItems.AppendElement(item);
    }
    mDataTransfer->TypesListMayHaveChanged();
  }

  return item;
}

const nsTArray<RefPtr<DataTransferItem>>* DataTransferItemList::MozItemsAt(
    uint32_t aIndex)  // -- INDEXED
{
  if (aIndex >= mIndexedItems.Length()) {
    return nullptr;
  }

  return &mIndexedItems[aIndex];
}

void DataTransferItemList::PopIndexZero() {
  MOZ_ASSERT(mIndexedItems.Length() > 1);
  MOZ_ASSERT(mIndexedItems[0].IsEmpty());

  mIndexedItems.RemoveElementAt(0);

  // Update the index of every element which has now been shifted
  for (uint32_t i = 0; i < mIndexedItems.Length(); i++) {
    nsTArray<RefPtr<DataTransferItem>>& items = mIndexedItems[i];
    for (uint32_t j = 0; j < items.Length(); j++) {
      items[j]->SetIndex(i);
    }
  }
}

void DataTransferItemList::ClearAllItems() {
  // We always need to have index 0, so don't delete that one
  mItems.Clear();
  mIndexedItems.Clear();
  mIndexedItems.SetLength(1);
  mDataTransfer->TypesListMayHaveChanged();

  // Re-generate files (into an empty list)
  RegenerateFiles();
}

void DataTransferItemList::ClearDataHelper(DataTransferItem* aItem,
                                           uint32_t aIndexHint,
                                           uint32_t aMozOffsetHint,
                                           nsIPrincipal& aSubjectPrincipal,
                                           ErrorResult& aRv) {
  MOZ_ASSERT(aItem);
  if (NS_WARN_IF(mDataTransfer->IsReadOnly())) {
    return;
  }

  if (aItem->Principal() && !aSubjectPrincipal.Subsumes(aItem->Principal())) {
    aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
    return;
  }

  // Check if the aIndexHint is actually the index, and then remove the item
  // from aItems
  bool found;
  if (IndexedGetter(aIndexHint, found) == aItem) {
    mItems.RemoveElementAt(aIndexHint);
  } else {
    mItems.RemoveElement(aItem);
  }

  // Check if the aMozIndexHint and aMozOffsetHint are actually the index and
  // offset, and then remove them from mIndexedItems
  MOZ_ASSERT(aItem->Index() < mIndexedItems.Length());
  nsTArray<RefPtr<DataTransferItem>>& items = mIndexedItems[aItem->Index()];
  if (aMozOffsetHint < items.Length() && aItem == items[aMozOffsetHint]) {
    items.RemoveElementAt(aMozOffsetHint);
  } else {
    items.RemoveElement(aItem);
  }

  mDataTransfer->TypesListMayHaveChanged();

  // Check if we should remove the index. We never remove index 0.
  if (items.Length() == 0 && aItem->Index() != 0) {
    mIndexedItems.RemoveElementAt(aItem->Index());

    // Update the index of every element which has now been shifted
    for (uint32_t i = aItem->Index(); i < mIndexedItems.Length(); i++) {
      nsTArray<RefPtr<DataTransferItem>>& items = mIndexedItems[i];
      for (uint32_t j = 0; j < items.Length(); j++) {
        items[j]->SetIndex(i);
      }
    }
  }

  // Give the removed item the invalid index
  aItem->SetIndex(-1);

  if (aItem->Kind() == DataTransferItem::KIND_FILE) {
    RegenerateFiles();
  }
}

void DataTransferItemList::RegenerateFiles() {
  // We don't want to regenerate the files list unless we already have a files
  // list. That way we can avoid the unnecessary work if the user never touches
  // the files list.
  if (mFiles) {
    // We clear the list rather than performing smaller updates, because it
    // simplifies the logic greatly on this code path, which should be very
    // infrequently used.
    mFiles->Clear();

    DataTransferItemList::GenerateFiles(mFiles, mFilesPrincipal);
  }
}

void DataTransferItemList::GenerateFiles(FileList* aFiles,
                                         nsIPrincipal* aFilesPrincipal) {
  MOZ_ASSERT(aFiles);
  MOZ_ASSERT(aFilesPrincipal);

  // For non-system principals, the Files list should be empty if the
  // DataTransfer is protected.
  if (!nsContentUtils::IsSystemPrincipal(aFilesPrincipal) &&
      mDataTransfer->IsProtected()) {
    return;
  }

  uint32_t count = Length();
  for (uint32_t i = 0; i < count; i++) {
    bool found;
    RefPtr<DataTransferItem> item = IndexedGetter(i, found);
    MOZ_ASSERT(found);

    if (item->Kind() == DataTransferItem::KIND_FILE) {
      RefPtr<File> file = item->GetAsFile(*aFilesPrincipal, IgnoreErrors());
      if (NS_WARN_IF(!file)) {
        continue;
      }
      aFiles->Append(file);
    }
  }
}

}  // namespace dom
}  // namespace mozilla