HttpServer.cc 12 KB

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