HttpResponseCommand.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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 "SingleFileDownloadContext.h"
  38. #include "FileEntry.h"
  39. #include "RequestGroup.h"
  40. #include "ServerHost.h"
  41. #include "RequestGroupMan.h"
  42. #include "Request.h"
  43. #include "HttpRequest.h"
  44. #include "HttpResponse.h"
  45. #include "HttpConnection.h"
  46. #include "SegmentMan.h"
  47. #include "Segment.h"
  48. #include "HttpDownloadCommand.h"
  49. #include "DiskAdaptor.h"
  50. #include "PieceStorage.h"
  51. #include "DefaultBtProgressInfoFile.h"
  52. #include "DownloadFailureException.h"
  53. #include "DlAbortEx.h"
  54. #include "Util.h"
  55. #include "File.h"
  56. #include "Option.h"
  57. #include "Logger.h"
  58. #include "Socket.h"
  59. #include "message.h"
  60. #include "prefs.h"
  61. #include "StringFormat.h"
  62. #include "HttpSkipResponseCommand.h"
  63. #include "HttpHeader.h"
  64. #include "LogFactory.h"
  65. #include "CookieStorage.h"
  66. #include "AuthConfigFactory.h"
  67. namespace aria2 {
  68. HttpResponseCommand::HttpResponseCommand(int32_t cuid,
  69. const RequestHandle& req,
  70. RequestGroup* requestGroup,
  71. const HttpConnectionHandle& httpConnection,
  72. DownloadEngine* e,
  73. const SocketHandle& s)
  74. :AbstractCommand(cuid, req, requestGroup, e, s),
  75. httpConnection(httpConnection) {}
  76. HttpResponseCommand::~HttpResponseCommand() {}
  77. bool HttpResponseCommand::executeInternal()
  78. {
  79. HttpRequestHandle httpRequest = httpConnection->getFirstHttpRequest();
  80. HttpResponseHandle httpResponse = httpConnection->receiveResponse();
  81. if(httpResponse.isNull()) {
  82. // The server has not responded to our request yet.
  83. // For socket->wantRead() == true, setReadCheckSocket(socket) is already
  84. // done in the constructor.
  85. setWriteCheckSocketIf(socket, socket->wantWrite());
  86. e->commands.push_back(this);
  87. return false;
  88. }
  89. // check HTTP status number
  90. httpResponse->validateResponse();
  91. httpResponse->retrieveCookie();
  92. SharedHandle<HttpHeader> httpHeader = httpResponse->getHttpHeader();
  93. // Disable persistent connection if:
  94. // Connection: close is received or the remote server is not HTTP/1.1.
  95. // We don't care whether non-HTTP/1.1 server returns Connection: keep-alive.
  96. req->supportsPersistentConnection
  97. (httpResponse->supportsPersistentConnection());
  98. if(req->isPipeliningEnabled()) {
  99. req->setMaxPipelinedRequest(e->option->getAsInt(PREF_MAX_HTTP_PIPELINING));
  100. }
  101. if(httpResponse->getResponseStatus() >= HttpHeader::S300) {
  102. if(httpResponse->getResponseStatus() == HttpHeader::S404) {
  103. _requestGroup->increaseAndValidateFileNotFoundCount();
  104. }
  105. return skipResponseBody(httpResponse);
  106. }
  107. if(!_requestGroup->isSingleHostMultiConnectionEnabled()) {
  108. // Query by hostname. Searching by CUID may returns NULL.
  109. // In case when resuming download, ServerHost is registered with CUID A.
  110. // Then if requested range is not equal to saved one,
  111. // StreamFileAllocationEntry is created with _nextCommand NULL and
  112. // _currentRequest not NULL. This results creating new command CUID, say
  113. // B and same URI. So searching ServerHost by CUID B fails.
  114. SharedHandle<ServerHost> sv =
  115. _requestGroup->searchServerHost(req->getHost());
  116. if(!sv.isNull()) {
  117. _requestGroup->removeURIWhoseHostnameIs(sv->getHostname());
  118. }
  119. }
  120. if(_requestGroup->getPieceStorage().isNull()) {
  121. uint64_t totalLength = httpResponse->getEntityLength();
  122. SingleFileDownloadContextHandle dctx =
  123. dynamic_pointer_cast<SingleFileDownloadContext>(_requestGroup->getDownloadContext());
  124. dctx->setTotalLength(totalLength);
  125. dctx->setFilename(httpResponse->determinFilename());
  126. dctx->setContentType(httpResponse->getContentType());
  127. _requestGroup->preDownloadProcessing();
  128. if(e->_requestGroupMan->isSameFileBeingDownloaded(_requestGroup)) {
  129. throw DownloadFailureException
  130. (StringFormat(EX_DUPLICATE_FILE_DOWNLOAD,
  131. _requestGroup->getFilePath().c_str()).str());
  132. }
  133. // update last modified time
  134. updateLastModifiedTime(httpResponse->getLastModifiedTime());
  135. if(totalLength == 0 || httpResponse->isTransferEncodingSpecified() ||
  136. shouldInflateContentEncoding(httpResponse)) {
  137. // we ignore content-length when transfer-encoding is set
  138. dctx->setTotalLength(0);
  139. if(req->getMethod() == Request::METHOD_GET &&
  140. (totalLength != 0 ||
  141. !httpResponse->getHttpHeader()->defined(HttpHeader::CONTENT_LENGTH))){
  142. dctx->markTotalLengthIsUnknown();
  143. }
  144. return handleOtherEncoding(httpResponse);
  145. } else {
  146. return handleDefaultEncoding(httpResponse);
  147. }
  148. } else {
  149. // validate totalsize
  150. _requestGroup->validateTotalLength(httpResponse->getEntityLength());
  151. // update last modified time
  152. updateLastModifiedTime(httpResponse->getLastModifiedTime());
  153. e->commands.push_back(createHttpDownloadCommand(httpResponse));
  154. return true;
  155. }
  156. }
  157. void HttpResponseCommand::updateLastModifiedTime(const Time& lastModified)
  158. {
  159. if(e->option->getAsBool(PREF_REMOTE_TIME)) {
  160. _requestGroup->updateLastModifiedTime(lastModified);
  161. }
  162. }
  163. static bool fileIsGzipped(const SharedHandle<HttpResponse>& httpResponse)
  164. {
  165. std::string filename =
  166. Util::toLower(httpResponse->getHttpRequest()->getRequest()->getFile());
  167. return Util::endsWith(filename, ".gz") || Util::endsWith(filename, ".tgz");
  168. }
  169. bool HttpResponseCommand::shouldInflateContentEncoding
  170. (const SharedHandle<HttpResponse>& httpResponse)
  171. {
  172. // Basically, on the fly inflation cannot be made with segment download,
  173. // because in each segment we don't know where the date should be written.
  174. // So turn off segmented downloading.
  175. // Meanwhile, Some server returns content-encoding: gzip for .tgz files.
  176. // I think those files should not be inflated by clients, because it is the
  177. // original format of those files. So I made filename ending ".gz" or ".tgz"
  178. // (case-insensitive) not inflated.
  179. return httpResponse->isContentEncodingSpecified() &&
  180. !fileIsGzipped(httpResponse);
  181. }
  182. bool HttpResponseCommand::handleDefaultEncoding(const HttpResponseHandle& httpResponse)
  183. {
  184. HttpRequestHandle httpRequest = httpResponse->getHttpRequest();
  185. _requestGroup->initPieceStorage();
  186. BtProgressInfoFileHandle infoFile(new DefaultBtProgressInfoFile(_requestGroup->getDownloadContext(), _requestGroup->getPieceStorage(), e->option));
  187. if(!infoFile->exists() && _requestGroup->downloadFinishedByFileLength()) {
  188. return true;
  189. }
  190. DownloadCommand* command = 0;
  191. try {
  192. _requestGroup->loadAndOpenFile(infoFile);
  193. File file(_requestGroup->getFilePath());
  194. SegmentHandle segment = _requestGroup->getSegmentMan()->getSegment(cuid, 0);
  195. // pipelining requires implicit range specified. But the request for
  196. // this response most likely dones't contains range header. This means
  197. // we can't continue to use this socket because server sends all entity
  198. // body instead of a segment.
  199. // Therefore, we shutdown the socket here if pipelining is enabled.
  200. if(req->getMethod() == Request::METHOD_GET &&
  201. !segment.isNull() && segment->getPositionToWrite() == 0 &&
  202. !req->isPipeliningEnabled()) {
  203. command = createHttpDownloadCommand(httpResponse);
  204. } else {
  205. _requestGroup->getSegmentMan()->cancelSegment(cuid);
  206. }
  207. prepareForNextAction(command);
  208. if(req->getMethod() == Request::METHOD_HEAD) {
  209. poolConnection();
  210. req->setMethod(Request::METHOD_GET);
  211. }
  212. } catch(Exception& e) {
  213. delete command;
  214. throw;
  215. }
  216. return true;
  217. }
  218. static SharedHandle<Decoder> getTransferEncodingDecoder
  219. (const SharedHandle<HttpResponse>& httpResponse)
  220. {
  221. SharedHandle<Decoder> decoder;
  222. if(httpResponse->isTransferEncodingSpecified()) {
  223. decoder = httpResponse->getTransferEncodingDecoder();
  224. if(decoder.isNull()) {
  225. throw DlAbortEx
  226. (StringFormat(EX_TRANSFER_ENCODING_NOT_SUPPORTED,
  227. httpResponse->getTransferEncoding().c_str()).str());
  228. }
  229. decoder->init();
  230. }
  231. return decoder;
  232. }
  233. static SharedHandle<Decoder> getContentEncodingDecoder
  234. (const SharedHandle<HttpResponse>& httpResponse)
  235. {
  236. SharedHandle<Decoder> decoder;
  237. if(httpResponse->isContentEncodingSpecified()) {
  238. decoder = httpResponse->getContentEncodingDecoder();
  239. if(decoder.isNull()) {
  240. LogFactory::getInstance()->info
  241. ("Content-Encoding %s is specified, but the current implementation"
  242. "doesn't support it. The decoding process is skipped and the"
  243. "downloaded content will be still encoded.",
  244. httpResponse->getContentEncoding().c_str());
  245. } else {
  246. decoder->init();
  247. }
  248. }
  249. return decoder;
  250. }
  251. bool HttpResponseCommand::handleOtherEncoding(const HttpResponseHandle& httpResponse) {
  252. // We assume that RequestGroup::getTotalLength() == 0 here
  253. HttpRequestHandle httpRequest = httpResponse->getHttpRequest();
  254. if(req->getMethod() == Request::METHOD_HEAD) {
  255. poolConnection();
  256. req->setMethod(Request::METHOD_GET);
  257. return prepareForRetry(0);
  258. }
  259. _requestGroup->initPieceStorage();
  260. // For zero-length file, check existing file comparing its size
  261. if(_requestGroup->getDownloadContext()->knowsTotalLength() &&
  262. _requestGroup->downloadFinishedByFileLength()) {
  263. poolConnection();
  264. return true;
  265. }
  266. _requestGroup->shouldCancelDownloadForSafety();
  267. _requestGroup->getPieceStorage()->getDiskAdaptor()->initAndOpenFile();
  268. if(_requestGroup->getDownloadContext()->knowsTotalLength()) {
  269. poolConnection();
  270. return true;
  271. }
  272. e->commands.push_back
  273. (createHttpDownloadCommand(httpResponse,
  274. getTransferEncodingDecoder(httpResponse),
  275. getContentEncodingDecoder(httpResponse)));
  276. return true;
  277. }
  278. bool HttpResponseCommand::skipResponseBody
  279. (const SharedHandle<HttpResponse>& httpResponse)
  280. {
  281. SharedHandle<Decoder> decoder = getTransferEncodingDecoder(httpResponse);
  282. // We don't use Content-Encoding here because this response body is just
  283. // thrown away.
  284. HttpSkipResponseCommand* command = new HttpSkipResponseCommand
  285. (cuid, req, _requestGroup, httpConnection, httpResponse, e, socket);
  286. command->setTransferEncodingDecoder(decoder);
  287. // If request method is HEAD or the response body is zero-length,
  288. // set command's status to real time so that avoid read check blocking
  289. if(req->getMethod() == Request::METHOD_HEAD ||
  290. (httpResponse->getEntityLength() == 0 &&
  291. !httpResponse->isTransferEncodingSpecified())) {
  292. command->setStatusRealtime();
  293. // If entity length == 0, then socket read/write check must be disabled.
  294. command->disableSocketCheck();
  295. e->setNoWait(true);
  296. }
  297. e->commands.push_back(command);
  298. return true;
  299. }
  300. HttpDownloadCommand* HttpResponseCommand::createHttpDownloadCommand
  301. (const HttpResponseHandle& httpResponse,
  302. const SharedHandle<Decoder>& transferEncodingDecoder,
  303. const SharedHandle<Decoder>& contentEncodingDecoder)
  304. {
  305. HttpDownloadCommand* command =
  306. new HttpDownloadCommand(cuid, req, _requestGroup,
  307. httpResponse, httpConnection, e, socket);
  308. command->setMaxDownloadSpeedLimit
  309. (e->option->getAsInt(PREF_MAX_DOWNLOAD_LIMIT));
  310. command->setStartupIdleTime(e->option->getAsInt(PREF_STARTUP_IDLE_TIME));
  311. command->setLowestDownloadSpeedLimit
  312. (e->option->getAsInt(PREF_LOWEST_SPEED_LIMIT));
  313. command->setTransferEncodingDecoder(transferEncodingDecoder);
  314. if(!contentEncodingDecoder.isNull()) {
  315. command->setContentEncodingDecoder(contentEncodingDecoder);
  316. // Since the compressed file's length are returned in the response header
  317. // and the decompressed file size is unknown at this point, disable file
  318. // allocation here.
  319. _requestGroup->setFileAllocationEnabled(false);
  320. }
  321. _requestGroup->tuneDownloadCommand(command);
  322. return command;
  323. }
  324. void HttpResponseCommand::poolConnection()
  325. {
  326. if(req->supportsPersistentConnection()) {
  327. e->poolSocket(req, isProxyDefined(), socket);
  328. }
  329. }
  330. } // namespace aria2