HttpServer.cc 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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_->findAsLLInt(HttpHeader::CONTENT_LENGTH);
  88. if(lastContentLength_ < 0) {
  89. throw DL_ABORT_EX("Content-Length must be positive.");
  90. }
  91. headerProcessor_->clear();
  92. const std::string& connection =
  93. lastRequestHeader_->find(HttpHeader::CONNECTION);
  94. acceptsPersistentConnection_ =
  95. util::strifind(connection.begin(),
  96. connection.end(),
  97. HttpHeader::CLOSE.begin(),
  98. HttpHeader::CLOSE.end()) == connection.end() &&
  99. (lastRequestHeader_->getVersion() == HttpHeader::HTTP_1_1 ||
  100. util::strifind(connection.begin(),
  101. connection.end(),
  102. HttpHeader::KEEP_ALIVE.begin(),
  103. HttpHeader::KEEP_ALIVE.end()) != connection.end());
  104. std::vector<Scip> acceptEncodings;
  105. const std::string& acceptEnc =
  106. lastRequestHeader_->find(HttpHeader::ACCEPT_ENCODING);
  107. util::splitIter(acceptEnc.begin(), acceptEnc.end(),
  108. std::back_inserter(acceptEncodings), ',', true);
  109. acceptsGZip_ = false;
  110. for(std::vector<Scip>::const_iterator i = acceptEncodings.begin(),
  111. eoi = acceptEncodings.end(); i != eoi; ++i) {
  112. if(util::strieq((*i).first, (*i).second,
  113. HttpHeader::GZIP.begin(), HttpHeader::GZIP.end())) {
  114. acceptsGZip_ = true;
  115. break;
  116. }
  117. }
  118. return header;
  119. } else {
  120. socketRecvBuffer_->clearBuffer();
  121. return SharedHandle<HttpHeader>();
  122. }
  123. }
  124. bool HttpServer::receiveBody()
  125. {
  126. if(lastContentLength_ == 0) {
  127. return true;
  128. }
  129. if(socketRecvBuffer_->bufferEmpty()) {
  130. if(socketRecvBuffer_->recv() == 0 &&
  131. !socket_->wantRead() && !socket_->wantWrite()) {
  132. throw DL_ABORT_EX(EX_EOF_FROM_PEER);
  133. }
  134. }
  135. size_t length =
  136. std::min(socketRecvBuffer_->getBufferLength(),
  137. static_cast<size_t>(lastContentLength_-lastBody_.tellg()));
  138. lastBody_.write(reinterpret_cast<const char*>(socketRecvBuffer_->getBuffer()),
  139. length);
  140. socketRecvBuffer_->shiftBuffer(length);
  141. return lastContentLength_ == lastBody_.tellp();
  142. }
  143. std::string HttpServer::getBody() const
  144. {
  145. return lastBody_.str();
  146. }
  147. const std::string& HttpServer::getMethod() const
  148. {
  149. return lastRequestHeader_->getMethod();
  150. }
  151. const std::string& HttpServer::getRequestPath() const
  152. {
  153. return lastRequestHeader_->getRequestPath();
  154. }
  155. void HttpServer::feedResponse(std::string& text, const std::string& contentType)
  156. {
  157. feedResponse("200 OK", "", text, contentType);
  158. }
  159. void HttpServer::feedResponse(const std::string& status,
  160. const std::string& headers,
  161. std::string& text,
  162. const std::string& contentType)
  163. {
  164. std::string httpDate = Time().toHTTPDate();
  165. std::string header= fmt("HTTP/1.1 %s\r\n"
  166. "Date: %s\r\n"
  167. "Content-Type: %s\r\n"
  168. "Content-Length: %lu\r\n"
  169. "Expires: %s\r\n"
  170. "Cache-Control: no-cache\r\n"
  171. "%s%s",
  172. status.c_str(),
  173. httpDate.c_str(),
  174. contentType.c_str(),
  175. static_cast<unsigned long>(text.size()),
  176. httpDate.c_str(),
  177. supportsGZip() ?
  178. "Content-Encoding: gzip\r\n" : "",
  179. !supportsPersistentConnection() ?
  180. "Connection: close\r\n" : "");
  181. if(!allowOrigin_.empty()) {
  182. header += "Access-Control-Allow-Origin: ";
  183. header += allowOrigin_;
  184. header += "\r\n";
  185. }
  186. if(!headers.empty()) {
  187. header += headers;
  188. if(headers.size() < 2 ||
  189. (headers[headers.size()-2] != '\r' &&
  190. headers[headers.size()-1] != '\n')) {
  191. header += "\r\n";
  192. }
  193. }
  194. header += "\r\n";
  195. A2_LOG_DEBUG(fmt("HTTP Server sends response:\n%s", header.c_str()));
  196. socketBuffer_.pushStr(header);
  197. socketBuffer_.pushStr(text);
  198. }
  199. void HttpServer::feedUpgradeResponse(const std::string& protocol,
  200. const std::string& headers)
  201. {
  202. std::string header= fmt("HTTP/1.1 101 Switching Protocols\r\n"
  203. "Upgrade: %s\r\n"
  204. "Connection: Upgrade\r\n"
  205. "%s"
  206. "\r\n",
  207. protocol.c_str(),
  208. headers.c_str());
  209. A2_LOG_DEBUG(fmt("HTTP Server sends upgrade response:\n%s", header.c_str()));
  210. socketBuffer_.pushStr(header);
  211. }
  212. ssize_t HttpServer::sendResponse()
  213. {
  214. return socketBuffer_.send();
  215. }
  216. bool HttpServer::sendBufferIsEmpty() const
  217. {
  218. return socketBuffer_.sendBufferIsEmpty();
  219. }
  220. bool HttpServer::authenticate()
  221. {
  222. if(username_.empty()) {
  223. return true;
  224. }
  225. const std::string& authHeader =
  226. lastRequestHeader_->find(HttpHeader::AUTHORIZATION);
  227. if(authHeader.empty()) {
  228. return false;
  229. }
  230. std::pair<Scip, Scip> p;
  231. util::divide(p, authHeader.begin(), authHeader.end(), ' ');
  232. if(!util::streq(p.first.first, p.first.second, "Basic")) {
  233. return false;
  234. }
  235. std::string userpass = base64::decode(p.second.first, p.second.second);
  236. std::pair<Sip, Sip> up;
  237. util::divide(up, userpass.begin(), userpass.end(), ':');
  238. return util::streq(up.first.first, up.first.second,
  239. username_.begin(), username_.end()) &&
  240. util::streq(up.second.first, up.second.second,
  241. password_.begin(), password_.end());
  242. }
  243. void HttpServer::setUsernamePassword
  244. (const std::string& username, const std::string& password)
  245. {
  246. username_ = username;
  247. password_ = password;
  248. }
  249. } // namespace aria2