HttpSkipResponseCommand.cc 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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 "HttpSkipResponseCommand.h"
  36. #include "HttpConnection.h"
  37. #include "HttpResponse.h"
  38. #include "message.h"
  39. #include "SocketCore.h"
  40. #include "DlRetryEx.h"
  41. #include "Request.h"
  42. #include "DownloadEngine.h"
  43. #include "Logger.h"
  44. #include "LogFactory.h"
  45. #include "HttpRequest.h"
  46. #include "Segment.h"
  47. #include "util.h"
  48. #include "fmt.h"
  49. #include "DlAbortEx.h"
  50. #include "HttpHeader.h"
  51. #include "prefs.h"
  52. #include "Option.h"
  53. #include "CookieStorage.h"
  54. #include "AuthConfigFactory.h"
  55. #include "AuthConfig.h"
  56. #include "DownloadContext.h"
  57. #include "StreamFilter.h"
  58. #include "BinaryStream.h"
  59. #include "NullSinkStreamFilter.h"
  60. #include "SinkStreamFilter.h"
  61. #include "error_code.h"
  62. #include "SocketRecvBuffer.h"
  63. namespace aria2 {
  64. HttpSkipResponseCommand::HttpSkipResponseCommand(
  65. cuid_t cuid, const std::shared_ptr<Request>& req,
  66. const std::shared_ptr<FileEntry>& fileEntry, RequestGroup* requestGroup,
  67. const std::shared_ptr<HttpConnection>& httpConnection,
  68. std::unique_ptr<HttpResponse> httpResponse, DownloadEngine* e,
  69. const std::shared_ptr<SocketCore>& s)
  70. : AbstractCommand(cuid, req, fileEntry, requestGroup, e, s,
  71. httpConnection->getSocketRecvBuffer()),
  72. sinkFilterOnly_(true),
  73. totalLength_(httpResponse->getEntityLength()),
  74. receivedBytes_(0),
  75. httpConnection_(httpConnection),
  76. httpResponse_(std::move(httpResponse)),
  77. streamFilter_(make_unique<NullSinkStreamFilter>())
  78. {
  79. checkSocketRecvBuffer();
  80. }
  81. HttpSkipResponseCommand::~HttpSkipResponseCommand() {}
  82. void HttpSkipResponseCommand::installStreamFilter(
  83. std::unique_ptr<StreamFilter> streamFilter)
  84. {
  85. if (!streamFilter) {
  86. return;
  87. }
  88. streamFilter->installDelegate(std::move(streamFilter_));
  89. streamFilter_ = std::move(streamFilter);
  90. const std::string& name = streamFilter_->getName();
  91. sinkFilterOnly_ = util::endsWith(name, SinkStreamFilter::NAME);
  92. }
  93. bool HttpSkipResponseCommand::executeInternal()
  94. {
  95. if (getRequest()->getMethod() == Request::METHOD_HEAD ||
  96. (totalLength_ == 0 && sinkFilterOnly_)) {
  97. // If request method is HEAD or content-length header is present and
  98. // it's value is 0, then pool socket for reuse.
  99. // If content-length header is not present, then EOF is expected in the end.
  100. // In this case, the content is thrown away and socket cannot be pooled.
  101. if (getRequest()->getMethod() == Request::METHOD_HEAD ||
  102. httpResponse_->getHttpHeader()->defined(HttpHeader::CONTENT_LENGTH)) {
  103. poolConnection();
  104. }
  105. return processResponse();
  106. }
  107. bool eof = false;
  108. try {
  109. size_t bufSize;
  110. if (getSocketRecvBuffer()->bufferEmpty()) {
  111. eof = getSocketRecvBuffer()->recv() == 0 && !getSocket()->wantRead() &&
  112. !getSocket()->wantWrite();
  113. }
  114. if (!eof) {
  115. if (sinkFilterOnly_) {
  116. if (totalLength_ > 0) {
  117. bufSize = std::min(
  118. totalLength_ - receivedBytes_,
  119. static_cast<int64_t>(getSocketRecvBuffer()->getBufferLength()));
  120. }
  121. else {
  122. bufSize = getSocketRecvBuffer()->getBufferLength();
  123. }
  124. receivedBytes_ += bufSize;
  125. }
  126. else {
  127. // receivedBytes_ is not updated if transferEncoding is set.
  128. // The return value is safely ignored here.
  129. streamFilter_->transform(std::shared_ptr<BinaryStream>(),
  130. std::shared_ptr<Segment>(),
  131. getSocketRecvBuffer()->getBuffer(),
  132. getSocketRecvBuffer()->getBufferLength());
  133. bufSize = streamFilter_->getBytesProcessed();
  134. }
  135. getSocketRecvBuffer()->drain(bufSize);
  136. }
  137. if (totalLength_ != 0 && eof) {
  138. throw DL_RETRY_EX(EX_GOT_EOF);
  139. }
  140. }
  141. catch (RecoverableException& e) {
  142. A2_LOG_DEBUG_EX(EX_EXCEPTION_CAUGHT, e)
  143. return processResponse();
  144. }
  145. if (eof) {
  146. // we may get EOF before non-sink streamFilter reports its
  147. // completion. There are some broken servers to prevent
  148. // streamFilter from completion. Since we just discard the
  149. // response body anyway, so we assume that the response is
  150. // completed.
  151. return processResponse();
  152. }
  153. bool finished = false;
  154. if (sinkFilterOnly_) {
  155. finished = (totalLength_ == receivedBytes_);
  156. }
  157. else {
  158. finished = streamFilter_->finished();
  159. }
  160. if (finished) {
  161. if (getSegments().size() <= 1) {
  162. // Don't pool connection if the command has multiple
  163. // segments. This means it did HTTP pipelined request. If this
  164. // response is for the first request, then successive response
  165. // may arrived to the socket.
  166. poolConnection();
  167. }
  168. return processResponse();
  169. }
  170. else {
  171. setWriteCheckSocketIf(getSocket(), getSocket()->wantWrite());
  172. addCommandSelf();
  173. return false;
  174. }
  175. }
  176. void HttpSkipResponseCommand::poolConnection() const
  177. {
  178. if (getRequest()->supportsPersistentConnection()) {
  179. getDownloadEngine()->poolSocket(getRequest(), createProxyRequest(),
  180. getSocket());
  181. }
  182. }
  183. bool HttpSkipResponseCommand::processResponse()
  184. {
  185. if (httpResponse_->isRedirect()) {
  186. int rnum =
  187. httpResponse_->getHttpRequest()->getRequest()->getRedirectCount();
  188. if (rnum >= Request::MAX_REDIRECT) {
  189. throw DL_ABORT_EX2(fmt("Too many redirects: count=%u", rnum),
  190. error_code::HTTP_TOO_MANY_REDIRECTS);
  191. }
  192. httpResponse_->processRedirect();
  193. return prepareForRetry(0);
  194. }
  195. auto statusCode = httpResponse_->getStatusCode();
  196. if (statusCode >= 400) {
  197. switch (statusCode) {
  198. case 401:
  199. if (getOption()->getAsBool(PREF_HTTP_AUTH_CHALLENGE) &&
  200. !httpResponse_->getHttpRequest()->authenticationUsed() &&
  201. getDownloadEngine()->getAuthConfigFactory()->activateBasicCred(
  202. getRequest()->getHost(), getRequest()->getPort(),
  203. getRequest()->getDir(), getOption().get())) {
  204. return prepareForRetry(0);
  205. }
  206. throw DL_ABORT_EX2(EX_AUTH_FAILED, error_code::HTTP_AUTH_FAILED);
  207. case 404:
  208. if (getOption()->getAsInt(PREF_MAX_FILE_NOT_FOUND) == 0) {
  209. throw DL_ABORT_EX2(MSG_RESOURCE_NOT_FOUND,
  210. error_code::RESOURCE_NOT_FOUND);
  211. }
  212. throw DL_RETRY_EX2(MSG_RESOURCE_NOT_FOUND,
  213. error_code::RESOURCE_NOT_FOUND);
  214. case 503:
  215. // Only retry if pretry-wait > 0. Hammering 'busy' server is not
  216. // a good idea.
  217. if (getOption()->getAsInt(PREF_RETRY_WAIT) > 0) {
  218. throw DL_RETRY_EX2(fmt(EX_BAD_STATUS, statusCode),
  219. error_code::HTTP_SERVICE_UNAVAILABLE);
  220. }
  221. throw DL_ABORT_EX2(fmt(EX_BAD_STATUS, statusCode),
  222. error_code::HTTP_SERVICE_UNAVAILABLE);
  223. case 504:
  224. // This is Gateway Timeout, so try again
  225. throw DL_RETRY_EX2(fmt(EX_BAD_STATUS, statusCode),
  226. error_code::HTTP_SERVICE_UNAVAILABLE);
  227. };
  228. throw DL_ABORT_EX2(fmt(EX_BAD_STATUS, statusCode),
  229. error_code::HTTP_PROTOCOL_ERROR);
  230. }
  231. return prepareForRetry(0);
  232. }
  233. void HttpSkipResponseCommand::disableSocketCheck()
  234. {
  235. disableReadCheckSocket();
  236. disableWriteCheckSocket();
  237. }
  238. } // namespace aria2