HttpServerBodyCommand.cc 11 KB

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