HttpResponseCommand.cc 18 KB

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