HttpSkipResponseCommand.cc 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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,
  66. const std::shared_ptr<Request>& req,
  67. const std::shared_ptr<FileEntry>& fileEntry,
  68. RequestGroup* requestGroup,
  69. const std::shared_ptr<HttpConnection>& httpConnection,
  70. std::unique_ptr<HttpResponse> httpResponse,
  71. DownloadEngine* e,
  72. const std::shared_ptr<SocketCore>& s)
  73. : AbstractCommand(cuid, req, fileEntry, requestGroup, e, s,
  74. httpConnection->getSocketRecvBuffer()),
  75. httpConnection_(httpConnection),
  76. httpResponse_(std::move(httpResponse)),
  77. streamFilter_(new NullSinkStreamFilter()),
  78. sinkFilterOnly_(true),
  79. totalLength_(httpResponse_->getEntityLength()),
  80. receivedBytes_(0)
  81. {
  82. checkSocketRecvBuffer();
  83. }
  84. HttpSkipResponseCommand::~HttpSkipResponseCommand() {}
  85. void HttpSkipResponseCommand::installStreamFilter
  86. (std::unique_ptr<StreamFilter> streamFilter)
  87. {
  88. if(!streamFilter) {
  89. return;
  90. }
  91. streamFilter->installDelegate(std::move(streamFilter_));
  92. streamFilter_ = std::move(streamFilter);
  93. const std::string& name = streamFilter_->getName();
  94. sinkFilterOnly_ = util::endsWith(name, SinkStreamFilter::NAME);
  95. }
  96. bool HttpSkipResponseCommand::executeInternal()
  97. {
  98. if(getRequest()->getMethod() == Request::METHOD_HEAD ||
  99. (totalLength_ == 0 && sinkFilterOnly_)) {
  100. // If request method is HEAD or content-length header is present and
  101. // it's value is 0, then pool socket for reuse.
  102. // If content-length header is not present, then EOF is expected in the end.
  103. // In this case, the content is thrown away and socket cannot be pooled.
  104. if(getRequest()->getMethod() == Request::METHOD_HEAD ||
  105. httpResponse_->getHttpHeader()->defined(HttpHeader::CONTENT_LENGTH)) {
  106. poolConnection();
  107. }
  108. return processResponse();
  109. }
  110. bool eof = false;
  111. try {
  112. size_t bufSize;
  113. if(getSocketRecvBuffer()->bufferEmpty()) {
  114. eof = getSocketRecvBuffer()->recv() == 0 &&
  115. !getSocket()->wantRead() && !getSocket()->wantWrite();
  116. }
  117. if(!eof) {
  118. if(sinkFilterOnly_) {
  119. if(totalLength_ > 0) {
  120. bufSize = std::min
  121. (totalLength_-receivedBytes_,
  122. static_cast<int64_t>(getSocketRecvBuffer()->getBufferLength()));
  123. } else {
  124. bufSize = getSocketRecvBuffer()->getBufferLength();
  125. }
  126. receivedBytes_ += bufSize;
  127. } else {
  128. // receivedBytes_ is not updated if transferEncoding is set.
  129. // The return value is safely ignored here.
  130. streamFilter_->transform(std::shared_ptr<BinaryStream>(),
  131. std::shared_ptr<Segment>(),
  132. getSocketRecvBuffer()->getBuffer(),
  133. getSocketRecvBuffer()->getBufferLength());
  134. bufSize = streamFilter_->getBytesProcessed();
  135. }
  136. getSocketRecvBuffer()->shiftBuffer(bufSize);
  137. }
  138. if(totalLength_ != 0 && eof) {
  139. throw DL_RETRY_EX(EX_GOT_EOF);
  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. } else {
  157. finished = streamFilter_->finished();
  158. }
  159. if(finished) {
  160. if(getSegments().size() <= 1) {
  161. // Don't pool connection if the command has multiple
  162. // segments. This means it did HTTP pipelined request. If this
  163. // response is for the first request, then successive response
  164. // may arrived to the socket.
  165. poolConnection();
  166. }
  167. return processResponse();
  168. } else {
  169. setWriteCheckSocketIf(getSocket(), getSocket()->wantWrite());
  170. addCommandSelf();
  171. return false;
  172. }
  173. }
  174. void HttpSkipResponseCommand::poolConnection() const
  175. {
  176. if(getRequest()->supportsPersistentConnection()) {
  177. getDownloadEngine()->poolSocket
  178. (getRequest(), createProxyRequest(), getSocket());
  179. }
  180. }
  181. bool HttpSkipResponseCommand::processResponse()
  182. {
  183. int statusCode;
  184. if(httpResponse_->isRedirect()) {
  185. int rnum =
  186. httpResponse_->getHttpRequest()->getRequest()->getRedirectCount();
  187. if(rnum >= Request::MAX_REDIRECT) {
  188. throw DL_ABORT_EX2(fmt("Too many redirects: count=%u", rnum),
  189. error_code::HTTP_TOO_MANY_REDIRECTS);
  190. }
  191. httpResponse_->processRedirect();
  192. return prepareForRetry(0);
  193. } else if((statusCode = httpResponse_->getStatusCode()) >= 400) {
  194. if(statusCode == 401) {
  195. if(getOption()->getAsBool(PREF_HTTP_AUTH_CHALLENGE) &&
  196. !httpResponse_->getHttpRequest()->authenticationUsed() &&
  197. getDownloadEngine()->getAuthConfigFactory()->activateBasicCred
  198. (getRequest()->getHost(), getRequest()->getPort(),
  199. getRequest()->getDir(), getOption().get())) {
  200. return prepareForRetry(0);
  201. } else {
  202. throw DL_ABORT_EX2(EX_AUTH_FAILED,
  203. error_code::HTTP_AUTH_FAILED);
  204. }
  205. } else if(statusCode == 404) {
  206. throw DL_ABORT_EX2(MSG_RESOURCE_NOT_FOUND,
  207. error_code::RESOURCE_NOT_FOUND);
  208. } else if(statusCode == 503) {
  209. // Only retry if pretry-wait > 0. Hammering 'busy' server is not
  210. // a good idea.
  211. if(getOption()->getAsInt(PREF_RETRY_WAIT) > 0) {
  212. throw DL_RETRY_EX2(fmt(EX_BAD_STATUS, statusCode),
  213. error_code::HTTP_SERVICE_UNAVAILABLE);
  214. } else {
  215. throw DL_ABORT_EX2(fmt(EX_BAD_STATUS, statusCode),
  216. error_code::HTTP_SERVICE_UNAVAILABLE);
  217. }
  218. } else {
  219. throw DL_ABORT_EX2(fmt(EX_BAD_STATUS, statusCode),
  220. error_code::HTTP_PROTOCOL_ERROR);
  221. }
  222. } else {
  223. return prepareForRetry(0);
  224. }
  225. }
  226. void HttpSkipResponseCommand::disableSocketCheck()
  227. {
  228. disableReadCheckSocket();
  229. disableWriteCheckSocket();
  230. }
  231. } // namespace aria2