HttpServerBodyCommand.cc 11 KB

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