nsMultiMixedConv.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122
  1. /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. #include "nsMultiMixedConv.h"
  6. #include "plstr.h"
  7. #include "nsIHttpChannel.h"
  8. #include "nsNetCID.h"
  9. #include "nsMimeTypes.h"
  10. #include "nsIStringStream.h"
  11. #include "nsCRT.h"
  12. #include "nsIHttpChannelInternal.h"
  13. #include "nsURLHelper.h"
  14. #include "nsIStreamConverterService.h"
  15. #include "nsICacheInfoChannel.h"
  16. #include <algorithm>
  17. #include "nsContentSecurityManager.h"
  18. #include "nsHttp.h"
  19. #include "nsNetUtil.h"
  20. #include "nsIURI.h"
  21. #include "nsHttpHeaderArray.h"
  22. //
  23. // Helper function for determining the length of data bytes up to
  24. // the next multipart token. A token is usually preceded by a LF
  25. // or CRLF delimiter.
  26. //
  27. static uint32_t
  28. LengthToToken(const char *cursor, const char *token)
  29. {
  30. uint32_t len = token - cursor;
  31. // Trim off any LF or CRLF preceding the token
  32. if (len && *(token-1) == '\n') {
  33. --len;
  34. if (len && *(token-2) == '\r')
  35. --len;
  36. }
  37. return len;
  38. }
  39. nsPartChannel::nsPartChannel(nsIChannel *aMultipartChannel, uint32_t aPartID,
  40. nsIStreamListener* aListener) :
  41. mMultipartChannel(aMultipartChannel),
  42. mListener(aListener),
  43. mStatus(NS_OK),
  44. mContentLength(UINT64_MAX),
  45. mIsByteRangeRequest(false),
  46. mByteRangeStart(0),
  47. mByteRangeEnd(0),
  48. mPartID(aPartID),
  49. mIsLastPart(false)
  50. {
  51. // Inherit the load flags from the original channel...
  52. mMultipartChannel->GetLoadFlags(&mLoadFlags);
  53. mMultipartChannel->GetLoadGroup(getter_AddRefs(mLoadGroup));
  54. }
  55. nsPartChannel::~nsPartChannel()
  56. {
  57. }
  58. void nsPartChannel::InitializeByteRange(int64_t aStart, int64_t aEnd)
  59. {
  60. mIsByteRangeRequest = true;
  61. mByteRangeStart = aStart;
  62. mByteRangeEnd = aEnd;
  63. }
  64. nsresult nsPartChannel::SendOnStartRequest(nsISupports* aContext)
  65. {
  66. return mListener->OnStartRequest(this, aContext);
  67. }
  68. nsresult nsPartChannel::SendOnDataAvailable(nsISupports* aContext,
  69. nsIInputStream* aStream,
  70. uint64_t aOffset, uint32_t aLen)
  71. {
  72. return mListener->OnDataAvailable(this, aContext, aStream, aOffset, aLen);
  73. }
  74. nsresult nsPartChannel::SendOnStopRequest(nsISupports* aContext,
  75. nsresult aStatus)
  76. {
  77. // Drop the listener
  78. nsCOMPtr<nsIStreamListener> listener;
  79. listener.swap(mListener);
  80. return listener->OnStopRequest(this, aContext, aStatus);
  81. }
  82. void nsPartChannel::SetContentDisposition(const nsACString& aContentDispositionHeader)
  83. {
  84. mContentDispositionHeader = aContentDispositionHeader;
  85. nsCOMPtr<nsIURI> uri;
  86. GetURI(getter_AddRefs(uri));
  87. NS_GetFilenameFromDisposition(mContentDispositionFilename,
  88. mContentDispositionHeader, uri);
  89. mContentDisposition = NS_GetContentDispositionFromHeader(mContentDispositionHeader, this);
  90. }
  91. //
  92. // nsISupports implementation...
  93. //
  94. NS_IMPL_ADDREF(nsPartChannel)
  95. NS_IMPL_RELEASE(nsPartChannel)
  96. NS_INTERFACE_MAP_BEGIN(nsPartChannel)
  97. NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIChannel)
  98. NS_INTERFACE_MAP_ENTRY(nsIRequest)
  99. NS_INTERFACE_MAP_ENTRY(nsIChannel)
  100. NS_INTERFACE_MAP_ENTRY(nsIByteRangeRequest)
  101. NS_INTERFACE_MAP_ENTRY(nsIMultiPartChannel)
  102. NS_INTERFACE_MAP_END
  103. //
  104. // nsIRequest implementation...
  105. //
  106. NS_IMETHODIMP
  107. nsPartChannel::GetName(nsACString &aResult)
  108. {
  109. return mMultipartChannel->GetName(aResult);
  110. }
  111. NS_IMETHODIMP
  112. nsPartChannel::IsPending(bool *aResult)
  113. {
  114. // For now, consider the active lifetime of each part the same as
  115. // the underlying multipart channel... This is not exactly right,
  116. // but it is good enough :-)
  117. return mMultipartChannel->IsPending(aResult);
  118. }
  119. NS_IMETHODIMP
  120. nsPartChannel::GetStatus(nsresult *aResult)
  121. {
  122. nsresult rv = NS_OK;
  123. if (NS_FAILED(mStatus)) {
  124. *aResult = mStatus;
  125. } else {
  126. rv = mMultipartChannel->GetStatus(aResult);
  127. }
  128. return rv;
  129. }
  130. NS_IMETHODIMP
  131. nsPartChannel::Cancel(nsresult aStatus)
  132. {
  133. // Cancelling an individual part must not cancel the underlying
  134. // multipart channel...
  135. // XXX but we should stop sending data for _this_ part channel!
  136. mStatus = aStatus;
  137. return NS_OK;
  138. }
  139. NS_IMETHODIMP
  140. nsPartChannel::Suspend(void)
  141. {
  142. // Suspending an individual part must not suspend the underlying
  143. // multipart channel...
  144. // XXX why not?
  145. return NS_OK;
  146. }
  147. NS_IMETHODIMP
  148. nsPartChannel::Resume(void)
  149. {
  150. // Resuming an individual part must not resume the underlying
  151. // multipart channel...
  152. // XXX why not?
  153. return NS_OK;
  154. }
  155. //
  156. // nsIChannel implementation
  157. //
  158. NS_IMETHODIMP
  159. nsPartChannel::GetOriginalURI(nsIURI * *aURI)
  160. {
  161. return mMultipartChannel->GetOriginalURI(aURI);
  162. }
  163. NS_IMETHODIMP
  164. nsPartChannel::SetOriginalURI(nsIURI *aURI)
  165. {
  166. return mMultipartChannel->SetOriginalURI(aURI);
  167. }
  168. NS_IMETHODIMP
  169. nsPartChannel::GetURI(nsIURI * *aURI)
  170. {
  171. return mMultipartChannel->GetURI(aURI);
  172. }
  173. NS_IMETHODIMP
  174. nsPartChannel::Open(nsIInputStream **result)
  175. {
  176. // This channel cannot be opened!
  177. return NS_ERROR_FAILURE;
  178. }
  179. NS_IMETHODIMP
  180. nsPartChannel::Open2(nsIInputStream** aStream)
  181. {
  182. nsCOMPtr<nsIStreamListener> listener;
  183. nsresult rv = nsContentSecurityManager::doContentSecurityCheck(this, listener);
  184. NS_ENSURE_SUCCESS(rv, rv);
  185. return Open(aStream);
  186. }
  187. NS_IMETHODIMP
  188. nsPartChannel::AsyncOpen(nsIStreamListener *aListener, nsISupports *aContext)
  189. {
  190. // This channel cannot be opened!
  191. return NS_ERROR_FAILURE;
  192. }
  193. NS_IMETHODIMP
  194. nsPartChannel::AsyncOpen2(nsIStreamListener *aListener)
  195. {
  196. nsCOMPtr<nsIStreamListener> listener = aListener;
  197. nsresult rv = nsContentSecurityManager::doContentSecurityCheck(this, listener);
  198. NS_ENSURE_SUCCESS(rv, rv);
  199. return AsyncOpen(listener, nullptr);
  200. }
  201. NS_IMETHODIMP
  202. nsPartChannel::GetLoadFlags(nsLoadFlags *aLoadFlags)
  203. {
  204. *aLoadFlags = mLoadFlags;
  205. return NS_OK;
  206. }
  207. NS_IMETHODIMP
  208. nsPartChannel::SetLoadFlags(nsLoadFlags aLoadFlags)
  209. {
  210. mLoadFlags = aLoadFlags;
  211. return NS_OK;
  212. }
  213. NS_IMETHODIMP
  214. nsPartChannel::GetLoadGroup(nsILoadGroup* *aLoadGroup)
  215. {
  216. *aLoadGroup = mLoadGroup;
  217. NS_IF_ADDREF(*aLoadGroup);
  218. return NS_OK;
  219. }
  220. NS_IMETHODIMP
  221. nsPartChannel::SetLoadGroup(nsILoadGroup* aLoadGroup)
  222. {
  223. mLoadGroup = aLoadGroup;
  224. return NS_OK;
  225. }
  226. NS_IMETHODIMP
  227. nsPartChannel::GetOwner(nsISupports* *aOwner)
  228. {
  229. return mMultipartChannel->GetOwner(aOwner);
  230. }
  231. NS_IMETHODIMP
  232. nsPartChannel::SetOwner(nsISupports* aOwner)
  233. {
  234. return mMultipartChannel->SetOwner(aOwner);
  235. }
  236. NS_IMETHODIMP
  237. nsPartChannel::GetLoadInfo(nsILoadInfo* *aLoadInfo)
  238. {
  239. return mMultipartChannel->GetLoadInfo(aLoadInfo);
  240. }
  241. NS_IMETHODIMP
  242. nsPartChannel::SetLoadInfo(nsILoadInfo* aLoadInfo)
  243. {
  244. return mMultipartChannel->SetLoadInfo(aLoadInfo);
  245. }
  246. NS_IMETHODIMP
  247. nsPartChannel::GetNotificationCallbacks(nsIInterfaceRequestor* *aCallbacks)
  248. {
  249. return mMultipartChannel->GetNotificationCallbacks(aCallbacks);
  250. }
  251. NS_IMETHODIMP
  252. nsPartChannel::SetNotificationCallbacks(nsIInterfaceRequestor* aCallbacks)
  253. {
  254. return mMultipartChannel->SetNotificationCallbacks(aCallbacks);
  255. }
  256. NS_IMETHODIMP
  257. nsPartChannel::GetSecurityInfo(nsISupports * *aSecurityInfo)
  258. {
  259. return mMultipartChannel->GetSecurityInfo(aSecurityInfo);
  260. }
  261. NS_IMETHODIMP
  262. nsPartChannel::GetContentType(nsACString &aContentType)
  263. {
  264. aContentType = mContentType;
  265. return NS_OK;
  266. }
  267. NS_IMETHODIMP
  268. nsPartChannel::SetContentType(const nsACString &aContentType)
  269. {
  270. bool dummy;
  271. net_ParseContentType(aContentType, mContentType, mContentCharset, &dummy);
  272. return NS_OK;
  273. }
  274. NS_IMETHODIMP
  275. nsPartChannel::GetContentCharset(nsACString &aContentCharset)
  276. {
  277. aContentCharset = mContentCharset;
  278. return NS_OK;
  279. }
  280. NS_IMETHODIMP
  281. nsPartChannel::SetContentCharset(const nsACString &aContentCharset)
  282. {
  283. mContentCharset = aContentCharset;
  284. return NS_OK;
  285. }
  286. NS_IMETHODIMP
  287. nsPartChannel::GetContentLength(int64_t *aContentLength)
  288. {
  289. *aContentLength = mContentLength;
  290. return NS_OK;
  291. }
  292. NS_IMETHODIMP
  293. nsPartChannel::SetContentLength(int64_t aContentLength)
  294. {
  295. mContentLength = aContentLength;
  296. return NS_OK;
  297. }
  298. NS_IMETHODIMP
  299. nsPartChannel::GetContentDisposition(uint32_t *aContentDisposition)
  300. {
  301. if (mContentDispositionHeader.IsEmpty())
  302. return NS_ERROR_NOT_AVAILABLE;
  303. *aContentDisposition = mContentDisposition;
  304. return NS_OK;
  305. }
  306. NS_IMETHODIMP
  307. nsPartChannel::SetContentDisposition(uint32_t aContentDisposition)
  308. {
  309. return NS_ERROR_NOT_AVAILABLE;
  310. }
  311. NS_IMETHODIMP
  312. nsPartChannel::GetContentDispositionFilename(nsAString &aContentDispositionFilename)
  313. {
  314. if (mContentDispositionFilename.IsEmpty())
  315. return NS_ERROR_NOT_AVAILABLE;
  316. aContentDispositionFilename = mContentDispositionFilename;
  317. return NS_OK;
  318. }
  319. NS_IMETHODIMP
  320. nsPartChannel::SetContentDispositionFilename(const nsAString &aContentDispositionFilename)
  321. {
  322. return NS_ERROR_NOT_AVAILABLE;
  323. }
  324. NS_IMETHODIMP
  325. nsPartChannel::GetContentDispositionHeader(nsACString &aContentDispositionHeader)
  326. {
  327. if (mContentDispositionHeader.IsEmpty())
  328. return NS_ERROR_NOT_AVAILABLE;
  329. aContentDispositionHeader = mContentDispositionHeader;
  330. return NS_OK;
  331. }
  332. NS_IMETHODIMP
  333. nsPartChannel::GetPartID(uint32_t *aPartID)
  334. {
  335. *aPartID = mPartID;
  336. return NS_OK;
  337. }
  338. NS_IMETHODIMP
  339. nsPartChannel::GetIsLastPart(bool *aIsLastPart)
  340. {
  341. *aIsLastPart = mIsLastPart;
  342. return NS_OK;
  343. }
  344. //
  345. // nsIByteRangeRequest implementation...
  346. //
  347. NS_IMETHODIMP
  348. nsPartChannel::GetIsByteRangeRequest(bool *aIsByteRangeRequest)
  349. {
  350. *aIsByteRangeRequest = mIsByteRangeRequest;
  351. return NS_OK;
  352. }
  353. NS_IMETHODIMP
  354. nsPartChannel::GetStartRange(int64_t *aStartRange)
  355. {
  356. *aStartRange = mByteRangeStart;
  357. return NS_OK;
  358. }
  359. NS_IMETHODIMP
  360. nsPartChannel::GetEndRange(int64_t *aEndRange)
  361. {
  362. *aEndRange = mByteRangeEnd;
  363. return NS_OK;
  364. }
  365. NS_IMETHODIMP
  366. nsPartChannel::GetBaseChannel(nsIChannel ** aReturn)
  367. {
  368. NS_ENSURE_ARG_POINTER(aReturn);
  369. *aReturn = mMultipartChannel;
  370. NS_IF_ADDREF(*aReturn);
  371. return NS_OK;
  372. }
  373. // nsISupports implementation
  374. NS_IMPL_ISUPPORTS(nsMultiMixedConv,
  375. nsIStreamConverter,
  376. nsIStreamListener,
  377. nsIRequestObserver)
  378. // nsIStreamConverter implementation
  379. // No syncronous conversion at this time.
  380. NS_IMETHODIMP
  381. nsMultiMixedConv::Convert(nsIInputStream *aFromStream,
  382. const char *aFromType,
  383. const char *aToType,
  384. nsISupports *aCtxt, nsIInputStream **_retval) {
  385. return NS_ERROR_NOT_IMPLEMENTED;
  386. }
  387. // Stream converter service calls this to initialize the actual stream converter (us).
  388. NS_IMETHODIMP
  389. nsMultiMixedConv::AsyncConvertData(const char *aFromType, const char *aToType,
  390. nsIStreamListener *aListener, nsISupports *aCtxt) {
  391. NS_ASSERTION(aListener && aFromType && aToType, "null pointer passed into multi mixed converter");
  392. // hook up our final listener. this guy gets the various On*() calls we want to throw
  393. // at him.
  394. //
  395. // WARNING: this listener must be able to handle multiple OnStartRequest, OnDataAvail()
  396. // and OnStopRequest() call combinations. We call of series of these for each sub-part
  397. // in the raw stream.
  398. mFinalListener = aListener;
  399. return NS_OK;
  400. }
  401. // AutoFree implementation to prevent memory leaks
  402. class AutoFree
  403. {
  404. public:
  405. AutoFree() : mBuffer(nullptr) {}
  406. explicit AutoFree(char *buffer) : mBuffer(buffer) {}
  407. ~AutoFree() {
  408. free(mBuffer);
  409. }
  410. AutoFree& operator=(char *buffer) {
  411. mBuffer = buffer;
  412. return *this;
  413. }
  414. operator char*() const {
  415. return mBuffer;
  416. }
  417. private:
  418. char *mBuffer;
  419. };
  420. // nsIStreamListener implementation
  421. NS_IMETHODIMP
  422. nsMultiMixedConv::OnDataAvailable(nsIRequest *request, nsISupports *context,
  423. nsIInputStream *inStr, uint64_t sourceOffset,
  424. uint32_t count) {
  425. nsresult rv = NS_OK;
  426. AutoFree buffer(nullptr);
  427. uint32_t bufLen = 0, read = 0;
  428. NS_ASSERTION(request, "multimixed converter needs a request");
  429. nsCOMPtr<nsIChannel> channel = do_QueryInterface(request, &rv);
  430. if (NS_FAILED(rv)) return rv;
  431. // fill buffer
  432. {
  433. bufLen = count + mBufLen;
  434. NS_ENSURE_TRUE((bufLen >= count) && (bufLen >= mBufLen),
  435. NS_ERROR_FAILURE);
  436. buffer = (char *) malloc(bufLen);
  437. if (!buffer)
  438. return NS_ERROR_OUT_OF_MEMORY;
  439. if (mBufLen) {
  440. // incorporate any buffered data into the parsing
  441. memcpy(buffer, mBuffer, mBufLen);
  442. free(mBuffer);
  443. mBuffer = 0;
  444. mBufLen = 0;
  445. }
  446. rv = inStr->Read(buffer + (bufLen - count), count, &read);
  447. if (NS_FAILED(rv) || read == 0) return rv;
  448. NS_ASSERTION(read == count, "poor data size assumption");
  449. }
  450. char *cursor = buffer;
  451. if (mFirstOnData) {
  452. // this is the first OnData() for this request. some servers
  453. // don't bother sending a token in the first "part." This is
  454. // illegal, but we'll handle the case anyway by shoving the
  455. // boundary token in for the server.
  456. mFirstOnData = false;
  457. NS_ASSERTION(!mBufLen, "this is our first time through, we can't have buffered data");
  458. const char * token = mToken.get();
  459. PushOverLine(cursor, bufLen);
  460. bool needMoreChars = bufLen < mTokenLen + 2;
  461. nsAutoCString firstBuffer(buffer, bufLen);
  462. int32_t posCR = firstBuffer.Find("\r");
  463. if (needMoreChars || (posCR == kNotFound)) {
  464. // we don't have enough data yet to make this comparison.
  465. // skip this check, and try again the next time OnData()
  466. // is called.
  467. mFirstOnData = true;
  468. } else if (!PL_strnstr(cursor, token, mTokenLen + 2)) {
  469. char *newBuffer = (char *) realloc(buffer, bufLen + mTokenLen + 1);
  470. if (!newBuffer)
  471. return NS_ERROR_OUT_OF_MEMORY;
  472. buffer = newBuffer;
  473. memmove(buffer + mTokenLen + 1, buffer, bufLen);
  474. memcpy(buffer, token, mTokenLen);
  475. buffer[mTokenLen] = '\n';
  476. bufLen += (mTokenLen + 1);
  477. // need to reset cursor to the buffer again (bug 100595)
  478. cursor = buffer;
  479. }
  480. }
  481. char *token = nullptr;
  482. if (mProcessingHeaders) {
  483. // we were not able to process all the headers
  484. // for this "part" given the previous buffer given to
  485. // us in the previous OnDataAvailable callback.
  486. bool done = false;
  487. rv = ParseHeaders(channel, cursor, bufLen, &done);
  488. if (NS_FAILED(rv)) return rv;
  489. if (done) {
  490. mProcessingHeaders = false;
  491. rv = SendStart(channel);
  492. if (NS_FAILED(rv)) return rv;
  493. }
  494. }
  495. int32_t tokenLinefeed = 1;
  496. while ( (token = FindToken(cursor, bufLen)) ) {
  497. if (((token + mTokenLen + 1) < (cursor + bufLen)) &&
  498. (*(token + mTokenLen + 1) == '-')) {
  499. // This was the last delimiter so we can stop processing
  500. rv = SendData(cursor, LengthToToken(cursor, token));
  501. if (NS_FAILED(rv)) return rv;
  502. if (mPartChannel) {
  503. mPartChannel->SetIsLastPart();
  504. }
  505. return SendStop(NS_OK);
  506. }
  507. if (!mNewPart && token > cursor) {
  508. // headers are processed, we're pushing data now.
  509. NS_ASSERTION(!mProcessingHeaders, "we should be pushing raw data");
  510. rv = SendData(cursor, LengthToToken(cursor, token));
  511. bufLen -= token - cursor;
  512. if (NS_FAILED(rv)) return rv;
  513. }
  514. // XXX else NS_ASSERTION(token == cursor, "?");
  515. token += mTokenLen;
  516. bufLen -= mTokenLen;
  517. tokenLinefeed = PushOverLine(token, bufLen);
  518. if (mNewPart) {
  519. // parse headers
  520. mNewPart = false;
  521. cursor = token;
  522. bool done = false;
  523. rv = ParseHeaders(channel, cursor, bufLen, &done);
  524. if (NS_FAILED(rv)) return rv;
  525. if (done) {
  526. rv = SendStart(channel);
  527. if (NS_FAILED(rv)) return rv;
  528. }
  529. else {
  530. // we haven't finished processing header info.
  531. // we'll break out and try to process later.
  532. mProcessingHeaders = true;
  533. break;
  534. }
  535. }
  536. else {
  537. mNewPart = true;
  538. // Reset state so we don't carry it over from part to part
  539. mContentType.Truncate();
  540. mContentLength = UINT64_MAX;
  541. mContentDisposition.Truncate();
  542. mIsByteRangeRequest = false;
  543. mByteRangeStart = 0;
  544. mByteRangeEnd = 0;
  545. rv = SendStop(NS_OK);
  546. if (NS_FAILED(rv)) return rv;
  547. // reset the token to front. this allows us to treat
  548. // the token as a starting token.
  549. token -= mTokenLen + tokenLinefeed;
  550. bufLen += mTokenLen + tokenLinefeed;
  551. cursor = token;
  552. }
  553. }
  554. // at this point, we want to buffer up whatever amount (bufLen)
  555. // we have leftover. However, we *always* want to ensure that
  556. // we buffer enough data to handle a broken token.
  557. // carry over
  558. uint32_t bufAmt = 0;
  559. if (mProcessingHeaders)
  560. bufAmt = bufLen;
  561. else if (bufLen) {
  562. // if the data ends in a linefeed, and we're in the middle
  563. // of a "part" (ie. mPartChannel exists) don't bother
  564. // buffering, go ahead and send the data we have. Otherwise
  565. // if we don't have a channel already, then we don't even
  566. // have enough info to start a part, go ahead and buffer
  567. // enough to collect a boundary token.
  568. if (!mPartChannel || !(cursor[bufLen-1] == nsCRT::LF) )
  569. bufAmt = std::min(mTokenLen - 1, bufLen);
  570. }
  571. if (bufAmt) {
  572. rv = BufferData(cursor + (bufLen - bufAmt), bufAmt);
  573. if (NS_FAILED(rv)) return rv;
  574. bufLen -= bufAmt;
  575. }
  576. if (bufLen) {
  577. rv = SendData(cursor, bufLen);
  578. if (NS_FAILED(rv)) return rv;
  579. }
  580. return rv;
  581. }
  582. // nsIRequestObserver implementation
  583. NS_IMETHODIMP
  584. nsMultiMixedConv::OnStartRequest(nsIRequest *request, nsISupports *ctxt) {
  585. // we're assuming the content-type is available at this stage
  586. NS_ASSERTION(mToken.IsEmpty(), "a second on start???");
  587. const char *bndry = nullptr;
  588. nsAutoCString delimiter;
  589. nsresult rv = NS_OK;
  590. mContext = ctxt;
  591. mFirstOnData = true;
  592. mTotalSent = 0;
  593. nsCOMPtr<nsIChannel> channel = do_QueryInterface(request, &rv);
  594. if (NS_FAILED(rv)) return rv;
  595. // ask the HTTP channel for the content-type and extract the boundary from it.
  596. nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(channel, &rv);
  597. if (NS_SUCCEEDED(rv)) {
  598. rv = httpChannel->GetResponseHeader(NS_LITERAL_CSTRING("content-type"), delimiter);
  599. if (NS_FAILED(rv)) {
  600. return rv;
  601. }
  602. } else {
  603. // try asking the channel directly
  604. rv = channel->GetContentType(delimiter);
  605. if (NS_FAILED(rv)) {
  606. return NS_ERROR_FAILURE;
  607. }
  608. }
  609. bndry = strstr(delimiter.BeginWriting(), "boundary");
  610. if (!bndry) {
  611. return NS_ERROR_FAILURE;
  612. }
  613. bndry = strchr(bndry, '=');
  614. if (!bndry) return NS_ERROR_FAILURE;
  615. bndry++; // move past the equals sign
  616. char *attrib = (char *) strchr(bndry, ';');
  617. if (attrib) *attrib = '\0';
  618. nsAutoCString boundaryString(bndry);
  619. if (attrib) *attrib = ';';
  620. boundaryString.Trim(" \"");
  621. mToken = boundaryString;
  622. mTokenLen = boundaryString.Length();
  623. if (mTokenLen == 0) {
  624. return NS_ERROR_FAILURE;
  625. }
  626. return NS_OK;
  627. }
  628. NS_IMETHODIMP
  629. nsMultiMixedConv::OnStopRequest(nsIRequest *request, nsISupports *ctxt,
  630. nsresult aStatus)
  631. {
  632. if (mToken.IsEmpty()) { // no token, no love.
  633. return NS_ERROR_FAILURE;
  634. }
  635. if (mPartChannel) {
  636. mPartChannel->SetIsLastPart();
  637. // we've already called SendStart() (which sets up the mPartChannel,
  638. // and fires an OnStart()) send any data left over, and then fire the stop.
  639. if (mBufLen > 0 && mBuffer) {
  640. (void) SendData(mBuffer, mBufLen);
  641. // don't bother checking the return value here, if the send failed
  642. // we're done anyway as we're in the OnStop() callback.
  643. free(mBuffer);
  644. mBuffer = nullptr;
  645. mBufLen = 0;
  646. }
  647. (void) SendStop(aStatus);
  648. } else if (NS_FAILED(aStatus)) {
  649. // underlying data production problem. we should not be in
  650. // the middle of sending data. if we were, mPartChannel,
  651. // above, would have been true.
  652. // if we send the start, the URI Loader's m_targetStreamListener, may
  653. // be pointing at us causing a nice stack overflow. So, don't call
  654. // OnStartRequest! - This breaks necko's semantecs.
  655. //(void) mFinalListener->OnStartRequest(request, ctxt);
  656. (void) mFinalListener->OnStopRequest(request, ctxt, aStatus);
  657. }
  658. return NS_OK;
  659. }
  660. // nsMultiMixedConv methods
  661. nsMultiMixedConv::nsMultiMixedConv() :
  662. mCurrentPartID(0)
  663. {
  664. mTokenLen = 0;
  665. mNewPart = true;
  666. mContentLength = UINT64_MAX;
  667. mBuffer = nullptr;
  668. mBufLen = 0;
  669. mProcessingHeaders = false;
  670. mByteRangeStart = 0;
  671. mByteRangeEnd = 0;
  672. mTotalSent = 0;
  673. mIsByteRangeRequest = false;
  674. }
  675. nsMultiMixedConv::~nsMultiMixedConv() {
  676. NS_ASSERTION(!mBuffer, "all buffered data should be gone");
  677. if (mBuffer) {
  678. free(mBuffer);
  679. mBuffer = nullptr;
  680. }
  681. }
  682. nsresult
  683. nsMultiMixedConv::BufferData(char *aData, uint32_t aLen) {
  684. NS_ASSERTION(!mBuffer, "trying to over-write buffer");
  685. char *buffer = (char *) malloc(aLen);
  686. if (!buffer) return NS_ERROR_OUT_OF_MEMORY;
  687. memcpy(buffer, aData, aLen);
  688. mBuffer = buffer;
  689. mBufLen = aLen;
  690. return NS_OK;
  691. }
  692. nsresult
  693. nsMultiMixedConv::SendStart(nsIChannel *aChannel) {
  694. nsresult rv = NS_OK;
  695. nsCOMPtr<nsIStreamListener> partListener(mFinalListener);
  696. if (mContentType.IsEmpty()) {
  697. mContentType.AssignLiteral(UNKNOWN_CONTENT_TYPE);
  698. nsCOMPtr<nsIStreamConverterService> serv =
  699. do_GetService(NS_STREAMCONVERTERSERVICE_CONTRACTID, &rv);
  700. if (NS_SUCCEEDED(rv)) {
  701. nsCOMPtr<nsIStreamListener> converter;
  702. rv = serv->AsyncConvertData(UNKNOWN_CONTENT_TYPE,
  703. "*/*",
  704. mFinalListener,
  705. mContext,
  706. getter_AddRefs(converter));
  707. if (NS_SUCCEEDED(rv)) {
  708. partListener = converter;
  709. }
  710. }
  711. }
  712. // if we already have an mPartChannel, that means we never sent a Stop()
  713. // before starting up another "part." that would be bad.
  714. NS_ASSERTION(!mPartChannel, "tisk tisk, shouldn't be overwriting a channel");
  715. nsPartChannel *newChannel;
  716. newChannel = new nsPartChannel(aChannel, mCurrentPartID++, partListener);
  717. if (!newChannel)
  718. return NS_ERROR_OUT_OF_MEMORY;
  719. if (mIsByteRangeRequest) {
  720. newChannel->InitializeByteRange(mByteRangeStart, mByteRangeEnd);
  721. }
  722. mTotalSent = 0;
  723. // Set up the new part channel...
  724. mPartChannel = newChannel;
  725. rv = mPartChannel->SetContentType(mContentType);
  726. if (NS_FAILED(rv)) return rv;
  727. rv = mPartChannel->SetContentLength(mContentLength);
  728. if (NS_FAILED(rv)) return rv;
  729. mPartChannel->SetContentDisposition(mContentDisposition);
  730. nsLoadFlags loadFlags = 0;
  731. mPartChannel->GetLoadFlags(&loadFlags);
  732. loadFlags |= nsIChannel::LOAD_REPLACE;
  733. mPartChannel->SetLoadFlags(loadFlags);
  734. nsCOMPtr<nsILoadGroup> loadGroup;
  735. (void)mPartChannel->GetLoadGroup(getter_AddRefs(loadGroup));
  736. // Add the new channel to the load group (if any)
  737. if (loadGroup) {
  738. rv = loadGroup->AddRequest(mPartChannel, nullptr);
  739. if (NS_FAILED(rv)) return rv;
  740. }
  741. // Let's start off the load. NOTE: we don't forward on the channel passed
  742. // into our OnDataAvailable() as it's the root channel for the raw stream.
  743. return mPartChannel->SendOnStartRequest(mContext);
  744. }
  745. nsresult
  746. nsMultiMixedConv::SendStop(nsresult aStatus) {
  747. nsresult rv = NS_OK;
  748. if (mPartChannel) {
  749. rv = mPartChannel->SendOnStopRequest(mContext, aStatus);
  750. // don't check for failure here, we need to remove the channel from
  751. // the loadgroup.
  752. // Remove the channel from its load group (if any)
  753. nsCOMPtr<nsILoadGroup> loadGroup;
  754. (void) mPartChannel->GetLoadGroup(getter_AddRefs(loadGroup));
  755. if (loadGroup)
  756. (void) loadGroup->RemoveRequest(mPartChannel, mContext, aStatus);
  757. }
  758. mPartChannel = nullptr;
  759. return rv;
  760. }
  761. nsresult
  762. nsMultiMixedConv::SendData(char *aBuffer, uint32_t aLen) {
  763. nsresult rv = NS_OK;
  764. if (!mPartChannel) return NS_ERROR_FAILURE; // something went wrong w/ processing
  765. if (mContentLength != UINT64_MAX) {
  766. // make sure that we don't send more than the mContentLength
  767. // XXX why? perhaps the Content-Length header was actually wrong!!
  768. if ((uint64_t(aLen) + mTotalSent) > mContentLength)
  769. aLen = static_cast<uint32_t>(mContentLength - mTotalSent);
  770. if (aLen == 0)
  771. return NS_OK;
  772. }
  773. uint64_t offset = mTotalSent;
  774. mTotalSent += aLen;
  775. nsCOMPtr<nsIStringInputStream> ss(
  776. do_CreateInstance("@mozilla.org/io/string-input-stream;1", &rv));
  777. if (NS_FAILED(rv))
  778. return rv;
  779. rv = ss->ShareData(aBuffer, aLen);
  780. if (NS_FAILED(rv))
  781. return rv;
  782. nsCOMPtr<nsIInputStream> inStream(do_QueryInterface(ss, &rv));
  783. if (NS_FAILED(rv)) return rv;
  784. return mPartChannel->SendOnDataAvailable(mContext, inStream, offset, aLen);
  785. }
  786. int32_t
  787. nsMultiMixedConv::PushOverLine(char *&aPtr, uint32_t &aLen) {
  788. int32_t chars = 0;
  789. if ((aLen > 0) && (*aPtr == nsCRT::CR || *aPtr == nsCRT::LF)) {
  790. if ((aLen > 1) && (aPtr[1] == nsCRT::LF))
  791. chars++;
  792. chars++;
  793. aPtr += chars;
  794. aLen -= chars;
  795. }
  796. return chars;
  797. }
  798. nsresult
  799. nsMultiMixedConv::ParseHeaders(nsIChannel *aChannel, char *&aPtr,
  800. uint32_t &aLen, bool *_retval) {
  801. // NOTE: this data must be ascii.
  802. // NOTE: aPtr is NOT null terminated!
  803. nsresult rv = NS_OK;
  804. char *cursor = aPtr, *newLine = nullptr;
  805. uint32_t cursorLen = aLen;
  806. bool done = false;
  807. uint32_t lineFeedIncrement = 1;
  808. mContentLength = UINT64_MAX; // XXX what if we were already called?
  809. while (cursorLen && (newLine = (char *) memchr(cursor, nsCRT::LF, cursorLen))) {
  810. // adjust for linefeeds
  811. if ((newLine > cursor) && (newLine[-1] == nsCRT::CR) ) { // CRLF
  812. lineFeedIncrement = 2;
  813. newLine--;
  814. }
  815. else
  816. lineFeedIncrement = 1; // reset
  817. if (newLine == cursor) {
  818. // move the newLine beyond the linefeed marker
  819. NS_ASSERTION(cursorLen >= lineFeedIncrement, "oops!");
  820. cursor += lineFeedIncrement;
  821. cursorLen -= lineFeedIncrement;
  822. done = true;
  823. break;
  824. }
  825. char tmpChar = *newLine;
  826. *newLine = '\0'; // cursor is now null terminated
  827. char *colon = (char *) strchr(cursor, ':');
  828. if (colon) {
  829. *colon = '\0';
  830. nsAutoCString headerStr(cursor);
  831. headerStr.CompressWhitespace();
  832. *colon = ':';
  833. nsAutoCString headerVal(colon + 1);
  834. headerVal.CompressWhitespace();
  835. // examine header
  836. if (headerStr.LowerCaseEqualsLiteral("content-type")) {
  837. mContentType = headerVal;
  838. } else if (headerStr.LowerCaseEqualsLiteral("content-length")) {
  839. mContentLength = nsCRT::atoll(headerVal.get());
  840. } else if (headerStr.LowerCaseEqualsLiteral("content-disposition")) {
  841. mContentDisposition = headerVal;
  842. } else if (headerStr.LowerCaseEqualsLiteral("set-cookie")) {
  843. nsCOMPtr<nsIHttpChannelInternal> httpInternal =
  844. do_QueryInterface(aChannel);
  845. if (httpInternal) {
  846. httpInternal->SetCookie(headerVal.get());
  847. }
  848. } else if (headerStr.LowerCaseEqualsLiteral("content-range") ||
  849. headerStr.LowerCaseEqualsLiteral("range") ) {
  850. // something like: Content-range: bytes 7000-7999/8000
  851. char* tmpPtr;
  852. tmpPtr = (char *) strchr(colon + 1, '/');
  853. if (tmpPtr)
  854. *tmpPtr = '\0';
  855. // pass the bytes-unit and the SP
  856. char *range = (char *) strchr(colon + 2, ' ');
  857. if (!range)
  858. return NS_ERROR_FAILURE;
  859. do {
  860. range++;
  861. } while (*range == ' ');
  862. if (range[0] == '*'){
  863. mByteRangeStart = mByteRangeEnd = 0;
  864. }
  865. else {
  866. tmpPtr = (char *) strchr(range, '-');
  867. if (!tmpPtr)
  868. return NS_ERROR_FAILURE;
  869. tmpPtr[0] = '\0';
  870. mByteRangeStart = nsCRT::atoll(range);
  871. tmpPtr++;
  872. mByteRangeEnd = nsCRT::atoll(tmpPtr);
  873. }
  874. mIsByteRangeRequest = true;
  875. if (mContentLength == UINT64_MAX)
  876. mContentLength = uint64_t(mByteRangeEnd - mByteRangeStart + 1);
  877. }
  878. }
  879. *newLine = tmpChar;
  880. newLine += lineFeedIncrement;
  881. cursorLen -= (newLine - cursor);
  882. cursor = newLine;
  883. }
  884. aPtr = cursor;
  885. aLen = cursorLen;
  886. *_retval = done;
  887. return rv;
  888. }
  889. char *
  890. nsMultiMixedConv::FindToken(char *aCursor, uint32_t aLen) {
  891. // strnstr without looking for null termination
  892. const char *token = mToken.get();
  893. char *cur = aCursor;
  894. if (!(token && aCursor && *token)) {
  895. NS_WARNING("bad data");
  896. return nullptr;
  897. }
  898. for (; aLen >= mTokenLen; aCursor++, aLen--) {
  899. if (!memcmp(aCursor, token, mTokenLen) ) {
  900. if ((aCursor - cur) >= 2) {
  901. // back the cursor up over a double dash for backwards compat.
  902. if ((*(aCursor-1) == '-') && (*(aCursor-2) == '-')) {
  903. aCursor -= 2;
  904. aLen += 2;
  905. // we're playing w/ double dash tokens, adjust.
  906. mToken.Assign(aCursor, mTokenLen + 2);
  907. mTokenLen = mToken.Length();
  908. }
  909. }
  910. return aCursor;
  911. }
  912. }
  913. return nullptr;
  914. }
  915. nsresult
  916. NS_NewMultiMixedConv(nsMultiMixedConv** aMultiMixedConv)
  917. {
  918. NS_PRECONDITION(aMultiMixedConv != nullptr, "null ptr");
  919. if (! aMultiMixedConv)
  920. return NS_ERROR_NULL_POINTER;
  921. *aMultiMixedConv = new nsMultiMixedConv();
  922. if (! *aMultiMixedConv)
  923. return NS_ERROR_OUT_OF_MEMORY;
  924. NS_ADDREF(*aMultiMixedConv);
  925. return NS_OK;
  926. }