HttpServerBodyCommand.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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 "HttpServerBodyCommand.h"
  36. #include "SocketCore.h"
  37. #include "DownloadEngine.h"
  38. #include "HttpServer.h"
  39. #include "HttpHeader.h"
  40. #include "Logger.h"
  41. #include "LogFactory.h"
  42. #include "RequestGroup.h"
  43. #include "RequestGroupMan.h"
  44. #include "RecoverableException.h"
  45. #include "HttpServerResponseCommand.h"
  46. #include "DelayedCommand.h"
  47. #include "OptionParser.h"
  48. #include "OptionHandler.h"
  49. #include "wallclock.h"
  50. #include "util.h"
  51. #include "fmt.h"
  52. #include "SocketRecvBuffer.h"
  53. #include "json.h"
  54. #include "DlAbortEx.h"
  55. #include "message.h"
  56. #include "RpcMethod.h"
  57. #include "RpcMethodFactory.h"
  58. #include "RpcRequest.h"
  59. #include "RpcResponse.h"
  60. #include "rpc_helper.h"
  61. #include "JsonDiskWriter.h"
  62. #include "ValueBaseJsonParser.h"
  63. #ifdef ENABLE_XML_RPC
  64. #include "XmlRpcRequestParserStateMachine.h"
  65. #include "XmlRpcDiskWriter.h"
  66. #endif // ENABLE_XML_RPC
  67. namespace aria2 {
  68. HttpServerBodyCommand::HttpServerBodyCommand(
  69. cuid_t cuid, const std::shared_ptr<HttpServer>& httpServer,
  70. DownloadEngine* e, const std::shared_ptr<SocketCore>& socket)
  71. : Command(cuid),
  72. e_(e),
  73. socket_(socket),
  74. httpServer_(httpServer),
  75. writeCheck_(false)
  76. {
  77. // To handle Content-Length == 0 case
  78. setStatus(Command::STATUS_ONESHOT_REALTIME);
  79. e_->addSocketForReadCheck(socket_, this);
  80. if (!httpServer_->getSocketRecvBuffer()->bufferEmpty() ||
  81. socket_->getRecvBufferedLength()) {
  82. e_->setNoWait(true);
  83. }
  84. }
  85. HttpServerBodyCommand::~HttpServerBodyCommand()
  86. {
  87. e_->deleteSocketForReadCheck(socket_, this);
  88. if (writeCheck_) {
  89. e_->deleteSocketForWriteCheck(socket_, this);
  90. }
  91. }
  92. namespace {
  93. std::string getJsonRpcContentType(bool script)
  94. {
  95. return script ? "text/javascript" : "application/json-rpc";
  96. }
  97. } // namespace
  98. void HttpServerBodyCommand::sendJsonRpcResponse(const rpc::RpcResponse& res,
  99. const std::string& callback)
  100. {
  101. bool notauthorized = rpc::not_authorized(res);
  102. bool gzip = httpServer_->supportsGZip();
  103. std::string responseData = rpc::toJson(res, callback, gzip);
  104. if (res.code == 0) {
  105. httpServer_->feedResponse(std::move(responseData),
  106. getJsonRpcContentType(!callback.empty()));
  107. }
  108. else {
  109. httpServer_->disableKeepAlive();
  110. int httpCode;
  111. switch (res.code) {
  112. case 1:
  113. // error caught while executing RpcMethod
  114. httpCode = 400;
  115. break;
  116. case -32600:
  117. httpCode = 400;
  118. break;
  119. case -32601:
  120. httpCode = 404;
  121. break;
  122. default:
  123. httpCode = 500;
  124. };
  125. httpServer_->feedResponse(httpCode, A2STR::NIL, std::move(responseData),
  126. getJsonRpcContentType(!callback.empty()));
  127. }
  128. addHttpServerResponseCommand(notauthorized);
  129. }
  130. void HttpServerBodyCommand::sendJsonRpcBatchResponse(
  131. const std::vector<rpc::RpcResponse>& results, const std::string& callback)
  132. {
  133. bool notauthorized = rpc::any_not_authorized(results.begin(), results.end());
  134. bool gzip = httpServer_->supportsGZip();
  135. std::string responseData = rpc::toJsonBatch(results, callback, gzip);
  136. httpServer_->feedResponse(std::move(responseData),
  137. getJsonRpcContentType(!callback.empty()));
  138. addHttpServerResponseCommand(notauthorized);
  139. }
  140. void HttpServerBodyCommand::addHttpServerResponseCommand(bool delayed)
  141. {
  142. auto resp = make_unique<HttpServerResponseCommand>(getCuid(), httpServer_, e_,
  143. socket_);
  144. if (delayed) {
  145. e_->addCommand(
  146. make_unique<DelayedCommand>(getCuid(), e_, 1_s, std::move(resp), true));
  147. return;
  148. }
  149. e_->addCommand(std::move(resp));
  150. e_->setNoWait(true);
  151. }
  152. void HttpServerBodyCommand::updateWriteCheck()
  153. {
  154. if (httpServer_->wantWrite()) {
  155. if (!writeCheck_) {
  156. writeCheck_ = true;
  157. e_->addSocketForWriteCheck(socket_, this);
  158. }
  159. }
  160. else if (writeCheck_) {
  161. writeCheck_ = false;
  162. e_->deleteSocketForWriteCheck(socket_, this);
  163. }
  164. }
  165. bool HttpServerBodyCommand::execute()
  166. {
  167. if (e_->getRequestGroupMan()->downloadFinished() || e_->isHaltRequested()) {
  168. return true;
  169. }
  170. try {
  171. if (socket_->isReadable(0) || (writeCheck_ && socket_->isWritable(0)) ||
  172. socket_->getRecvBufferedLength() ||
  173. !httpServer_->getSocketRecvBuffer()->bufferEmpty() ||
  174. httpServer_->getContentLength() == 0) {
  175. timeoutTimer_ = global::wallclock();
  176. if (httpServer_->receiveBody()) {
  177. std::string reqPath = httpServer_->getRequestPath();
  178. reqPath.erase(std::find(reqPath.begin(), reqPath.end(), '#'),
  179. reqPath.end());
  180. std::string query(std::find(reqPath.begin(), reqPath.end(), '?'),
  181. reqPath.end());
  182. reqPath.erase(reqPath.size() - query.size(), query.size());
  183. if (httpServer_->getMethod() == "OPTIONS") {
  184. // Response to Preflight Request.
  185. // See http://www.w3.org/TR/cors/
  186. auto& header = httpServer_->getRequestHeader();
  187. std::string accessControlHeaders;
  188. if (!header->find(HttpHeader::ORIGIN).empty() &&
  189. !header->find(HttpHeader::ACCESS_CONTROL_REQUEST_METHOD)
  190. .empty() &&
  191. !httpServer_->getAllowOrigin().empty()) {
  192. accessControlHeaders +=
  193. "Access-Control-Allow-Methods: POST, GET, OPTIONS\r\n"
  194. "Access-Control-Max-Age: 1728000\r\n";
  195. const std::string& accReqHeaders =
  196. header->find(HttpHeader::ACCESS_CONTROL_REQUEST_HEADERS);
  197. if (!accReqHeaders.empty()) {
  198. // We allow all headers requested.
  199. accessControlHeaders += "Access-Control-Allow-Headers: ";
  200. accessControlHeaders += accReqHeaders;
  201. accessControlHeaders += "\r\n";
  202. }
  203. }
  204. httpServer_->feedResponse(200, accessControlHeaders);
  205. addHttpServerResponseCommand(false);
  206. return true;
  207. }
  208. // Do something for requestpath and body
  209. switch (httpServer_->getRequestType()) {
  210. case RPC_TYPE_XML: {
  211. #ifdef ENABLE_XML_RPC
  212. auto dw = static_cast<rpc::XmlRpcDiskWriter*>(httpServer_->getBody());
  213. int error;
  214. error = dw->finalize();
  215. rpc::RpcRequest req;
  216. if (error == 0) {
  217. req = dw->getResult();
  218. }
  219. dw->reset();
  220. if (error < 0) {
  221. A2_LOG_INFO(fmt("CUID#%" PRId64
  222. " - Failed to parse XML-RPC request",
  223. getCuid()));
  224. httpServer_->feedResponse(400);
  225. addHttpServerResponseCommand(false);
  226. return true;
  227. }
  228. A2_LOG_INFO(fmt("Executing RPC method %s", req.methodName.c_str()));
  229. auto method = rpc::getMethod(req.methodName);
  230. auto res = method->execute(std::move(req), e_);
  231. bool gzip = httpServer_->supportsGZip();
  232. std::string responseData = rpc::toXml(res, gzip);
  233. httpServer_->feedResponse(std::move(responseData), "text/xml");
  234. addHttpServerResponseCommand(false);
  235. #else // !ENABLE_XML_RPC
  236. httpServer_->feedResponse(404);
  237. addHttpServerResponseCommand(false);
  238. #endif // !ENABLE_XML_RPC
  239. return true;
  240. }
  241. case RPC_TYPE_JSON:
  242. case RPC_TYPE_JSONP: {
  243. std::string callback;
  244. std::unique_ptr<ValueBase> json;
  245. ssize_t error = 0;
  246. if (httpServer_->getRequestType() == RPC_TYPE_JSONP) {
  247. json::JsonGetParam param = json::decodeGetParams(query);
  248. callback = param.callback;
  249. ssize_t error = 0;
  250. json = json::ValueBaseJsonParser().parseFinal(
  251. param.request.c_str(), param.request.size(), error);
  252. }
  253. else {
  254. auto dw =
  255. static_cast<json::JsonDiskWriter*>(httpServer_->getBody());
  256. error = dw->finalize();
  257. if (error == 0) {
  258. json = dw->getResult();
  259. }
  260. dw->reset();
  261. }
  262. if (error < 0) {
  263. A2_LOG_INFO(fmt("CUID#%" PRId64
  264. " - Failed to parse JSON-RPC request",
  265. getCuid()));
  266. rpc::RpcResponse res(rpc::createJsonRpcErrorResponse(
  267. -32700, "Parse error.", Null::g()));
  268. sendJsonRpcResponse(res, callback);
  269. return true;
  270. }
  271. Dict* jsondict = downcast<Dict>(json);
  272. if (jsondict) {
  273. auto res = rpc::processJsonRpcRequest(jsondict, e_);
  274. sendJsonRpcResponse(res, callback);
  275. }
  276. else {
  277. List* jsonlist = downcast<List>(json);
  278. if (jsonlist) {
  279. // This is batch call
  280. std::vector<rpc::RpcResponse> results;
  281. for (List::ValueType::const_iterator i = jsonlist->begin(),
  282. eoi = jsonlist->end();
  283. i != eoi; ++i) {
  284. Dict* jsondict = downcast<Dict>(*i);
  285. if (jsondict) {
  286. auto resp = rpc::processJsonRpcRequest(jsondict, e_);
  287. results.push_back(std::move(resp));
  288. }
  289. }
  290. sendJsonRpcBatchResponse(results, callback);
  291. }
  292. else {
  293. rpc::RpcResponse res(rpc::createJsonRpcErrorResponse(
  294. -32600, "Invalid Request.", Null::g()));
  295. sendJsonRpcResponse(res, callback);
  296. }
  297. }
  298. return true;
  299. }
  300. default:
  301. httpServer_->feedResponse(404);
  302. addHttpServerResponseCommand(false);
  303. return true;
  304. }
  305. }
  306. else {
  307. updateWriteCheck();
  308. e_->addCommand(std::unique_ptr<Command>(this));
  309. return false;
  310. }
  311. }
  312. else {
  313. if (timeoutTimer_.difference(global::wallclock()) >= 30_s) {
  314. A2_LOG_INFO("HTTP request body timeout.");
  315. return true;
  316. }
  317. else {
  318. e_->addCommand(std::unique_ptr<Command>(this));
  319. return false;
  320. }
  321. }
  322. }
  323. catch (RecoverableException& e) {
  324. A2_LOG_INFO_EX(fmt("CUID#%" PRId64
  325. " - Error occurred while reading HTTP request body",
  326. getCuid()),
  327. e);
  328. return true;
  329. }
  330. }
  331. } // namespace aria2