Source code

Revision control

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
/* -*- Mode: C++; tab-width: 4; 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
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/**
 * The MIME stream separates headers and a datastream. It also allows
 * automatic creation of the content-length header.
 */

#include "ipc/IPCMessageUtils.h"

#include "nsCOMPtr.h"
#include "nsComponentManagerUtils.h"
#include "nsIAsyncInputStream.h"
#include "nsIInputStreamLength.h"
#include "nsIHttpHeaderVisitor.h"
#include "nsIMIMEInputStream.h"
#include "nsISeekableStream.h"
#include "nsString.h"
#include "nsMIMEInputStream.h"
#include "nsIClassInfoImpl.h"
#include "nsIIPCSerializableInputStream.h"
#include "mozilla/Move.h"
#include "mozilla/Mutex.h"
#include "mozilla/ipc/InputStreamUtils.h"

using namespace mozilla::ipc;
using mozilla::Maybe;

class nsMIMEInputStream : public nsIMIMEInputStream,
                          public nsISeekableStream,
                          public nsIIPCSerializableInputStream,
                          public nsIAsyncInputStream,
                          public nsIInputStreamCallback,
                          public nsIInputStreamLength,
                          public nsIAsyncInputStreamLength,
                          public nsIInputStreamLengthCallback,
                          public nsICloneableInputStream {
  virtual ~nsMIMEInputStream() = default;

 public:
  nsMIMEInputStream();

  NS_DECL_THREADSAFE_ISUPPORTS
  NS_DECL_NSIINPUTSTREAM
  NS_DECL_NSIMIMEINPUTSTREAM
  NS_DECL_NSISEEKABLESTREAM
  NS_DECL_NSITELLABLESTREAM
  NS_DECL_NSIIPCSERIALIZABLEINPUTSTREAM
  NS_DECL_NSIASYNCINPUTSTREAM
  NS_DECL_NSIINPUTSTREAMCALLBACK
  NS_DECL_NSIINPUTSTREAMLENGTH
  NS_DECL_NSIASYNCINPUTSTREAMLENGTH
  NS_DECL_NSIINPUTSTREAMLENGTHCALLBACK
  NS_DECL_NSICLONEABLEINPUTSTREAM

 private:
  void InitStreams();

  template <typename M>
  void SerializeInternal(InputStreamParams& aParams,
                         FileDescriptorArray& aFileDescriptors,
                         bool aDelayedStart, uint32_t aMaxSize,
                         uint32_t* aSizeUsed, M* aManager);

  struct MOZ_STACK_CLASS ReadSegmentsState {
    nsCOMPtr<nsIInputStream> mThisStream;
    nsWriteSegmentFun mWriter;
    void* mClosure;
  };
  static nsresult ReadSegCb(nsIInputStream* aIn, void* aClosure,
                            const char* aFromRawSegment, uint32_t aToOffset,
                            uint32_t aCount, uint32_t* aWriteCount);

  bool IsSeekableInputStream() const;
  bool IsAsyncInputStream() const;
  bool IsIPCSerializable() const;
  bool IsInputStreamLength() const;
  bool IsAsyncInputStreamLength() const;
  bool IsCloneableInputStream() const;

  nsTArray<HeaderEntry> mHeaders;

  nsCOMPtr<nsIInputStream> mStream;
  bool mStartedReading;

  mozilla::Mutex mMutex;

  // This is protected by mutex.
  nsCOMPtr<nsIInputStreamCallback> mAsyncWaitCallback;

  // This is protected by mutex.
  nsCOMPtr<nsIInputStreamLengthCallback> mAsyncInputStreamLengthCallback;
};

NS_IMPL_ADDREF(nsMIMEInputStream)
NS_IMPL_RELEASE(nsMIMEInputStream)

NS_IMPL_CLASSINFO(nsMIMEInputStream, nullptr, nsIClassInfo::THREADSAFE,
                  NS_MIMEINPUTSTREAM_CID)

