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