HttpServer.cc 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2009 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 "HttpServer.h"
  36. #include <sstream>
  37. #include "HttpHeader.h"
  38. #include "SocketCore.h"
  39. #include "HttpHeaderProcessor.h"
  40. #include "DlAbortEx.h"
  41. #include "message.h"
  42. #include "util.h"
  43. #include "LogFactory.h"
  44. #include "Logger.h"
  45. #include "Base64.h"
  46. #include "a2functional.h"
  47. #include "fmt.h"
  48. #include "SocketRecvBuffer.h"
  49. namespace aria2 {
  50. HttpServer::HttpServer
  51. (const SharedHandle<SocketCore>& socket,
  52. DownloadEngine* e)
  53. : socket_(socket),
  54. socketRecvBuffer_(new SocketRecvBuffer(socket_)),
  55. socketBuffer_(socket),
  56. e_(e),
  57. headerProcessor_(new HttpHeaderProcessor()),
  58. keepAlive_(true),
  59. gzip_(false),
  60. acceptsPersistentConnection_(true),
  61. acceptsGZip_(false)
  62. {}
  63. HttpServer::~HttpServer() {}
  64. SharedHandle<HttpHeader> HttpServer::receiveRequest()
  65. {
  66. if(socketRecvBuffer_->bufferEmpty()) {
  67. if(socketRecvBuffer_->recv() == 0 &&
  68. !socket_->wantRead() && !socket_->wantWrite()) {
  69. throw DL_ABORT_EX(EX_EOF_FROM_PEER);
  70. }
  71. }
  72. headerProcessor_->update(socketRecvBuffer_->getBuffer(),
  73. socketRecvBuffer_->getBufferLength());
  74. if(headerProcessor_->eoh()) {
  75. SharedHandle<HttpHeader> header = headerProcessor_->getHttpRequestHeader();
  76. size_t putbackDataLength = headerProcessor_->getPutBackDataLength();
  77. A2_LOG_INFO(fmt("HTTP Server received request\n%s",
  78. headerProcessor_->getHeaderString().c_str()));
  79. socketRecvBuffer_->shiftBuffer
  80. (socketRecvBuffer_->getBufferLength()-putbackDataLength);
  81. lastRequestHeader_ = header;
  82. lastBody_.clear();
  83. lastBody_.str("");
  84. lastContentLength_ =
  85. lastRequestHeader_->getFirstAsUInt(HttpHeader::CONTENT_LENGTH);
  86. headerProcessor_->clear();
  87. std::string connection =
  88. util::toLower(lastRequestHeader_->getFirst(HttpHeader::CONNECTION));
  89. acceptsPersistentConnection_ =
  90. connection.find(HttpHeader::CLOSE) == std::string::npos &&
  91. (lastRequestHeader_->getVersion() == HttpHeader::HTTP_1_1 ||
  92. connection.find("keep-alive") != std::string::npos);
  93. std::vector<std::string> acceptEncodings;
  94. util::split(lastRequestHeader_->getFirst(HttpHeader::ACCEPT_ENCODING),
  95. std::back_inserter(acceptEncodings), A2STR::COMMA_C, true);
  96. acceptsGZip_ =
  97. std::find(acceptEncodings.begin(), acceptEncodings.end(), "gzip")
  98. != acceptEncodings.end();
  99. return header;
  100. } else {
  101. socketRecvBuffer_->clearBuffer();
  102. return SharedHandle<HttpHeader>();
  103. }
  104. }
  105. bool HttpServer::receiveBody()
  106. {
  107. if(lastContentLength_ == 0) {
  108. return true;
  109. }
  110. if(socketRecvBuffer_->bufferEmpty()) {
  111. if(socketRecvBuffer_->recv() == 0 &&
  112. !socket_->wantRead() && !socket_->wantWrite()) {
  113. throw DL_ABORT_EX(EX_EOF_FROM_PEER);
  114. }
  115. }
  116. size_t length =
  117. std::min(socketRecvBuffer_->getBufferLength(),
  118. static_cast<size_t>(lastContentLength_-lastBody_.tellg()));
  119. lastBody_.write(reinterpret_cast<const char*>(socketRecvBuffer_->getBuffer()),
  120. length);
  121. socketRecvBuffer_->shiftBuffer(length);
  122. return lastContentLength_ == static_cast<uint64_t>(lastBody_.tellp());
  123. }
  124. std::string HttpServer::getBody() const
  125. {
  126. return lastBody_.str();
  127. }
  128. const std::string& HttpServer::getRequestPath() const
  129. {
  130. return lastRequestHeader_->getRequestPath();
  131. }
  132. void HttpServer::feedResponse(const std::string& text, const std::string& contentType)
  133. {
  134. feedResponse("200 OK", "", text, contentType);
  135. }
  136. void HttpServer::feedResponse(const std::string& status,
  137. const std::string& headers,
  138. const std::string& text,
  139. const std::string& contentType)
  140. {
  141. std::string header = "HTTP/1.1 ";
  142. strappend(header, status, "\r\n",
  143. "Content-Type: ", contentType, "\r\n",
  144. "Content-Length: ", util::uitos(text.size()), "\r\n");
  145. if(supportsGZip()) {
  146. header += "Content-Encoding: gzip\r\n";
  147. }
  148. if(!supportsPersistentConnection()) {
  149. header += "Connection: close\r\n";
  150. }
  151. if(!headers.empty()) {
  152. header += headers;
  153. if(!util::endsWith(headers, "\r\n")) {
  154. header += "\r\n";
  155. }
  156. }
  157. header += "\r\n";
  158. A2_LOG_DEBUG(fmt("HTTP Server sends response:\n%s", header.c_str()));
  159. socketBuffer_.pushStr(header);
  160. socketBuffer_.pushStr(text);
  161. }
  162. ssize_t HttpServer::sendResponse()
  163. {
  164. return socketBuffer_.send();
  165. }
  166. bool HttpServer::sendBufferIsEmpty() const
  167. {
  168. return socketBuffer_.sendBufferIsEmpty();
  169. }
  170. bool HttpServer::authenticate()
  171. {
  172. if(username_.empty()) {
  173. return true;
  174. }
  175. std::string authHeader = lastRequestHeader_->getFirst("Authorization");
  176. if(authHeader.empty()) {
  177. return false;
  178. }
  179. std::pair<std::string, std::string> p;
  180. util::divide(p, authHeader, ' ');
  181. if(p.first != "Basic") {
  182. return false;
  183. }
  184. std::string userpass = Base64::decode(p.second);
  185. std::pair<std::string, std::string> userpassPair;
  186. util::divide(userpassPair, userpass, ':');
  187. return username_ == userpassPair.first && password_ == userpassPair.second;
  188. }
  189. void HttpServer::setUsernamePassword
  190. (const std::string& username, const std::string& password)
  191. {
  192. username_ = username;
  193. password_ = password;
  194. }
  195. } // namespace aria2