HttpResponseCommand.cc 17 KB

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