HttpResponseCommand.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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. (int32_t cuid,
  76. const RequestHandle& 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. HttpRequestHandle httpRequest = httpConnection->getFirstHttpRequest();
  89. HttpResponseHandle 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. static bool fileIsGzipped(const SharedHandle<HttpResponse>& httpResponse)
  185. {
  186. std::string filename =
  187. util::toLower(httpResponse->getHttpRequest()->getRequest()->getFile());
  188. return util::endsWith(filename, ".gz") || util::endsWith(filename, ".tgz");
  189. }
  190. bool HttpResponseCommand::shouldInflateContentEncoding
  191. (const SharedHandle<HttpResponse>& httpResponse)
  192. {
  193. // Basically, on the fly inflation cannot be made with segment download,
  194. // because in each segment we don't know where the date should be written.
  195. // So turn off segmented downloading.
  196. // Meanwhile, Some server returns content-encoding: gzip for .tgz files.
  197. // I think those files should not be inflated by clients, because it is the
  198. // original format of those files. So I made filename ending ".gz" or ".tgz"
  199. // (case-insensitive) not inflated.
  200. return httpResponse->isContentEncodingSpecified() &&
  201. !fileIsGzipped(httpResponse);
  202. }
  203. bool HttpResponseCommand::handleDefaultEncoding(const HttpResponseHandle& httpResponse)
  204. {
  205. HttpRequestHandle httpRequest = httpResponse->getHttpRequest();
  206. _requestGroup->adjustFilename
  207. (SharedHandle<BtProgressInfoFile>(new DefaultBtProgressInfoFile
  208. (_requestGroup->getDownloadContext(),
  209. SharedHandle<PieceStorage>(),
  210. getOption().get())));
  211. _requestGroup->initPieceStorage();
  212. if(getOption()->getAsBool(PREF_DRY_RUN)) {
  213. onDryRunFileFound();
  214. return true;
  215. }
  216. BtProgressInfoFileHandle infoFile(new DefaultBtProgressInfoFile(_requestGroup->getDownloadContext(), _requestGroup->getPieceStorage(), getOption().get()));
  217. if(!infoFile->exists() && _requestGroup->downloadFinishedByFileLength()) {
  218. _requestGroup->getPieceStorage()->markAllPiecesDone();
  219. logger->notice(MSG_DOWNLOAD_ALREADY_COMPLETED,
  220. _requestGroup->getGID(),
  221. _requestGroup->getFirstFilePath().c_str());
  222. return true;
  223. }
  224. DownloadCommand* command = 0;
  225. try {
  226. _requestGroup->loadAndOpenFile(infoFile);
  227. File file(_requestGroup->getFirstFilePath());
  228. SegmentHandle segment = _requestGroup->getSegmentMan()->getSegment(cuid, 0);
  229. // pipelining requires implicit range specified. But the request for
  230. // this response most likely dones't contains range header. This means
  231. // we can't continue to use this socket because server sends all entity
  232. // body instead of a segment.
  233. // Therefore, we shutdown the socket here if pipelining is enabled.
  234. if(req->getMethod() == Request::METHOD_GET &&
  235. !segment.isNull() && segment->getPositionToWrite() == 0 &&
  236. !req->isPipeliningEnabled()) {
  237. command = createHttpDownloadCommand(httpResponse);
  238. } else {
  239. _requestGroup->getSegmentMan()->cancelSegment(cuid);
  240. _fileEntry->poolRequest(req);
  241. }
  242. prepareForNextAction(command);
  243. if(req->getMethod() == Request::METHOD_HEAD) {
  244. poolConnection();
  245. req->setMethod(Request::METHOD_GET);
  246. }
  247. } catch(Exception& e) {
  248. delete command;
  249. throw;
  250. }
  251. return true;
  252. }
  253. static SharedHandle<Decoder> getTransferEncodingDecoder
  254. (const SharedHandle<HttpResponse>& httpResponse)
  255. {
  256. SharedHandle<Decoder> decoder;
  257. if(httpResponse->isTransferEncodingSpecified()) {
  258. decoder = httpResponse->getTransferEncodingDecoder();
  259. if(decoder.isNull()) {
  260. throw DL_ABORT_EX
  261. (StringFormat(EX_TRANSFER_ENCODING_NOT_SUPPORTED,
  262. httpResponse->getTransferEncoding().c_str()).str());
  263. }
  264. decoder->init();
  265. }
  266. return decoder;
  267. }
  268. static SharedHandle<Decoder> getContentEncodingDecoder
  269. (const SharedHandle<HttpResponse>& httpResponse)
  270. {
  271. SharedHandle<Decoder> decoder;
  272. if(httpResponse->isContentEncodingSpecified()) {
  273. decoder = httpResponse->getContentEncodingDecoder();
  274. if(decoder.isNull()) {
  275. LogFactory::getInstance()->info
  276. ("Content-Encoding %s is specified, but the current implementation"
  277. "doesn't support it. The decoding process is skipped and the"
  278. "downloaded content will be still encoded.",
  279. httpResponse->getContentEncoding().c_str());
  280. } else {
  281. decoder->init();
  282. }
  283. }
  284. return decoder;
  285. }
  286. bool HttpResponseCommand::handleOtherEncoding(const HttpResponseHandle& httpResponse) {
  287. // We assume that RequestGroup::getTotalLength() == 0 here
  288. HttpRequestHandle 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. _requestGroup->getGID(),
  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. e->commands.push_back
  319. (createHttpDownloadCommand(httpResponse,
  320. getTransferEncodingDecoder(httpResponse),
  321. getContentEncodingDecoder(httpResponse)));
  322. return true;
  323. }
  324. bool HttpResponseCommand::skipResponseBody
  325. (const SharedHandle<HttpResponse>& httpResponse)
  326. {
  327. SharedHandle<Decoder> decoder = getTransferEncodingDecoder(httpResponse);
  328. // We don't use Content-Encoding here because this response body is just
  329. // thrown away.
  330. HttpSkipResponseCommand* command = new HttpSkipResponseCommand
  331. (cuid, req, _fileEntry, _requestGroup, httpConnection, httpResponse, e, socket);
  332. command->setTransferEncodingDecoder(decoder);
  333. // If request method is HEAD or the response body is zero-length,
  334. // set command's status to real time so that avoid read check blocking
  335. if(req->getMethod() == Request::METHOD_HEAD ||
  336. (httpResponse->getEntityLength() == 0 &&
  337. !httpResponse->isTransferEncodingSpecified())) {
  338. command->setStatusRealtime();
  339. // If entity length == 0, then socket read/write check must be disabled.
  340. command->disableSocketCheck();
  341. e->setNoWait(true);
  342. }
  343. e->commands.push_back(command);
  344. return true;
  345. }
  346. HttpDownloadCommand* HttpResponseCommand::createHttpDownloadCommand
  347. (const HttpResponseHandle& httpResponse,
  348. const SharedHandle<Decoder>& transferEncodingDecoder,
  349. const SharedHandle<Decoder>& contentEncodingDecoder)
  350. {
  351. HttpDownloadCommand* command =
  352. new HttpDownloadCommand(cuid, req, _fileEntry, _requestGroup,
  353. httpResponse, httpConnection, e, socket);
  354. command->setStartupIdleTime(getOption()->getAsInt(PREF_STARTUP_IDLE_TIME));
  355. command->setLowestDownloadSpeedLimit
  356. (getOption()->getAsInt(PREF_LOWEST_SPEED_LIMIT));
  357. command->setTransferEncodingDecoder(transferEncodingDecoder);
  358. if(!contentEncodingDecoder.isNull()) {
  359. command->setContentEncodingDecoder(contentEncodingDecoder);
  360. // Since the compressed file's length are returned in the response header
  361. // and the decompressed file size is unknown at this point, disable file
  362. // allocation here.
  363. _requestGroup->setFileAllocationEnabled(false);
  364. }
  365. _requestGroup->getURISelector()->tuneDownloadCommand
  366. (_fileEntry->getRemainingUris(), command);
  367. return command;
  368. }
  369. void HttpResponseCommand::poolConnection()
  370. {
  371. if(req->supportsPersistentConnection()) {
  372. e->poolSocket(req, isProxyDefined(), socket);
  373. }
  374. }
  375. void HttpResponseCommand::onDryRunFileFound()
  376. {
  377. _requestGroup->getPieceStorage()->markAllPiecesDone();
  378. poolConnection();
  379. }
  380. } // namespace aria2