nsInputStreamPump.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  1. /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
  2. /* vim:set ts=4 sts=4 sw=4 et cin: */
  3. /* This Source Code Form is subject to the terms of the Mozilla Public
  4. * License, v. 2.0. If a copy of the MPL was not distributed with this
  5. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  6. #include "nsIOService.h"
  7. #include "nsInputStreamPump.h"
  8. #include "nsIStreamTransportService.h"
  9. #include "nsISeekableStream.h"
  10. #include "nsITransport.h"
  11. #include "nsIThreadRetargetableStreamListener.h"
  12. #include "nsThreadUtils.h"
  13. #include "nsCOMPtr.h"
  14. #include "mozilla/Logging.h"
  15. #include "GeckoProfiler.h"
  16. #include "nsIStreamListener.h"
  17. #include "nsILoadGroup.h"
  18. #include "nsNetCID.h"
  19. #include <algorithm>
  20. using namespace mozilla;
  21. using namespace mozilla::net;
  22. static NS_DEFINE_CID(kStreamTransportServiceCID, NS_STREAMTRANSPORTSERVICE_CID);
  23. //
  24. // MOZ_LOG=nsStreamPump:5
  25. //
  26. static mozilla::LazyLogModule gStreamPumpLog("nsStreamPump");
  27. #undef LOG
  28. #define LOG(args) MOZ_LOG(gStreamPumpLog, mozilla::LogLevel::Debug, args)
  29. //-----------------------------------------------------------------------------
  30. // nsInputStreamPump methods
  31. //-----------------------------------------------------------------------------
  32. nsInputStreamPump::nsInputStreamPump()
  33. : mState(STATE_IDLE)
  34. , mStreamOffset(0)
  35. , mStreamLength(UINT64_MAX)
  36. , mStatus(NS_OK)
  37. , mSuspendCount(0)
  38. , mLoadFlags(LOAD_NORMAL)
  39. , mProcessingCallbacks(false)
  40. , mWaitingForInputStreamReady(false)
  41. , mCloseWhenDone(false)
  42. , mRetargeting(false)
  43. , mMonitor("nsInputStreamPump")
  44. {
  45. }
  46. nsInputStreamPump::~nsInputStreamPump()
  47. {
  48. }
  49. nsresult
  50. nsInputStreamPump::Create(nsInputStreamPump **result,
  51. nsIInputStream *stream,
  52. int64_t streamPos,
  53. int64_t streamLen,
  54. uint32_t segsize,
  55. uint32_t segcount,
  56. bool closeWhenDone)
  57. {
  58. nsresult rv = NS_ERROR_OUT_OF_MEMORY;
  59. RefPtr<nsInputStreamPump> pump = new nsInputStreamPump();
  60. if (pump) {
  61. rv = pump->Init(stream, streamPos, streamLen,
  62. segsize, segcount, closeWhenDone);
  63. if (NS_SUCCEEDED(rv)) {
  64. pump.forget(result);
  65. }
  66. }
  67. return rv;
  68. }
  69. struct PeekData {
  70. PeekData(nsInputStreamPump::PeekSegmentFun fun, void* closure)
  71. : mFunc(fun), mClosure(closure) {}
  72. nsInputStreamPump::PeekSegmentFun mFunc;
  73. void* mClosure;
  74. };
  75. static nsresult
  76. CallPeekFunc(nsIInputStream *aInStream, void *aClosure,
  77. const char *aFromSegment, uint32_t aToOffset, uint32_t aCount,
  78. uint32_t *aWriteCount)
  79. {
  80. NS_ASSERTION(aToOffset == 0, "Called more than once?");
  81. NS_ASSERTION(aCount > 0, "Called without data?");
  82. PeekData* data = static_cast<PeekData*>(aClosure);
  83. data->mFunc(data->mClosure,
  84. reinterpret_cast<const uint8_t*>(aFromSegment), aCount);
  85. return NS_BINDING_ABORTED;
  86. }
  87. nsresult
  88. nsInputStreamPump::PeekStream(PeekSegmentFun callback, void* closure)
  89. {
  90. ReentrantMonitorAutoEnter mon(mMonitor);
  91. NS_ASSERTION(mAsyncStream, "PeekStream called without stream");
  92. // See if the pipe is closed by checking the return of Available.
  93. uint64_t dummy64;
  94. nsresult rv = mAsyncStream->Available(&dummy64);
  95. if (NS_FAILED(rv))
  96. return rv;
  97. uint32_t dummy = (uint32_t)std::min(dummy64, (uint64_t)UINT32_MAX);
  98. PeekData data(callback, closure);
  99. return mAsyncStream->ReadSegments(CallPeekFunc,
  100. &data,
  101. nsIOService::gDefaultSegmentSize,
  102. &dummy);
  103. }
  104. nsresult
  105. nsInputStreamPump::EnsureWaiting()
  106. {
  107. mMonitor.AssertCurrentThreadIn();
  108. // no need to worry about multiple threads... an input stream pump lives
  109. // on only one thread at a time.
  110. MOZ_ASSERT(mAsyncStream);
  111. if (!mWaitingForInputStreamReady && !mProcessingCallbacks) {
  112. // Ensure OnStateStop is called on the main thread.
  113. if (mState == STATE_STOP) {
  114. nsCOMPtr<nsIThread> mainThread = do_GetMainThread();
  115. if (mTargetThread != mainThread) {
  116. mTargetThread = do_QueryInterface(mainThread);
  117. }
  118. }
  119. MOZ_ASSERT(mTargetThread);
  120. nsresult rv = mAsyncStream->AsyncWait(this, 0, 0, mTargetThread);
  121. if (NS_FAILED(rv)) {
  122. NS_ERROR("AsyncWait failed");
  123. return rv;
  124. }
  125. // Any retargeting during STATE_START or START_TRANSFER is complete
  126. // after the call to AsyncWait; next callback wil be on mTargetThread.
  127. mRetargeting = false;
  128. mWaitingForInputStreamReady = true;
  129. }
  130. return NS_OK;
  131. }
  132. //-----------------------------------------------------------------------------
  133. // nsInputStreamPump::nsISupports
  134. //-----------------------------------------------------------------------------
  135. // although this class can only be accessed from one thread at a time, we do
  136. // allow its ownership to move from thread to thread, assuming the consumer
  137. // understands the limitations of this.
  138. NS_IMPL_ISUPPORTS(nsInputStreamPump,
  139. nsIRequest,
  140. nsIThreadRetargetableRequest,
  141. nsIInputStreamCallback,
  142. nsIInputStreamPump)
  143. //-----------------------------------------------------------------------------
  144. // nsInputStreamPump::nsIRequest
  145. //-----------------------------------------------------------------------------
  146. NS_IMETHODIMP
  147. nsInputStreamPump::GetName(nsACString &result)
  148. {
  149. ReentrantMonitorAutoEnter mon(mMonitor);
  150. result.Truncate();
  151. return NS_OK;
  152. }
  153. NS_IMETHODIMP
  154. nsInputStreamPump::IsPending(bool *result)
  155. {
  156. ReentrantMonitorAutoEnter mon(mMonitor);
  157. *result = (mState != STATE_IDLE);
  158. return NS_OK;
  159. }
  160. NS_IMETHODIMP
  161. nsInputStreamPump::GetStatus(nsresult *status)
  162. {
  163. ReentrantMonitorAutoEnter mon(mMonitor);
  164. *status = mStatus;
  165. return NS_OK;
  166. }
  167. NS_IMETHODIMP
  168. nsInputStreamPump::Cancel(nsresult status)
  169. {
  170. MOZ_ASSERT(NS_IsMainThread());
  171. ReentrantMonitorAutoEnter mon(mMonitor);
  172. LOG(("nsInputStreamPump::Cancel [this=%p status=%x]\n",
  173. this, status));
  174. if (NS_FAILED(mStatus)) {
  175. LOG((" already canceled\n"));
  176. return NS_OK;
  177. }
  178. NS_ASSERTION(NS_FAILED(status), "cancel with non-failure status code");
  179. mStatus = status;
  180. // close input stream
  181. if (mAsyncStream) {
  182. mAsyncStream->CloseWithStatus(status);
  183. if (mSuspendCount == 0)
  184. EnsureWaiting();
  185. // Otherwise, EnsureWaiting will be called by Resume().
  186. // Note that while suspended, OnInputStreamReady will
  187. // not do anything, and also note that calling asyncWait
  188. // on a closed stream works and will dispatch an event immediately.
  189. }
  190. return NS_OK;
  191. }
  192. NS_IMETHODIMP
  193. nsInputStreamPump::Suspend()
  194. {
  195. ReentrantMonitorAutoEnter mon(mMonitor);
  196. LOG(("nsInputStreamPump::Suspend [this=%p]\n", this));
  197. NS_ENSURE_TRUE(mState != STATE_IDLE, NS_ERROR_UNEXPECTED);
  198. ++mSuspendCount;
  199. return NS_OK;
  200. }
  201. NS_IMETHODIMP
  202. nsInputStreamPump::Resume()
  203. {
  204. ReentrantMonitorAutoEnter mon(mMonitor);
  205. LOG(("nsInputStreamPump::Resume [this=%p]\n", this));
  206. NS_ENSURE_TRUE(mSuspendCount > 0, NS_ERROR_UNEXPECTED);
  207. NS_ENSURE_TRUE(mState != STATE_IDLE, NS_ERROR_UNEXPECTED);
  208. if (--mSuspendCount == 0)
  209. EnsureWaiting();
  210. return NS_OK;
  211. }
  212. NS_IMETHODIMP
  213. nsInputStreamPump::GetLoadFlags(nsLoadFlags *aLoadFlags)
  214. {
  215. ReentrantMonitorAutoEnter mon(mMonitor);
  216. *aLoadFlags = mLoadFlags;
  217. return NS_OK;
  218. }
  219. NS_IMETHODIMP
  220. nsInputStreamPump::SetLoadFlags(nsLoadFlags aLoadFlags)
  221. {
  222. ReentrantMonitorAutoEnter mon(mMonitor);
  223. mLoadFlags = aLoadFlags;
  224. return NS_OK;
  225. }
  226. NS_IMETHODIMP
  227. nsInputStreamPump::GetLoadGroup(nsILoadGroup **aLoadGroup)
  228. {
  229. ReentrantMonitorAutoEnter mon(mMonitor);
  230. NS_IF_ADDREF(*aLoadGroup = mLoadGroup);
  231. return NS_OK;
  232. }
  233. NS_IMETHODIMP
  234. nsInputStreamPump::SetLoadGroup(nsILoadGroup *aLoadGroup)
  235. {
  236. ReentrantMonitorAutoEnter mon(mMonitor);
  237. mLoadGroup = aLoadGroup;
  238. return NS_OK;
  239. }
  240. //-----------------------------------------------------------------------------
  241. // nsInputStreamPump::nsIInputStreamPump implementation
  242. //-----------------------------------------------------------------------------
  243. NS_IMETHODIMP
  244. nsInputStreamPump::Init(nsIInputStream *stream,
  245. int64_t streamPos, int64_t streamLen,
  246. uint32_t segsize, uint32_t segcount,
  247. bool closeWhenDone)
  248. {
  249. NS_ENSURE_TRUE(mState == STATE_IDLE, NS_ERROR_IN_PROGRESS);
  250. mStreamOffset = uint64_t(streamPos);
  251. if (int64_t(streamLen) >= int64_t(0))
  252. mStreamLength = uint64_t(streamLen);
  253. mStream = stream;
  254. mSegSize = segsize;
  255. mSegCount = segcount;
  256. mCloseWhenDone = closeWhenDone;
  257. return NS_OK;
  258. }
  259. NS_IMETHODIMP
  260. nsInputStreamPump::AsyncRead(nsIStreamListener *listener, nsISupports *ctxt)
  261. {
  262. ReentrantMonitorAutoEnter mon(mMonitor);
  263. NS_ENSURE_TRUE(mState == STATE_IDLE, NS_ERROR_IN_PROGRESS);
  264. NS_ENSURE_ARG_POINTER(listener);
  265. MOZ_ASSERT(NS_IsMainThread(), "nsInputStreamPump should be read from the "
  266. "main thread only.");
  267. //
  268. // OK, we need to use the stream transport service if
  269. //
  270. // (1) the stream is blocking
  271. // (2) the stream does not support nsIAsyncInputStream
  272. //
  273. bool nonBlocking;
  274. nsresult rv = mStream->IsNonBlocking(&nonBlocking);
  275. if (NS_FAILED(rv)) return rv;
  276. if (nonBlocking) {
  277. mAsyncStream = do_QueryInterface(mStream);
  278. //
  279. // if the stream supports nsIAsyncInputStream, and if we need to seek
  280. // to a starting offset, then we must do so here. in the non-async
  281. // stream case, the stream transport service will take care of seeking
  282. // for us.
  283. //
  284. if (mAsyncStream && (mStreamOffset != UINT64_MAX)) {
  285. nsCOMPtr<nsISeekableStream> seekable = do_QueryInterface(mStream);
  286. if (seekable)
  287. seekable->Seek(nsISeekableStream::NS_SEEK_SET, mStreamOffset);
  288. }
  289. }
  290. if (!mAsyncStream) {
  291. // ok, let's use the stream transport service to read this stream.
  292. nsCOMPtr<nsIStreamTransportService> sts =
  293. do_GetService(kStreamTransportServiceCID, &rv);
  294. if (NS_FAILED(rv)) return rv;
  295. nsCOMPtr<nsITransport> transport;
  296. rv = sts->CreateInputTransport(mStream, mStreamOffset, mStreamLength,
  297. mCloseWhenDone, getter_AddRefs(transport));
  298. if (NS_FAILED(rv)) return rv;
  299. nsCOMPtr<nsIInputStream> wrapper;
  300. rv = transport->OpenInputStream(0, mSegSize, mSegCount, getter_AddRefs(wrapper));
  301. if (NS_FAILED(rv)) return rv;
  302. mAsyncStream = do_QueryInterface(wrapper, &rv);
  303. if (NS_FAILED(rv)) return rv;
  304. }
  305. // release our reference to the original stream. from this point forward,
  306. // we only reference the "stream" via mAsyncStream.
  307. mStream = nullptr;
  308. // mStreamOffset now holds the number of bytes currently read. we use this
  309. // to enforce the mStreamLength restriction.
  310. mStreamOffset = 0;
  311. // grab event queue (we must do this here by contract, since all notifications
  312. // must go to the thread which called AsyncRead)
  313. mTargetThread = do_GetCurrentThread();
  314. NS_ENSURE_STATE(mTargetThread);
  315. rv = EnsureWaiting();
  316. if (NS_FAILED(rv)) return rv;
  317. if (mLoadGroup)
  318. mLoadGroup->AddRequest(this, nullptr);
  319. mState = STATE_START;
  320. mListener = listener;
  321. mListenerContext = ctxt;
  322. return NS_OK;
  323. }
  324. //-----------------------------------------------------------------------------
  325. // nsInputStreamPump::nsIInputStreamCallback implementation
  326. //-----------------------------------------------------------------------------
  327. NS_IMETHODIMP
  328. nsInputStreamPump::OnInputStreamReady(nsIAsyncInputStream *stream)
  329. {
  330. LOG(("nsInputStreamPump::OnInputStreamReady [this=%p]\n", this));
  331. PROFILER_LABEL("nsInputStreamPump", "OnInputStreamReady",
  332. js::ProfileEntry::Category::NETWORK);
  333. // this function has been called from a PLEvent, so we can safely call
  334. // any listener or progress sink methods directly from here.
  335. for (;;) {
  336. // There should only be one iteration of this loop happening at a time.
  337. // To prevent AsyncWait() (called during callbacks or on other threads)
  338. // from creating a parallel OnInputStreamReady(), we use:
  339. // -- a monitor; and
  340. // -- a boolean mProcessingCallbacks to detect parallel loops
  341. // when exiting the monitor for callbacks.
  342. ReentrantMonitorAutoEnter lock(mMonitor);
  343. // Prevent parallel execution during callbacks, while out of monitor.
  344. if (mProcessingCallbacks) {
  345. MOZ_ASSERT(!mProcessingCallbacks);
  346. break;
  347. }
  348. mProcessingCallbacks = true;
  349. if (mSuspendCount || mState == STATE_IDLE) {
  350. mWaitingForInputStreamReady = false;
  351. mProcessingCallbacks = false;
  352. break;
  353. }
  354. uint32_t nextState;
  355. switch (mState) {
  356. case STATE_START:
  357. nextState = OnStateStart();
  358. break;
  359. case STATE_TRANSFER:
  360. nextState = OnStateTransfer();
  361. break;
  362. case STATE_STOP:
  363. mRetargeting = false;
  364. nextState = OnStateStop();
  365. break;
  366. default:
  367. nextState = 0;
  368. NS_NOTREACHED("Unknown enum value.");
  369. return NS_ERROR_UNEXPECTED;
  370. }
  371. bool stillTransferring = (mState == STATE_TRANSFER &&
  372. nextState == STATE_TRANSFER);
  373. if (stillTransferring) {
  374. NS_ASSERTION(NS_SUCCEEDED(mStatus),
  375. "Should not have failed status for ongoing transfer");
  376. } else {
  377. NS_ASSERTION(mState != nextState,
  378. "Only OnStateTransfer can be called more than once.");
  379. }
  380. if (mRetargeting) {
  381. NS_ASSERTION(mState != STATE_STOP,
  382. "Retargeting should not happen during OnStateStop.");
  383. }
  384. // Set mRetargeting so EnsureWaiting will be called. It ensures that
  385. // OnStateStop is called on the main thread.
  386. if (nextState == STATE_STOP && !NS_IsMainThread()) {
  387. mRetargeting = true;
  388. }
  389. // Unset mProcessingCallbacks here (while we have lock) so our own call to
  390. // EnsureWaiting isn't blocked by it.
  391. mProcessingCallbacks = false;
  392. // We must break the loop when we're switching event delivery to another
  393. // thread and the input stream pump is suspended, otherwise
  394. // OnStateStop() might be called off the main thread. See bug 1026951
  395. // comment #107 for the exact scenario.
  396. if (mSuspendCount && mRetargeting) {
  397. mState = nextState;
  398. mWaitingForInputStreamReady = false;
  399. break;
  400. }
  401. // Wait asynchronously if there is still data to transfer, or we're
  402. // switching event delivery to another thread.
  403. if (!mSuspendCount && (stillTransferring || mRetargeting)) {
  404. mState = nextState;
  405. mWaitingForInputStreamReady = false;
  406. nsresult rv = EnsureWaiting();
  407. if (NS_SUCCEEDED(rv))
  408. break;
  409. // Failure to start asynchronous wait: stop transfer.
  410. // Do not set mStatus if it was previously set to report a failure.
  411. if (NS_SUCCEEDED(mStatus)) {
  412. mStatus = rv;
  413. }
  414. nextState = STATE_STOP;
  415. }
  416. mState = nextState;
  417. }
  418. return NS_OK;
  419. }
  420. uint32_t
  421. nsInputStreamPump::OnStateStart()
  422. {
  423. mMonitor.AssertCurrentThreadIn();
  424. PROFILER_LABEL("nsInputStreamPump", "OnStateStart",
  425. js::ProfileEntry::Category::NETWORK);
  426. LOG((" OnStateStart [this=%p]\n", this));
  427. nsresult rv;
  428. // need to check the reason why the stream is ready. this is required
  429. // so our listener can check our status from OnStartRequest.
  430. // XXX async streams should have a GetStatus method!
  431. if (NS_SUCCEEDED(mStatus)) {
  432. uint64_t avail;
  433. rv = mAsyncStream->Available(&avail);
  434. if (NS_FAILED(rv) && rv != NS_BASE_STREAM_CLOSED)
  435. mStatus = rv;
  436. }
  437. {
  438. // Note: Must exit monitor for call to OnStartRequest to avoid
  439. // deadlocks when calls to RetargetDeliveryTo for multiple
  440. // nsInputStreamPumps are needed (e.g. nsHttpChannel).
  441. mMonitor.Exit();
  442. rv = mListener->OnStartRequest(this, mListenerContext);
  443. mMonitor.Enter();
  444. }
  445. // an error returned from OnStartRequest should cause us to abort; however,
  446. // we must not stomp on mStatus if already canceled.
  447. if (NS_FAILED(rv) && NS_SUCCEEDED(mStatus))
  448. mStatus = rv;
  449. return NS_SUCCEEDED(mStatus) ? STATE_TRANSFER : STATE_STOP;
  450. }
  451. uint32_t
  452. nsInputStreamPump::OnStateTransfer()
  453. {
  454. mMonitor.AssertCurrentThreadIn();
  455. PROFILER_LABEL("nsInputStreamPump", "OnStateTransfer",
  456. js::ProfileEntry::Category::NETWORK);
  457. LOG((" OnStateTransfer [this=%p]\n", this));
  458. // if canceled, go directly to STATE_STOP...
  459. if (NS_FAILED(mStatus))
  460. return STATE_STOP;
  461. nsresult rv;
  462. uint64_t avail;
  463. rv = mAsyncStream->Available(&avail);
  464. LOG((" Available returned [stream=%x rv=%x avail=%llu]\n", mAsyncStream.get(), rv, avail));
  465. if (rv == NS_BASE_STREAM_CLOSED) {
  466. rv = NS_OK;
  467. avail = 0;
  468. }
  469. else if (NS_SUCCEEDED(rv) && avail) {
  470. // figure out how much data to report (XXX detect overflow??)
  471. if (avail > mStreamLength - mStreamOffset)
  472. avail = mStreamLength - mStreamOffset;
  473. if (avail) {
  474. // we used to limit avail to 16K - we were afraid some ODA handlers
  475. // might assume they wouldn't get more than 16K at once
  476. // we're removing that limit since it speeds up local file access.
  477. // Now there's an implicit 64K limit of 4 16K segments
  478. // NOTE: ok, so the story is as follows. OnDataAvailable impls
  479. // are by contract supposed to consume exactly |avail| bytes.
  480. // however, many do not... mailnews... stream converters...
  481. // cough, cough. the input stream pump is fairly tolerant
  482. // in this regard; however, if an ODA does not consume any
  483. // data from the stream, then we could potentially end up in
  484. // an infinite loop. we do our best here to try to catch
  485. // such an error. (see bug 189672)
  486. // in most cases this QI will succeed (mAsyncStream is almost always
  487. // a nsPipeInputStream, which implements nsISeekableStream::Tell).
  488. int64_t offsetBefore;
  489. nsCOMPtr<nsISeekableStream> seekable = do_QueryInterface(mAsyncStream);
  490. if (seekable && NS_FAILED(seekable->Tell(&offsetBefore))) {
  491. NS_NOTREACHED("Tell failed on readable stream");
  492. offsetBefore = 0;
  493. }
  494. uint32_t odaAvail =
  495. avail > UINT32_MAX ?
  496. UINT32_MAX : uint32_t(avail);
  497. LOG((" calling OnDataAvailable [offset=%llu count=%llu(%u)]\n",
  498. mStreamOffset, avail, odaAvail));
  499. {
  500. // Note: Must exit monitor for call to OnStartRequest to avoid
  501. // deadlocks when calls to RetargetDeliveryTo for multiple
  502. // nsInputStreamPumps are needed (e.g. nsHttpChannel).
  503. mMonitor.Exit();
  504. rv = mListener->OnDataAvailable(this, mListenerContext,
  505. mAsyncStream, mStreamOffset,
  506. odaAvail);
  507. mMonitor.Enter();
  508. }
  509. // don't enter this code if ODA failed or called Cancel
  510. if (NS_SUCCEEDED(rv) && NS_SUCCEEDED(mStatus)) {
  511. // test to see if this ODA failed to consume data
  512. if (seekable) {
  513. // NOTE: if Tell fails, which can happen if the stream is
  514. // now closed, then we assume that everything was read.
  515. int64_t offsetAfter;
  516. if (NS_FAILED(seekable->Tell(&offsetAfter)))
  517. offsetAfter = offsetBefore + odaAvail;
  518. if (offsetAfter > offsetBefore)
  519. mStreamOffset += (offsetAfter - offsetBefore);
  520. else if (mSuspendCount == 0) {
  521. //
  522. // possible infinite loop if we continue pumping data!
  523. //
  524. // NOTE: although not allowed by nsIStreamListener, we
  525. // will allow the ODA impl to Suspend the pump. IMAP
  526. // does this :-(
  527. //
  528. NS_ERROR("OnDataAvailable implementation consumed no data");
  529. mStatus = NS_ERROR_UNEXPECTED;
  530. }
  531. }
  532. else
  533. mStreamOffset += odaAvail; // assume ODA behaved well
  534. }
  535. }
  536. }
  537. // an error returned from Available or OnDataAvailable should cause us to
  538. // abort; however, we must not stomp on mStatus if already canceled.
  539. if (NS_SUCCEEDED(mStatus)) {
  540. if (NS_FAILED(rv))
  541. mStatus = rv;
  542. else if (avail) {
  543. // if stream is now closed, advance to STATE_STOP right away.
  544. // Available may return 0 bytes available at the moment; that
  545. // would not mean that we are done.
  546. // XXX async streams should have a GetStatus method!
  547. rv = mAsyncStream->Available(&avail);
  548. if (NS_SUCCEEDED(rv))
  549. return STATE_TRANSFER;
  550. if (rv != NS_BASE_STREAM_CLOSED)
  551. mStatus = rv;
  552. }
  553. }
  554. return STATE_STOP;
  555. }
  556. nsresult
  557. nsInputStreamPump::CallOnStateStop()
  558. {
  559. ReentrantMonitorAutoEnter mon(mMonitor);
  560. MOZ_ASSERT(NS_IsMainThread(),
  561. "CallOnStateStop should only be called on the main thread.");
  562. mState = OnStateStop();
  563. return NS_OK;
  564. }
  565. uint32_t
  566. nsInputStreamPump::OnStateStop()
  567. {
  568. mMonitor.AssertCurrentThreadIn();
  569. if (!NS_IsMainThread()) {
  570. // Hopefully temporary hack: OnStateStop should only run on the main
  571. // thread, but we're seeing some rare off-main-thread calls. For now
  572. // just redispatch to the main thread in release builds, and crash in
  573. // debug builds.
  574. MOZ_ASSERT(NS_IsMainThread(),
  575. "OnStateStop should only be called on the main thread.");
  576. nsresult rv = NS_DispatchToMainThread(
  577. NewRunnableMethod(this, &nsInputStreamPump::CallOnStateStop));
  578. NS_ENSURE_SUCCESS(rv, STATE_IDLE);
  579. return STATE_IDLE;
  580. }
  581. PROFILER_LABEL("nsInputStreamPump", "OnStateStop",
  582. js::ProfileEntry::Category::NETWORK);
  583. LOG((" OnStateStop [this=%p status=%x]\n", this, mStatus));
  584. // if an error occurred, we must be sure to pass the error onto the async
  585. // stream. in some cases, this is redundant, but since close is idempotent,
  586. // this is OK. otherwise, be sure to honor the "close-when-done" option.
  587. if (!mAsyncStream || !mListener) {
  588. MOZ_ASSERT(mAsyncStream, "null mAsyncStream: OnStateStop called twice?");
  589. MOZ_ASSERT(mListener, "null mListener: OnStateStop called twice?");
  590. return STATE_IDLE;
  591. }
  592. if (NS_FAILED(mStatus))
  593. mAsyncStream->CloseWithStatus(mStatus);
  594. else if (mCloseWhenDone)
  595. mAsyncStream->Close();
  596. mAsyncStream = nullptr;
  597. mTargetThread = nullptr;
  598. mIsPending = false;
  599. {
  600. // Note: Must exit monitor for call to OnStartRequest to avoid
  601. // deadlocks when calls to RetargetDeliveryTo for multiple
  602. // nsInputStreamPumps are needed (e.g. nsHttpChannel).
  603. mMonitor.Exit();
  604. mListener->OnStopRequest(this, mListenerContext, mStatus);
  605. mMonitor.Enter();
  606. }
  607. mListener = nullptr;
  608. mListenerContext = nullptr;
  609. if (mLoadGroup)
  610. mLoadGroup->RemoveRequest(this, nullptr, mStatus);
  611. return STATE_IDLE;
  612. }
  613. //-----------------------------------------------------------------------------
  614. // nsIThreadRetargetableRequest
  615. //-----------------------------------------------------------------------------
  616. NS_IMETHODIMP
  617. nsInputStreamPump::RetargetDeliveryTo(nsIEventTarget* aNewTarget)
  618. {
  619. ReentrantMonitorAutoEnter mon(mMonitor);
  620. NS_ENSURE_ARG(aNewTarget);
  621. NS_ENSURE_TRUE(mState == STATE_START || mState == STATE_TRANSFER,
  622. NS_ERROR_UNEXPECTED);
  623. // If canceled, do not retarget. Return with canceled status.
  624. if (NS_FAILED(mStatus)) {
  625. return mStatus;
  626. }
  627. if (aNewTarget == mTargetThread) {
  628. NS_WARNING("Retargeting delivery to same thread");
  629. return NS_OK;
  630. }
  631. // Ensure that |mListener| and any subsequent listeners can be retargeted
  632. // to another thread.
  633. nsresult rv = NS_OK;
  634. nsCOMPtr<nsIThreadRetargetableStreamListener> retargetableListener =
  635. do_QueryInterface(mListener, &rv);
  636. if (NS_SUCCEEDED(rv) && retargetableListener) {
  637. rv = retargetableListener->CheckListenerChain();
  638. if (NS_SUCCEEDED(rv)) {
  639. mTargetThread = aNewTarget;
  640. mRetargeting = true;
  641. }
  642. }
  643. LOG(("nsInputStreamPump::RetargetDeliveryTo [this=%x aNewTarget=%p] "
  644. "%s listener [%p] rv[%x]",
  645. this, aNewTarget, (mTargetThread == aNewTarget ? "success" : "failure"),
  646. (nsIStreamListener*)mListener, rv));
  647. return rv;
  648. }