HttpResponseCommand.cc 15 KB

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