NS_INTERFACE_MAP_BEGIN(nsMIMEInputStream)
  NS_INTERFACE_MAP_ENTRY(nsIMIMEInputStream)
  NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsIInputStream, nsIMIMEInputStream)
  NS_INTERFACE_MAP_ENTRY(nsITellableStream)
  NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsISeekableStream, IsSeekableInputStream())
  NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIIPCSerializableInputStream,
                                     IsIPCSerializable())
  NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIAsyncInputStream, IsAsyncInputStream())
  NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIInputStreamCallback,
                                     IsAsyncInputStream())
  NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIMIMEInputStream)
  NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIInputStreamLength,
                                     IsInputStreamLength())
  NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIAsyncInputStreamLength,
                                     IsAsyncInputStreamLength())
  NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIInputStreamLengthCallback,
                                     IsAsyncInputStreamLength())
  NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsICloneableInputStream,
                                     IsCloneableInputStream())
  NS_IMPL_QUERY_CLASSINFO(nsMIMEInputStream)
NS_INTERFACE_MAP_END

NS_IMPL_CI_INTERFACE_GETTER(nsMIMEInputStream, nsIMIMEInputStream,
                            nsIAsyncInputStream, nsIInputStream,
                            nsISeekableStream, nsITellableStream)

nsMIMEInputStream::nsMIMEInputStream()
    : mStartedReading(false), mMutex("nsMIMEInputStream::mMutex") {}

NS_IMETHODIMP
nsMIMEInputStream::AddHeader(const char* aName, const char* aValue) {
  NS_ENSURE_FALSE(mStartedReading, NS_ERROR_FAILURE);

  HeaderEntry* entry = mHeaders.AppendElement();
  entry->name().Append(aName);
  entry->value().Append(aValue);

  return NS_OK;
}

NS_IMETHODIMP
nsMIMEInputStream::VisitHeaders(nsIHttpHeaderVisitor* visitor) {
  nsresult rv;

  for (auto& header : mHeaders) {
    rv = visitor->VisitHeader(header.name(), header.value());
    if (NS_FAILED(rv)) {
      return rv;
    }
  }
  return NS_OK;
}

NS_IMETHODIMP
nsMIMEInputStream::SetData(nsIInputStream* aStream) {
  NS_ENSURE_FALSE(mStartedReading, NS_ERROR_FAILURE);

  nsCOMPtr<nsISeekableStream> seekable = do_QueryInterface(aStream);
  if (!seekable) {
    return NS_ERROR_INVALID_ARG;
  }

  mStream = aStream;
  return NS_OK;
}

NS_IMETHODIMP
nsMIMEInputStream::GetData(nsIInputStream** aStream) {
  NS_ENSURE_ARG_POINTER(aStream);
  *aStream = mStream;
  NS_IF_ADDREF(*aStream);
  return NS_OK;
}

// set up the internal streams
void nsMIMEInputStream::InitStreams() {
  NS_ASSERTION(!mStartedReading,
               "Don't call initStreams twice without rewinding");

  mStartedReading = true;
}

#define INITSTREAMS                               \
  if (!mStartedReading) {                         \
    NS_ENSURE_TRUE(mStream, NS_ERROR_UNEXPECTED); \
    InitStreams();                                \
  }

// Reset mStartedReading when Seek-ing to start
NS_IMETHODIMP
nsMIMEInputStream::Seek(int32_t whence, int64_t offset) {
  NS_ENSURE_TRUE(mStream, NS_ERROR_UNEXPECTED);

  nsresult rv;
  nsCOMPtr<nsISeekableStream> stream = do_QueryInterface(mStream);

  if (whence == NS_SEEK_SET && offset == 0) {
    rv = stream->Seek(whence, offset);
    if (NS_SUCCEEDED(rv)) mStartedReading = false;
  } else {
    INITSTREAMS;
    rv = stream->Seek(whence, offset);
  }

  return rv;
}

// Proxy ReadSegments since we need to be a good little nsIInputStream
NS_IMETHODIMP nsMIMEInputStream::ReadSegments(nsWriteSegmentFun aWriter,
                                              void* aClosure, uint32_t aCount,
                                              uint32_t* _retval) {
  INITSTREAMS;
  ReadSegmentsState state;
  // Disambiguate ambiguous nsIInputStream.
  state.mThisStream =
      static_cast<nsIInputStream*>(static_cast<nsIMIMEInputStream*>(this));
  state.mWriter = aWriter;
  state.mClosure = aClosure;
  return mStream->ReadSegments(ReadSegCb, &state, aCount, _retval);
}

