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