WebSocketSession.cc 8.8 KB

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