HttpServer.cc 6.3 KB

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