WebSocketSession.cc 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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. if(error < 0) {
  158. A2_LOG_INFO("Failed to parse JSON-RPC request");
  159. RpcResponse res
  160. (createJsonRpcErrorResponse(-32700, "Parse error.", Null::g()));
  161. addResponse(wsSession, res);
  162. return;
  163. }
  164. Dict* jsondict = downcast<Dict>(json);
  165. auto e = wsSession->getDownloadEngine();
  166. if(jsondict) {
  167. RpcResponse res =
  168. processJsonRpcRequest(jsondict, e);
  169. addResponse(wsSession, res);
  170. } else {
  171. List* jsonlist = downcast<List>(json);
  172. if(jsonlist) {
  173. // This is batch call
  174. std::vector<RpcResponse> results;
  175. for(List::ValueType::const_iterator i = jsonlist->begin(),
  176. eoi = jsonlist->end(); i != eoi; ++i) {
  177. Dict* jsondict = downcast<Dict>(*i);
  178. if (jsondict) {
  179. auto resp = processJsonRpcRequest(jsondict, e);
  180. results.push_back(std::move(resp));
  181. }
  182. }
  183. addResponse(wsSession, results);
  184. } else {
  185. RpcResponse res(createJsonRpcErrorResponse
  186. (-32600, "Invalid Request.", Null::g()));
  187. addResponse(wsSession, res);
  188. }
  189. }
  190. } else {
  191. RpcResponse res(createJsonRpcErrorResponse
  192. (-32600, "Invalid Request.", Null::g()));
  193. addResponse(wsSession, res);
  194. }
  195. }
  196. } // namespace
  197. WebSocketSession::WebSocketSession(const std::shared_ptr<SocketCore>& socket,
  198. DownloadEngine* e)
  199. : socket_(socket),
  200. e_(e),
  201. ignorePayload_(false),
  202. receivedLength_(0),
  203. command_(nullptr)
  204. {
  205. wslay_event_callbacks callbacks;
  206. memset(&callbacks, 0, sizeof(wslay_event_callbacks));
  207. callbacks.recv_callback = recvCallback;
  208. callbacks.send_callback = sendCallback;
  209. callbacks.on_msg_recv_callback = onMsgRecvCallback;
  210. callbacks.on_frame_recv_start_callback = onFrameRecvStartCallback;
  211. callbacks.on_frame_recv_chunk_callback = onFrameRecvChunkCallback;
  212. int r = wslay_event_context_server_init(&wsctx_, &callbacks, this);
  213. assert(r == 0);
  214. wslay_event_config_set_no_buffering(wsctx_, 1);
  215. }
  216. WebSocketSession::~WebSocketSession()
  217. {
  218. wslay_event_context_free(wsctx_);
  219. }
  220. bool WebSocketSession::wantRead()
  221. {
  222. return wslay_event_want_read(wsctx_);
  223. }
  224. bool WebSocketSession::wantWrite()
  225. {
  226. return wslay_event_want_write(wsctx_);
  227. }
  228. bool WebSocketSession::finish()
  229. {
  230. return !wantRead() && !wantWrite();
  231. }
  232. int WebSocketSession::onReadEvent()
  233. {
  234. if(wslay_event_recv(wsctx_) == 0) {
  235. return 0;
  236. } else {
  237. return -1;
  238. }
  239. }
  240. int WebSocketSession::onWriteEvent()
  241. {
  242. if(wslay_event_send(wsctx_) == 0) {
  243. return 0;
  244. } else {
  245. return -1;
  246. }
  247. }
  248. namespace {
  249. class TextMessageCommand : public Command
  250. {
  251. private:
  252. std::shared_ptr<WebSocketSession> session_;
  253. const std::string msg_;
  254. public:
  255. TextMessageCommand(cuid_t cuid, std::shared_ptr<WebSocketSession> session,
  256. const std::string& msg)
  257. : Command(cuid), session_{std::move(session)}, msg_{msg}
  258. {}
  259. virtual bool execute() CXX11_OVERRIDE
  260. {
  261. session_->addTextMessage(msg_, false);
  262. return true;
  263. }
  264. };
  265. } // namespace
  266. void WebSocketSession::addTextMessage(const std::string& msg, bool delayed)
  267. {
  268. if (delayed) {
  269. auto e = getDownloadEngine();
  270. auto cuid = command_->getCuid();
  271. auto c = make_unique<TextMessageCommand>(cuid, command_->getSession(), msg);
  272. e->addCommand(make_unique<DelayedCommand>(cuid, e, 1, std::move(c), false));
  273. return;
  274. }
  275. // TODO Don't add text message if the size of outbound queue in
  276. // wsctx_ exceeds certain limit.
  277. wslay_event_msg arg = {
  278. WSLAY_TEXT_FRAME, reinterpret_cast<const uint8_t*>(msg.c_str()), msg.size()
  279. };
  280. wslay_event_queue_msg(wsctx_, &arg);
  281. }
  282. bool WebSocketSession::closeReceived()
  283. {
  284. return wslay_event_get_close_received(wsctx_);
  285. }
  286. bool WebSocketSession::closeSent()
  287. {
  288. return wslay_event_get_close_sent(wsctx_);
  289. }
  290. ssize_t WebSocketSession::parseUpdate(const uint8_t* data, size_t len)
  291. {
  292. // Cap the number of bytes to feed the parser
  293. size_t maxlen = e_->getOption()->getAsInt(PREF_RPC_MAX_REQUEST_SIZE);
  294. if(receivedLength_ + len <= maxlen) {
  295. receivedLength_ += len;
  296. } else {
  297. len = 0;
  298. }
  299. return parser_.parseUpdate(reinterpret_cast<const char*>(data), len);
  300. }
  301. std::unique_ptr<ValueBase> WebSocketSession::parseFinal
  302. (const uint8_t* data, size_t len, ssize_t& error)
  303. {
  304. auto res =
  305. parser_.parseFinal(reinterpret_cast<const char*>(data), len, error);
  306. receivedLength_ = 0;
  307. return res;
  308. }
  309. } // namespace rpc
  310. } // namespace aria2