WebSocketSession.cc 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2012 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 "WebSocketSession.h"
  36. #include <cerrno>
  37. #include <cstring>
  38. #include <cassert>
  39. #include "SocketCore.h"
  40. #include "LogFactory.h"
  41. #include "RecoverableException.h"
  42. #include "message.h"
  43. #include "DownloadEngine.h"
  44. #include "DelayedCommand.h"
  45. #include "WebSocketInteractionCommand.h"
  46. #include "rpc_helper.h"
  47. #include "RpcResponse.h"
  48. #include "json.h"
  49. #include "prefs.h"
  50. #include "Option.h"
  51. namespace aria2 {
  52. namespace rpc {
  53. namespace {
  54. ssize_t sendCallback(wslay_event_context_ptr wsctx,
  55. const uint8_t* data, size_t len, int flags,
  56. void* userData)
  57. {
  58. WebSocketSession* session = reinterpret_cast<WebSocketSession*>(userData);
  59. const std::shared_ptr<SocketCore>& socket = session->getSocket();
  60. try {
  61. ssize_t r = socket->writeData(data, len);
  62. if(r == 0) {
  63. if(socket->wantRead() || socket->wantWrite()) {
  64. wslay_event_set_error(wsctx, WSLAY_ERR_WOULDBLOCK);
  65. } else {
  66. wslay_event_set_error(wsctx, WSLAY_ERR_CALLBACK_FAILURE);
  67. }
  68. r = -1;
  69. }
  70. return r;
  71. } catch(RecoverableException& e) {
  72. A2_LOG_DEBUG_EX(EX_EXCEPTION_CAUGHT, e);
  73. wslay_event_set_error(wsctx, WSLAY_ERR_CALLBACK_FAILURE);
  74. return -1;
  75. }
  76. }
  77. } // namespace
  78. namespace {
  79. ssize_t recvCallback(wslay_event_context_ptr wsctx,
  80. uint8_t* buf, size_t len, int flags,
  81. void* userData)
  82. {
  83. WebSocketSession* session = reinterpret_cast<WebSocketSession*>(userData);
  84. const std::shared_ptr<SocketCore>& socket = session->getSocket();
  85. try {
  86. ssize_t r;
  87. socket->readData(buf, len);
  88. if(len == 0) {
  89. if(socket->wantRead() || socket->wantWrite()) {
  90. wslay_event_set_error(wsctx, WSLAY_ERR_WOULDBLOCK);
  91. } else {
  92. wslay_event_set_error(wsctx, WSLAY_ERR_CALLBACK_FAILURE);
  93. }
  94. r = -1;
  95. } else {
  96. r = len;
  97. }
  98. return r;
  99. } catch(RecoverableException& e) {
  100. A2_LOG_DEBUG_EX(EX_EXCEPTION_CAUGHT, e);
  101. wslay_event_set_error(wsctx, WSLAY_ERR_CALLBACK_FAILURE);
  102. return -1;
  103. }
  104. }
  105. } // namespace
  106. namespace {
  107. void addResponse(WebSocketSession* wsSession, const RpcResponse& res)
  108. {
  109. bool notauthorized = rpc::not_authorized(res);
  110. std::string response = toJson(res, "", false);
  111. wsSession->addTextMessage(response, notauthorized);
  112. }
  113. } // namespace
  114. namespace {
  115. void addResponse(WebSocketSession* wsSession,
  116. const std::vector<RpcResponse>& results)
  117. {
  118. bool notauthorized = rpc::any_not_authorized(results.begin(), results.end());
  119. std::string response = toJsonBatch(results, "", false);
  120. wsSession->addTextMessage(response, notauthorized);
  121. }
  122. } // namespace
  123. namespace {
  124. void onFrameRecvStartCallback
  125. (wslay_event_context_ptr wsctx,
  126. const struct wslay_event_on_frame_recv_start_arg* arg,
  127. void* userData)
  128. {
  129. WebSocketSession* wsSession = reinterpret_cast<WebSocketSession*>(userData);
  130. wsSession->setIgnorePayload(wslay_is_ctrl_frame(arg->opcode));
  131. }
  132. } // namespace
  133. namespace {
  134. void onFrameRecvChunkCallback
  135. (wslay_event_context_ptr wsctx,
  136. const struct wslay_event_on_frame_recv_chunk_arg* arg,
  137. void* userData)
  138. {
  139. WebSocketSession* wsSession = reinterpret_cast<WebSocketSession*>(userData);
  140. if(!wsSession->getIgnorePayload()) {
  141. // The return value is ignored here. It will be evaluated in
  142. // onMsgRecvCallback.
  143. wsSession->parseUpdate(arg->data, arg->data_length);
  144. }
  145. }
  146. } // namespace
  147. namespace {
  148. void onMsgRecvCallback(wslay_event_context_ptr wsctx,
  149. const struct wslay_event_on_msg_recv_arg* arg,
  150. void* userData)
  151. {
  152. WebSocketSession* wsSession = reinterpret_cast<WebSocketSession*>(userData);
  153. if(!wslay_is_ctrl_frame(arg->opcode)) {
  154. // TODO Only process text frame
  155. ssize_t error = 0;
  156. auto json = wsSession->parseFinal(nullptr, 0, error);
  157. auto preauthorized = RpcRequest::MUST_AUTHORIZE;
  158. if(error < 0) {
  159. A2_LOG_INFO("Failed to parse JSON-RPC request");
  160. RpcResponse res
  161. (createJsonRpcErrorResponse(-32700, "Parse error.", Null::g()));
  162. addResponse(wsSession, res);
  163. return;
  164. }
  165. Dict* jsondict = downcast<Dict>(json);
  166. auto e = wsSession->getDownloadEngine();
  167. if(jsondict) {
  168. RpcResponse res =
  169. processJsonRpcRequest(jsondict, e, preauthorized);
  170. addResponse(wsSession, res);
  171. } else {
  172. List* jsonlist = downcast<List>(json);
  173. if(jsonlist) {
  174. // This is batch call
  175. std::vector<RpcResponse> results;
  176. for(List::ValueType::const_iterator i = jsonlist->begin(),
  177. eoi = jsonlist->end(); i != eoi; ++i) {
  178. Dict* jsondict = downcast<Dict>(*i);
  179. if (jsondict) {
  180. auto resp = processJsonRpcRequest(jsondict, e, preauthorized);
  181. if (resp.code == 0) {
  182. preauthorized = RpcRequest::PREAUTHORIZED;
  183. }
  184. results.push_back(std::move(resp));
  185. }
  186. }
  187. addResponse(wsSession, results);
  188. } else {
  189. RpcResponse res(createJsonRpcErrorResponse
  190. (-32600, "Invalid Request.", Null::g()));
  191. addResponse(wsSession, res);
  192. }
  193. }
  194. } else {
  195. RpcResponse res(createJsonRpcErrorResponse
  196. (-32600, "Invalid Request.", Null::g()));
  197. addResponse(wsSession, res);
  198. }
  199. }
  200. } // namespace
  201. WebSocketSession::WebSocketSession(const std::shared_ptr<SocketCore>& socket,
  202. DownloadEngine* e)
  203. : socket_(socket),
  204. e_(e),
  205. ignorePayload_(false),
  206. receivedLength_(0)
  207. {
  208. wslay_event_callbacks callbacks;
  209. memset(&callbacks, 0, sizeof(wslay_event_callbacks));
  210. callbacks.recv_callback = recvCallback;
  211. callbacks.send_callback = sendCallback;
  212. callbacks.on_msg_recv_callback = onMsgRecvCallback;
  213. callbacks.on_frame_recv_start_callback = onFrameRecvStartCallback;
  214. callbacks.on_frame_recv_chunk_callback = onFrameRecvChunkCallback;
  215. int r = wslay_event_context_server_init(&wsctx_, &callbacks, this);
  216. assert(r == 0);
  217. wslay_event_config_set_no_buffering(wsctx_, 1);
  218. }
  219. WebSocketSession::~WebSocketSession()
  220. {
  221. wslay_event_context_free(wsctx_);
  222. }
  223. bool WebSocketSession::wantRead()
  224. {
  225. return wslay_event_want_read(wsctx_);
  226. }
  227. bool WebSocketSession::wantWrite()
  228. {
  229. return wslay_event_want_write(wsctx_);
  230. }
  231. bool WebSocketSession::finish()
  232. {
  233. return !wantRead() && !wantWrite();
  234. }
  235. int WebSocketSession::onReadEvent()
  236. {
  237. if(wslay_event_recv(wsctx_) == 0) {
  238. return 0;
  239. } else {
  240. return -1;
  241. }
  242. }
  243. int WebSocketSession::onWriteEvent()
  244. {
  245. if(wslay_event_send(wsctx_) == 0) {
  246. return 0;
  247. } else {
  248. return -1;
  249. }
  250. }
  251. namespace {
  252. class TextMessageCommand : public Command
  253. {
  254. private:
  255. std::shared_ptr<WebSocketSession> session_;
  256. const std::string msg_;
  257. public:
  258. TextMessageCommand(cuid_t cuid, std::shared_ptr<WebSocketSession> session,
  259. const std::string& msg)
  260. : Command(cuid), session_{std::move(session)}, msg_{msg}
  261. {}
  262. virtual bool execute() CXX11_OVERRIDE
  263. {
  264. session_->addTextMessage(msg_, false);
  265. return true;
  266. }
  267. };
  268. } // namespace
  269. void WebSocketSession::addTextMessage(const std::string& msg, bool delayed)
  270. {
  271. if (delayed) {
  272. auto e = getDownloadEngine();
  273. auto cuid = command_->getCuid();
  274. auto c = make_unique<TextMessageCommand>(cuid, command_->getSession(), msg);
  275. e->addCommand(make_unique<DelayedCommand>(cuid, e, 1, std::move(c), false));
  276. return;
  277. }
  278. // TODO Don't add text message if the size of outbound queue in
  279. // wsctx_ exceeds certain limit.
  280. wslay_event_msg arg = {
  281. WSLAY_TEXT_FRAME, reinterpret_cast<const uint8_t*>(msg.c_str()), msg.size()
  282. };
  283. wslay_event_queue_msg(wsctx_, &arg);
  284. }
  285. bool WebSocketSession::closeReceived()
  286. {
  287. return wslay_event_get_close_received(wsctx_);
  288. }
  289. bool WebSocketSession::closeSent()
  290. {
  291. return wslay_event_get_close_sent(wsctx_);
  292. }
  293. ssize_t WebSocketSession::parseUpdate(const uint8_t* data, size_t len)
  294. {
  295. // Cap the number of bytes to feed the parser
  296. size_t maxlen = e_->getOption()->getAsInt(PREF_RPC_MAX_REQUEST_SIZE);
  297. if(receivedLength_ + len <= maxlen) {
  298. receivedLength_ += len;
  299. } else {
  300. len = 0;
  301. }
  302. return parser_.parseUpdate(reinterpret_cast<const char*>(data), len);
  303. }
  304. std::unique_ptr<ValueBase> WebSocketSession::parseFinal
  305. (const uint8_t* data, size_t len, ssize_t& error)
  306. {
  307. auto res =
  308. parser_.parseFinal(reinterpret_cast<const char*>(data), len, error);
  309. receivedLength_ = 0;
  310. return res;
  311. }
  312. } // namespace rpc
  313. } // namespace aria2