HttpResponseCommand.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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. namespace aria2 {
  67. HttpResponseCommand::HttpResponseCommand(int32_t cuid,
  68. const RequestHandle& req,
  69. RequestGroup* requestGroup,
  70. const HttpConnectionHandle& httpConnection,
  71. DownloadEngine* e,
  72. const SocketHandle& s)
  73. :AbstractCommand(cuid, req, requestGroup, e, s),
  74. httpConnection(httpConnection) {}
  75. HttpResponseCommand::~HttpResponseCommand() {}
  76. bool HttpResponseCommand::executeInternal()
  77. {
  78. HttpRequestHandle httpRequest = httpConnection->getFirstHttpRequest();
  79. HttpResponseHandle httpResponse = httpConnection->receiveResponse();
  80. if(httpResponse.isNull()) {
  81. // The server has not responded to our request yet.
  82. e->commands.push_back(this);
  83. return false;
  84. }
  85. // check HTTP status number
  86. httpResponse->validateResponse();
  87. httpResponse->retrieveCookie();
  88. if(httpResponse->getResponseStatus() >= HttpHeader::S300) {
  89. return skipResponseBody(httpResponse);
  90. }
  91. if(!_requestGroup->isSingleHostMultiConnectionEnabled()) {
  92. // Query by hostname. Searching by CUID may returns NULL.
  93. // In case when resuming download, ServerHost is registered with CUID A.
  94. // Then if requested range is not equal to saved one,
  95. // StreamFileAllocationEntry is created with _nextCommand NULL and
  96. // _currentRequest not NULL. This results creating new command CUID, say
  97. // B and same URI. So searching ServerHost by CUID B fails.
  98. SharedHandle<ServerHost> sv =
  99. _requestGroup->searchServerHost(req->getHost());
  100. if(!sv.isNull()) {
  101. _requestGroup->removeURIWhoseHostnameIs(sv->getHostname());
  102. }
  103. }
  104. if(_requestGroup->getPieceStorage().isNull()) {
  105. uint64_t totalLength = httpResponse->getEntityLength();
  106. SingleFileDownloadContextHandle dctx =
  107. dynamic_pointer_cast<SingleFileDownloadContext>(_requestGroup->getDownloadContext());
  108. dctx->setTotalLength(totalLength);
  109. dctx->setFilename(httpResponse->determinFilename());
  110. dctx->setContentType(httpResponse->getContentType());
  111. _requestGroup->preDownloadProcessing();
  112. if(e->_requestGroupMan->isSameFileBeingDownloaded(_requestGroup)) {
  113. throw DownloadFailureException
  114. (StringFormat(EX_DUPLICATE_FILE_DOWNLOAD,
  115. _requestGroup->getFilePath().c_str()).str());
  116. }
  117. // update last modified time
  118. updateLastModifiedTime(httpResponse->getLastModifiedTime());
  119. if(totalLength == 0 || httpResponse->isTransferEncodingSpecified() ||
  120. shouldInflateContentEncoding(httpResponse)) {
  121. // we ignore content-length when transfer-encoding is set
  122. dctx->setTotalLength(0);
  123. return handleOtherEncoding(httpResponse);
  124. } else {
  125. return handleDefaultEncoding(httpResponse);
  126. }
  127. } else {
  128. // validate totalsize
  129. _requestGroup->validateTotalLength(httpResponse->getEntityLength());
  130. // update last modified time
  131. updateLastModifiedTime(httpResponse->getLastModifiedTime());
  132. e->commands.push_back(createHttpDownloadCommand(httpResponse));
  133. return true;
  134. }
  135. }
  136. void HttpResponseCommand::updateLastModifiedTime(const Time& lastModified)
  137. {
  138. if(e->option->getAsBool(PREF_REMOTE_TIME)) {
  139. _requestGroup->updateLastModifiedTime(lastModified);
  140. }
  141. }
  142. static bool fileIsGzipped(const SharedHandle<HttpResponse>& httpResponse)
  143. {
  144. std::string filename =
  145. Util::toLower(httpResponse->getHttpRequest()->getRequest()->getFile());
  146. return Util::endsWith(filename, ".gz") || Util::endsWith(filename, ".tgz");
  147. }
  148. bool HttpResponseCommand::shouldInflateContentEncoding
  149. (const SharedHandle<HttpResponse>& httpResponse)
  150. {
  151. // Basically, on the fly inflation cannot be made with segment download,
  152. // because in each segment we don't know where the date should be written.
  153. // So turn off segmented downloading.
  154. // Meanwhile, Some server returns content-encoding: gzip for .tgz files.
  155. // I think those files should not be inflated by clients, because it is the
  156. // original format of those files. So I made filename ending ".gz" or ".tgz"
  157. // (case-insensitive) not inflated.
  158. return httpResponse->isContentEncodingSpecified() &&
  159. !fileIsGzipped(httpResponse);
  160. }
  161. bool HttpResponseCommand::handleDefaultEncoding(const HttpResponseHandle& httpResponse)
  162. {
  163. HttpRequestHandle httpRequest = httpResponse->getHttpRequest();
  164. _requestGroup->initPieceStorage();
  165. // quick hack for method 'head',, is it necessary?
  166. if(httpRequest->getMethod() == Request::METHOD_HEAD) {
  167. // TODO because we don't want segment file to be saved.
  168. return true;
  169. }
  170. BtProgressInfoFileHandle infoFile(new DefaultBtProgressInfoFile(_requestGroup->getDownloadContext(), _requestGroup->getPieceStorage(), e->option));
  171. if(!infoFile->exists() && _requestGroup->downloadFinishedByFileLength()) {
  172. return true;
  173. }
  174. DownloadCommand* command = 0;
  175. try {
  176. _requestGroup->loadAndOpenFile(infoFile);
  177. File file(_requestGroup->getFilePath());
  178. SegmentHandle segment = _requestGroup->getSegmentMan()->getSegment(cuid, 0);
  179. // pipelining requires implicit range specified. But the request for
  180. // this response most likely dones't contains range header. This means
  181. // we can't continue to use this socket because server sends all entity
  182. // body instead of a segment.
  183. // Therefore, we shutdown the socket here if pipelining is enabled.
  184. if(!segment.isNull() && segment->getPositionToWrite() == 0 &&
  185. !req->isPipeliningEnabled()) {
  186. command = createHttpDownloadCommand(httpResponse);
  187. } else {
  188. _requestGroup->getSegmentMan()->cancelSegment(cuid);
  189. }
  190. prepareForNextAction(command);
  191. } catch(Exception& e) {
  192. delete command;
  193. throw;
  194. }
  195. return true;
  196. }
  197. static SharedHandle<Decoder> getTransferEncodingDecoder
  198. (const SharedHandle<HttpResponse>& httpResponse)
  199. {
  200. SharedHandle<Decoder> decoder;
  201. if(httpResponse->isTransferEncodingSpecified()) {
  202. decoder = httpResponse->getTransferEncodingDecoder();
  203. if(decoder.isNull()) {
  204. throw DlAbortEx
  205. (StringFormat(EX_TRANSFER_ENCODING_NOT_SUPPORTED,
  206. httpResponse->getTransferEncoding().c_str()).str());
  207. }
  208. decoder->init();
  209. }
  210. return decoder;
  211. }
  212. static SharedHandle<Decoder> getContentEncodingDecoder
  213. (const SharedHandle<HttpResponse>& httpResponse)
  214. {
  215. SharedHandle<Decoder> decoder;
  216. if(httpResponse->isContentEncodingSpecified()) {
  217. decoder = httpResponse->getContentEncodingDecoder();
  218. if(decoder.isNull()) {
  219. LogFactory::getInstance()->info
  220. ("Content-Encoding %s is specified, but the current implementation"
  221. "doesn't support it. The decoding process is skipped and the"
  222. "downloaded content will be still encoded.",
  223. httpResponse->getContentEncoding().c_str());
  224. } else {
  225. decoder->init();
  226. }
  227. }
  228. return decoder;
  229. }
  230. bool HttpResponseCommand::handleOtherEncoding(const HttpResponseHandle& httpResponse) {
  231. HttpRequestHandle httpRequest = httpResponse->getHttpRequest();
  232. // quick hack for method 'head',, is it necessary?
  233. if(httpRequest->getMethod() == Request::METHOD_HEAD) {
  234. return true;
  235. }
  236. _requestGroup->initPieceStorage();
  237. _requestGroup->shouldCancelDownloadForSafety();
  238. _requestGroup->getPieceStorage()->getDiskAdaptor()->initAndOpenFile();
  239. e->commands.push_back
  240. (createHttpDownloadCommand(httpResponse,
  241. getTransferEncodingDecoder(httpResponse),
  242. getContentEncodingDecoder(httpResponse)));
  243. return true;
  244. }
  245. bool HttpResponseCommand::skipResponseBody
  246. (const SharedHandle<HttpResponse>& httpResponse)
  247. {
  248. SharedHandle<Decoder> decoder = getTransferEncodingDecoder(httpResponse);
  249. // We don't use Content-Encoding here because this response body is just
  250. // thrown away.
  251. HttpSkipResponseCommand* command = new HttpSkipResponseCommand
  252. (cuid, req, _requestGroup, httpConnection, httpResponse, e, socket);
  253. command->setTransferEncodingDecoder(decoder);
  254. // If the response body is zero-length, set command's status to real time
  255. // so that avoid read check blocking
  256. if(httpResponse->getEntityLength() == 0 &&
  257. !httpResponse->isTransferEncodingSpecified()) {
  258. command->setStatusRealtime();
  259. e->setNoWait(true);
  260. }
  261. e->commands.push_back(command);
  262. return true;
  263. }
  264. HttpDownloadCommand* HttpResponseCommand::createHttpDownloadCommand
  265. (const HttpResponseHandle& httpResponse,
  266. const SharedHandle<Decoder>& transferEncodingDecoder,
  267. const SharedHandle<Decoder>& contentEncodingDecoder)
  268. {
  269. HttpDownloadCommand* command =
  270. new HttpDownloadCommand(cuid, req, _requestGroup, httpConnection, e,
  271. socket);
  272. command->setMaxDownloadSpeedLimit
  273. (e->option->getAsInt(PREF_MAX_DOWNLOAD_LIMIT));
  274. command->setStartupIdleTime(e->option->getAsInt(PREF_STARTUP_IDLE_TIME));
  275. command->setLowestDownloadSpeedLimit
  276. (e->option->getAsInt(PREF_LOWEST_SPEED_LIMIT));
  277. command->setTransferEncodingDecoder(transferEncodingDecoder);
  278. if(!contentEncodingDecoder.isNull()) {
  279. command->setContentEncodingDecoder(contentEncodingDecoder);
  280. // Since the compressed file's length are returned in the response header
  281. // and the decompressed file size is unknown at this point, disable file
  282. // allocation here.
  283. _requestGroup->setFileAllocationEnabled(false);
  284. }
  285. return command;
  286. }
  287. } // namespace aria2