HttpServerBodyCommand.cc 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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. #ifdef ENABLE_XML_RPC
  60. # include "XmlRpcRequestProcessor.h"
  61. # include "XmlRpcRequestParserStateMachine.h"
  62. #endif // ENABLE_XML_RPC
  63. namespace aria2 {
  64. HttpServerBodyCommand::HttpServerBodyCommand
  65. (cuid_t cuid,
  66. const SharedHandle<HttpServer>& httpServer,
  67. DownloadEngine* e,
  68. const SharedHandle<SocketCore>& socket)
  69. : Command(cuid),
  70. e_(e),
  71. socket_(socket),
  72. httpServer_(httpServer)
  73. {
  74. // To handle Content-Length == 0 case
  75. setStatus(Command::STATUS_ONESHOT_REALTIME);
  76. e_->addSocketForReadCheck(socket_, this);
  77. if(!httpServer_->getSocketRecvBuffer()->bufferEmpty()) {
  78. e_->setNoWait(true);
  79. }
  80. }
  81. HttpServerBodyCommand::~HttpServerBodyCommand()
  82. {
  83. e_->deleteSocketForReadCheck(socket_, this);
  84. }
  85. namespace {
  86. rpc::RpcResponse
  87. createJsonRpcErrorResponse
  88. (int code,
  89. const std::string& msg,
  90. const SharedHandle<ValueBase>& id)
  91. {
  92. SharedHandle<Dict> params = Dict::g();
  93. params->put("code", Integer::g(code));
  94. params->put("message", msg);
  95. rpc::RpcResponse res(code, params, id);
  96. return res;
  97. }
  98. } // namespace
  99. namespace {
  100. std::string getJsonRpcContentType(bool script)
  101. {
  102. return script ? "text/javascript" : "application/json-rpc";
  103. }
  104. } // namespace
  105. void HttpServerBodyCommand::sendJsonRpcResponse
  106. (const rpc::RpcResponse& res,
  107. const std::string& callback)
  108. {
  109. bool gzip = httpServer_->supportsGZip();
  110. std::string responseData = res.toJson(callback, gzip);
  111. if(res.code == 0) {
  112. httpServer_->feedResponse(responseData,
  113. getJsonRpcContentType(!callback.empty()));
  114. } else {
  115. httpServer_->disableKeepAlive();
  116. std::string httpCode;
  117. switch(res.code) {
  118. case -32600:
  119. httpCode = "400 Bad Request";
  120. break;
  121. case -32601:
  122. httpCode = "404 Not Found";
  123. break;
  124. default:
  125. httpCode = "500 Internal Server Error";
  126. };
  127. httpServer_->feedResponse(httpCode, A2STR::NIL,
  128. responseData,
  129. getJsonRpcContentType(!callback.empty()));
  130. }
  131. addHttpServerResponseCommand();
  132. }
  133. void HttpServerBodyCommand::sendJsonRpcBatchResponse
  134. (const std::vector<rpc::RpcResponse>& results,
  135. const std::string& callback)
  136. {
  137. bool gzip = httpServer_->supportsGZip();
  138. std::string responseData = rpc::toJsonBatch(results, callback, gzip);
  139. httpServer_->feedResponse(responseData,
  140. getJsonRpcContentType(!callback.empty()));
  141. addHttpServerResponseCommand();
  142. }
  143. void HttpServerBodyCommand::addHttpServerResponseCommand()
  144. {
  145. Command* command =
  146. new HttpServerResponseCommand(getCuid(), httpServer_, e_, socket_);
  147. e_->addCommand(command);
  148. e_->setNoWait(true);
  149. }
  150. rpc::RpcResponse
  151. HttpServerBodyCommand::processJsonRpcRequest(const Dict* jsondict)
  152. {
  153. SharedHandle<ValueBase> id = jsondict->get("id");
  154. if(!id) {
  155. return createJsonRpcErrorResponse(-32600, "Invalid Request.", Null::g());
  156. }
  157. const String* methodName = asString(jsondict->get("method"));
  158. if(!methodName) {
  159. return createJsonRpcErrorResponse(-32600, "Invalid Request.", id);
  160. }
  161. SharedHandle<List> params;
  162. const SharedHandle<ValueBase>& tempParams = jsondict->get("params");
  163. if(asList(tempParams)) {
  164. params = static_pointer_cast<List>(tempParams);
  165. } else if(!tempParams) {
  166. params = List::g();
  167. } else {
  168. // TODO No support for Named params
  169. return createJsonRpcErrorResponse(-32602, "Invalid params.", id);
  170. }
  171. rpc::RpcRequest req(methodName->s(), params, id);
  172. req.jsonRpc = true;
  173. SharedHandle<rpc::RpcMethod> method;
  174. try {
  175. method = rpc::RpcMethodFactory::create(req.methodName);
  176. } catch(RecoverableException& e) {
  177. A2_LOG_INFO_EX(EX_EXCEPTION_CAUGHT, e);
  178. return createJsonRpcErrorResponse(-32601, "Method not found.", id);
  179. }
  180. A2_LOG_INFO(fmt("Executing RPC method %s", req.methodName.c_str()));
  181. rpc::RpcResponse res = method->execute(req, e_);
  182. return res;
  183. }
  184. bool HttpServerBodyCommand::execute()
  185. {
  186. if(e_->getRequestGroupMan()->downloadFinished() || e_->isHaltRequested()) {
  187. return true;
  188. }
  189. try {
  190. if(socket_->isReadable(0) ||
  191. !httpServer_->getSocketRecvBuffer()->bufferEmpty() ||
  192. httpServer_->getContentLength() == 0) {
  193. timeoutTimer_ = global::wallclock;
  194. if(httpServer_->receiveBody()) {
  195. std::string reqPath = httpServer_->getRequestPath();
  196. reqPath.erase(std::find(reqPath.begin(), reqPath.end(), '#'),
  197. reqPath.end());
  198. std::string query(std::find(reqPath.begin(), reqPath.end(), '?'),
  199. reqPath.end());
  200. reqPath.erase(reqPath.size()-query.size(), query.size());
  201. // Do something for requestpath and body
  202. if(reqPath == "/rpc") {
  203. #ifdef ENABLE_XML_RPC
  204. rpc::RpcRequest req =
  205. rpc::XmlRpcRequestProcessor().parseMemory(httpServer_->getBody());
  206. SharedHandle<rpc::RpcMethod> method =
  207. rpc::RpcMethodFactory::create(req.methodName);
  208. A2_LOG_INFO(fmt("Executing RPC method %s", req.methodName.c_str()));
  209. rpc::RpcResponse res = method->execute(req, e_);
  210. bool gzip = httpServer_->supportsGZip();
  211. std::string responseData = res.toXml(gzip);
  212. httpServer_->feedResponse(responseData, "text/xml");
  213. addHttpServerResponseCommand();
  214. #endif // ENABLE_XML_RPC
  215. return true;
  216. } else if(reqPath == "/jsonrpc") {
  217. std::string callback;
  218. SharedHandle<ValueBase> json;
  219. try {
  220. if(httpServer_->getMethod() == "GET") {
  221. json::JsonGetParam param = json::decodeGetParams(query);
  222. callback = param.callback;
  223. json = json::decode(param.request);
  224. } else {
  225. json = json::decode(httpServer_->getBody());
  226. }
  227. } catch(RecoverableException& e) {
  228. A2_LOG_INFO_EX
  229. (fmt("CUID#%lld - Failed to parse JSON-RPC request",
  230. getCuid()),
  231. e);
  232. rpc::RpcResponse res
  233. (createJsonRpcErrorResponse(-32700, "Parse error.", Null::g()));
  234. sendJsonRpcResponse(res, callback);
  235. return true;
  236. }
  237. const Dict* jsondict = asDict(json);
  238. if(jsondict) {
  239. rpc::RpcResponse res = processJsonRpcRequest(jsondict);
  240. sendJsonRpcResponse(res, callback);
  241. } else {
  242. const List* jsonlist = asList(json);
  243. if(jsonlist) {
  244. // This is batch call
  245. std::vector<rpc::RpcResponse> results;
  246. for(List::ValueType::const_iterator i = jsonlist->begin(),
  247. eoi = jsonlist->end(); i != eoi; ++i) {
  248. const Dict* jsondict = asDict(*i);
  249. if(jsondict) {
  250. rpc::RpcResponse r = processJsonRpcRequest(jsondict);
  251. results.push_back(r);
  252. }
  253. }
  254. sendJsonRpcBatchResponse(results, callback);
  255. } else {
  256. rpc::RpcResponse res
  257. (createJsonRpcErrorResponse
  258. (-32600, "Invalid Request.", Null::g()));
  259. sendJsonRpcResponse(res, callback);
  260. }
  261. }
  262. return true;
  263. } else {
  264. return true;
  265. }
  266. } else {
  267. e_->addCommand(this);
  268. return false;
  269. }
  270. } else {
  271. if(timeoutTimer_.difference(global::wallclock) >= 30) {
  272. A2_LOG_INFO("HTTP request body timeout.");
  273. return true;
  274. } else {
  275. e_->addCommand(this);
  276. return false;
  277. }
  278. }
  279. } catch(RecoverableException& e) {
  280. A2_LOG_INFO_EX
  281. (fmt("CUID#%lld - Error occurred while reading HTTP request body",
  282. getCuid()),
  283. e);
  284. return true;
  285. }
  286. }
  287. } // namespace aria2