HttpServer.cc 12 KB

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