HttpServer.cc 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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. namespace aria2 {
  48. HttpServer::HttpServer(const SharedHandle<SocketCore>& socket,
  49. DownloadEngine* e):
  50. socket_(socket),
  51. socketBuffer_(socket),
  52. e_(e),
  53. headerProcessor_(new HttpHeaderProcessor()),
  54. logger_(LogFactory::getInstance()),
  55. keepAlive_(true),
  56. gzip_(false),
  57. acceptsPersistentConnection_(true),
  58. acceptsGZip_(false)
  59. {}
  60. HttpServer::~HttpServer() {}
  61. SharedHandle<HttpHeader> HttpServer::receiveRequest()
  62. {
  63. size_t size = 512;
  64. unsigned char buf[size];
  65. socket_->peekData(buf, size);
  66. if(size == 0 && !(socket_->wantRead() || socket_->wantWrite())) {
  67. throw DL_ABORT_EX(EX_EOF_FROM_PEER);
  68. }
  69. headerProcessor_->update(buf, size);
  70. if(!headerProcessor_->eoh()) {
  71. socket_->readData(buf, size);
  72. return SharedHandle<HttpHeader>();
  73. }
  74. size_t putbackDataLength = headerProcessor_->getPutBackDataLength();
  75. size -= putbackDataLength;
  76. socket_->readData(buf, size);
  77. SharedHandle<HttpHeader> header = headerProcessor_->getHttpRequestHeader();
  78. if(!header.isNull()) {
  79. logger_->info("HTTP Server received request\n%s",
  80. headerProcessor_->getHeaderString().c_str());
  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. }
  100. return header;
  101. }
  102. bool HttpServer::receiveBody()
  103. {
  104. if(lastContentLength_ == 0) {
  105. return true;
  106. }
  107. const size_t BUFLEN = 4096;
  108. char buf[BUFLEN];
  109. size_t length = std::min(BUFLEN,
  110. static_cast<size_t>
  111. (lastContentLength_-lastBody_.tellg()));
  112. socket_->readData(buf, length);
  113. if(length == 0 && !(socket_->wantRead() || socket_->wantWrite())) {
  114. throw DL_ABORT_EX(EX_EOF_FROM_PEER);
  115. }
  116. lastBody_.write(buf, length);
  117. return lastContentLength_ == static_cast<uint64_t>(lastBody_.tellp());
  118. }
  119. std::string HttpServer::getBody() const
  120. {
  121. return lastBody_.str();
  122. }
  123. const std::string& HttpServer::getRequestPath() const
  124. {
  125. return lastRequestHeader_->getRequestPath();
  126. }
  127. void HttpServer::feedResponse(const std::string& text, const std::string& contentType)
  128. {
  129. feedResponse("200 OK", "", text, contentType);
  130. }
  131. void HttpServer::feedResponse(const std::string& status,
  132. const std::string& headers,
  133. const std::string& text,
  134. const std::string& contentType)
  135. {
  136. std::string header = "HTTP/1.1 ";
  137. strappend(header, status, "\r\n",
  138. "Content-Type: ", contentType, "\r\n",
  139. "Content-Length: ", util::uitos(text.size()), "\r\n");
  140. if(supportsGZip()) {
  141. header += "Content-Encoding: gzip\r\n";
  142. }
  143. if(!supportsPersistentConnection()) {
  144. header += "Connection: close\r\n";
  145. }
  146. if(!headers.empty()) {
  147. header += headers;
  148. if(!util::endsWith(headers, "\r\n")) {
  149. header += "\r\n";
  150. }
  151. }
  152. header += "\r\n";
  153. if(logger_->debug()) {
  154. logger_->debug("HTTP Server sends response:\n%s", header.c_str());
  155. }
  156. socketBuffer_.pushStr(header);
  157. socketBuffer_.pushStr(text);
  158. }
  159. ssize_t HttpServer::sendResponse()
  160. {
  161. return socketBuffer_.send();
  162. }
  163. bool HttpServer::sendBufferIsEmpty() const
  164. {
  165. return socketBuffer_.sendBufferIsEmpty();
  166. }
  167. bool HttpServer::authenticate()
  168. {
  169. if(username_.empty()) {
  170. return true;
  171. }
  172. std::string authHeader = lastRequestHeader_->getFirst("Authorization");
  173. if(authHeader.empty()) {
  174. return false;
  175. }
  176. std::pair<std::string, std::string> p = util::split(authHeader, " ");
  177. if(p.first != "Basic") {
  178. return false;
  179. }
  180. std::string userpass = Base64::decode(p.second);
  181. std::pair<std::string, std::string> userpassPair = util::split(userpass, ":");
  182. return username_ == userpassPair.first && password_ == userpassPair.second;
  183. }
  184. } // namespace aria2