HttpResponseCommand.cc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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_EXCEPTION
  209. (fmt(EX_DUPLICATE_FILE_DOWNLOAD,
  210. getRequestGroup()->getFirstFilePath().c_str()));
  211. }
  212. // update last modified time
  213. updateLastModifiedTime(httpResponse->getLastModifiedTime());
  214. // If both transfer-encoding and total length is specified, we
  215. // assume we can do segmented downloading
  216. if(totalLength == 0 || shouldInflateContentEncoding(httpResponse)) {
  217. // we ignore content-length when inflate is required
  218. getFileEntry()->setLength(0);
  219. if(getRequest()->getMethod() == Request::METHOD_GET &&
  220. (totalLength != 0 ||
  221. !httpResponse->getHttpHeader()->defined(HttpHeader::CONTENT_LENGTH))){
  222. // DownloadContext::knowsTotalLength() == true only when
  223. // server says the size of file is 0 explicitly.
  224. getDownloadContext()->markTotalLengthIsUnknown();
  225. }
  226. return handleOtherEncoding(httpResponse);
  227. } else {
  228. return handleDefaultEncoding(httpResponse);
  229. }
  230. } else {
  231. // validate totalsize
  232. getRequestGroup()->validateTotalLength(getFileEntry()->getLength(),
  233. httpResponse->getEntityLength());
  234. // update last modified time
  235. updateLastModifiedTime(httpResponse->getLastModifiedTime());
  236. if(getRequestGroup()->getTotalLength() == 0) {
  237. // Since total length is unknown, the file size in previously
  238. // failed download could be larger than the size this time.
  239. // Also we can't resume in this case too. So truncate the file
  240. // anyway.
  241. getPieceStorage()->getDiskAdaptor()->truncate(0);
  242. getDownloadEngine()->addCommand
  243. (createHttpDownloadCommand
  244. (httpResponse,
  245. getTransferEncodingStreamFilter
  246. (httpResponse,
  247. getContentEncodingStreamFilter(httpResponse))));
  248. } else {
  249. getDownloadEngine()->addCommand
  250. (createHttpDownloadCommand
  251. (httpResponse,
  252. getTransferEncodingStreamFilter(httpResponse)));
  253. }
  254. return true;
  255. }
  256. }
  257. void HttpResponseCommand::updateLastModifiedTime(const Time& lastModified)
  258. {
  259. if(getOption()->getAsBool(PREF_REMOTE_TIME)) {
  260. getRequestGroup()->updateLastModifiedTime(lastModified);
  261. }
  262. }
  263. bool HttpResponseCommand::shouldInflateContentEncoding
  264. (const SharedHandle<HttpResponse>& httpResponse)
  265. {
  266. // Basically, on the fly inflation cannot be made with segment
  267. // download, because in each segment we don't know where the date
  268. // should be written. So turn off segmented downloading.
  269. // Meanwhile, Some server returns content-encoding: gzip for .tgz
  270. // files. I think those files should not be inflated by clients,
  271. // because it is the original format of those files. Current
  272. // implementation just inflates these files nonetheless.
  273. const std::string& ce = httpResponse->getContentEncoding();
  274. return httpResponse->getHttpRequest()->acceptGZip() &&
  275. (ce == "gzip" || ce == "deflate");
  276. }
  277. bool HttpResponseCommand::handleDefaultEncoding
  278. (const SharedHandle<HttpResponse>& httpResponse)
  279. {
  280. SharedHandle<HttpRequest> httpRequest = httpResponse->getHttpRequest();
  281. SharedHandle<BtProgressInfoFile> progressInfoFile
  282. (new DefaultBtProgressInfoFile
  283. (getDownloadContext(), SharedHandle<PieceStorage>(), getOption().get()));
  284. getRequestGroup()->adjustFilename(progressInfoFile);
  285. getRequestGroup()->initPieceStorage();
  286. if(getOption()->getAsBool(PREF_DRY_RUN)) {
  287. onDryRunFileFound();
  288. return true;
  289. }
  290. SharedHandle<CheckIntegrityEntry> checkEntry =
  291. getRequestGroup()->createCheckIntegrityEntry();
  292. if(!checkEntry) {
  293. return true;
  294. }
  295. File file(getRequestGroup()->getFirstFilePath());
  296. // We have to make sure that command that has Request object must
  297. // have segment after PieceStorage is initialized. See
  298. // AbstractCommand::execute()
  299. SharedHandle<Segment> segment =
  300. getSegmentMan()->getSegmentWithIndex(getCuid(), 0);
  301. // pipelining requires implicit range specified. But the request for
  302. // this response most likely dones't contains range header. This means
  303. // we can't continue to use this socket because server sends all entity
  304. // body instead of a segment.
  305. // Therefore, we shutdown the socket here if pipelining is enabled.
  306. DownloadCommand* command = 0;
  307. if(getRequest()->getMethod() == Request::METHOD_GET &&
  308. segment && segment->getPositionToWrite() == 0 &&
  309. !getRequest()->isPipeliningEnabled()) {
  310. command = createHttpDownloadCommand
  311. (httpResponse,
  312. getTransferEncodingStreamFilter(httpResponse));
  313. } else {
  314. getSegmentMan()->cancelSegment(getCuid());
  315. getFileEntry()->poolRequest(getRequest());
  316. }
  317. // After command is passed to prepareForNextAction(), it is managed
  318. // by CheckIntegrityEntry.
  319. checkEntry->pushNextCommand(command);
  320. command = 0;
  321. prepareForNextAction(checkEntry);
  322. if(getRequest()->getMethod() == Request::METHOD_HEAD) {
  323. poolConnection();
  324. getRequest()->setMethod(Request::METHOD_GET);
  325. }
  326. return true;
  327. }
  328. bool HttpResponseCommand::handleOtherEncoding
  329. (const SharedHandle<HttpResponse>& httpResponse) {
  330. // We assume that RequestGroup::getTotalLength() == 0 here
  331. SharedHandle<HttpRequest> httpRequest = httpResponse->getHttpRequest();
  332. if(getOption()->getAsBool(PREF_DRY_RUN)) {
  333. getRequestGroup()->initPieceStorage();
  334. onDryRunFileFound();
  335. return true;
  336. }
  337. if(getRequest()->getMethod() == Request::METHOD_HEAD) {
  338. poolConnection();
  339. getRequest()->setMethod(Request::METHOD_GET);
  340. return prepareForRetry(0);
  341. }
  342. // In this context, knowsTotalLength() is true only when the file is
  343. // really zero-length.
  344. SharedHandle<StreamFilter> streamFilter =
  345. getTransferEncodingStreamFilter
  346. (httpResponse,
  347. getContentEncodingStreamFilter(httpResponse));
  348. // If chunked transfer-encoding is specified, we have to read end of
  349. // chunk markers(0\r\n\r\n, for example).
  350. bool chunkedUsed = streamFilter &&
  351. streamFilter->getName() == ChunkedDecodingStreamFilter::NAME;
  352. // For zero-length file, check existing file comparing its size
  353. if(!chunkedUsed && getDownloadContext()->knowsTotalLength() &&
  354. getRequestGroup()->downloadFinishedByFileLength()) {
  355. // TODO If metalink file does not contain size and it contains
  356. // hash and file is not zero length, but remote server says the
  357. // file size is 0, no hash check is performed in the current
  358. // implementation. See also
  359. // FtpNegotiationCommand::onFileSizeDetermined()
  360. getRequestGroup()->initPieceStorage();
  361. getPieceStorage()->markAllPiecesDone();
  362. getDownloadContext()->setChecksumVerified(true);
  363. A2_LOG_NOTICE(fmt(MSG_DOWNLOAD_ALREADY_COMPLETED,
  364. util::itos(getRequestGroup()->getGID()).c_str(),
  365. getRequestGroup()->getFirstFilePath().c_str()));
  366. poolConnection();
  367. return true;
  368. }
  369. getRequestGroup()->shouldCancelDownloadForSafety();
  370. getRequestGroup()->initPieceStorage();
  371. getPieceStorage()->getDiskAdaptor()->initAndOpenFile();
  372. // Local file size becomes zero when DiskAdaptor::initAndOpenFile()
  373. // is called. So zero-length file is complete if chunked encoding is
  374. // not used.
  375. if(!chunkedUsed && getDownloadContext()->knowsTotalLength()) {
  376. getRequestGroup()->getPieceStorage()->markAllPiecesDone();
  377. poolConnection();
  378. return true;
  379. }
  380. // We have to make sure that command that has Request object must
  381. // have segment after PieceStorage is initialized. See
  382. // AbstractCommand::execute()
  383. getSegmentMan()->getSegmentWithIndex(getCuid(), 0);
  384. getDownloadEngine()->addCommand
  385. (createHttpDownloadCommand(httpResponse, streamFilter));
  386. return true;
  387. }
  388. bool HttpResponseCommand::skipResponseBody
  389. (const SharedHandle<HttpResponse>& httpResponse)
  390. {
  391. SharedHandle<StreamFilter> filter =
  392. getTransferEncodingStreamFilter(httpResponse);
  393. // We don't use Content-Encoding here because this response body is just
  394. // thrown away.
  395. HttpSkipResponseCommand* command = new HttpSkipResponseCommand
  396. (getCuid(), getRequest(), getFileEntry(), getRequestGroup(),
  397. httpConnection_, httpResponse,
  398. getDownloadEngine(), getSocket());
  399. command->installStreamFilter(filter);
  400. // If request method is HEAD or the response body is zero-length,
  401. // set command's status to real time so that avoid read check blocking
  402. if(getRequest()->getMethod() == Request::METHOD_HEAD ||
  403. (httpResponse->getEntityLength() == 0 &&
  404. !httpResponse->isTransferEncodingSpecified())) {
  405. command->setStatusRealtime();
  406. // If entity length == 0, then socket read/write check must be disabled.
  407. command->disableSocketCheck();
  408. getDownloadEngine()->setNoWait(true);
  409. }
  410. getDownloadEngine()->addCommand(command);
  411. return true;
  412. }
  413. namespace {
  414. bool decideFileAllocation
  415. (const SharedHandle<StreamFilter>& filter)
  416. {
  417. #ifdef HAVE_LIBZ
  418. for(SharedHandle<StreamFilter> f = filter; f; f = f->getDelegate()){
  419. // Since the compressed file's length are returned in the response header
  420. // and the decompressed file size is unknown at this point, disable file
  421. // allocation here.
  422. if(f->getName() == GZipDecodingStreamFilter::NAME) {
  423. return false;
  424. }
  425. }
  426. #endif // HAVE_LIBZ
  427. return true;
  428. }
  429. } // namespace
  430. HttpDownloadCommand* HttpResponseCommand::createHttpDownloadCommand
  431. (const SharedHandle<HttpResponse>& httpResponse,
  432. const SharedHandle<StreamFilter>& filter)
  433. {
  434. HttpDownloadCommand* command =
  435. new HttpDownloadCommand(getCuid(), getRequest(), getFileEntry(),
  436. getRequestGroup(),
  437. httpResponse, httpConnection_,
  438. getDownloadEngine(), getSocket());
  439. command->setStartupIdleTime(getOption()->getAsInt(PREF_STARTUP_IDLE_TIME));
  440. command->setLowestDownloadSpeedLimit
  441. (getOption()->getAsInt(PREF_LOWEST_SPEED_LIMIT));
  442. command->installStreamFilter(filter);
  443. if(getRequestGroup()->isFileAllocationEnabled() &&
  444. !decideFileAllocation(filter)) {
  445. getRequestGroup()->setFileAllocationEnabled(false);
  446. }
  447. getRequestGroup()->getURISelector()->tuneDownloadCommand
  448. (getFileEntry()->getRemainingUris(), command);
  449. return command;
  450. }
  451. void HttpResponseCommand::poolConnection()
  452. {
  453. if(getRequest()->supportsPersistentConnection()) {
  454. getDownloadEngine()->poolSocket(getRequest(), createProxyRequest(),
  455. getSocket());
  456. }
  457. }
  458. void HttpResponseCommand::onDryRunFileFound()
  459. {
  460. getPieceStorage()->markAllPiecesDone();
  461. getDownloadContext()->setChecksumVerified(true);
  462. poolConnection();
  463. }
  464. } // namespace aria2