nsresult nsMIMEInputStream::ReadSegCb(nsIInputStream* aIn, void* aClosure,
                                      const char* aFromRawSegment,
                                      uint32_t aToOffset, uint32_t aCount,
                                      uint32_t* aWriteCount) {
  ReadSegmentsState* state = (ReadSegmentsState*)aClosure;
  return (state->mWriter)(state->mThisStream, state->mClosure, aFromRawSegment,
                          aToOffset, aCount, aWriteCount);
}

/**
 * Forward everything else to the mStream after calling InitStreams()
 */

// nsIInputStream
NS_IMETHODIMP nsMIMEInputStream::Close(void) {
  INITSTREAMS;
  return mStream->Close();
}
NS_IMETHODIMP nsMIMEInputStream::Available(uint64_t* _retval) {
  INITSTREAMS;
  return mStream->Available(_retval);
}
NS_IMETHODIMP nsMIMEInputStream::Read(char* buf, uint32_t count,
                                      uint32_t* _retval) {
  INITSTREAMS;
  return mStream->Read(buf, count, _retval);
}
NS_IMETHODIMP nsMIMEInputStream::IsNonBlocking(bool* aNonBlocking) {
  INITSTREAMS;
  return mStream->IsNonBlocking(aNonBlocking);
}

// nsIAsyncInputStream
NS_IMETHODIMP
nsMIMEInputStream::CloseWithStatus(nsresult aStatus) {
  INITSTREAMS;
  nsCOMPtr<nsIAsyncInputStream> asyncStream = do_QueryInterface(mStream);
  return asyncStream->CloseWithStatus(aStatus);
}

NS_IMETHODIMP
nsMIMEInputStream::AsyncWait(nsIInputStreamCallback* aCallback, uint32_t aFlags,
                             uint32_t aRequestedCount,
                             nsIEventTarget* aEventTarget) {
  INITSTREAMS;
  nsCOMPtr<nsIAsyncInputStream> asyncStream = do_QueryInterface(mStream);
  if (NS_WARN_IF(!asyncStream)) {
    return NS_ERROR_FAILURE;
  }

  nsCOMPtr<nsIInputStreamCallback> callback = aCallback ? this : nullptr;
  {
    MutexAutoLock lock(mMutex);
    if (mAsyncWaitCallback && aCallback) {
      return NS_ERROR_FAILURE;
    }

    mAsyncWaitCallback = aCallback;
  }

  return asyncStream->AsyncWait(callback, aFlags, aRequestedCount,
                                aEventTarget);
}

// nsIInputStreamCallback

NS_IMETHODIMP
nsMIMEInputStream::OnInputStreamReady(nsIAsyncInputStream* aStream) {
  nsCOMPtr<nsIInputStreamCallback> callback;

  {
    MutexAutoLock lock(mMutex);

    // We have been canceled in the meanwhile.
    if (!mAsyncWaitCallback) {
      return NS_OK;
    }

    callback.swap(mAsyncWaitCallback);
  }

  MOZ_ASSERT(callback);
  return callback->OnInputStreamReady(this);
}

// nsITellableStream
NS_IMETHODIMP nsMIMEInputStream::Tell(int64_t* _retval) {
  INITSTREAMS;
  nsCOMPtr<nsITellableStream> stream = do_QueryInterface(mStream);
  return stream->Tell(_retval);
}

// nsISeekableStream
NS_IMETHODIMP nsMIMEInputStream::SetEOF(void) {
  INITSTREAMS;
  nsCOMPtr<nsISeekableStream> stream = do_QueryInterface(mStream);
  return stream->SetEOF();
}

/**
 * Factory method used by do_CreateInstance
 */

