HttpResponseCommand.cc 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2006 Tatsuhiro Tsujikawa
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * In addition, as a special exception, the copyright holders give
  22. * permission to link the code of portions of this program with the
  23. * OpenSSL library under certain conditions as described in each
  24. * individual source file, and distribute linked combinations
  25. * including the two.
  26. * You must obey the GNU General Public License in all respects
  27. * for all of the code used other than OpenSSL. If you modify
  28. * file(s) with this exception, you may extend this exception to your
  29. * version of the file(s), but you are not obligated to do so. If you
  30. * do not wish to do so, delete this exception statement from your
  31. * version. If you delete this exception statement from all source
  32. * files in the program, then also delete it here.
  33. */
  34. /* copyright --> */
  35. #include "HttpResponseCommand.h"
  36. #include "DownloadEngine.h"
  37. #include "DownloadContext.h"
  38. #include "FileEntry.h"
  39. #include "RequestGroup.h"
  40. #include "RequestGroupMan.h"
  41. #include "Request.h"
  42. #include "HttpRequest.h"
  43. #include "HttpResponse.h"
  44. #include "HttpConnection.h"
  45. #include "SegmentMan.h"
  46. #include "Segment.h"
  47. #include "HttpDownloadCommand.h"
  48. #include "DiskAdaptor.h"
  49. #include "PieceStorage.h"
  50. #include "DefaultBtProgressInfoFile.h"
  51. #include "DownloadFailureException.h"
  52. #include "DlAbortEx.h"
  53. #include "util.h"
  54. #include "File.h"
  55. #include "Option.h"
  56. #include "Logger.h"
  57. #include "Socket.h"
  58. #include "message.h"
  59. #include "prefs.h"
  60. #include "StringFormat.h"
  61. #include "HttpSkipResponseCommand.h"
  62. #include "HttpHeader.h"
  63. #include "LogFactory.h"
  64. #include "CookieStorage.h"
  65. #include "AuthConfigFactory.h"
  66. #include "AuthConfig.h"
  67. #include "a2functional.h"
  68. #include "URISelector.h"
  69. #include "ServerStatMan.h"
  70. #include "FileAllocationEntry.h"
  71. #include "CheckIntegrityEntry.h"
  72. #include "StreamFilter.h"
  73. #include "SinkStreamFilter.h"
  74. #include "ChunkedDecodingStreamFilter.h"
  75. #include "GZipDecodingStreamFilter.h"
  76. namespace aria2 {
  77. static SharedHandle<StreamFilter> getTransferEncodingStreamFilter
  78. (const SharedHandle<HttpResponse>& httpResponse,
  79. const SharedHandle<StreamFilter>& delegate = SharedHandle<StreamFilter>());
  80. static SharedHandle<StreamFilter> getContentEncodingStreamFilter
  81. (const SharedHandle<HttpResponse>& httpResponse,
  82. const SharedHandle<StreamFilter>& delegate = SharedHandle<StreamFilter>());
  83. HttpResponseCommand::HttpResponseCommand
  84. (cuid_t cuid,
  85. const SharedHandle<Request>& req,
  86. const SharedHandle<FileEntry>& fileEntry,
  87. RequestGroup* requestGroup,
  88. const HttpConnectionHandle& httpConnection,
  89. DownloadEngine* e,
  90. const SocketHandle& s)
  91. :AbstractCommand(cuid, req, fileEntry, requestGroup, e, s),
  92. httpConnection_(httpConnection)
  93. {}
  94. HttpResponseCommand::~HttpResponseCommand() {}
  95. bool HttpResponseCommand::executeInternal()
  96. {
  97. SharedHandle<HttpRequest> httpRequest =httpConnection_->getFirstHttpRequest();
  98. SharedHandle<HttpResponse> httpResponse = httpConnection_->receiveResponse();
  99. if(httpResponse.isNull()) {
  100. // The server has not responded to our request yet.
  101. // For socket->wantRead() == true, setReadCheckSocket(socket) is already
  102. // done in the constructor.
  103. setWriteCheckSocketIf(getSocket(), getSocket()->wantWrite());
  104. getDownloadEngine()->addCommand(this);
  105. return false;
  106. }
  107. // check HTTP status number
  108. httpResponse->validateResponse();
  109. httpResponse->retrieveCookie();
  110. SharedHandle<HttpHeader> httpHeader = httpResponse->getHttpHeader();
  111. // Disable persistent connection if:
  112. // Connection: close is received or the remote server is not HTTP/1.1.
  113. // We don't care whether non-HTTP/1.1 server returns Connection: keep-alive.
  114. getRequest()->supportsPersistentConnection
  115. (httpResponse->supportsPersistentConnection());
  116. if(getRequest()->isPipeliningEnabled()) {
  117. getRequest()->setMaxPipelinedRequest
  118. (getOption()->getAsInt(PREF_MAX_HTTP_PIPELINING));
  119. }
  120. if(!httpResponse->getHttpRequest()->getIfModifiedSinceHeader().empty()) {
  121. if(httpResponse->getResponseStatus() == HttpHeader::S304) {
  122. uint64_t totalLength = httpResponse->getEntityLength();
  123. getFileEntry()->setLength(totalLength);
  124. getRequestGroup()->initPieceStorage();
  125. getPieceStorage()->markAllPiecesDone();
  126. // TODO It would be good to issue ChecksumCheckIntegrity here
  127. // instead of just pretending checksum verification is done.
  128. getDownloadContext()->setChecksumVerified(true);
  129. getLogger()->notice(MSG_DOWNLOAD_ALREADY_COMPLETED,
  130. util::itos(getRequestGroup()->getGID()).c_str(),
  131. getRequestGroup()->getFirstFilePath().c_str());
  132. poolConnection();
  133. getFileEntry()->poolRequest(getRequest());
  134. return true;
  135. } else if(httpResponse->getResponseStatus() == HttpHeader::S200 ||
  136. httpResponse->getResponseStatus() == HttpHeader::S206) {
  137. // Remote file is newer than local file. We allow overwrite.
  138. getOption()->put(PREF_ALLOW_OVERWRITE, V_TRUE);
  139. }
  140. }
  141. if(httpResponse->getResponseStatus() >= HttpHeader::S300 &&
  142. httpResponse->getResponseStatus() != HttpHeader::S304) {
  143. if(httpResponse->getResponseStatus() == HttpHeader::S404) {
  144. getRequestGroup()->increaseAndValidateFileNotFoundCount();
  145. }
  146. return skipResponseBody(httpResponse);
  147. }
  148. if(getFileEntry()->isUniqueProtocol()) {
  149. // Redirection should be considered here. We need to parse
  150. // original URI to get hostname.
  151. Request req;
  152. req.setUri(getRequest()->getUri());
  153. getFileEntry()->removeURIWhoseHostnameIs(req.getHost());
  154. }
  155. if(getPieceStorage().isNull()) {
  156. uint64_t totalLength = httpResponse->getEntityLength();
  157. getFileEntry()->setLength(totalLength);
  158. if(getFileEntry()->getPath().empty()) {
  159. getFileEntry()->setPath
  160. (util::applyDir
  161. (getDownloadContext()->getDir(),
  162. util::fixTaintedBasename(httpResponse->determinFilename())));
  163. }
  164. getFileEntry()->setContentType(httpResponse->getContentType());
  165. getRequestGroup()->preDownloadProcessing();
  166. if(getDownloadEngine()->getRequestGroupMan()->
  167. isSameFileBeingDownloaded(getRequestGroup())) {
  168. throw DOWNLOAD_FAILURE_EXCEPTION
  169. (StringFormat(EX_DUPLICATE_FILE_DOWNLOAD,
  170. getRequestGroup()->getFirstFilePath().c_str()).str());
  171. }
  172. // update last modified time
  173. updateLastModifiedTime(httpResponse->getLastModifiedTime());
  174. // If both transfer-encoding and total length is specified, we
  175. // assume we can do segmented downloading
  176. if(totalLength == 0 || shouldInflateContentEncoding(httpResponse)) {
  177. // we ignore content-length when inflate is required
  178. getFileEntry()->setLength(0);
  179. if(getRequest()->getMethod() == Request::METHOD_GET &&
  180. (totalLength != 0 ||
  181. !httpResponse->getHttpHeader()->defined(HttpHeader::CONTENT_LENGTH))){
  182. // DownloadContext::knowsTotalLength() == true only when
  183. // server says the size of file is 0 explicitly.
  184. getDownloadContext()->markTotalLengthIsUnknown();
  185. }
  186. return handleOtherEncoding(httpResponse);
  187. } else {
  188. return handleDefaultEncoding(httpResponse);
  189. }
  190. } else {
  191. // validate totalsize
  192. getRequestGroup()->validateTotalLength(getFileEntry()->getLength(),
  193. httpResponse->getEntityLength());
  194. // update last modified time
  195. updateLastModifiedTime(httpResponse->getLastModifiedTime());
  196. if(getRequestGroup()->getTotalLength() == 0) {
  197. // Since total length is unknown, the file size in previously
  198. // failed download could be larger than the size this time.
  199. // Also we can't resume in this case too. So truncate the file
  200. // anyway.
  201. getPieceStorage()->getDiskAdaptor()->truncate(0);
  202. getDownloadEngine()->addCommand
  203. (createHttpDownloadCommand
  204. (httpResponse,
  205. getTransferEncodingStreamFilter
  206. (httpResponse,
  207. getContentEncodingStreamFilter(httpResponse))));
  208. } else {
  209. getDownloadEngine()->addCommand
  210. (createHttpDownloadCommand
  211. (httpResponse,
  212. getTransferEncodingStreamFilter(httpResponse)));
  213. }
  214. return true;
  215. }
  216. }
  217. void HttpResponseCommand::updateLastModifiedTime(const Time& lastModified)
  218. {
  219. if(getOption()->getAsBool(PREF_REMOTE_TIME)) {
  220. getRequestGroup()->updateLastModifiedTime(lastModified);
  221. }
  222. }
  223. bool HttpResponseCommand::shouldInflateContentEncoding
  224. (const SharedHandle<HttpResponse>& httpResponse)
  225. {
  226. // Basically, on the fly inflation cannot be made with segment
  227. // download, because in each segment we don't know where the date
  228. // should be written. So turn off segmented downloading.
  229. // Meanwhile, Some server returns content-encoding: gzip for .tgz
  230. // files. I think those files should not be inflated by clients,
  231. // because it is the original format of those files. Current
  232. // implementation just inflates these files nonetheless.
  233. const std::string& ce = httpResponse->getContentEncoding();
  234. return httpResponse->getHttpRequest()->acceptGZip() &&
  235. (ce == "gzip" || ce == "deflate");
  236. }
  237. bool HttpResponseCommand::handleDefaultEncoding
  238. (const SharedHandle<HttpResponse>& httpResponse)
  239. {
  240. SharedHandle<HttpRequest> httpRequest = httpResponse->getHttpRequest();
  241. getRequestGroup()->adjustFilename
  242. (SharedHandle<BtProgressInfoFile>(new DefaultBtProgressInfoFile
  243. (getDownloadContext(),
  244. SharedHandle<PieceStorage>(),
  245. getOption().get())));
  246. getRequestGroup()->initPieceStorage();
  247. if(getOption()->getAsBool(PREF_DRY_RUN)) {
  248. onDryRunFileFound();
  249. return true;
  250. }
  251. BtProgressInfoFileHandle infoFile
  252. (new DefaultBtProgressInfoFile(getDownloadContext(),
  253. getPieceStorage(),
  254. getOption().get()));
  255. if(!infoFile->exists() && getRequestGroup()->downloadFinishedByFileLength()) {
  256. getPieceStorage()->markAllPiecesDone();
  257. // TODO It would be good to issue ChecksumCheckIntegrity here
  258. // instead of just pretending checksum verification is done.
  259. getDownloadContext()->setChecksumVerified(true);
  260. getLogger()->notice(MSG_DOWNLOAD_ALREADY_COMPLETED,
  261. util::itos(getRequestGroup()->getGID()).c_str(),
  262. getRequestGroup()->getFirstFilePath().c_str());
  263. return true;
  264. }
  265. getRequestGroup()->loadAndOpenFile(infoFile);
  266. File file(getRequestGroup()->getFirstFilePath());
  267. // We have to make sure that command that has Request object must
  268. // have segment after PieceStorage is initialized. See
  269. // AbstractCommand::execute()
  270. SharedHandle<Segment> segment =
  271. getSegmentMan()->getSegmentWithIndex(getCuid(), 0);
  272. // pipelining requires implicit range specified. But the request for
  273. // this response most likely dones't contains range header. This means
  274. // we can't continue to use this socket because server sends all entity
  275. // body instead of a segment.
  276. // Therefore, we shutdown the socket here if pipelining is enabled.
  277. DownloadCommand* command = 0;
  278. if(getRequest()->getMethod() == Request::METHOD_GET &&
  279. !segment.isNull() && segment->getPositionToWrite() == 0 &&
  280. !getRequest()->isPipeliningEnabled()) {
  281. command = createHttpDownloadCommand
  282. (httpResponse,
  283. getTransferEncodingStreamFilter(httpResponse));
  284. } else {
  285. getSegmentMan()->cancelSegment(getCuid());
  286. getFileEntry()->poolRequest(getRequest());
  287. }
  288. // After command is passed to prepareForNextAction(), it is managed
  289. // by CheckIntegrityEntry.
  290. prepareForNextAction(command);
  291. command = 0;
  292. if(getRequest()->getMethod() == Request::METHOD_HEAD) {
  293. poolConnection();
  294. getRequest()->setMethod(Request::METHOD_GET);
  295. }
  296. return true;
  297. }
  298. static SharedHandle<StreamFilter> getTransferEncodingStreamFilter
  299. (const SharedHandle<HttpResponse>& httpResponse,
  300. const SharedHandle<StreamFilter>& delegate)
  301. {
  302. SharedHandle<StreamFilter> filter;
  303. if(httpResponse->isTransferEncodingSpecified()) {
  304. filter = httpResponse->getTransferEncodingStreamFilter();
  305. if(filter.isNull()) {
  306. throw DL_ABORT_EX
  307. (StringFormat(EX_TRANSFER_ENCODING_NOT_SUPPORTED,
  308. httpResponse->getTransferEncoding().c_str()).str());
  309. }
  310. filter->init();
  311. filter->installDelegate(delegate);
  312. }
  313. if(filter.isNull()) {
  314. filter = delegate;
  315. }
  316. return filter;
  317. }
  318. static SharedHandle<StreamFilter> getContentEncodingStreamFilter
  319. (const SharedHandle<HttpResponse>& httpResponse,
  320. const SharedHandle<StreamFilter>& delegate)
  321. {
  322. SharedHandle<StreamFilter> filter;
  323. if(httpResponse->isContentEncodingSpecified()) {
  324. filter = httpResponse->getContentEncodingStreamFilter();
  325. if(filter.isNull()) {
  326. LogFactory::getInstance()->info
  327. ("Content-Encoding %s is specified, but the current implementation"
  328. "doesn't support it. The decoding process is skipped and the"
  329. "downloaded content will be still encoded.",
  330. httpResponse->getContentEncoding().c_str());
  331. } else {
  332. filter->init();
  333. filter->installDelegate(delegate);
  334. }
  335. }
  336. if(filter.isNull()) {
  337. filter = delegate;
  338. }
  339. return filter;
  340. }
  341. bool HttpResponseCommand::handleOtherEncoding
  342. (const SharedHandle<HttpResponse>& httpResponse) {
  343. // We assume that RequestGroup::getTotalLength() == 0 here
  344. SharedHandle<HttpRequest> httpRequest = httpResponse->getHttpRequest();
  345. if(getOption()->getAsBool(PREF_DRY_RUN)) {
  346. getRequestGroup()->initPieceStorage();
  347. onDryRunFileFound();
  348. return true;
  349. }
  350. if(getRequest()->getMethod() == Request::METHOD_HEAD) {
  351. poolConnection();
  352. getRequest()->setMethod(Request::METHOD_GET);
  353. return prepareForRetry(0);
  354. }
  355. // For zero-length file, check existing file comparing its size
  356. if(getRequestGroup()->downloadFinishedByFileLength()) {
  357. getRequestGroup()->initPieceStorage();
  358. getPieceStorage()->markAllPiecesDone();
  359. // TODO It would be good to issue ChecksumCheckIntegrity here
  360. // instead of just pretending checksum verification is done.
  361. getDownloadContext()->setChecksumVerified(true);
  362. getLogger()->notice(MSG_DOWNLOAD_ALREADY_COMPLETED,
  363. util::itos(getRequestGroup()->getGID()).c_str(),
  364. getRequestGroup()->getFirstFilePath().c_str());
  365. poolConnection();
  366. return true;
  367. }
  368. getRequestGroup()->shouldCancelDownloadForSafety();
  369. getRequestGroup()->initPieceStorage();
  370. getPieceStorage()->getDiskAdaptor()->initAndOpenFile();
  371. SharedHandle<StreamFilter> streamFilter =
  372. getTransferEncodingStreamFilter
  373. (httpResponse,
  374. getContentEncodingStreamFilter(httpResponse));
  375. // In this context, knowsTotalLength() is true only when the file is
  376. // really zero-length.
  377. if(getDownloadContext()->knowsTotalLength() &&
  378. (streamFilter.isNull() ||
  379. streamFilter->getName() != ChunkedDecodingStreamFilter::NAME)) {
  380. // If chunked transfer-encoding is specified, we have to read end
  381. // of chunk markers(0\r\n\r\n, for example), so cannot pool
  382. // connection here.
  383. poolConnection();
  384. return true;
  385. }
  386. // We have to make sure that command that has Request object must
  387. // have segment after PieceStorage is initialized. See
  388. // AbstractCommand::execute()
  389. getSegmentMan()->getSegmentWithIndex(getCuid(), 0);
  390. getDownloadEngine()->addCommand
  391. (createHttpDownloadCommand(httpResponse, streamFilter));
  392. return true;
  393. }
  394. bool HttpResponseCommand::skipResponseBody
  395. (const SharedHandle<HttpResponse>& httpResponse)
  396. {
  397. SharedHandle<StreamFilter> filter =
  398. getTransferEncodingStreamFilter(httpResponse);
  399. // We don't use Content-Encoding here because this response body is just
  400. // thrown away.
  401. HttpSkipResponseCommand* command = new HttpSkipResponseCommand
  402. (getCuid(), getRequest(), getFileEntry(), getRequestGroup(),
  403. httpConnection_, httpResponse,
  404. getDownloadEngine(), getSocket());
  405. command->installStreamFilter(filter);
  406. // If request method is HEAD or the response body is zero-length,
  407. // set command's status to real time so that avoid read check blocking
  408. if(getRequest()->getMethod() == Request::METHOD_HEAD ||
  409. (httpResponse->getEntityLength() == 0 &&
  410. !httpResponse->isTransferEncodingSpecified())) {
  411. command->setStatusRealtime();
  412. // If entity length == 0, then socket read/write check must be disabled.
  413. command->disableSocketCheck();
  414. getDownloadEngine()->setNoWait(true);
  415. }
  416. getDownloadEngine()->addCommand(command);
  417. return true;
  418. }
  419. static bool decideFileAllocation
  420. (const SharedHandle<StreamFilter>& filter)
  421. {
  422. for(SharedHandle<StreamFilter> f = filter; !f.isNull(); f = f->getDelegate()){
  423. // Since the compressed file's length are returned in the response header
  424. // and the decompressed file size is unknown at this point, disable file
  425. // allocation here.
  426. if(f->getName() == GZipDecodingStreamFilter::NAME) {
  427. return false;
  428. }
  429. }
  430. return true;
  431. }
  432. HttpDownloadCommand* HttpResponseCommand::createHttpDownloadCommand
  433. (const SharedHandle<HttpResponse>& httpResponse,
  434. const SharedHandle<StreamFilter>& filter)
  435. {
  436. HttpDownloadCommand* command =
  437. new HttpDownloadCommand(getCuid(), getRequest(), getFileEntry(),
  438. getRequestGroup(),
  439. httpResponse, httpConnection_,
  440. getDownloadEngine(), getSocket());
  441. command->setStartupIdleTime(getOption()->getAsInt(PREF_STARTUP_IDLE_TIME));
  442. command->setLowestDownloadSpeedLimit
  443. (getOption()->getAsInt(PREF_LOWEST_SPEED_LIMIT));
  444. command->installStreamFilter(filter);
  445. getRequestGroup()->setFileAllocationEnabled(decideFileAllocation(filter));
  446. getRequestGroup()->getURISelector()->tuneDownloadCommand
  447. (getFileEntry()->getRemainingUris(), command);
  448. return command;
  449. }
  450. void HttpResponseCommand::poolConnection()
  451. {
  452. if(getRequest()->supportsPersistentConnection()) {
  453. getDownloadEngine()->poolSocket(getRequest(), createProxyRequest(),
  454. getSocket());
  455. }
  456. }
  457. void HttpResponseCommand::onDryRunFileFound()
  458. {
  459. getPieceStorage()->markAllPiecesDone();
  460. poolConnection();
  461. }
  462. } // namespace aria2