HttpResponseCommand.cc 18 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. // Just set checksum verification done.
  127. getDownloadContext()->setChecksumVerified(true);
  128. getLogger()->notice(MSG_DOWNLOAD_ALREADY_COMPLETED,
  129. util::itos(getRequestGroup()->getGID()).c_str(),
  130. getRequestGroup()->getFirstFilePath().c_str());
  131. poolConnection();
  132. getFileEntry()->poolRequest(getRequest());
  133. return true;
  134. } else if(httpResponse->getResponseStatus() == HttpHeader::S200 ||
  135. httpResponse->getResponseStatus() == HttpHeader::S206) {
  136. // Remote file is newer than local file. We allow overwrite.
  137. getOption()->put(PREF_ALLOW_OVERWRITE, V_TRUE);
  138. }
  139. }
  140. if(httpResponse->getResponseStatus() >= HttpHeader::S300 &&
  141. httpResponse->getResponseStatus() != HttpHeader::S304) {
  142. if(httpResponse->getResponseStatus() == HttpHeader::S404) {
  143. getRequestGroup()->increaseAndValidateFileNotFoundCount();
  144. }
  145. return skipResponseBody(httpResponse);
  146. }
  147. if(getFileEntry()->isUniqueProtocol()) {
  148. // Redirection should be considered here. We need to parse
  149. // original URI to get hostname.
  150. Request req;
  151. req.setUri(getRequest()->getUri());
  152. getFileEntry()->removeURIWhoseHostnameIs(req.getHost());
  153. }
  154. if(getPieceStorage().isNull()) {
  155. uint64_t totalLength = httpResponse->getEntityLength();
  156. getFileEntry()->setLength(totalLength);
  157. if(getFileEntry()->getPath().empty()) {
  158. getFileEntry()->setPath
  159. (util::applyDir
  160. (getDownloadContext()->getDir(),
  161. util::fixTaintedBasename(httpResponse->determinFilename())));
  162. }
  163. getFileEntry()->setContentType(httpResponse->getContentType());
  164. getRequestGroup()->preDownloadProcessing();
  165. if(getDownloadEngine()->getRequestGroupMan()->
  166. isSameFileBeingDownloaded(getRequestGroup())) {
  167. throw DOWNLOAD_FAILURE_EXCEPTION
  168. (StringFormat(EX_DUPLICATE_FILE_DOWNLOAD,
  169. getRequestGroup()->getFirstFilePath().c_str()).str());
  170. }
  171. // update last modified time
  172. updateLastModifiedTime(httpResponse->getLastModifiedTime());
  173. // If both transfer-encoding and total length is specified, we
  174. // assume we can do segmented downloading
  175. if(totalLength == 0 || shouldInflateContentEncoding(httpResponse)) {
  176. // we ignore content-length when inflate is required
  177. getFileEntry()->setLength(0);
  178. if(getRequest()->getMethod() == Request::METHOD_GET &&
  179. (totalLength != 0 ||
  180. !httpResponse->getHttpHeader()->defined(HttpHeader::CONTENT_LENGTH))){
  181. // DownloadContext::knowsTotalLength() == true only when
  182. // server says the size of file is 0 explicitly.
  183. getDownloadContext()->markTotalLengthIsUnknown();
  184. }
  185. return handleOtherEncoding(httpResponse);
  186. } else {
  187. return handleDefaultEncoding(httpResponse);
  188. }
  189. } else {
  190. // validate totalsize
  191. getRequestGroup()->validateTotalLength(getFileEntry()->getLength(),
  192. httpResponse->getEntityLength());
  193. // update last modified time
  194. updateLastModifiedTime(httpResponse->getLastModifiedTime());
  195. if(getRequestGroup()->getTotalLength() == 0) {
  196. // Since total length is unknown, the file size in previously
  197. // failed download could be larger than the size this time.
  198. // Also we can't resume in this case too. So truncate the file
  199. // anyway.
  200. getPieceStorage()->getDiskAdaptor()->truncate(0);
  201. getDownloadEngine()->addCommand
  202. (createHttpDownloadCommand
  203. (httpResponse,
  204. getTransferEncodingStreamFilter
  205. (httpResponse,
  206. getContentEncodingStreamFilter(httpResponse))));
  207. } else {
  208. getDownloadEngine()->addCommand
  209. (createHttpDownloadCommand
  210. (httpResponse,
  211. getTransferEncodingStreamFilter(httpResponse)));
  212. }
  213. return true;
  214. }
  215. }
  216. void HttpResponseCommand::updateLastModifiedTime(const Time& lastModified)
  217. {
  218. if(getOption()->getAsBool(PREF_REMOTE_TIME)) {
  219. getRequestGroup()->updateLastModifiedTime(lastModified);
  220. }
  221. }
  222. bool HttpResponseCommand::shouldInflateContentEncoding
  223. (const SharedHandle<HttpResponse>& httpResponse)
  224. {
  225. // Basically, on the fly inflation cannot be made with segment
  226. // download, because in each segment we don't know where the date
  227. // should be written. So turn off segmented downloading.
  228. // Meanwhile, Some server returns content-encoding: gzip for .tgz
  229. // files. I think those files should not be inflated by clients,
  230. // because it is the original format of those files. Current
  231. // implementation just inflates these files nonetheless.
  232. const std::string& ce = httpResponse->getContentEncoding();
  233. return httpResponse->getHttpRequest()->acceptGZip() &&
  234. (ce == "gzip" || ce == "deflate");
  235. }
  236. bool HttpResponseCommand::handleDefaultEncoding
  237. (const SharedHandle<HttpResponse>& httpResponse)
  238. {
  239. SharedHandle<HttpRequest> httpRequest = httpResponse->getHttpRequest();
  240. getRequestGroup()->adjustFilename
  241. (SharedHandle<BtProgressInfoFile>(new DefaultBtProgressInfoFile
  242. (getDownloadContext(),
  243. SharedHandle<PieceStorage>(),
  244. getOption().get())));
  245. getRequestGroup()->initPieceStorage();
  246. if(getOption()->getAsBool(PREF_DRY_RUN)) {
  247. onDryRunFileFound();
  248. return true;
  249. }
  250. BtProgressInfoFileHandle infoFile
  251. (new DefaultBtProgressInfoFile(getDownloadContext(),
  252. getPieceStorage(),
  253. getOption().get()));
  254. if(!infoFile->exists() && getRequestGroup()->downloadFinishedByFileLength()) {
  255. getPieceStorage()->markAllPiecesDone();
  256. // See also RequestGroup::createInitialCommand()
  257. if(!getOption()->getAsBool(PREF_CHECK_INTEGRITY) ||
  258. !getDownloadContext()->isChecksumVerificationNeeded()) {
  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. }
  266. getRequestGroup()->loadAndOpenFile(infoFile);
  267. File file(getRequestGroup()->getFirstFilePath());
  268. // We have to make sure that command that has Request object must
  269. // have segment after PieceStorage is initialized. See
  270. // AbstractCommand::execute()
  271. SharedHandle<Segment> segment =
  272. getSegmentMan()->getSegmentWithIndex(getCuid(), 0);
  273. // pipelining requires implicit range specified. But the request for
  274. // this response most likely dones't contains range header. This means
  275. // we can't continue to use this socket because server sends all entity
  276. // body instead of a segment.
  277. // Therefore, we shutdown the socket here if pipelining is enabled.
  278. DownloadCommand* command = 0;
  279. if(getRequest()->getMethod() == Request::METHOD_GET &&
  280. !segment.isNull() && segment->getPositionToWrite() == 0 &&
  281. !getRequest()->isPipeliningEnabled()) {
  282. command = createHttpDownloadCommand
  283. (httpResponse,
  284. getTransferEncodingStreamFilter(httpResponse));
  285. } else {
  286. getSegmentMan()->cancelSegment(getCuid());
  287. getFileEntry()->poolRequest(getRequest());
  288. }
  289. // After command is passed to prepareForNextAction(), it is managed
  290. // by CheckIntegrityEntry.
  291. prepareForNextAction(command);
  292. command = 0;
  293. if(getRequest()->getMethod() == Request::METHOD_HEAD) {
  294. poolConnection();
  295. getRequest()->setMethod(Request::METHOD_GET);
  296. }
  297. return true;
  298. }
  299. static SharedHandle<StreamFilter> getTransferEncodingStreamFilter
  300. (const SharedHandle<HttpResponse>& httpResponse,
  301. const SharedHandle<StreamFilter>& delegate)
  302. {
  303. SharedHandle<StreamFilter> filter;
  304. if(httpResponse->isTransferEncodingSpecified()) {
  305. filter = httpResponse->getTransferEncodingStreamFilter();
  306. if(filter.isNull()) {
  307. throw DL_ABORT_EX
  308. (StringFormat(EX_TRANSFER_ENCODING_NOT_SUPPORTED,
  309. httpResponse->getTransferEncoding().c_str()).str());
  310. }
  311. filter->init();
  312. filter->installDelegate(delegate);
  313. }
  314. if(filter.isNull()) {
  315. filter = delegate;
  316. }
  317. return filter;
  318. }
  319. static SharedHandle<StreamFilter> getContentEncodingStreamFilter
  320. (const SharedHandle<HttpResponse>& httpResponse,
  321. const SharedHandle<StreamFilter>& delegate)
  322. {
  323. SharedHandle<StreamFilter> filter;
  324. if(httpResponse->isContentEncodingSpecified()) {
  325. filter = httpResponse->getContentEncodingStreamFilter();
  326. if(filter.isNull()) {
  327. LogFactory::getInstance()->info
  328. ("Content-Encoding %s is specified, but the current implementation"
  329. "doesn't support it. The decoding process is skipped and the"
  330. "downloaded content will be still encoded.",
  331. httpResponse->getContentEncoding().c_str());
  332. } else {
  333. filter->init();
  334. filter->installDelegate(delegate);
  335. }
  336. }
  337. if(filter.isNull()) {
  338. filter = delegate;
  339. }
  340. return filter;
  341. }
  342. bool HttpResponseCommand::handleOtherEncoding
  343. (const SharedHandle<HttpResponse>& httpResponse) {
  344. // We assume that RequestGroup::getTotalLength() == 0 here
  345. SharedHandle<HttpRequest> httpRequest = httpResponse->getHttpRequest();
  346. if(getOption()->getAsBool(PREF_DRY_RUN)) {
  347. getRequestGroup()->initPieceStorage();
  348. onDryRunFileFound();
  349. return true;
  350. }
  351. if(getRequest()->getMethod() == Request::METHOD_HEAD) {
  352. poolConnection();
  353. getRequest()->setMethod(Request::METHOD_GET);
  354. return prepareForRetry(0);
  355. }
  356. // For zero-length file, check existing file comparing its size
  357. if(getRequestGroup()->downloadFinishedByFileLength()) {
  358. getRequestGroup()->initPieceStorage();
  359. getPieceStorage()->markAllPiecesDone();
  360. // This is zero-size file, so hash check is no use.
  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