HttpResponseCommand.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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 "Decoder.h"
  65. #include "LogFactory.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. if(totalLength == 0 || httpResponse->isTransferEncodingSpecified() ||
  118. shouldInflateContentEncoding(httpResponse)) {
  119. // we ignore content-length when transfer-encoding is set
  120. dctx->setTotalLength(0);
  121. return handleOtherEncoding(httpResponse);
  122. } else {
  123. return handleDefaultEncoding(httpResponse);
  124. }
  125. } else {
  126. // validate totalsize
  127. _requestGroup->validateTotalLength(httpResponse->getEntityLength());
  128. e->commands.push_back(createHttpDownloadCommand(httpResponse));
  129. return true;
  130. }
  131. }
  132. bool HttpResponseCommand::shouldInflateContentEncoding
  133. (const SharedHandle<HttpResponse>& httpResponse)
  134. {
  135. // Basically, on the fly inflation cannot be made with segment download,
  136. // because in each segment we don't know where the date should be written.
  137. // So turn off segmented downloading.
  138. // Meanwhile, Some server returns content-encoding: gzip for .tgz files.
  139. // Those files tend to be large enough to speed up using segmented
  140. // downloading. Therefore, I choose threshold size to determine on the fly
  141. // inflation should be done. I expect gzipped content such as metalink xml
  142. // files tend to be smaller than the threshold size, those contents are
  143. // inflated on the fly properly.
  144. return httpResponse->isContentEncodingSpecified() &&
  145. httpResponse->getEntityLength() <=
  146. static_cast<uint64_t>(e->option->getAsInt(PREF_SEGMENT_SIZE));
  147. }
  148. bool HttpResponseCommand::handleDefaultEncoding(const HttpResponseHandle& httpResponse)
  149. {
  150. HttpRequestHandle httpRequest = httpResponse->getHttpRequest();
  151. _requestGroup->initPieceStorage();
  152. // quick hack for method 'head',, is it necessary?
  153. if(httpRequest->getMethod() == Request::METHOD_HEAD) {
  154. // TODO because we don't want segment file to be saved.
  155. return true;
  156. }
  157. BtProgressInfoFileHandle infoFile(new DefaultBtProgressInfoFile(_requestGroup->getDownloadContext(), _requestGroup->getPieceStorage(), e->option));
  158. if(!infoFile->exists() && _requestGroup->downloadFinishedByFileLength()) {
  159. return true;
  160. }
  161. DownloadCommand* command = 0;
  162. try {
  163. _requestGroup->loadAndOpenFile(infoFile);
  164. File file(_requestGroup->getFilePath());
  165. SegmentHandle segment = _requestGroup->getSegmentMan()->getSegment(cuid, 0);
  166. // pipelining requires implicit range specified. But the request for
  167. // this response most likely dones't contains range header. This means
  168. // we can't continue to use this socket because server sends all entity
  169. // body instead of a segment.
  170. // Therefore, we shutdown the socket here if pipelining is enabled.
  171. if(!segment.isNull() && segment->getPositionToWrite() == 0 &&
  172. !req->isPipeliningEnabled()) {
  173. command = createHttpDownloadCommand(httpResponse);
  174. } else {
  175. _requestGroup->getSegmentMan()->cancelSegment(cuid);
  176. }
  177. prepareForNextAction(command);
  178. } catch(Exception& e) {
  179. delete command;
  180. throw;
  181. }
  182. return true;
  183. }
  184. bool HttpResponseCommand::handleOtherEncoding(const HttpResponseHandle& httpResponse) {
  185. HttpRequestHandle httpRequest = httpResponse->getHttpRequest();
  186. // quick hack for method 'head',, is it necessary?
  187. if(httpRequest->getMethod() == Request::METHOD_HEAD) {
  188. return true;
  189. }
  190. _requestGroup->initPieceStorage();
  191. _requestGroup->shouldCancelDownloadForSafety();
  192. _requestGroup->getPieceStorage()->getDiskAdaptor()->initAndOpenFile();
  193. e->commands.push_back(createHttpDownloadCommand(httpResponse));
  194. return true;
  195. }
  196. static SharedHandle<Decoder> getTransferEncodingDecoder
  197. (const SharedHandle<HttpResponse>& httpResponse)
  198. {
  199. SharedHandle<Decoder> decoder;
  200. if(httpResponse->isTransferEncodingSpecified()) {
  201. decoder = httpResponse->getTransferEncodingDecoder();
  202. if(decoder.isNull()) {
  203. throw DlAbortEx
  204. (StringFormat(EX_TRANSFER_ENCODING_NOT_SUPPORTED,
  205. httpResponse->getTransferEncoding().c_str()).str());
  206. }
  207. decoder->init();
  208. }
  209. return decoder;
  210. }
  211. static SharedHandle<Decoder> getContentEncodingDecoder
  212. (const SharedHandle<HttpResponse>& httpResponse)
  213. {
  214. SharedHandle<Decoder> decoder;
  215. if(httpResponse->isContentEncodingSpecified()) {
  216. decoder = httpResponse->getContentEncodingDecoder();
  217. if(decoder.isNull()) {
  218. LogFactory::getInstance()->info
  219. ("Content-Encoding %s is specified, but the current implementation"
  220. "doesn't support it. The decoding process is skipped and the"
  221. "downloaded content will be still encoded.",
  222. httpResponse->getContentEncoding().c_str());
  223. } else {
  224. decoder->init();
  225. }
  226. }
  227. return decoder;
  228. }
  229. bool HttpResponseCommand::skipResponseBody
  230. (const SharedHandle<HttpResponse>& httpResponse)
  231. {
  232. SharedHandle<Decoder> decoder = getTransferEncodingDecoder(httpResponse);
  233. // We don't use Content-Encoding here because this response body is just
  234. // thrown away.
  235. HttpSkipResponseCommand* command = new HttpSkipResponseCommand
  236. (cuid, req, _requestGroup, httpConnection, httpResponse, e, socket);
  237. command->setTransferEncodingDecoder(decoder);
  238. // If the response body is zero-length, set command's status to real time
  239. // so that avoid read check blocking
  240. if(httpResponse->getEntityLength() == 0 &&
  241. !httpResponse->isTransferEncodingSpecified()) {
  242. command->setStatusRealtime();
  243. e->setNoWait(true);
  244. }
  245. e->commands.push_back(command);
  246. return true;
  247. }
  248. HttpDownloadCommand* HttpResponseCommand::createHttpDownloadCommand
  249. (const HttpResponseHandle& httpResponse)
  250. {
  251. SharedHandle<Decoder> transferEncodingDecoder =
  252. getTransferEncodingDecoder(httpResponse);
  253. SharedHandle<Decoder> contentEncodingDecoder =
  254. getContentEncodingDecoder(httpResponse);
  255. HttpDownloadCommand* command =
  256. new HttpDownloadCommand(cuid, req, _requestGroup, httpConnection, e,
  257. socket);
  258. command->setMaxDownloadSpeedLimit
  259. (e->option->getAsInt(PREF_MAX_DOWNLOAD_LIMIT));
  260. command->setStartupIdleTime(e->option->getAsInt(PREF_STARTUP_IDLE_TIME));
  261. command->setLowestDownloadSpeedLimit
  262. (e->option->getAsInt(PREF_LOWEST_SPEED_LIMIT));
  263. command->setTransferEncodingDecoder(transferEncodingDecoder);
  264. if(shouldInflateContentEncoding(httpResponse)) {
  265. command->setContentEncodingDecoder(contentEncodingDecoder);
  266. // Since the compressed file's length are returned in the response header
  267. // and the decompressed file size is unknown at this point, disable file
  268. // allocation here.
  269. _requestGroup->setFileAllocationEnabled(false);
  270. }
  271. return command;
  272. }
  273. } // namespace aria2