HttpServer.cc 6.9 KB

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