HttpServer.cc 7.9 KB

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