File: WebSocketSession.cc

package info (click to toggle)
aria2 1.18.8-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 19,392 kB
  • ctags: 16,036
  • sloc: cpp: 115,823; sh: 12,015; ansic: 7,394; makefile: 1,445; ruby: 462; python: 216; xml: 176; asm: 58; sed: 16
file content (337 lines) | stat: -rw-r--r-- 9,880 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
/* <!-- copyright */
/*
 * aria2 - The high speed download utility
 *
 * Copyright (C) 2012 Tatsuhiro Tsujikawa
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 *
 * In addition, as a special exception, the copyright holders give
 * permission to link the code of portions of this program with the
 * OpenSSL library under certain conditions as described in each
 * individual source file, and distribute linked combinations
 * including the two.
 * You must obey the GNU General Public License in all respects
 * for all of the code used other than OpenSSL.  If you modify
 * file(s) with this exception, you may extend this exception to your
 * version of the file(s), but you are not obligated to do so.  If you
 * do not wish to do so, delete this exception statement from your
 * version.  If you delete this exception statement from all source
 * files in the program, then also delete it here.
 */
/* copyright --> */
#include "WebSocketSession.h"

#include <cerrno>
#include <cstring>
#include <cassert>

#include "SocketCore.h"
#include "LogFactory.h"
#include "RecoverableException.h"
#include "message.h"
#include "DownloadEngine.h"
#include "DelayedCommand.h"
#include "WebSocketInteractionCommand.h"
#include "rpc_helper.h"
#include "RpcResponse.h"
#include "json.h"
#include "prefs.h"
#include "Option.h"

