HttpServer.cc 7.7 KB

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