HttpResponseCommand.cc 18 KB

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