HttpResponseCommand.cc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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 "uri.h"
  76. #ifdef HAVE_LIBZ
  77. # include "GZipDecodingStreamFilter.h"
  78. #endif // HAVE_LIBZ
  79. namespace aria2 {
  80. static SharedHandle<StreamFilter> getTransferEncodingStreamFilter
  81. (const SharedHandle<HttpResponse>& httpResponse,
  82. const SharedHandle<StreamFilter>& delegate = SharedHandle<StreamFilter>());
  83. static SharedHandle<StreamFilter> getContentEncodingStreamFilter
  84. (const SharedHandle<HttpResponse>& httpResponse,
  85. const SharedHandle<StreamFilter>& delegate = SharedHandle<StreamFilter>());
  86. HttpResponseCommand::HttpResponseCommand
  87. (cuid_t cuid,
  88. const SharedHandle<Request>& req,
  89. const SharedHandle<FileEntry>& fileEntry,
  90. RequestGroup* requestGroup,
  91. const HttpConnectionHandle& httpConnection,
  92. DownloadEngine* e,
  93. const SocketHandle& s)
  94. :AbstractCommand(cuid, req, fileEntry, requestGroup, e, s),
  95. httpConnection_(httpConnection)
  96. {}
  97. HttpResponseCommand::~HttpResponseCommand() {}
  98. bool HttpResponseCommand::executeInternal()
  99. {
  100. SharedHandle<HttpRequest> httpRequest =httpConnection_->getFirstHttpRequest();
  101. SharedHandle<HttpResponse> httpResponse = httpConnection_->receiveResponse();
  102. if(httpResponse.isNull()) {
  103. // The server has not responded to our request yet.
  104. // For socket->wantRead() == true, setReadCheckSocket(socket) is already
  105. // done in the constructor.
  106. setWriteCheckSocketIf(getSocket(), getSocket()->wantWrite());
  107. getDownloadEngine()->addCommand(this);
  108. return false;
  109. }
  110. // check HTTP status number
  111. httpResponse->validateResponse();
  112. httpResponse->retrieveCookie();
  113. SharedHandle<HttpHeader> httpHeader = httpResponse->getHttpHeader();
  114. // Disable persistent connection if:
  115. // Connection: close is received or the remote server is not HTTP/1.1.
  116. // We don't care whether non-HTTP/1.1 server returns Connection: keep-alive.
  117. getRequest()->supportsPersistentConnection
  118. (httpResponse->supportsPersistentConnection());
  119. if(getRequest()->isPipeliningEnabled()) {
  120. getRequest()->setMaxPipelinedRequest
  121. (getOption()->getAsInt(PREF_MAX_HTTP_PIPELINING));
  122. }
  123. if(!httpResponse->getHttpRequest()->getIfModifiedSinceHeader().empty()) {
  124. if(httpResponse->getResponseStatus() == HttpHeader::S304) {
  125. uint64_t totalLength = httpResponse->getEntityLength();
  126. getFileEntry()->setLength(totalLength);
  127. getRequestGroup()->initPieceStorage();
  128. getPieceStorage()->markAllPiecesDone();
  129. // Just set checksum verification done.
  130. getDownloadContext()->setChecksumVerified(true);
  131. getLogger()->notice(MSG_DOWNLOAD_ALREADY_COMPLETED,
  132. util::itos(getRequestGroup()->getGID()).c_str(),
  133. getRequestGroup()->getFirstFilePath().c_str());
  134. poolConnection();
  135. getFileEntry()->poolRequest(getRequest());
  136. return true;
  137. } else if(httpResponse->getResponseStatus() == HttpHeader::S200 ||
  138. httpResponse->getResponseStatus() == HttpHeader::S206) {
  139. // Remote file is newer than local file. We allow overwrite.
  140. getOption()->put(PREF_ALLOW_OVERWRITE, A2_V_TRUE);
  141. }
  142. }
  143. if(httpResponse->getResponseStatus() >= HttpHeader::S300 &&
  144. httpResponse->getResponseStatus() != HttpHeader::S304) {
  145. if(httpResponse->getResponseStatus() == HttpHeader::S404) {
  146. getRequestGroup()->increaseAndValidateFileNotFoundCount();
  147. }
  148. return skipResponseBody(httpResponse);
  149. }
  150. if(getFileEntry()->isUniqueProtocol()) {
  151. // Redirection should be considered here. We need to parse
  152. // original URI to get hostname.
  153. uri::UriStruct us;
  154. if(uri::parse(us, getRequest()->getUri())) {
  155. getFileEntry()->removeURIWhoseHostnameIs(us.host);
  156. }
  157. }
  158. if(getPieceStorage().isNull()) {
  159. uint64_t totalLength = httpResponse->getEntityLength();
  160. getFileEntry()->setLength(totalLength);
  161. if(getFileEntry()->getPath().empty()) {
  162. getFileEntry()->setPath
  163. (util::applyDir
  164. (getDownloadContext()->getDir(),
  165. util::fixTaintedBasename(httpResponse->determinFilename())));
  166. }
  167. getFileEntry()->setContentType(httpResponse->getContentType());
  168. getRequestGroup()->preDownloadProcessing();
  169. if(getDownloadEngine()->getRequestGroupMan()->
  170. isSameFileBeingDownloaded(getRequestGroup())) {
  171. throw DOWNLOAD_FAILURE_EXCEPTION
  172. (StringFormat(EX_DUPLICATE_FILE_DOWNLOAD,
  173. getRequestGroup()->getFirstFilePath().c_str()).str());
  174. }
  175. // update last modified time
  176. updateLastModifiedTime(httpResponse->getLastModifiedTime());
  177. // If both transfer-encoding and total length is specified, we
  178. // assume we can do segmented downloading
  179. if(totalLength == 0 || shouldInflateContentEncoding(httpResponse)) {
  180. // we ignore content-length when inflate is required
  181. getFileEntry()->setLength(0);
  182. if(getRequest()->getMethod() == Request::METHOD_GET &&
  183. (totalLength != 0 ||
  184. !httpResponse->getHttpHeader()->defined(HttpHeader::CONTENT_LENGTH))){
  185. // DownloadContext::knowsTotalLength() == true only when
  186. // server says the size of file is 0 explicitly.
  187. getDownloadContext()->markTotalLengthIsUnknown();
  188. }
  189. return handleOtherEncoding(httpResponse);
  190. } else {
  191. return handleDefaultEncoding(httpResponse);
  192. }
  193. } else {
  194. // validate totalsize
  195. getRequestGroup()->validateTotalLength(getFileEntry()->getLength(),
  196. httpResponse->getEntityLength());
  197. // update last modified time
  198. updateLastModifiedTime(httpResponse->getLastModifiedTime());
  199. if(getRequestGroup()->getTotalLength() == 0) {
  200. // Since total length is unknown, the file size in previously
  201. // failed download could be larger than the size this time.
  202. // Also we can't resume in this case too. So truncate the file
  203. // anyway.
  204. getPieceStorage()->getDiskAdaptor()->truncate(0);
  205. getDownloadEngine()->addCommand
  206. (createHttpDownloadCommand
  207. (httpResponse,
  208. getTransferEncodingStreamFilter
  209. (httpResponse,
  210. getContentEncodingStreamFilter(httpResponse))));
  211. } else {
  212. getDownloadEngine()->addCommand
  213. (createHttpDownloadCommand
  214. (httpResponse,
  215. getTransferEncodingStreamFilter(httpResponse)));
  216. }
  217. return true;
  218. }
  219. }
  220. void HttpResponseCommand::updateLastModifiedTime(const Time& lastModified)
  221. {
  222. if(getOption()->getAsBool(PREF_REMOTE_TIME)) {
  223. getRequestGroup()->updateLastModifiedTime(lastModified);
  224. }
  225. }
  226. bool HttpResponseCommand::shouldInflateContentEncoding
  227. (const SharedHandle<HttpResponse>& httpResponse)
  228. {
  229. // Basically, on the fly inflation cannot be made with segment
  230. // download, because in each segment we don't know where the date
  231. // should be written. So turn off segmented downloading.
  232. // Meanwhile, Some server returns content-encoding: gzip for .tgz
  233. // files. I think those files should not be inflated by clients,
  234. // because it is the original format of those files. Current
  235. // implementation just inflates these files nonetheless.
  236. const std::string& ce = httpResponse->getContentEncoding();
  237. return httpResponse->getHttpRequest()->acceptGZip() &&
  238. (ce == "gzip" || ce == "deflate");
  239. }
  240. bool HttpResponseCommand::handleDefaultEncoding
  241. (const SharedHandle<HttpResponse>& httpResponse)
  242. {
  243. SharedHandle<HttpRequest> httpRequest = httpResponse->getHttpRequest();
  244. getRequestGroup()->adjustFilename
  245. (SharedHandle<BtProgressInfoFile>(new DefaultBtProgressInfoFile
  246. (getDownloadContext(),
  247. SharedHandle<PieceStorage>(),
  248. getOption().get())));
  249. getRequestGroup()->initPieceStorage();
  250. if(getOption()->getAsBool(PREF_DRY_RUN)) {
  251. onDryRunFileFound();
  252. return true;
  253. }
  254. SharedHandle<CheckIntegrityEntry> checkEntry =
  255. getRequestGroup()->createCheckIntegrityEntry();
  256. if(checkEntry.isNull()) {
  257. return true;
  258. }
  259. File file(getRequestGroup()->getFirstFilePath());
  260. // We have to make sure that command that has Request object must
  261. // have segment after PieceStorage is initialized. See
  262. // AbstractCommand::execute()
  263. SharedHandle<Segment> segment =
  264. getSegmentMan()->getSegmentWithIndex(getCuid(), 0);
  265. // pipelining requires implicit range specified. But the request for
  266. // this response most likely dones't contains range header. This means
  267. // we can't continue to use this socket because server sends all entity
  268. // body instead of a segment.
  269. // Therefore, we shutdown the socket here if pipelining is enabled.
  270. DownloadCommand* command = 0;
  271. if(getRequest()->getMethod() == Request::METHOD_GET &&
  272. !segment.isNull() && segment->getPositionToWrite() == 0 &&
  273. !getRequest()->isPipeliningEnabled()) {
  274. command = createHttpDownloadCommand
  275. (httpResponse,
  276. getTransferEncodingStreamFilter(httpResponse));
  277. } else {
  278. getSegmentMan()->cancelSegment(getCuid());
  279. getFileEntry()->poolRequest(getRequest());
  280. }
  281. // After command is passed to prepareForNextAction(), it is managed
  282. // by CheckIntegrityEntry.
  283. checkEntry->pushNextCommand(command);
  284. command = 0;
  285. prepareForNextAction(checkEntry);
  286. if(getRequest()->getMethod() == Request::METHOD_HEAD) {
  287. poolConnection();
  288. getRequest()->setMethod(Request::METHOD_GET);
  289. }
  290. return true;
  291. }
  292. static SharedHandle<StreamFilter> getTransferEncodingStreamFilter
  293. (const SharedHandle<HttpResponse>& httpResponse,
  294. const SharedHandle<StreamFilter>& delegate)
  295. {
  296. SharedHandle<StreamFilter> filter;
  297. if(httpResponse->isTransferEncodingSpecified()) {
  298. filter = httpResponse->getTransferEncodingStreamFilter();
  299. if(filter.isNull()) {
  300. throw DL_ABORT_EX
  301. (StringFormat(EX_TRANSFER_ENCODING_NOT_SUPPORTED,
  302. httpResponse->getTransferEncoding().c_str()).str());
  303. }
  304. filter->init();
  305. filter->installDelegate(delegate);
  306. }
  307. if(filter.isNull()) {
  308. filter = delegate;
  309. }
  310. return filter;
  311. }
  312. static SharedHandle<StreamFilter> getContentEncodingStreamFilter
  313. (const SharedHandle<HttpResponse>& httpResponse,
  314. const SharedHandle<StreamFilter>& delegate)
  315. {
  316. SharedHandle<StreamFilter> filter;
  317. if(httpResponse->isContentEncodingSpecified()) {
  318. filter = httpResponse->getContentEncodingStreamFilter();
  319. if(filter.isNull()) {
  320. LogFactory::getInstance()->info
  321. ("Content-Encoding %s is specified, but the current implementation"
  322. "doesn't support it. The decoding process is skipped and the"
  323. "downloaded content will be still encoded.",
  324. httpResponse->getContentEncoding().c_str());
  325. } else {
  326. filter->init();
  327. filter->installDelegate(delegate);
  328. }
  329. }
  330. if(filter.isNull()) {
  331. filter = delegate;
  332. }
  333. return filter;
  334. }
  335. bool HttpResponseCommand::handleOtherEncoding
  336. (const SharedHandle<HttpResponse>& httpResponse) {
  337. // We assume that RequestGroup::getTotalLength() == 0 here
  338. SharedHandle<HttpRequest> httpRequest = httpResponse->getHttpRequest();
  339. if(getOption()->getAsBool(PREF_DRY_RUN)) {
  340. getRequestGroup()->initPieceStorage();
  341. onDryRunFileFound();
  342. return true;
  343. }
  344. if(getRequest()->getMethod() == Request::METHOD_HEAD) {
  345. poolConnection();
  346. getRequest()->setMethod(Request::METHOD_GET);
  347. return prepareForRetry(0);
  348. }
  349. // In this context, knowsTotalLength() is true only when the file is
  350. // really zero-length.
  351. SharedHandle<StreamFilter> streamFilter =
  352. getTransferEncodingStreamFilter
  353. (httpResponse,
  354. getContentEncodingStreamFilter(httpResponse));
  355. // If chunked transfer-encoding is specified, we have to read end of
  356. // chunk markers(0\r\n\r\n, for example).
  357. bool chunkedUsed = !streamFilter.isNull() &&
  358. streamFilter->getName() == ChunkedDecodingStreamFilter::NAME;
  359. // For zero-length file, check existing file comparing its size
  360. if(!chunkedUsed && getDownloadContext()->knowsTotalLength() &&
  361. getRequestGroup()->downloadFinishedByFileLength()) {
  362. // TODO If metalink file does not contain size and it contains
  363. // hash and file is not zero length, but remote server says the
  364. // file size is 0, no hash check is performed in the current
  365. // implementation. See also
  366. // FtpNegotiationCommand::onFileSizeDetermined()
  367. getRequestGroup()->initPieceStorage();
  368. getPieceStorage()->markAllPiecesDone();
  369. getDownloadContext()->setChecksumVerified(true);
  370. getLogger()->notice(MSG_DOWNLOAD_ALREADY_COMPLETED,
  371. util::itos(getRequestGroup()->getGID()).c_str(),
  372. getRequestGroup()->getFirstFilePath().c_str());
  373. poolConnection();
  374. return true;
  375. }
  376. getRequestGroup()->shouldCancelDownloadForSafety();
  377. getRequestGroup()->initPieceStorage();
  378. getPieceStorage()->getDiskAdaptor()->initAndOpenFile();
  379. // Local file size becomes zero when DiskAdaptor::initAndOpenFile()
  380. // is called. So zero-length file is complete if chunked encoding is
  381. // not used.
  382. if(!chunkedUsed && getDownloadContext()->knowsTotalLength()) {
  383. getRequestGroup()->getPieceStorage()->markAllPiecesDone();
  384. poolConnection();
  385. return true;
  386. }
  387. // We have to make sure that command that has Request object must
  388. // have segment after PieceStorage is initialized. See
  389. // AbstractCommand::execute()
  390. getSegmentMan()->getSegmentWithIndex(getCuid(), 0);
  391. getDownloadEngine()->addCommand
  392. (createHttpDownloadCommand(httpResponse, streamFilter));
  393. return true;
  394. }
  395. bool HttpResponseCommand::skipResponseBody
  396. (const SharedHandle<HttpResponse>& httpResponse)
  397. {
  398. SharedHandle<StreamFilter> filter =
  399. getTransferEncodingStreamFilter(httpResponse);
  400. // We don't use Content-Encoding here because this response body is just
  401. // thrown away.
  402. HttpSkipResponseCommand* command = new HttpSkipResponseCommand
  403. (getCuid(), getRequest(), getFileEntry(), getRequestGroup(),
  404. httpConnection_, httpResponse,
  405. getDownloadEngine(), getSocket());
  406. command->installStreamFilter(filter);
  407. // If request method is HEAD or the response body is zero-length,
  408. // set command's status to real time so that avoid read check blocking
  409. if(getRequest()->getMethod() == Request::METHOD_HEAD ||
  410. (httpResponse->getEntityLength() == 0 &&
  411. !httpResponse->isTransferEncodingSpecified())) {
  412. command->setStatusRealtime();
  413. // If entity length == 0, then socket read/write check must be disabled.
  414. command->disableSocketCheck();
  415. getDownloadEngine()->setNoWait(true);
  416. }
  417. getDownloadEngine()->addCommand(command);
  418. return true;
  419. }
  420. static bool decideFileAllocation
  421. (const SharedHandle<StreamFilter>& filter)
  422. {
  423. #ifdef HAVE_LIBZ
  424. for(SharedHandle<StreamFilter> f = filter; !f.isNull(); f = f->getDelegate()){
  425. // Since the compressed file's length are returned in the response header
  426. // and the decompressed file size is unknown at this point, disable file
  427. // allocation here.
  428. if(f->getName() == GZipDecodingStreamFilter::NAME) {
  429. return false;
  430. }
  431. }
  432. #endif // HAVE_LIBZ
  433. return true;
  434. }
  435. HttpDownloadCommand* HttpResponseCommand::createHttpDownloadCommand
  436. (const SharedHandle<HttpResponse>& httpResponse,
  437. const SharedHandle<StreamFilter>& filter)
  438. {
  439. HttpDownloadCommand* command =
  440. new HttpDownloadCommand(getCuid(), getRequest(), getFileEntry(),
  441. getRequestGroup(),
  442. httpResponse, httpConnection_,
  443. getDownloadEngine(), getSocket());
  444. command->setStartupIdleTime(getOption()->getAsInt(PREF_STARTUP_IDLE_TIME));
  445. command->setLowestDownloadSpeedLimit
  446. (getOption()->getAsInt(PREF_LOWEST_SPEED_LIMIT));
  447. command->installStreamFilter(filter);
  448. getRequestGroup()->setFileAllocationEnabled(decideFileAllocation(filter));
  449. getRequestGroup()->getURISelector()->tuneDownloadCommand
  450. (getFileEntry()->getRemainingUris(), command);
  451. return command;
  452. }
  453. void HttpResponseCommand::poolConnection()
  454. {
  455. if(getRequest()->supportsPersistentConnection()) {
  456. getDownloadEngine()->poolSocket(getRequest(), createProxyRequest(),
  457. getSocket());
  458. }
  459. }
  460. void HttpResponseCommand::onDryRunFileFound()
  461. {
  462. getPieceStorage()->markAllPiecesDone();
  463. getDownloadContext()->setChecksumVerified(true);
  464. poolConnection();
  465. }
  466. } // namespace aria2