nsIncrementalDownload.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916
  1. /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* vim:set ts=2 sw=2 sts=2 et cindent: */
  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 "mozilla/Attributes.h"
  7. #include "mozilla/UniquePtrExtensions.h"
  8. #include "mozilla/UniquePtr.h"
  9. #include "nsIIncrementalDownload.h"
  10. #include "nsIRequestObserver.h"
  11. #include "nsIProgressEventSink.h"
  12. #include "nsIChannelEventSink.h"
  13. #include "nsIAsyncVerifyRedirectCallback.h"
  14. #include "nsIInterfaceRequestor.h"
  15. #include "nsIObserverService.h"
  16. #include "nsIObserver.h"
  17. #include "nsIStreamListener.h"
  18. #include "nsIFile.h"
  19. #include "nsITimer.h"
  20. #include "nsIURI.h"
  21. #include "nsIInputStream.h"
  22. #include "nsNetUtil.h"
  23. #include "nsWeakReference.h"
  24. #include "prio.h"
  25. #include "prprf.h"
  26. #include <algorithm>
  27. #include "nsIContentPolicy.h"
  28. #include "nsContentUtils.h"
  29. #include "mozilla/UniquePtr.h"
  30. // Default values used to initialize a nsIncrementalDownload object.
  31. #define DEFAULT_CHUNK_SIZE (4096 * 16) // bytes
  32. #define DEFAULT_INTERVAL 60 // seconds
  33. #define UPDATE_PROGRESS_INTERVAL PRTime(500 * PR_USEC_PER_MSEC) // 500ms
  34. // Number of times to retry a failed byte-range request.
  35. #define MAX_RETRY_COUNT 20
  36. using namespace mozilla;
  37. //-----------------------------------------------------------------------------
  38. static nsresult
  39. WriteToFile(nsIFile *lf, const char *data, uint32_t len, int32_t flags)
  40. {
  41. PRFileDesc *fd;
  42. int32_t mode = 0600;
  43. nsresult rv;
  44. rv = lf->OpenNSPRFileDesc(flags, mode, &fd);
  45. if (NS_FAILED(rv))
  46. return rv;
  47. if (len)
  48. rv = PR_Write(fd, data, len) == int32_t(len) ? NS_OK : NS_ERROR_FAILURE;
  49. PR_Close(fd);
  50. return rv;
  51. }
  52. static nsresult
  53. AppendToFile(nsIFile *lf, const char *data, uint32_t len)
  54. {
  55. int32_t flags = PR_WRONLY | PR_CREATE_FILE | PR_APPEND;
  56. return WriteToFile(lf, data, len, flags);
  57. }
  58. // maxSize may be -1 if unknown
  59. static void
  60. MakeRangeSpec(const int64_t &size, const int64_t &maxSize, int32_t chunkSize,
  61. bool fetchRemaining, nsCString &rangeSpec)
  62. {
  63. rangeSpec.AssignLiteral("bytes=");
  64. rangeSpec.AppendInt(int64_t(size));
  65. rangeSpec.Append('-');
  66. if (fetchRemaining)
  67. return;
  68. int64_t end = size + int64_t(chunkSize);
  69. if (maxSize != int64_t(-1) && end > maxSize)
  70. end = maxSize;
  71. end -= 1;
  72. rangeSpec.AppendInt(int64_t(end));
  73. }
  74. //-----------------------------------------------------------------------------
  75. class nsIncrementalDownload final
  76. : public nsIIncrementalDownload
  77. , public nsIStreamListener
  78. , public nsIObserver
  79. , public nsIInterfaceRequestor
  80. , public nsIChannelEventSink
  81. , public nsSupportsWeakReference
  82. , public nsIAsyncVerifyRedirectCallback
  83. {
  84. public:
  85. NS_DECL_ISUPPORTS
  86. NS_DECL_NSIREQUEST
  87. NS_DECL_NSIINCREMENTALDOWNLOAD
  88. NS_DECL_NSIREQUESTOBSERVER
  89. NS_DECL_NSISTREAMLISTENER
  90. NS_DECL_NSIOBSERVER
  91. NS_DECL_NSIINTERFACEREQUESTOR
  92. NS_DECL_NSICHANNELEVENTSINK
  93. NS_DECL_NSIASYNCVERIFYREDIRECTCALLBACK
  94. nsIncrementalDownload();
  95. private:
  96. ~nsIncrementalDownload() {}
  97. nsresult FlushChunk();
  98. void UpdateProgress();
  99. nsresult CallOnStartRequest();
  100. void CallOnStopRequest();
  101. nsresult StartTimer(int32_t interval);
  102. nsresult ProcessTimeout();
  103. nsresult ReadCurrentSize();
  104. nsresult ClearRequestHeader(nsIHttpChannel *channel);
  105. nsCOMPtr<nsIRequestObserver> mObserver;
  106. nsCOMPtr<nsISupports> mObserverContext;
  107. nsCOMPtr<nsIProgressEventSink> mProgressSink;
  108. nsCOMPtr<nsIURI> mURI;
  109. nsCOMPtr<nsIURI> mFinalURI;
  110. nsCOMPtr<nsIFile> mDest;
  111. nsCOMPtr<nsIChannel> mChannel;
  112. nsCOMPtr<nsITimer> mTimer;
  113. mozilla::UniquePtr<char[]> mChunk;
  114. int32_t mChunkLen;
  115. int32_t mChunkSize;
  116. int32_t mInterval;
  117. int64_t mTotalSize;
  118. int64_t mCurrentSize;
  119. uint32_t mLoadFlags;
  120. int32_t mNonPartialCount;
  121. nsresult mStatus;
  122. bool mIsPending;
  123. bool mDidOnStartRequest;
  124. PRTime mLastProgressUpdate;
  125. nsCOMPtr<nsIAsyncVerifyRedirectCallback> mRedirectCallback;
  126. nsCOMPtr<nsIChannel> mNewRedirectChannel;
  127. nsCString mPartialValidator;
  128. bool mCacheBust;
  129. };
  130. nsIncrementalDownload::nsIncrementalDownload()
  131. : mChunkLen(0)
  132. , mChunkSize(DEFAULT_CHUNK_SIZE)
  133. , mInterval(DEFAULT_INTERVAL)
  134. , mTotalSize(-1)
  135. , mCurrentSize(-1)
  136. , mLoadFlags(LOAD_NORMAL)
  137. , mNonPartialCount(0)
  138. , mStatus(NS_OK)
  139. , mIsPending(false)
  140. , mDidOnStartRequest(false)
  141. , mLastProgressUpdate(0)
  142. , mRedirectCallback(nullptr)
  143. , mNewRedirectChannel(nullptr)
  144. , mCacheBust(false)
  145. {
  146. }
  147. nsresult
  148. nsIncrementalDownload::FlushChunk()
  149. {
  150. NS_ASSERTION(mTotalSize != int64_t(-1), "total size should be known");
  151. if (mChunkLen == 0)
  152. return NS_OK;
  153. nsresult rv = AppendToFile(mDest, mChunk.get(), mChunkLen);
  154. if (NS_FAILED(rv))
  155. return rv;
  156. mCurrentSize += int64_t(mChunkLen);
  157. mChunkLen = 0;
  158. return NS_OK;
  159. }
  160. void
  161. nsIncrementalDownload::UpdateProgress()
  162. {
  163. mLastProgressUpdate = PR_Now();
  164. if (mProgressSink)
  165. mProgressSink->OnProgress(this, mObserverContext,
  166. mCurrentSize + mChunkLen,
  167. mTotalSize);
  168. }
  169. nsresult
  170. nsIncrementalDownload::CallOnStartRequest()
  171. {
  172. if (!mObserver || mDidOnStartRequest)
  173. return NS_OK;
  174. mDidOnStartRequest = true;
  175. return mObserver->OnStartRequest(this, mObserverContext);
  176. }
  177. void
  178. nsIncrementalDownload::CallOnStopRequest()
  179. {
  180. if (!mObserver)
  181. return;
  182. // Ensure that OnStartRequest is always called once before OnStopRequest.
  183. nsresult rv = CallOnStartRequest();
  184. if (NS_SUCCEEDED(mStatus))
  185. mStatus = rv;
  186. mIsPending = false;
  187. mObserver->OnStopRequest(this, mObserverContext, mStatus);
  188. mObserver = nullptr;
  189. mObserverContext = nullptr;
  190. }
  191. nsresult
  192. nsIncrementalDownload::StartTimer(int32_t interval)
  193. {
  194. nsresult rv;
  195. mTimer = do_CreateInstance(NS_TIMER_CONTRACTID, &rv);
  196. if (NS_FAILED(rv))
  197. return rv;
  198. return mTimer->Init(this, interval * 1000, nsITimer::TYPE_ONE_SHOT);
  199. }
  200. nsresult
  201. nsIncrementalDownload::ProcessTimeout()
  202. {
  203. NS_ASSERTION(!mChannel, "how can we have a channel?");
  204. // Handle existing error conditions
  205. if (NS_FAILED(mStatus)) {
  206. CallOnStopRequest();
  207. return NS_OK;
  208. }
  209. // Fetch next chunk
  210. nsCOMPtr<nsIChannel> channel;
  211. nsresult rv = NS_NewChannel(getter_AddRefs(channel),
  212. mFinalURI,
  213. nsContentUtils::GetSystemPrincipal(),
  214. nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
  215. nsIContentPolicy::TYPE_OTHER,
  216. nullptr, // loadGroup
  217. this, // aCallbacks
  218. mLoadFlags);
  219. if (NS_FAILED(rv))
  220. return rv;
  221. nsCOMPtr<nsIHttpChannel> http = do_QueryInterface(channel, &rv);
  222. if (NS_FAILED(rv))
  223. return rv;
  224. NS_ASSERTION(mCurrentSize != int64_t(-1),
  225. "we should know the current file size by now");
  226. rv = ClearRequestHeader(http);
  227. if (NS_FAILED(rv))
  228. return rv;
  229. // Don't bother making a range request if we are just going to fetch the
  230. // entire document.
  231. if (mInterval || mCurrentSize != int64_t(0)) {
  232. nsAutoCString range;
  233. MakeRangeSpec(mCurrentSize, mTotalSize, mChunkSize, mInterval == 0, range);
  234. rv = http->SetRequestHeader(NS_LITERAL_CSTRING("Range"), range, false);
  235. if (NS_FAILED(rv))
  236. return rv;
  237. if (!mPartialValidator.IsEmpty())
  238. http->SetRequestHeader(NS_LITERAL_CSTRING("If-Range"),
  239. mPartialValidator, false);
  240. if (mCacheBust) {
  241. http->SetRequestHeader(NS_LITERAL_CSTRING("Cache-Control"),
  242. NS_LITERAL_CSTRING("no-cache"), false);
  243. http->SetRequestHeader(NS_LITERAL_CSTRING("Pragma"),
  244. NS_LITERAL_CSTRING("no-cache"), false);
  245. }
  246. }
  247. rv = channel->AsyncOpen2(this);
  248. if (NS_FAILED(rv))
  249. return rv;
  250. // Wait to assign mChannel when we know we are going to succeed. This is
  251. // important because we don't want to introduce a reference cycle between
  252. // mChannel and this until we know for a fact that AsyncOpen has succeeded,
  253. // thus ensuring that our stream listener methods will be invoked.
  254. mChannel = channel;
  255. return NS_OK;
  256. }
  257. // Reads the current file size and validates it.
  258. nsresult
  259. nsIncrementalDownload::ReadCurrentSize()
  260. {
  261. int64_t size;
  262. nsresult rv = mDest->GetFileSize((int64_t *) &size);
  263. if (rv == NS_ERROR_FILE_NOT_FOUND ||
  264. rv == NS_ERROR_FILE_TARGET_DOES_NOT_EXIST) {
  265. mCurrentSize = 0;
  266. return NS_OK;
  267. }
  268. if (NS_FAILED(rv))
  269. return rv;
  270. mCurrentSize = size;
  271. return NS_OK;
  272. }
  273. // nsISupports
  274. NS_IMPL_ISUPPORTS(nsIncrementalDownload,
  275. nsIIncrementalDownload,
  276. nsIRequest,
  277. nsIStreamListener,
  278. nsIRequestObserver,
  279. nsIObserver,
  280. nsIInterfaceRequestor,
  281. nsIChannelEventSink,
  282. nsISupportsWeakReference,
  283. nsIAsyncVerifyRedirectCallback)
  284. // nsIRequest
  285. NS_IMETHODIMP
  286. nsIncrementalDownload::GetName(nsACString &name)
  287. {
  288. NS_ENSURE_TRUE(mURI, NS_ERROR_NOT_INITIALIZED);
  289. return mURI->GetSpec(name);
  290. }
  291. NS_IMETHODIMP
  292. nsIncrementalDownload::IsPending(bool *isPending)
  293. {
  294. *isPending = mIsPending;
  295. return NS_OK;
  296. }
  297. NS_IMETHODIMP
  298. nsIncrementalDownload::GetStatus(nsresult *status)
  299. {
  300. *status = mStatus;
  301. return NS_OK;
  302. }
  303. NS_IMETHODIMP
  304. nsIncrementalDownload::Cancel(nsresult status)
  305. {
  306. NS_ENSURE_ARG(NS_FAILED(status));
  307. // Ignore this cancelation if we're already canceled.
  308. if (NS_FAILED(mStatus))
  309. return NS_OK;
  310. mStatus = status;
  311. // Nothing more to do if callbacks aren't pending.
  312. if (!mIsPending)
  313. return NS_OK;
  314. if (mChannel) {
  315. mChannel->Cancel(mStatus);
  316. NS_ASSERTION(!mTimer, "what is this timer object doing here?");
  317. }
  318. else {
  319. // dispatch a timer callback event to drive invoking our listener's
  320. // OnStopRequest.
  321. if (mTimer)
  322. mTimer->Cancel();
  323. StartTimer(0);
  324. }
  325. return NS_OK;
  326. }
  327. NS_IMETHODIMP
  328. nsIncrementalDownload::Suspend()
  329. {
  330. return NS_ERROR_NOT_IMPLEMENTED;
  331. }
  332. NS_IMETHODIMP
  333. nsIncrementalDownload::Resume()
  334. {
  335. return NS_ERROR_NOT_IMPLEMENTED;
  336. }
  337. NS_IMETHODIMP
  338. nsIncrementalDownload::GetLoadFlags(nsLoadFlags *loadFlags)
  339. {
  340. *loadFlags = mLoadFlags;
  341. return NS_OK;
  342. }
  343. NS_IMETHODIMP
  344. nsIncrementalDownload::SetLoadFlags(nsLoadFlags loadFlags)
  345. {
  346. mLoadFlags = loadFlags;
  347. return NS_OK;
  348. }
  349. NS_IMETHODIMP
  350. nsIncrementalDownload::GetLoadGroup(nsILoadGroup **loadGroup)
  351. {
  352. return NS_ERROR_NOT_IMPLEMENTED;
  353. }
  354. NS_IMETHODIMP
  355. nsIncrementalDownload::SetLoadGroup(nsILoadGroup *loadGroup)
  356. {
  357. return NS_ERROR_NOT_IMPLEMENTED;
  358. }
  359. // nsIIncrementalDownload
  360. NS_IMETHODIMP
  361. nsIncrementalDownload::Init(nsIURI *uri, nsIFile *dest,
  362. int32_t chunkSize, int32_t interval)
  363. {
  364. // Keep it simple: only allow initialization once
  365. NS_ENSURE_FALSE(mURI, NS_ERROR_ALREADY_INITIALIZED);
  366. mDest = do_QueryInterface(dest);
  367. NS_ENSURE_ARG(mDest);
  368. mURI = uri;
  369. mFinalURI = uri;
  370. if (chunkSize > 0)
  371. mChunkSize = chunkSize;
  372. if (interval >= 0)
  373. mInterval = interval;
  374. return NS_OK;
  375. }
  376. NS_IMETHODIMP
  377. nsIncrementalDownload::GetURI(nsIURI **result)
  378. {
  379. NS_IF_ADDREF(*result = mURI);
  380. return NS_OK;
  381. }
  382. NS_IMETHODIMP
  383. nsIncrementalDownload::GetFinalURI(nsIURI **result)
  384. {
  385. NS_IF_ADDREF(*result = mFinalURI);
  386. return NS_OK;
  387. }
  388. NS_IMETHODIMP
  389. nsIncrementalDownload::GetDestination(nsIFile **result)
  390. {
  391. if (!mDest) {
  392. *result = nullptr;
  393. return NS_OK;
  394. }
  395. // Return a clone of mDest so that callers may modify the resulting nsIFile
  396. // without corrupting our internal object. This also works around the fact
  397. // that some nsIFile impls may cache the result of stat'ing the filesystem.
  398. return mDest->Clone(result);
  399. }
  400. NS_IMETHODIMP
  401. nsIncrementalDownload::GetTotalSize(int64_t *result)
  402. {
  403. *result = mTotalSize;
  404. return NS_OK;
  405. }
  406. NS_IMETHODIMP
  407. nsIncrementalDownload::GetCurrentSize(int64_t *result)
  408. {
  409. *result = mCurrentSize;
  410. return NS_OK;
  411. }
  412. NS_IMETHODIMP
  413. nsIncrementalDownload::Start(nsIRequestObserver *observer,
  414. nsISupports *context)
  415. {
  416. NS_ENSURE_ARG(observer);
  417. NS_ENSURE_FALSE(mIsPending, NS_ERROR_IN_PROGRESS);
  418. // Observe system shutdown so we can be sure to release any reference held
  419. // between ourselves and the timer. We have the observer service hold a weak
  420. // reference to us, so that we don't have to worry about calling
  421. // RemoveObserver. XXX(darin): The timer code should do this for us.
  422. nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
  423. if (obs)
  424. obs->AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, true);
  425. nsresult rv = ReadCurrentSize();
  426. if (NS_FAILED(rv))
  427. return rv;
  428. rv = StartTimer(0);
  429. if (NS_FAILED(rv))
  430. return rv;
  431. mObserver = observer;
  432. mObserverContext = context;
  433. mProgressSink = do_QueryInterface(observer); // ok if null
  434. mIsPending = true;
  435. return NS_OK;
  436. }
  437. // nsIRequestObserver
  438. NS_IMETHODIMP
  439. nsIncrementalDownload::OnStartRequest(nsIRequest *request,
  440. nsISupports *context)
  441. {
  442. nsresult rv;
  443. nsCOMPtr<nsIHttpChannel> http = do_QueryInterface(request, &rv);
  444. if (NS_FAILED(rv))
  445. return rv;
  446. // Ensure that we are receiving a 206 response.
  447. uint32_t code;
  448. rv = http->GetResponseStatus(&code);
  449. if (NS_FAILED(rv))
  450. return rv;
  451. if (code != 206) {
  452. // We may already have the entire file downloaded, in which case
  453. // our request for a range beyond the end of the file would have
  454. // been met with an error response code.
  455. if (code == 416 && mTotalSize == int64_t(-1)) {
  456. mTotalSize = mCurrentSize;
  457. // Return an error code here to suppress OnDataAvailable.
  458. return NS_ERROR_DOWNLOAD_COMPLETE;
  459. }
  460. // The server may have decided to give us all of the data in one chunk. If
  461. // we requested a partial range, then we don't want to download all of the
  462. // data at once. So, we'll just try again, but if this keeps happening then
  463. // we'll eventually give up.
  464. if (code == 200) {
  465. if (mInterval) {
  466. mChannel = nullptr;
  467. if (++mNonPartialCount > MAX_RETRY_COUNT) {
  468. NS_WARNING("unable to fetch a byte range; giving up");
  469. return NS_ERROR_FAILURE;
  470. }
  471. // Increase delay with each failure.
  472. StartTimer(mInterval * mNonPartialCount);
  473. return NS_ERROR_DOWNLOAD_NOT_PARTIAL;
  474. }
  475. // Since we have been asked to download the rest of the file, we can deal
  476. // with a 200 response. This may result in downloading the beginning of
  477. // the file again, but that can't really be helped.
  478. } else {
  479. NS_WARNING("server response was unexpected");
  480. return NS_ERROR_UNEXPECTED;
  481. }
  482. } else {
  483. // We got a partial response, so clear this counter in case the next chunk
  484. // results in a 200 response.
  485. mNonPartialCount = 0;
  486. // confirm that the content-range response header is consistent with
  487. // expectations on each 206. If it is not then drop this response and
  488. // retry with no-cache set.
  489. if (!mCacheBust) {
  490. nsAutoCString buf;
  491. int64_t startByte = 0;
  492. bool confirmedOK = false;
  493. rv = http->GetResponseHeader(NS_LITERAL_CSTRING("Content-Range"), buf);
  494. if (NS_FAILED(rv))
  495. return rv; // it isn't a useful 206 without a CONTENT-RANGE of some sort
  496. // Content-Range: bytes 0-299999/25604694
  497. int32_t p = buf.Find("bytes ");
  498. // first look for the starting point of the content-range
  499. // to make sure it is what we expect
  500. if (p != -1) {
  501. char *endptr = nullptr;
  502. const char *s = buf.get() + p + 6;
  503. while (*s && *s == ' ')
  504. s++;
  505. startByte = strtol(s, &endptr, 10);
  506. if (*s && endptr && (endptr != s) &&
  507. (mCurrentSize == startByte)) {
  508. // ok the starting point is confirmed. We still need to check the
  509. // total size of the range for consistency if this isn't
  510. // the first chunk
  511. if (mTotalSize == int64_t(-1)) {
  512. // first chunk
  513. confirmedOK = true;
  514. } else {
  515. int32_t slash = buf.FindChar('/');
  516. int64_t rangeSize = 0;
  517. if (slash != kNotFound &&
  518. (PR_sscanf(buf.get() + slash + 1, "%lld", (int64_t *) &rangeSize) == 1) &&
  519. rangeSize == mTotalSize) {
  520. confirmedOK = true;
  521. }
  522. }
  523. }
  524. }
  525. if (!confirmedOK) {
  526. NS_WARNING("unexpected content-range");
  527. mCacheBust = true;
  528. mChannel = nullptr;
  529. if (++mNonPartialCount > MAX_RETRY_COUNT) {
  530. NS_WARNING("unable to fetch a byte range; giving up");
  531. return NS_ERROR_FAILURE;
  532. }
  533. // Increase delay with each failure.
  534. StartTimer(mInterval * mNonPartialCount);
  535. return NS_ERROR_DOWNLOAD_NOT_PARTIAL;
  536. }
  537. }
  538. }
  539. // Do special processing after the first response.
  540. if (mTotalSize == int64_t(-1)) {
  541. // Update knowledge of mFinalURI
  542. rv = http->GetURI(getter_AddRefs(mFinalURI));
  543. if (NS_FAILED(rv))
  544. return rv;
  545. http->GetResponseHeader(NS_LITERAL_CSTRING("Etag"), mPartialValidator);
  546. if (StringBeginsWith(mPartialValidator, NS_LITERAL_CSTRING("W/")))
  547. mPartialValidator.Truncate(); // don't use weak validators
  548. if (mPartialValidator.IsEmpty())
  549. http->GetResponseHeader(NS_LITERAL_CSTRING("Last-Modified"), mPartialValidator);
  550. if (code == 206) {
  551. // OK, read the Content-Range header to determine the total size of this
  552. // download file.
  553. nsAutoCString buf;
  554. rv = http->GetResponseHeader(NS_LITERAL_CSTRING("Content-Range"), buf);
  555. if (NS_FAILED(rv))
  556. return rv;
  557. int32_t slash = buf.FindChar('/');
  558. if (slash == kNotFound) {
  559. NS_WARNING("server returned invalid Content-Range header!");
  560. return NS_ERROR_UNEXPECTED;
  561. }
  562. if (PR_sscanf(buf.get() + slash + 1, "%lld", (int64_t *) &mTotalSize) != 1)
  563. return NS_ERROR_UNEXPECTED;
  564. } else {
  565. rv = http->GetContentLength(&mTotalSize);
  566. if (NS_FAILED(rv))
  567. return rv;
  568. // We need to know the total size of the thing we're trying to download.
  569. if (mTotalSize == int64_t(-1)) {
  570. NS_WARNING("server returned no content-length header!");
  571. return NS_ERROR_UNEXPECTED;
  572. }
  573. // Need to truncate (or create, if it doesn't exist) the file since we
  574. // are downloading the whole thing.
  575. WriteToFile(mDest, nullptr, 0, PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE);
  576. mCurrentSize = 0;
  577. }
  578. // Notify observer that we are starting...
  579. rv = CallOnStartRequest();
  580. if (NS_FAILED(rv))
  581. return rv;
  582. }
  583. // Adjust mChunkSize accordingly if mCurrentSize is close to mTotalSize.
  584. int64_t diff = mTotalSize - mCurrentSize;
  585. if (diff <= int64_t(0)) {
  586. NS_WARNING("about to set a bogus chunk size; giving up");
  587. return NS_ERROR_UNEXPECTED;
  588. }
  589. if (diff < int64_t(mChunkSize))
  590. mChunkSize = uint32_t(diff);
  591. mChunk = mozilla::MakeUniqueFallible<char[]>(mChunkSize);
  592. if (!mChunk)
  593. rv = NS_ERROR_OUT_OF_MEMORY;
  594. return rv;
  595. }
  596. NS_IMETHODIMP
  597. nsIncrementalDownload::OnStopRequest(nsIRequest *request,
  598. nsISupports *context,
  599. nsresult status)
  600. {
  601. // Not a real error; just a trick to kill off the channel without our
  602. // listener having to care.
  603. if (status == NS_ERROR_DOWNLOAD_NOT_PARTIAL)
  604. return NS_OK;
  605. // Not a real error; just a trick used to suppress OnDataAvailable calls.
  606. if (status == NS_ERROR_DOWNLOAD_COMPLETE)
  607. status = NS_OK;
  608. if (NS_SUCCEEDED(mStatus))
  609. mStatus = status;
  610. if (mChunk) {
  611. if (NS_SUCCEEDED(mStatus))
  612. mStatus = FlushChunk();
  613. mChunk = nullptr; // deletes memory
  614. mChunkLen = 0;
  615. UpdateProgress();
  616. }
  617. mChannel = nullptr;
  618. // Notify listener if we hit an error or finished
  619. if (NS_FAILED(mStatus) || mCurrentSize == mTotalSize) {
  620. CallOnStopRequest();
  621. return NS_OK;
  622. }
  623. return StartTimer(mInterval); // Do next chunk
  624. }
  625. // nsIStreamListener
  626. NS_IMETHODIMP
  627. nsIncrementalDownload::OnDataAvailable(nsIRequest *request,
  628. nsISupports *context,
  629. nsIInputStream *input,
  630. uint64_t offset,
  631. uint32_t count)
  632. {
  633. while (count) {
  634. uint32_t space = mChunkSize - mChunkLen;
  635. uint32_t n, len = std::min(space, count);
  636. nsresult rv = input->Read(&mChunk[mChunkLen], len, &n);
  637. if (NS_FAILED(rv))
  638. return rv;
  639. if (n != len)
  640. return NS_ERROR_UNEXPECTED;
  641. count -= n;
  642. mChunkLen += n;
  643. if (mChunkLen == mChunkSize) {
  644. rv = FlushChunk();
  645. if (NS_FAILED(rv))
  646. return rv;
  647. }
  648. }
  649. if (PR_Now() > mLastProgressUpdate + UPDATE_PROGRESS_INTERVAL)
  650. UpdateProgress();
  651. return NS_OK;
  652. }
  653. // nsIObserver
  654. NS_IMETHODIMP
  655. nsIncrementalDownload::Observe(nsISupports *subject, const char *topic,
  656. const char16_t *data)
  657. {
  658. if (strcmp(topic, NS_XPCOM_SHUTDOWN_OBSERVER_ID) == 0) {
  659. Cancel(NS_ERROR_ABORT);
  660. // Since the app is shutting down, we need to go ahead and notify our
  661. // observer here. Otherwise, we would notify them after XPCOM has been
  662. // shutdown or not at all.
  663. CallOnStopRequest();
  664. }
  665. else if (strcmp(topic, NS_TIMER_CALLBACK_TOPIC) == 0) {
  666. mTimer = nullptr;
  667. nsresult rv = ProcessTimeout();
  668. if (NS_FAILED(rv))
  669. Cancel(rv);
  670. }
  671. return NS_OK;
  672. }
  673. // nsIInterfaceRequestor
  674. NS_IMETHODIMP
  675. nsIncrementalDownload::GetInterface(const nsIID &iid, void **result)
  676. {
  677. if (iid.Equals(NS_GET_IID(nsIChannelEventSink))) {
  678. NS_ADDREF_THIS();
  679. *result = static_cast<nsIChannelEventSink *>(this);
  680. return NS_OK;
  681. }
  682. nsCOMPtr<nsIInterfaceRequestor> ir = do_QueryInterface(mObserver);
  683. if (ir)
  684. return ir->GetInterface(iid, result);
  685. return NS_ERROR_NO_INTERFACE;
  686. }
  687. nsresult
  688. nsIncrementalDownload::ClearRequestHeader(nsIHttpChannel *channel)
  689. {
  690. NS_ENSURE_ARG(channel);
  691. // We don't support encodings -- they make the Content-Length not equal
  692. // to the actual size of the data.
  693. return channel->SetRequestHeader(NS_LITERAL_CSTRING("Accept-Encoding"),
  694. NS_LITERAL_CSTRING(""), false);
  695. }
  696. // nsIChannelEventSink
  697. NS_IMETHODIMP
  698. nsIncrementalDownload::AsyncOnChannelRedirect(nsIChannel *oldChannel,
  699. nsIChannel *newChannel,
  700. uint32_t flags,
  701. nsIAsyncVerifyRedirectCallback *cb)
  702. {
  703. // In response to a redirect, we need to propagate the Range header. See bug
  704. // 311595. Any failure code returned from this function aborts the redirect.
  705. nsCOMPtr<nsIHttpChannel> http = do_QueryInterface(oldChannel);
  706. NS_ENSURE_STATE(http);
  707. nsCOMPtr<nsIHttpChannel> newHttpChannel = do_QueryInterface(newChannel);
  708. NS_ENSURE_STATE(newHttpChannel);
  709. NS_NAMED_LITERAL_CSTRING(rangeHdr, "Range");
  710. nsresult rv = ClearRequestHeader(newHttpChannel);
  711. if (NS_FAILED(rv))
  712. return rv;
  713. // If we didn't have a Range header, then we must be doing a full download.
  714. nsAutoCString rangeVal;
  715. http->GetRequestHeader(rangeHdr, rangeVal);
  716. if (!rangeVal.IsEmpty()) {
  717. rv = newHttpChannel->SetRequestHeader(rangeHdr, rangeVal, false);
  718. NS_ENSURE_SUCCESS(rv, rv);
  719. }
  720. // A redirection changes the validator
  721. mPartialValidator.Truncate();
  722. if (mCacheBust) {
  723. newHttpChannel->SetRequestHeader(NS_LITERAL_CSTRING("Cache-Control"),
  724. NS_LITERAL_CSTRING("no-cache"), false);
  725. newHttpChannel->SetRequestHeader(NS_LITERAL_CSTRING("Pragma"),
  726. NS_LITERAL_CSTRING("no-cache"), false);
  727. }
  728. // Prepare to receive callback
  729. mRedirectCallback = cb;
  730. mNewRedirectChannel = newChannel;
  731. // Give the observer a chance to see this redirect notification.
  732. nsCOMPtr<nsIChannelEventSink> sink = do_GetInterface(mObserver);
  733. if (sink) {
  734. rv = sink->AsyncOnChannelRedirect(oldChannel, newChannel, flags, this);
  735. if (NS_FAILED(rv)) {
  736. mRedirectCallback = nullptr;
  737. mNewRedirectChannel = nullptr;
  738. }
  739. return rv;
  740. }
  741. (void) OnRedirectVerifyCallback(NS_OK);
  742. return NS_OK;
  743. }
  744. NS_IMETHODIMP
  745. nsIncrementalDownload::OnRedirectVerifyCallback(nsresult result)
  746. {
  747. NS_ASSERTION(mRedirectCallback, "mRedirectCallback not set in callback");
  748. NS_ASSERTION(mNewRedirectChannel, "mNewRedirectChannel not set in callback");
  749. // Update mChannel, so we can Cancel the new channel.
  750. if (NS_SUCCEEDED(result))
  751. mChannel = mNewRedirectChannel;
  752. mRedirectCallback->OnRedirectVerifyCallback(result);
  753. mRedirectCallback = nullptr;
  754. mNewRedirectChannel = nullptr;
  755. return NS_OK;
  756. }
  757. extern nsresult
  758. net_NewIncrementalDownload(nsISupports *outer, const nsIID &iid, void **result)
  759. {
  760. if (outer)
  761. return NS_ERROR_NO_AGGREGATION;
  762. nsIncrementalDownload *d = new nsIncrementalDownload();
  763. if (!d)
  764. return NS_ERROR_OUT_OF_MEMORY;
  765. NS_ADDREF(d);
  766. nsresult rv = d->QueryInterface(iid, result);
  767. NS_RELEASE(d);
  768. return rv;
  769. }