nsresult nsMIMEInputStreamConstructor(nsISupports* outer, REFNSIID iid,
                                      void** result) {
  *result = nullptr;

  if (outer) return NS_ERROR_NO_AGGREGATION;

  RefPtr<nsMIMEInputStream> inst = new nsMIMEInputStream();
  if (!inst) return NS_ERROR_OUT_OF_MEMORY;

  return inst->QueryInterface(iid, result);
}

void nsMIMEInputStream::Serialize(InputStreamParams& aParams,
                                  FileDescriptorArray& aFileDescriptors,
                                  bool aDelayedStart, uint32_t aMaxSize,
                                  uint32_t* aSizeUsed,
                                  mozilla::dom::ContentChild* aManager) {
  SerializeInternal(aParams, aFileDescriptors, aDelayedStart, aMaxSize,
                    aSizeUsed, aManager);
}

void nsMIMEInputStream::Serialize(InputStreamParams& aParams,
                                  FileDescriptorArray& aFileDescriptors,
                                  bool aDelayedStart, uint32_t aMaxSize,
                                  uint32_t* aSizeUsed,
                                  PBackgroundChild* aManager) {
  SerializeInternal(aParams, aFileDescriptors, aDelayedStart, aMaxSize,
                    aSizeUsed, aManager);
}

void nsMIMEInputStream::Serialize(InputStreamParams& aParams,
                                  FileDescriptorArray& aFileDescriptors,
                                  bool aDelayedStart, uint32_t aMaxSize,
                                  uint32_t* aSizeUsed,
                                  mozilla::dom::ContentParent* aManager) {
  SerializeInternal(aParams, aFileDescriptors, aDelayedStart, aMaxSize,
                    aSizeUsed, aManager);
}

void nsMIMEInputStream::Serialize(InputStreamParams& aParams,
                                  FileDescriptorArray& aFileDescriptors,
                                  bool aDelayedStart, uint32_t aMaxSize,
                                  uint32_t* aSizeUsed,
                                  PBackgroundParent* aManager) {
  SerializeInternal(aParams, aFileDescriptors, aDelayedStart, aMaxSize,
                    aSizeUsed, aManager);
}

template <typename M>
void nsMIMEInputStream::SerializeInternal(InputStreamParams& aParams,
                                          FileDescriptorArray& aFileDescriptors,
                                          bool aDelayedStart, uint32_t aMaxSize,
                                          uint32_t* aSizeUsed, M* aManager) {
  MOZ_ASSERT(aSizeUsed);
  *aSizeUsed = 0;

  MIMEInputStreamParams params;

  if (mStream) {
    InputStreamParams wrappedParams;
    InputStreamHelper::SerializeInputStream(mStream, wrappedParams,
                                            aFileDescriptors, aDelayedStart,
                                            aMaxSize, aSizeUsed, aManager);

    NS_ASSERTION(wrappedParams.type() != InputStreamParams::T__None,
                 "Wrapped stream failed to serialize!");

    params.optionalStream().emplace(wrappedParams);
  }

  params.headers() = mHeaders;
  params.startedReading() = mStartedReading;

  aParams = params;
}

bool nsMIMEInputStream::Deserialize(
    const InputStreamParams& aParams,
    const FileDescriptorArray& aFileDescriptors) {
  if (aParams.type() != InputStreamParams::TMIMEInputStreamParams) {
    NS_ERROR("Received unknown parameters from the other process!");
    return false;
  }

  const MIMEInputStreamParams& params = aParams.get_MIMEInputStreamParams();
  const Maybe<InputStreamParams>& wrappedParams = params.optionalStream();

  mHeaders = params.headers();
  mStartedReading = params.startedReading();

  if (wrappedParams.isSome()) {
    nsCOMPtr<nsIInputStream> stream;
    stream = InputStreamHelper::DeserializeInputStream(wrappedParams.ref(),
                                                       aFileDescriptors);
    if (!stream) {
      NS_WARNING("Failed to deserialize wrapped stream!");
      return false;
    }

    mStream = stream;
  }

  return true;
}

