HttpServer.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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. #include "JsonDiskWriter.h"
  52. #ifdef ENABLE_XML_RPC
  53. # include "XmlRpcDiskWriter.h"
  54. #endif // ENABLE_XML_RPC
  55. namespace aria2 {
  56. HttpServer::HttpServer(const std::shared_ptr<SocketCore>& socket)
  57. : socket_(socket),
  58. socketRecvBuffer_(new SocketRecvBuffer(socket_)),
  59. socketBuffer_(socket),
  60. headerProcessor_(make_unique<HttpHeaderProcessor>
  61. (HttpHeaderProcessor::SERVER_PARSER)),
  62. lastContentLength_(0),
  63. bodyConsumed_(0),
  64. reqType_(RPC_TYPE_NONE),
  65. keepAlive_(true),
  66. gzip_(false),
  67. acceptsGZip_(false),
  68. secure_(false)
  69. {}
  70. HttpServer::~HttpServer() {}
  71. namespace {
  72. const char* getStatusString(int status)
  73. {
  74. switch(status) {
  75. case 100: return "100 Continue";
  76. case 101: return "101 Switching Protocols";
  77. case 200: return "200 OK";
  78. case 201: return "201 Created";
  79. case 202: return "202 Accepted";
  80. case 203: return "203 Non-Authoritative Information";
  81. case 204: return "204 No Content";
  82. case 205: return "205 Reset Content";
  83. case 206: return "206 Partial Content";
  84. case 300: return "300 Multiple Choices";
  85. case 301: return "301 Moved Permanently";
  86. case 302: return "302 Found";
  87. case 303: return "303 See Other";
  88. case 304: return "304 Not Modified";
  89. case 305: return "305 Use Proxy";
  90. // case 306: return "306 (Unused)";
  91. case 307: return "307 Temporary Redirect";
  92. case 400: return "400 Bad Request";
  93. case 401: return "401 Unauthorized";
  94. case 402: return "402 Payment Required";
  95. case 403: return "403 Forbidden";
  96. case 404: return "404 Not Found";
  97. case 405: return "405 Method Not Allowed";
  98. case 406: return "406 Not Acceptable";
  99. case 407: return "407 Proxy Authentication Required";
  100. case 408: return "408 Request Timeout";
  101. case 409: return "409 Conflict";
  102. case 410: return "410 Gone";
  103. case 411: return "411 Length Required";
  104. case 412: return "412 Precondition Failed";
  105. case 413: return "413 Request Entity Too Large";
  106. case 414: return "414 Request-URI Too Long";
  107. case 415: return "415 Unsupported Media Type";
  108. case 416: return "416 Requested Range Not Satisfiable";
  109. case 417: return "417 Expectation Failed";
  110. // RFC 2817 defines 426 status code.
  111. case 426: return "426 Upgrade Required";
  112. case 500: return "500 Internal Server Error";
  113. case 501: return "501 Not Implemented";
  114. case 502: return "502 Bad Gateway";
  115. case 503: return "503 Service Unavailable";
  116. case 504: return "504 Gateway Timeout";
  117. case 505: return "505 HTTP Version Not Supported";
  118. default: return "";
  119. }
  120. }
  121. } // namespace
  122. bool HttpServer::receiveRequest()
  123. {
  124. if(socketRecvBuffer_->bufferEmpty()) {
  125. if(socketRecvBuffer_->recv() == 0 &&
  126. !socket_->wantRead() && !socket_->wantWrite()) {
  127. throw DL_ABORT_EX(EX_EOF_FROM_PEER);
  128. }
  129. }
  130. if(headerProcessor_->parse(socketRecvBuffer_->getBuffer(),
  131. socketRecvBuffer_->getBufferLength())) {
  132. lastRequestHeader_ = headerProcessor_->getResult();
  133. A2_LOG_INFO(fmt("HTTP Server received request\n%s",
  134. headerProcessor_->getHeaderString().c_str()));
  135. socketRecvBuffer_->shiftBuffer(headerProcessor_->getLastBytesProcessed());
  136. bodyConsumed_ = 0;
  137. if(setupResponseRecv() < 0) {
  138. A2_LOG_INFO("Request path is invaild. Ignore the request body.");
  139. }
  140. const std::string& contentLengthHdr = lastRequestHeader_->
  141. find(HttpHeader::CONTENT_LENGTH);
  142. if(!contentLengthHdr.empty()) {
  143. if(!util::parseLLIntNoThrow(lastContentLength_, contentLengthHdr) ||
  144. lastContentLength_ < 0) {
  145. throw DL_ABORT_EX(fmt("Invalid Content-Length=%s",
  146. contentLengthHdr.c_str()));
  147. }
  148. } else {
  149. lastContentLength_ = 0;
  150. }
  151. headerProcessor_->clear();
  152. std::vector<Scip> acceptEncodings;
  153. const std::string& acceptEnc =
  154. lastRequestHeader_->find(HttpHeader::ACCEPT_ENCODING);
  155. util::splitIter(acceptEnc.begin(), acceptEnc.end(),
  156. std::back_inserter(acceptEncodings), ',', true);
  157. acceptsGZip_ = false;
  158. for(std::vector<Scip>::const_iterator i = acceptEncodings.begin(),
  159. eoi = acceptEncodings.end(); i != eoi; ++i) {
  160. if(util::strieq((*i).first, (*i).second, "gzip")) {
  161. acceptsGZip_ = true;
  162. break;
  163. }
  164. }
  165. return true;
  166. } else {
  167. socketRecvBuffer_->shiftBuffer(headerProcessor_->getLastBytesProcessed());
  168. return false;
  169. }
  170. }
  171. bool HttpServer::receiveBody()
  172. {
  173. if(lastContentLength_ == bodyConsumed_) {
  174. return true;
  175. }
  176. if(socketRecvBuffer_->bufferEmpty()) {
  177. if(socketRecvBuffer_->recv() == 0 &&
  178. !socket_->wantRead() && !socket_->wantWrite()) {
  179. throw DL_ABORT_EX(EX_EOF_FROM_PEER);
  180. }
  181. }
  182. size_t length =
  183. std::min(socketRecvBuffer_->getBufferLength(),
  184. static_cast<size_t>(lastContentLength_ - bodyConsumed_));
  185. if(lastBody_) {
  186. lastBody_->writeData(socketRecvBuffer_->getBuffer(), length, 0);
  187. }
  188. socketRecvBuffer_->shiftBuffer(length);
  189. bodyConsumed_ += length;
  190. return lastContentLength_ == bodyConsumed_;
  191. }
  192. const std::string& HttpServer::getMethod() const
  193. {
  194. return lastRequestHeader_->getMethod();
  195. }
  196. const std::string& HttpServer::getRequestPath() const
  197. {
  198. return lastRequestHeader_->getRequestPath();
  199. }
  200. void HttpServer::feedResponse(std::string text,
  201. const std::string& contentType)
  202. {
  203. feedResponse(200, "", std::move(text), contentType);
  204. }
  205. void HttpServer::feedResponse(int status,
  206. const std::string& headers,
  207. std::string text,
  208. const std::string& contentType)
  209. {
  210. std::string httpDate = Time().toHTTPDate();
  211. std::string header = fmt("HTTP/1.1 %s\r\n"
  212. "Date: %s\r\n"
  213. "Content-Length: %lu\r\n"
  214. "Expires: %s\r\n"
  215. "Cache-Control: no-cache\r\n",
  216. getStatusString(status),
  217. httpDate.c_str(),
  218. static_cast<unsigned long>(text.size()),
  219. httpDate.c_str());
  220. if(!contentType.empty()) {
  221. header += "Content-Type: ";
  222. header += contentType;
  223. header += "\r\n";
  224. }
  225. if(!allowOrigin_.empty()) {
  226. header += "Access-Control-Allow-Origin: ";
  227. header += allowOrigin_;
  228. header += "\r\n";
  229. }
  230. if(supportsGZip()) {
  231. header += "Content-Encoding: gzip\r\n";
  232. }
  233. if(!supportsPersistentConnection()) {
  234. header += "Connection: close\r\n";
  235. }
  236. header += headers;
  237. header += "\r\n";
  238. A2_LOG_DEBUG(fmt("HTTP Server sends response:\n%s", header.c_str()));
  239. socketBuffer_.pushStr(std::move(header));
  240. socketBuffer_.pushStr(std::move(text));
  241. }
  242. void HttpServer::feedUpgradeResponse(const std::string& protocol,
  243. const std::string& headers)
  244. {
  245. std::string header= fmt("HTTP/1.1 101 Switching Protocols\r\n"
  246. "Upgrade: %s\r\n"
  247. "Connection: Upgrade\r\n"
  248. "%s"
  249. "\r\n",
  250. protocol.c_str(),
  251. headers.c_str());
  252. A2_LOG_DEBUG(fmt("HTTP Server sends upgrade response:\n%s", header.c_str()));
  253. socketBuffer_.pushStr(std::move(header));
  254. }
  255. ssize_t HttpServer::sendResponse()
  256. {
  257. return socketBuffer_.send();
  258. }
  259. bool HttpServer::sendBufferIsEmpty() const
  260. {
  261. return socketBuffer_.sendBufferIsEmpty();
  262. }
  263. bool HttpServer::authenticate()
  264. {
  265. if(username_.empty()) {
  266. return true;
  267. }
  268. const std::string& authHeader =
  269. lastRequestHeader_->find(HttpHeader::AUTHORIZATION);
  270. if(authHeader.empty()) {
  271. return false;
  272. }
  273. auto p = util::divide(std::begin(authHeader), std::end(authHeader), ' ');
  274. if(!util::streq(p.first.first, p.first.second, "Basic")) {
  275. return false;
  276. }
  277. std::string userpass = base64::decode(p.second.first, p.second.second);
  278. auto up = util::divide(std::begin(userpass), std::end(userpass), ':');
  279. return util::streq(up.first.first, up.first.second,
  280. username_.begin(), username_.end()) &&
  281. util::streq(up.second.first, up.second.second,
  282. password_.begin(), password_.end());
  283. }
  284. void HttpServer::setUsernamePassword
  285. (const std::string& username, const std::string& password)
  286. {
  287. username_ = username;
  288. password_ = password;
  289. }
  290. int HttpServer::setupResponseRecv()
  291. {
  292. std::string path = createPath();
  293. if(getMethod() == "GET") {
  294. if(path == "/jsonrpc") {
  295. reqType_ = RPC_TYPE_JSONP;
  296. lastBody_.reset();
  297. return 0;
  298. }
  299. } else if(getMethod() == "POST") {
  300. if(path == "/jsonrpc") {
  301. if(reqType_ != RPC_TYPE_JSON) {
  302. reqType_ = RPC_TYPE_JSON;
  303. lastBody_.reset(new json::JsonDiskWriter());
  304. }
  305. return 0;
  306. }
  307. #ifdef ENABLE_XML_RPC
  308. if(path == "/rpc") {
  309. if(reqType_ != RPC_TYPE_XML) {
  310. reqType_ = RPC_TYPE_XML;
  311. lastBody_.reset(new rpc::XmlRpcDiskWriter());
  312. }
  313. return 0;
  314. }
  315. #endif // ENABLE_XML_RPC
  316. }
  317. reqType_ = RPC_TYPE_NONE;
  318. lastBody_.reset();
  319. return -1;
  320. }
  321. std::string HttpServer::createPath() const
  322. {
  323. std::string reqPath = getRequestPath();
  324. size_t i;
  325. size_t len = reqPath.size();
  326. for(i = 0; i < len; ++i) {
  327. if(reqPath[i] == '#' || reqPath[i] == '?') {
  328. break;
  329. }
  330. }
  331. reqPath = reqPath.substr(0, i);
  332. if(reqPath.empty()) {
  333. reqPath = "/";
  334. }
  335. return reqPath;
  336. }
  337. std::string HttpServer::createQuery() const
  338. {
  339. std::string reqPath = getRequestPath();
  340. size_t i;
  341. size_t len = reqPath.size();
  342. for(i = 0; i < len; ++i) {
  343. if(reqPath[i] == '#' || reqPath[i] == '?') {
  344. break;
  345. }
  346. }
  347. if(i == len || reqPath[i] == '#') {
  348. return "";
  349. } else {
  350. size_t start = i;
  351. for(; i < len; ++i) {
  352. if(reqPath[i] == '#') {
  353. break;
  354. }
  355. }
  356. return reqPath.substr(start, i - start);
  357. }
  358. }
  359. DiskWriter* HttpServer::getBody() const
  360. {
  361. return lastBody_.get();
  362. }
  363. bool HttpServer::supportsPersistentConnection() const
  364. {
  365. return keepAlive_ &&
  366. lastRequestHeader_ && lastRequestHeader_->isKeepAlive();
  367. }
  368. bool HttpServer::wantRead() const
  369. {
  370. return socket_->wantRead();
  371. }
  372. bool HttpServer::wantWrite() const
  373. {
  374. return socket_->wantWrite();
  375. }
  376. } // namespace aria2