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