NS_IMETHODIMP
nsMIMEInputStream::Length(int64_t* aLength) {
  nsCOMPtr<nsIInputStreamLength> stream = do_QueryInterface(mStream);
  if (NS_WARN_IF(!stream)) {
    return NS_ERROR_FAILURE;
  }

  return stream->Length(aLength);
}

NS_IMETHODIMP
nsMIMEInputStream::AsyncLengthWait(nsIInputStreamLengthCallback* aCallback,
                                   nsIEventTarget* aEventTarget) {
  nsCOMPtr<nsIAsyncInputStreamLength> stream = do_QueryInterface(mStream);
  if (NS_WARN_IF(!stream)) {
    return NS_ERROR_FAILURE;
  }

  nsCOMPtr<nsIInputStreamLengthCallback> callback = aCallback ? this : nullptr;
  {
    MutexAutoLock lock(mMutex);
    mAsyncInputStreamLengthCallback = aCallback;
  }

  return stream->AsyncLengthWait(callback, aEventTarget);
}

NS_IMETHODIMP
nsMIMEInputStream::OnInputStreamLengthReady(nsIAsyncInputStreamLength* aStream,
                                            int64_t aLength) {
  nsCOMPtr<nsIInputStreamLengthCallback> callback;
  {
    MutexAutoLock lock(mMutex);
    // We have been canceled in the meanwhile.
    if (!mAsyncInputStreamLengthCallback) {
      return NS_OK;
    }

    callback.swap(mAsyncInputStreamLengthCallback);
  }

  MOZ_ASSERT(callback);
  return callback->OnInputStreamLengthReady(this, aLength);
}

bool nsMIMEInputStream::IsSeekableInputStream() const {
  nsCOMPtr<nsISeekableStream> seekable = do_QueryInterface(mStream);
  return !!seekable;
}

bool nsMIMEInputStream::IsAsyncInputStream() const {
  nsCOMPtr<nsIAsyncInputStream> asyncStream = do_QueryInterface(mStream);
  return !!asyncStream;
}

bool nsMIMEInputStream::IsIPCSerializable() const {
  // If SetData() or Deserialize() has not be called yet, mStream is null.
  if (!mStream) {
    return true;
  }

  nsCOMPtr<nsIIPCSerializableInputStream> serializable =
      do_QueryInterface(mStream);
  return !!serializable;
}

bool nsMIMEInputStream::IsInputStreamLength() const {
  nsCOMPtr<nsIInputStreamLength> stream = do_QueryInterface(mStream);
  return !!stream;
}

bool nsMIMEInputStream::IsAsyncInputStreamLength() const {
  nsCOMPtr<nsIAsyncInputStreamLength> stream = do_QueryInterface(mStream);
  return !!stream;
}

bool nsMIMEInputStream::IsCloneableInputStream() const {
  nsCOMPtr<nsICloneableInputStream> stream = do_QueryInterface(mStream);
  return !!stream;
}

// nsICloneableInputStream interface

NS_IMETHODIMP
nsMIMEInputStream::GetCloneable(bool* aCloneable) {
  nsCOMPtr<nsICloneableInputStream> stream = do_QueryInterface(mStream);
  if (!mStream) {
    return NS_ERROR_FAILURE;
  }

  return stream->GetCloneable(aCloneable);
}

NS_IMETHODIMP
nsMIMEInputStream::Clone(nsIInputStream** aResult) {
  nsCOMPtr<nsICloneableInputStream> stream = do_QueryInterface(mStream);
  if (!mStream) {
    return NS_ERROR_FAILURE;
  }

  nsCOMPtr<nsIInputStream> clonedStream;
  nsresult rv = stream->Clone(getter_AddRefs(clonedStream));
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  nsCOMPtr<nsIMIMEInputStream> mimeStream = new nsMIMEInputStream();

  rv = mimeStream->SetData(clonedStream);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  for (const HeaderEntry& entry : mHeaders) {
    rv = mimeStream->AddHeader(entry.name().get(), entry.value().get());
    MOZ_ASSERT(NS_SUCCEEDED(rv));
  }

  static_cast<nsMIMEInputStream*>(mimeStream.get())->mStartedReading =
      mStartedReading;

  mimeStream.forget(aResult);
  return NS_OK;
}