namespace aria2 {

namespace rpc {

namespace {
ssize_t sendCallback(wslay_event_context_ptr wsctx,
                      const uint8_t* data, size_t len, int flags,
                      void* userData)
{
  WebSocketSession* session = reinterpret_cast<WebSocketSession*>(userData);
  const std::shared_ptr<SocketCore>& socket = session->getSocket();
  try {
    ssize_t r = socket->writeData(data, len);
    if(r == 0) {
      if(socket->wantRead() || socket->wantWrite()) {
        wslay_event_set_error(wsctx, WSLAY_ERR_WOULDBLOCK);
      } else {
        wslay_event_set_error(wsctx, WSLAY_ERR_CALLBACK_FAILURE);
      }
      r = -1;
    }
    return r;
  } catch(RecoverableException& e) {
    A2_LOG_DEBUG_EX(EX_EXCEPTION_CAUGHT, e);
    wslay_event_set_error(wsctx, WSLAY_ERR_CALLBACK_FAILURE);
    return -1;
  }
}
} // namespace

namespace {
ssize_t recvCallback(wslay_event_context_ptr wsctx,
                     uint8_t* buf, size_t len, int flags,
                     void* userData)
{
  WebSocketSession* session = reinterpret_cast<WebSocketSession*>(userData);
  const std::shared_ptr<SocketCore>& socket = session->getSocket();
  try {
    ssize_t r;
    socket->readData(buf, len);
    if(len == 0) {
      if(socket->wantRead() || socket->wantWrite()) {
        wslay_event_set_error(wsctx, WSLAY_ERR_WOULDBLOCK);
      } else {
        wslay_event_set_error(wsctx, WSLAY_ERR_CALLBACK_FAILURE);
      }
      r = -1;
    } else {
      r = len;
    }
    return r;
  } catch(RecoverableException& e) {
    A2_LOG_DEBUG_EX(EX_EXCEPTION_CAUGHT, e);
    wslay_event_set_error(wsctx, WSLAY_ERR_CALLBACK_FAILURE);
    return -1;
  }
}
} // namespace

namespace {
void addResponse(WebSocketSession* wsSession, const RpcResponse& res)
{
  bool notauthorized = rpc::not_authorized(res);
  std::string response = toJson(res, "", false);
  wsSession->addTextMessage(response, notauthorized);
}
} // namespace

namespace {
void addResponse(WebSocketSession* wsSession,
                 const std::vector<RpcResponse>& results)
{
  bool notauthorized = rpc::any_not_authorized(results.begin(), results.end());
  std::string response = toJsonBatch(results, "", false);
  wsSession->addTextMessage(response, notauthorized);
}
} // namespace

namespace {
void onFrameRecvStartCallback
(wslay_event_context_ptr wsctx,
 const struct wslay_event_on_frame_recv_start_arg* arg,
 void* userData)
{
  WebSocketSession* wsSession = reinterpret_cast<WebSocketSession*>(userData);
  wsSession->setIgnorePayload(wslay_is_ctrl_frame(arg->opcode));
}
} // namespace

namespace {
void onFrameRecvChunkCallback
(wslay_event_context_ptr wsctx,
 const struct wslay_event_on_frame_recv_chunk_arg* arg,
 void* userData)
{
  WebSocketSession* wsSession = reinterpret_cast<WebSocketSession*>(userData);
  if(!wsSession->getIgnorePayload()) {
    // The return value is ignored here. It will be evaluated in
    // onMsgRecvCallback.
    wsSession->parseUpdate(arg->data, arg->data_length);
  }
}
} // namespace

namespace {
void onMsgRecvCallback(wslay_event_context_ptr wsctx,
                       const struct wslay_event_on_msg_recv_arg* arg,
                       void* userData)
{
  WebSocketSession* wsSession = reinterpret_cast<WebSocketSession*>(userData);
  if(!wslay_is_ctrl_frame(arg->opcode)) {
    // TODO Only process text frame
    ssize_t error = 0;
    auto json = wsSession->parseFinal(nullptr, 0, error);
    if(error < 0) {
      A2_LOG_INFO("Failed to parse JSON-RPC request");
      RpcResponse res
        (createJsonRpcErrorResponse(-32700, "Parse error.", Null::g()));
      addResponse(wsSession, res);
      return;
    }
    Dict* jsondict = downcast<Dict>(json);
    auto e = wsSession->getDownloadEngine();
    if(jsondict) {
      RpcResponse res =
        processJsonRpcRequest(jsondict, e);
      addResponse(wsSession, res);
    } else {
      List* jsonlist = downcast<List>(json);
      if(jsonlist) {
        // This is batch call
        std::vector<RpcResponse> results;
        for(List::ValueType::const_iterator i = jsonlist->begin(),
              eoi = jsonlist->end(); i != eoi; ++i) {
          Dict* jsondict = downcast<Dict>(*i);
          if (jsondict) {
            auto resp = processJsonRpcRequest(jsondict, e);
            results.push_back(std::move(resp));
          }
        }
        addResponse(wsSession, results);
      } else {
        RpcResponse res(createJsonRpcErrorResponse
                        (-32600, "Invalid Request.", Null::g()));
        addResponse(wsSession, res);
      }
    }
  } else {
    RpcResponse res(createJsonRpcErrorResponse
                    (-32600, "Invalid Request.", Null::g()));
    addResponse(wsSession, res);
  }
}
} // namespace

WebSocketSession::WebSocketSession(const std::shared_ptr<SocketCore>& socket,
                                   DownloadEngine* e)
  : socket_(socket),
    e_(e),
    ignorePayload_(false),
    receivedLength_(0)
{
  wslay_event_callbacks callbacks;
  memset(&callbacks, 0, sizeof(wslay_event_callbacks));
  callbacks.recv_callback = recvCallback;
  callbacks.send_callback = sendCallback;
  callbacks.on_msg_recv_callback = onMsgRecvCallback;
  callbacks.on_frame_recv_start_callback = onFrameRecvStartCallback;
  callbacks.on_frame_recv_chunk_callback = onFrameRecvChunkCallback;

  int r = wslay_event_context_server_init(&wsctx_, &callbacks, this);
  assert(r == 0);
  wslay_event_config_set_no_buffering(wsctx_, 1);
}

WebSocketSession::~WebSocketSession()
{
  wslay_event_context_free(wsctx_);
}

bool WebSocketSession::wantRead()
{
  return wslay_event_want_read(wsctx_);
}

bool WebSocketSession::wantWrite()
{
  return wslay_event_want_write(wsctx_);
}

bool WebSocketSession::finish()
{
  return !wantRead() && !wantWrite();
}

int WebSocketSession::onReadEvent()
{
  if(wslay_event_recv(wsctx_) == 0) {
    return 0;
  } else {
    return -1;
  }
}

int WebSocketSession::onWriteEvent()
{
  if(wslay_event_send(wsctx_) == 0) {
    return 0;
  } else {
    return -1;
  }
}

namespace {
class TextMessageCommand : public Command
{
private:
  std::shared_ptr<WebSocketSession> session_;
  const std::string msg_;
public:
  TextMessageCommand(cuid_t cuid, std::shared_ptr<WebSocketSession> session,
                            const std::string& msg)
    : Command(cuid), session_{std::move(session)}, msg_{msg}
  {}
  virtual bool execute() CXX11_OVERRIDE
  {
    session_->addTextMessage(msg_, false);
    return true;
  }
};
} // namespace

void WebSocketSession::addTextMessage(const std::string& msg, bool delayed)
{
  if (delayed) {
    auto e = getDownloadEngine();
    auto cuid = command_->getCuid();
    auto c = make_unique<TextMessageCommand>(cuid, command_->getSession(), msg);
    e->addCommand(make_unique<DelayedCommand>(cuid, e, 1, std::move(c), false));
    return;
  }

  // TODO Don't add text message if the size of outbound queue in
  // wsctx_ exceeds certain limit.
  wslay_event_msg arg = {
    WSLAY_TEXT_FRAME, reinterpret_cast<const uint8_t*>(msg.c_str()), msg.size()
  };
  wslay_event_queue_msg(wsctx_, &arg);
}

bool WebSocketSession::closeReceived()
{
  return wslay_event_get_close_received(wsctx_);
}

bool WebSocketSession::closeSent()
{
  return wslay_event_get_close_sent(wsctx_);
}

ssize_t WebSocketSession::parseUpdate(const uint8_t* data, size_t len)
{
  // Cap the number of bytes to feed the parser
  size_t maxlen = e_->getOption()->getAsInt(PREF_RPC_MAX_REQUEST_SIZE);
  if(receivedLength_ + len <= maxlen) {
    receivedLength_ += len;
  } else {
    len = 0;
  }
  return parser_.parseUpdate(reinterpret_cast<const char*>(data), len);
}

std::unique_ptr<ValueBase> WebSocketSession::parseFinal
(const uint8_t* data, size_t len, ssize_t& error)
{
  auto res =
    parser_.parseFinal(reinterpret_cast<const char*>(data), len, error);
  receivedLength_ = 0;
  return res;
}

} // namespace rpc

} // namespace aria2