blob: d48d70070e4911624a089753ce8ffe0bd6de70d7 [file] [log] [blame]
Alex Perryb3b50792020-01-18 16:13:45 -08001#include "aos/network/web_proxy.h"
Alex Perry5f474f22020-02-01 12:14:24 -08002
Philipp Schrader790cb542023-07-05 21:06:52 -07003#include "glog/logging.h"
4
Alex Perry5f474f22020-02-01 12:14:24 -08005#include "aos/flatbuffer_merge.h"
6#include "aos/network/connect_generated.h"
Alex Perryb3b50792020-01-18 16:13:45 -08007#include "aos/network/web_proxy_generated.h"
Alex Perry5f474f22020-02-01 12:14:24 -08008#include "aos/network/web_proxy_utils.h"
James Kuszmaul71a81932020-12-15 21:08:01 -08009#include "aos/seasocks/seasocks_logger.h"
James Kuszmaul48671362020-12-24 13:54:16 -080010#include "internal/Embedded.h"
Alex Perryb3b50792020-01-18 16:13:45 -080011
Austin Schuh52e5e3a2021-04-24 22:30:02 -070012extern "C" {
13#include <rawrtc.h>
14
15#define DEBUG_LEVEL 7
16#define DEBUG_MODULE "web-proxy"
17#include <re_dbg.h>
18struct list *tmrl_get(void);
19}
20
Austin Schuhbbc3df32021-10-29 23:06:39 -070021DEFINE_int32(proxy_port, 1180, "Port to use for the web proxy server.");
James Kuszmaula5822682021-12-23 18:39:28 -080022DEFINE_int32(pre_send_messages, 10000,
23 "Number of messages / queue to send to a client before waiting on "
24 "confirmation that the initial message was received. If set to "
25 "-1, will not throttle messages at all. This prevents a situation "
26 "where, when run on localhost, the large number of WebRTC packets "
27 "can overwhelm the browser and crash the webpage.");
James Kuszmaule524ed02023-12-09 13:21:03 -080028// Note: sometimes it appears that WebRTC buffer up and stop sending message
29// ack's back from the client page. It is not clear *why* WebRTC is doing this,
30// but since the only reason we use those ack's is to stop ourselves from
31// overloading the client webpage, this setting lets us fall back to just a
32// time-based rate-limit when we stop receiving acks.
33DEFINE_double(max_buffer_pause_sec, 0.1,
34 "If we have not received any ack's in this amount of time, we "
35 "start to continue sending messages.");
James Kuszmaul1e95bed2021-01-09 21:02:49 -080036
Alex Perryb3b50792020-01-18 16:13:45 -080037namespace aos {
38namespace web_proxy {
James Kuszmaul7ad91522020-09-01 19:15:35 -070039WebsocketHandler::WebsocketHandler(::seasocks::Server *server,
James Kuszmaul1a29c082022-02-03 14:02:47 -080040 aos::EventLoop *event_loop,
41 StoreHistory store_history,
42 int per_channel_buffer_size_bytes)
James Kuszmaul7ad91522020-09-01 19:15:35 -070043 : server_(server),
James Kuszmaul71a81932020-12-15 21:08:01 -080044 config_(aos::CopyFlatBuffer(event_loop->configuration())),
45 event_loop_(event_loop) {
Austin Schuh52e5e3a2021-04-24 22:30:02 -070046 if (VLOG_IS_ON(2)) {
47 dbg_init(DBG_DEBUG, DBG_ALL);
48 }
49 CHECK_RAWRTC(rawrtc_init(true));
50
James Kuszmaul48671362020-12-24 13:54:16 -080051 // We need to reference findEmbeddedContent() to make the linker happy...
52 findEmbeddedContent("");
Austin Schuh52e5e3a2021-04-24 22:30:02 -070053 const aos::Node *self = event_loop_->node();
James Kuszmaul7ad91522020-09-01 19:15:35 -070054
Austin Schuh52e5e3a2021-04-24 22:30:02 -070055 subscribers_.reserve(event_loop_->configuration()->channels()->size());
56 for (uint i = 0; i < event_loop_->configuration()->channels()->size(); ++i) {
57 auto channel = event_loop_->configuration()->channels()->Get(i);
James Kuszmaul7ad91522020-09-01 19:15:35 -070058 if (aos::configuration::ChannelIsReadableOnNode(channel, self)) {
Austin Schuh52e5e3a2021-04-24 22:30:02 -070059 auto fetcher = event_loop_->MakeRawFetcher(channel);
James Kuszmaul71a81932020-12-15 21:08:01 -080060 subscribers_.emplace_back(std::make_unique<aos::web_proxy::Subscriber>(
James Kuszmaul1a29c082022-02-03 14:02:47 -080061 std::move(fetcher), i, store_history,
62 per_channel_buffer_size_bytes < 0
63 ? -1
64 : per_channel_buffer_size_bytes / channel->max_size()));
Austin Schuh52e5e3a2021-04-24 22:30:02 -070065 } else {
66 subscribers_.emplace_back(nullptr);
James Kuszmaul7ad91522020-09-01 19:15:35 -070067 }
68 }
Austin Schuh52e5e3a2021-04-24 22:30:02 -070069 TimerHandler *const timer = event_loop_->AddTimer([this]() {
James Kuszmaul7ad91522020-09-01 19:15:35 -070070 for (auto &subscriber : subscribers_) {
James Kuszmaul147b4c12022-07-13 20:35:27 -070071 if (subscriber) subscriber->RunIteration(recording_);
James Kuszmaul7ad91522020-09-01 19:15:35 -070072 }
73 });
74
Austin Schuh52e5e3a2021-04-24 22:30:02 -070075 event_loop_->OnRun([this, timer]() {
Philipp Schradera6712522023-07-05 20:25:11 -070076 timer->Schedule(event_loop_->monotonic_now(),
77 std::chrono::milliseconds(100));
James Kuszmaul7ad91522020-09-01 19:15:35 -070078 });
79}
Alex Perryb3b50792020-01-18 16:13:45 -080080
81void WebsocketHandler::onConnect(::seasocks::WebSocket *sock) {
Austin Schuh52e5e3a2021-04-24 22:30:02 -070082 std::unique_ptr<ApplicationConnection> connection =
83 std::make_unique<ApplicationConnection>(server_, sock, subscribers_,
84 config_, event_loop_);
85
86 connections_.insert({sock, std::move(connection)});
Alex Perryb3b50792020-01-18 16:13:45 -080087}
88
89void WebsocketHandler::onData(::seasocks::WebSocket *sock, const uint8_t *data,
90 size_t size) {
Austin Schuh52e5e3a2021-04-24 22:30:02 -070091 const FlatbufferSpan<WebSocketMessage> message({data, size});
92 if (!message.Verify()) {
93 LOG(ERROR) << "Invalid WebsocketMessage received from browser.";
94 return;
95 }
96 VLOG(1) << "Got msg " << aos::FlatbufferToJson(message);
97 switch (message.message().payload_type()) {
98 case Payload::WebSocketSdp: {
99 const WebSocketSdp *offer = message.message().payload_as_WebSocketSdp();
100 if (offer->type() != SdpType::OFFER) {
101 LOG(WARNING) << "Got the wrong sdp type from client";
102 break;
103 }
104 const flatbuffers::String *sdp = offer->payload();
105 connections_[sock]->OnSdp(sdp->c_str());
106 break;
107 }
108 case Payload::WebSocketIce: {
109 const WebSocketIce *ice = message.message().payload_as_WebSocketIce();
110 connections_[sock]->OnIce(ice);
111 break;
112 }
Brian Silverman225c5072021-11-17 19:56:31 -0800113 default: {
114 break;
115 }
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700116 }
Alex Perryb3b50792020-01-18 16:13:45 -0800117}
118
119void WebsocketHandler::onDisconnect(::seasocks::WebSocket *sock) {
120 connections_.erase(sock);
121}
122
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700123// Global epoll pointer
124static aos::internal::EPoll *global_epoll = nullptr;
125
126static int ReFdListen(int fd, int flags, fd_h *fh, void *arg) {
127 if (flags & 0x1) {
128 global_epoll->OnReadable(fd, [fh, arg]() { (*fh)(0x1, arg); });
129 }
130 if (flags & 0x2) {
131 global_epoll->OnWriteable(fd, [fh, arg]() { (*fh)(0x2, arg); });
132 }
133 if (flags & 0x4) {
134 global_epoll->OnError(fd, [fh, arg]() { (*fh)(0x4, arg); });
135 }
136 return 0;
137}
138
139static void ReFdClose(int fd) {
140 CHECK(global_epoll != nullptr);
141 global_epoll->DeleteFd(fd);
142}
143
James Kuszmaul1a29c082022-02-03 14:02:47 -0800144WebProxy::WebProxy(aos::EventLoop *event_loop, StoreHistory store_history,
145 int per_channel_buffer_size_bytes)
146 : WebProxy(event_loop, &internal_epoll_, store_history,
147 per_channel_buffer_size_bytes) {}
James Kuszmaul71a81932020-12-15 21:08:01 -0800148
James Kuszmaul1a29c082022-02-03 14:02:47 -0800149WebProxy::WebProxy(aos::ShmEventLoop *event_loop, StoreHistory store_history,
150 int per_channel_buffer_size_bytes)
151 : WebProxy(event_loop, event_loop->epoll(), store_history,
152 per_channel_buffer_size_bytes) {}
James Kuszmaul71a81932020-12-15 21:08:01 -0800153
154WebProxy::WebProxy(aos::EventLoop *event_loop, aos::internal::EPoll *epoll,
James Kuszmaul1a29c082022-02-03 14:02:47 -0800155 StoreHistory store_history,
156 int per_channel_buffer_size_bytes)
James Kuszmaul71a81932020-12-15 21:08:01 -0800157 : epoll_(epoll),
158 server_(std::make_shared<aos::seasocks::SeasocksLogger>(
159 ::seasocks::Logger::Level::Info)),
James Kuszmaul1a29c082022-02-03 14:02:47 -0800160 websocket_handler_(new WebsocketHandler(
161 &server_, event_loop, store_history, per_channel_buffer_size_bytes)) {
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700162 CHECK(!global_epoll);
163 global_epoll = epoll;
164
165 re_fd_set_listen_callback(&ReFdListen);
166 re_fd_set_close_callback(&ReFdClose);
167
168 epoll->BeforeWait([]() {
169 const uint64_t to = tmr_next_timeout(tmrl_get());
170 if (to != 0) {
Austin Schuh0c8dd362021-10-30 10:23:25 -0700171 VLOG(3) << "Next timeout " << to;
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700172 }
173 // Note: this only works because we are spinning on it...
174 // TODO(austin): If we choose to actually sleep, use a timerfd reserved just
175 // for handling tmr.
176 tmr_poll(tmrl_get());
177 });
178
James Kuszmaul71a81932020-12-15 21:08:01 -0800179 server_.addWebSocketHandler("/ws", websocket_handler_);
James Kuszmaul1e95bed2021-01-09 21:02:49 -0800180 CHECK(server_.startListening(FLAGS_proxy_port));
James Kuszmaul71a81932020-12-15 21:08:01 -0800181
182 epoll->OnReadable(server_.fd(), [this]() {
183 CHECK(::seasocks::Server::PollResult::Continue == server_.poll(0));
184 });
185
186 if (&internal_epoll_ == epoll) {
187 TimerHandler *const timer = event_loop->AddTimer([this]() {
188 // Run the epoll poller until there are no more events (if we are being
189 // backed by a shm event loop, there won't be anything registered to
190 // internal_epoll_ and this will just return false).
191 // We just deal with clearing all the epoll events using a simulated
192 // timer. This does mean that we will spin rather than actually sleeping
193 // in any coherent manner, which will be particularly noticeable when past
194 // the end of processing other events.
195 while (internal_epoll_.Poll(false)) {
196 continue;
197 }
198 });
199
200 event_loop->OnRun([timer, event_loop]() {
Philipp Schradera6712522023-07-05 20:25:11 -0700201 timer->Schedule(event_loop->monotonic_now(),
202 std::chrono::milliseconds(10));
James Kuszmaul71a81932020-12-15 21:08:01 -0800203 });
204 }
205}
206
207WebProxy::~WebProxy() {
208 epoll_->DeleteFd(server_.fd());
209 server_.terminate();
210 CHECK(::seasocks::Server::PollResult::Terminated == server_.poll(0));
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700211 CHECK(global_epoll == epoll_);
212 global_epoll = nullptr;
James Kuszmaul71a81932020-12-15 21:08:01 -0800213}
214
James Kuszmaul147b4c12022-07-13 20:35:27 -0700215void WebProxy::StopRecording() { websocket_handler_->StopRecording(); }
Alex Perry5f474f22020-02-01 12:14:24 -0800216
James Kuszmaul147b4c12022-07-13 20:35:27 -0700217void Subscriber::RunIteration(bool fetch_new) {
218 if (fetch_new) {
219 if (channels_.empty() && (buffer_size_ == 0 || !store_history_)) {
James Kuszmaul71a81932020-12-15 21:08:01 -0800220 fetcher_->Fetch();
James Kuszmaul147b4c12022-07-13 20:35:27 -0700221 message_buffer_.clear();
222 return;
James Kuszmaul71a81932020-12-15 21:08:01 -0800223 }
Alex Perry5f474f22020-02-01 12:14:24 -0800224
James Kuszmaul147b4c12022-07-13 20:35:27 -0700225 while (fetcher_->FetchNext()) {
226 // If we aren't building up a buffer, short-circuit the FetchNext().
227 if (buffer_size_ == 0) {
228 fetcher_->Fetch();
Austin Schuhd16ef442021-04-25 14:44:42 -0700229 }
James Kuszmaul147b4c12022-07-13 20:35:27 -0700230 Message message;
231 message.index = fetcher_->context().queue_index;
232 VLOG(2) << "Packing a message with "
233 << GetPacketCount(fetcher_->context()) << "packets";
234 for (int packet_index = 0;
235 packet_index < GetPacketCount(fetcher_->context()); ++packet_index) {
236 // Pack directly into the mbuffer. This is admittedly a bit painful.
237 const size_t packet_size =
238 PackedMessageSize(fetcher_->context(), packet_index);
239 struct mbuf *mbuffer = mbuf_alloc(packet_size);
Alex Perry5f474f22020-02-01 12:14:24 -0800240
James Kuszmaul147b4c12022-07-13 20:35:27 -0700241 {
242 // Wrap a pre-allocated builder around the mbuffer.
243 PreallocatedAllocator allocator(mbuf_buf(mbuffer), packet_size);
244 flatbuffers::FlatBufferBuilder fbb(packet_size, &allocator);
245 flatbuffers::Offset<MessageHeader> message_offset = PackMessage(
246 &fbb, fetcher_->context(), channel_index_, packet_index);
247 fbb.Finish(message_offset);
248
249 // Now, the flatbuffer is built from the back to the front. So any
Philipp Schradera6712522023-07-05 20:25:11 -0700250 // extra memory will be at the front. Set up the end and start
James Kuszmaul147b4c12022-07-13 20:35:27 -0700251 // pointers on the mbuf.
252 mbuf_set_end(mbuffer, packet_size);
253 mbuf_set_pos(mbuffer, packet_size - fbb.GetSize());
254 }
255
256 message.data.emplace_back(
257 std::shared_ptr<struct mbuf>(mbuffer, mem_deref));
258 }
259 message_buffer_.push_back(std::move(message));
260 // If we aren't keeping a buffer, then we should only do one iteration of
261 // the while loop--otherwise, if additional messages arrive between the
262 // first FetchNext() and the second iteration then we can end up behaving
263 // poorly (since we do a Fetch() when buffer_size_ == 0).
264 if (buffer_size_ == 0) {
265 break;
266 }
James Kuszmaul45139e62021-09-11 11:41:03 -0700267 }
James Kuszmaul71a81932020-12-15 21:08:01 -0800268 }
269 for (auto &conn : channels_) {
James Kuszmaula5822682021-12-23 18:39:28 -0800270 std::shared_ptr<ScopedDataChannel> rtc_channel = conn.first.lock();
271 CHECK(rtc_channel) << "data_channel was destroyed too early.";
James Kuszmaul71a81932020-12-15 21:08:01 -0800272 ChannelInformation *channel_data = &conn.second;
273 if (channel_data->transfer_method == TransferMethod::SUBSAMPLE) {
274 SkipToLastMessage(channel_data);
275 }
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700276 std::shared_ptr<struct mbuf> buffer = NextBuffer(channel_data);
277 while (buffer) {
278 // TODO(austin): This is a nop so we just buffer forever. Fix this when
279 // we care.
James Kuszmaul71a81932020-12-15 21:08:01 -0800280 if (rtc_channel->buffered_amount() > 14000000) {
Alex Perry3dfcb812020-03-04 19:32:17 -0800281 VLOG(1) << "skipping a send because buffered amount is too high";
James Kuszmaul71a81932020-12-15 21:08:01 -0800282 break;
Alex Perry3dfcb812020-03-04 19:32:17 -0800283 }
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700284
285 rtc_channel->Send(buffer.get());
James Kuszmaul71a81932020-12-15 21:08:01 -0800286 buffer = NextBuffer(channel_data);
287 }
288 }
289 if (buffer_size_ >= 0) {
290 while (message_buffer_.size() > static_cast<size_t>(buffer_size_)) {
291 message_buffer_.pop_front();
Alex Perry5f474f22020-02-01 12:14:24 -0800292 }
293 }
294}
295
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700296void Subscriber::AddListener(std::shared_ptr<ScopedDataChannel> data_channel,
297 TransferMethod transfer_method) {
James Kuszmaul71a81932020-12-15 21:08:01 -0800298 ChannelInformation info;
299 info.transfer_method = transfer_method;
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700300
James Kuszmaula5822682021-12-23 18:39:28 -0800301 channels_.emplace_back(std::make_pair(data_channel, info));
302
303 data_channel->set_on_message(
304 [this, index = channels_.size() - 1](
305 struct mbuf *const buffer,
306 const enum rawrtc_data_channel_message_flag /*flags*/) {
307 FlatbufferSpan<ChannelState> message(
308 {mbuf_buf(buffer), mbuf_get_left(buffer)});
309 if (!message.Verify()) {
310 LOG(ERROR) << "Invalid flatbuffer received from browser client.";
311 return;
312 }
313
314 channels_[index].second.reported_queue_index =
315 message.message().queue_index();
316 channels_[index].second.reported_packet_index =
317 message.message().packet_index();
James Kuszmaule524ed02023-12-09 13:21:03 -0800318 // Note: Uses actual clock to handle simulation time.
319 channels_[index].second.last_report = aos::monotonic_clock::now();
James Kuszmaula5822682021-12-23 18:39:28 -0800320 });
James Kuszmaul71a81932020-12-15 21:08:01 -0800321}
322
Austin Schuh60e77942022-05-16 17:48:24 -0700323void Subscriber::RemoveListener(
324 std::shared_ptr<ScopedDataChannel> data_channel) {
James Kuszmaula5822682021-12-23 18:39:28 -0800325 channels_.erase(
326 std::remove_if(
327 channels_.begin(), channels_.end(),
328 [data_channel](const std::pair<std::weak_ptr<ScopedDataChannel>,
329 ChannelInformation> &channel) {
330 return channel.first.lock().get() == data_channel.get();
331 }),
332 channels_.end());
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700333}
334
335std::shared_ptr<struct mbuf> Subscriber::NextBuffer(
336 ChannelInformation *channel) {
James Kuszmaul71a81932020-12-15 21:08:01 -0800337 CHECK_NOTNULL(channel);
338 if (message_buffer_.empty()) {
339 return nullptr;
340 }
341 const uint32_t earliest_index = message_buffer_.front().index;
342 const uint32_t latest_index = message_buffer_.back().index;
343 const bool fell_behind = channel->current_queue_index < earliest_index;
344 if (fell_behind) {
345 channel->current_queue_index = earliest_index;
346 channel->next_packet_number = 0;
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700347 return message_buffer_.front().data.at(0);
James Kuszmaul71a81932020-12-15 21:08:01 -0800348 }
James Kuszmaula5822682021-12-23 18:39:28 -0800349 // TODO(james): Handle queue index wrapping when >2^32 messages are sent on a
350 // channel.
James Kuszmaul71a81932020-12-15 21:08:01 -0800351 if (channel->current_queue_index > latest_index) {
352 // We are still waiting on the next message to appear; return.
353 return nullptr;
354 }
James Kuszmaula5822682021-12-23 18:39:28 -0800355 if (FLAGS_pre_send_messages > 0) {
James Kuszmaule524ed02023-12-09 13:21:03 -0800356 // Note: Uses actual clock to handle simulation time.
357 const aos::monotonic_clock::time_point now = aos::monotonic_clock::now();
358 if (channel->last_report.has_value() &&
359 channel->last_report.value() +
360 std::chrono::duration_cast<std::chrono::nanoseconds>(
361 std::chrono::duration<double>(FLAGS_max_buffer_pause_sec)) <
362 now) {
363 // Increment the number of messages that we will send over to the client
364 // webpage.
365 channel->reported_queue_index += FLAGS_pre_send_messages / 10;
366 channel->reported_packet_index = 0;
367 channel->last_report = now;
368 }
James Kuszmaula5822682021-12-23 18:39:28 -0800369 // Don't buffer up an excessive number of messages to the client.
370 // This currently ignores the packet index (and really, any concept of
371 // message size), but the main goal is just to avoid locking up the client
372 // browser, not to be ultra precise about anything. It's also not clear that
373 // message *size* is necessarily even the determining factor in causing
374 // issues.
375 if (channel->reported_queue_index + FLAGS_pre_send_messages <
376 channel->current_queue_index) {
377 return nullptr;
378 }
379 }
James Kuszmaul71a81932020-12-15 21:08:01 -0800380 CHECK_EQ(latest_index - earliest_index + 1, message_buffer_.size())
381 << "Inconsistent queue indices.";
382 const size_t packets_in_message =
383 message_buffer_[channel->current_queue_index - earliest_index]
384 .data.size();
385 CHECK_LT(0u, packets_in_message);
386 CHECK_LT(channel->next_packet_number, packets_in_message);
387
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700388 std::shared_ptr<struct mbuf> original_data =
389 message_buffer_[channel->current_queue_index - earliest_index].data.at(
James Kuszmaul71a81932020-12-15 21:08:01 -0800390 channel->next_packet_number);
391
392 ++channel->next_packet_number;
393 if (channel->next_packet_number == packets_in_message) {
394 ++channel->current_queue_index;
395 channel->next_packet_number = 0;
396 }
397
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700398 // Trigger a copy of the mbuf without copying the data.
399 return std::shared_ptr<struct mbuf>(mbuf_alloc_ref(original_data.get()),
400 mem_deref);
James Kuszmaul71a81932020-12-15 21:08:01 -0800401}
402
403void Subscriber::SkipToLastMessage(ChannelInformation *channel) {
404 CHECK_NOTNULL(channel);
405 if (message_buffer_.empty() ||
406 channel->current_queue_index == message_buffer_.back().index) {
407 return;
408 }
409 channel->current_queue_index = message_buffer_.back().index;
James Kuszmaul87200a42022-03-26 18:09:18 -0700410 channel->reported_queue_index = message_buffer_.back().index;
James Kuszmaule524ed02023-12-09 13:21:03 -0800411 channel->last_report.reset();
James Kuszmaul71a81932020-12-15 21:08:01 -0800412 channel->next_packet_number = 0;
413}
414
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700415ApplicationConnection::ApplicationConnection(
416 ::seasocks::Server *server, ::seasocks::WebSocket *sock,
Alex Perry5f474f22020-02-01 12:14:24 -0800417 const std::vector<std::unique_ptr<Subscriber>> &subscribers,
James Kuszmaul71a81932020-12-15 21:08:01 -0800418 const aos::FlatbufferDetachedBuffer<aos::Configuration> &config,
419 const EventLoop *event_loop)
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700420 : server_(server),
421 sock_(sock),
Alex Perry5f474f22020-02-01 12:14:24 -0800422 subscribers_(subscribers),
James Kuszmaul71a81932020-12-15 21:08:01 -0800423 config_headers_(PackBuffer(config.span())),
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700424 event_loop_(event_loop) {
425 connection_.set_on_negotiation_needed([]() {
426 VLOG(1) << "Negotiation needed, not offering so not creating offer.";
427 });
Alex Perryb3b50792020-01-18 16:13:45 -0800428
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700429 connection_.set_on_local_candidate(
430 [this](struct rawrtc_peer_connection_ice_candidate *const candidate,
431 char const *const url) { LocalCandidate(candidate, url); });
432
433 connection_.set_on_data_channel(
434 [this](std::shared_ptr<ScopedDataChannel> channel) {
435 OnDataChannel(channel);
436 });
437
438 connection_.Open();
439}
440
441ApplicationConnection::~ApplicationConnection() {
442 for (auto &it : channels_) {
443 it.second.data_channel->Close();
444 it.second.data_channel = nullptr;
445 }
446
447 // Eh, we are done, tell the channel to shut down. If we didn't, it would
448 // just hang around until the connection closes, which is rather shortly
449 // after.
450 if (channel_) {
451 channel_->Close();
452 }
453}
454
455void ApplicationConnection::OnSdp(const char *sdp) {
456 struct rawrtc_peer_connection_description *remote_description = NULL;
457
458 auto error = rawrtc_peer_connection_description_create(
459 &remote_description, RAWRTC_SDP_TYPE_OFFER, sdp);
460 if (error) {
461 LOG(WARNING) << "Cannot parse remote description: "
462 << rawrtc_code_to_str(error);
James Kuszmaul48671362020-12-24 13:54:16 -0800463 return;
464 }
Alex Perryb3b50792020-01-18 16:13:45 -0800465
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700466 CHECK_RAWRTC(rawrtc_peer_connection_set_remote_description(
467 connection_.connection(), remote_description));
Alex Perryb3b50792020-01-18 16:13:45 -0800468
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700469 struct rawrtc_peer_connection_description *local_description;
470 CHECK_RAWRTC(rawrtc_peer_connection_create_answer(&local_description,
471 connection_.connection()));
472 CHECK_RAWRTC(rawrtc_peer_connection_set_local_description(
473 connection_.connection(), local_description));
Alex Perryb3b50792020-01-18 16:13:45 -0800474
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700475 enum rawrtc_sdp_type type;
476 char *local_sdp = nullptr;
477 // Get SDP type & the SDP itself
478 CHECK_RAWRTC(rawrtc_peer_connection_description_get_sdp_type(
479 &type, local_description));
480 CHECK_RAWRTC(rawrtc_peer_connection_description_get_sdp(&local_sdp,
481 local_description));
James Kuszmaul8d928d02020-12-25 17:47:49 -0800482
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700483 flatbuffers::FlatBufferBuilder fbb;
Alex Perryb3b50792020-01-18 16:13:45 -0800484 flatbuffers::Offset<WebSocketSdp> sdp_fb =
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700485 CreateWebSocketSdpDirect(fbb, SdpType::ANSWER, local_sdp);
Alex Perryb3b50792020-01-18 16:13:45 -0800486 flatbuffers::Offset<WebSocketMessage> answer_message =
487 CreateWebSocketMessage(fbb, Payload::WebSocketSdp, sdp_fb.Union());
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700488
489 VLOG(1) << aos::FlatbufferToJson(
490 flatbuffers::GetTemporaryPointer(fbb, answer_message));
Alex Perryb3b50792020-01-18 16:13:45 -0800491 fbb.Finish(answer_message);
492
493 server_->execute(std::make_shared<UpdateData>(sock_, fbb.Release()));
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700494 mem_deref(local_sdp);
Alex Perryb3b50792020-01-18 16:13:45 -0800495}
496
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700497void ApplicationConnection::OnIce(const WebSocketIce *ice) {
498 if (!ice->has_candidate()) {
499 return;
500 }
Brian Silverman225c5072021-11-17 19:56:31 -0800501 uint8_t sdp_m_line_index = ice->sdp_m_line_index();
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700502
503 struct rawrtc_peer_connection_ice_candidate *ice_candidate = nullptr;
504 CHECK_RAWRTC(rawrtc_peer_connection_ice_candidate_create(
Brian Silverman225c5072021-11-17 19:56:31 -0800505 &ice_candidate, ice->candidate()->c_str(), ice->sdp_mid()->c_str(),
506 &sdp_m_line_index, nullptr));
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700507
508 rawrtc_peer_connection_add_ice_candidate(connection_.connection(),
509 ice_candidate);
510
511 mem_deref(ice_candidate);
512}
513
514void ApplicationConnection::LocalCandidate(
515 struct rawrtc_peer_connection_ice_candidate *const candidate,
516 char const *const url) {
517 struct rawrtc_ice_candidate *ortc_candidate = nullptr;
518 if (candidate) {
519 CHECK_RAWRTC(rawrtc_peer_connection_ice_candidate_get_ortc_candidate(
520 &ortc_candidate, candidate));
521
522 flatbuffers::FlatBufferBuilder fbb;
523 char *sdpp = nullptr;
524 CHECK_RAWRTC(
525 rawrtc_peer_connection_ice_candidate_get_sdp(&sdpp, candidate));
526 char *midp = nullptr;
527 CHECK_RAWRTC(
528 rawrtc_peer_connection_ice_candidate_get_sdp_mid(&midp, candidate));
529
530 uint8_t media_line_index;
531 enum rawrtc_code error =
532 rawrtc_peer_connection_ice_candidate_get_sdp_media_line_index(
533 &media_line_index, candidate);
534
535 flatbuffers::Offset<flatbuffers::String> sdpp_offset =
536 fbb.CreateString(sdpp);
537 flatbuffers::Offset<flatbuffers::String> sdp_mid_offset =
538 fbb.CreateString(midp);
539
540 WebSocketIce::Builder web_socket_ice_builder(fbb);
541
542 web_socket_ice_builder.add_candidate(sdpp_offset);
Brian Silverman225c5072021-11-17 19:56:31 -0800543 web_socket_ice_builder.add_sdp_mid(sdp_mid_offset);
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700544
545 if (error == RAWRTC_CODE_SUCCESS) {
Brian Silverman225c5072021-11-17 19:56:31 -0800546 web_socket_ice_builder.add_sdp_m_line_index(media_line_index);
James Kuszmaul1ec74432020-07-30 20:26:45 -0700547 }
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700548 flatbuffers::Offset<WebSocketIce> ice_offset =
549 web_socket_ice_builder.Finish();
550
551 flatbuffers::Offset<WebSocketMessage> ice_message =
552 CreateWebSocketMessage(fbb, Payload::WebSocketIce, ice_offset.Union());
553 VLOG(1) << url << ": "
554 << aos::FlatbufferToJson(
555 flatbuffers::GetTemporaryPointer(fbb, ice_message));
556 fbb.Finish(ice_message);
557
558 server_->execute(std::make_shared<UpdateData>(sock_, fbb.Release()));
559
560 mem_deref(sdpp);
561 mem_deref(midp);
Alex Perry5f474f22020-02-01 12:14:24 -0800562 }
563}
564
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700565void ApplicationConnection::OnDataChannel(
566 std::shared_ptr<ScopedDataChannel> channel) {
567 if (channel->label() == std::string_view("signalling")) {
568 CHECK(!channel_);
569 channel_ = channel;
570
571 channel_->set_on_message(
572 [this](struct mbuf *const buffer,
573 const enum rawrtc_data_channel_message_flag flags) {
574 HandleSignallingData(buffer, flags);
575 });
576
577 channel_->set_on_open([this]() {
578 for (const auto &header : config_headers_) {
579 channel_->Send(header.buffer());
580 }
581 });
582
583 channel_->set_on_error([this]() { LOG(ERROR) << "Error on " << this; });
584
585 // Register an on_close callback which does nothing but keeps channel alive
586 // until it is done. This keeps the memory around until rawrtc can finish
587 // calling the close callback.
588 channel_->set_on_close([channel]() {});
589 } else {
590 channel_->set_on_close([channel]() {});
591 channel->Close();
592 }
593}
594
595void ApplicationConnection::HandleSignallingData(
596 struct mbuf *const
597 buffer, // nullable (in case partial delivery has been requested)
598 const enum rawrtc_data_channel_message_flag /*flags*/) {
James Kuszmaul71a81932020-12-15 21:08:01 -0800599 FlatbufferSpan<SubscriberRequest> message(
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700600 {mbuf_buf(buffer), mbuf_get_left(buffer)});
James Kuszmaul71a81932020-12-15 21:08:01 -0800601 if (!message.Verify()) {
602 LOG(ERROR) << "Invalid flatbuffer received from browser client.";
603 return;
604 }
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700605 VLOG(1) << "Got a subscription message "
James Kuszmaul71a81932020-12-15 21:08:01 -0800606 << aos::FlatbufferToJson(&message.message());
607 if (!message.message().has_channels_to_transfer()) {
608 LOG(ERROR) << "No channels requested for transfer.";
609 return;
610 }
Alex Perry5f474f22020-02-01 12:14:24 -0800611
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700612 // The client each time sends a full list of everything it wants to be
613 // subscribed to. It is our responsibility to remove channels which aren't
614 // in that list and add ones which need to be.
615 //
616 // Start by clearing a tracking bit on each channel. This takes O(number of
617 // open channels), which should be small.
618 //
619 // Then open any new channels. For any we visit which are already open,
620 // don't update those.
621 //
622 // Finally, iterate over the channel list and purge anything which we didn't
623 // touch.
624 for (auto &it : channels_) {
625 it.second.requested = false;
626 }
627 for (auto channel_request : *message.message().channels_to_transfer()) {
628 const Channel *channel = channel_request->channel();
629 if (channel == nullptr) {
630 LOG(ERROR) << "Got unpopulated channel.";
631 continue;
Alex Perry5f474f22020-02-01 12:14:24 -0800632 }
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700633 const TransferMethod transfer_method = channel_request->method();
634 // Call GetChannel() before comparing the channel name/type to each
635 // subscriber. This allows us to resolve any node or application
636 // specific mappings.
637 const Channel *comparison_channel =
638 configuration::GetChannel(event_loop_->configuration(), channel,
639 event_loop_->name(), event_loop_->node());
640 if (comparison_channel == nullptr) {
James Kuszmaul5e6aa252021-08-28 22:19:29 -0700641 LOG(ERROR) << "Channel does not exist: "
642 << configuration::StrippedChannelToString(channel);
643 continue;
644 }
645 if (!configuration::ChannelIsReadableOnNode(comparison_channel,
646 event_loop_->node())) {
647 LOG(ERROR) << "Channel not available on node "
648 << event_loop_->node()->name()->string_view() << ": "
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700649 << configuration::StrippedChannelToString(channel);
650 continue;
651 }
652
653 size_t channel_index = configuration::ChannelIndex(
654 event_loop_->configuration(), comparison_channel);
655
656 auto it = channels_.find(channel_index);
657 if (it == channels_.end()) {
658 std::shared_ptr<ScopedDataChannel> data_channel =
James Kuszmaula5822682021-12-23 18:39:28 -0800659 ScopedDataChannel::MakeDataChannel();
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700660
661 std::weak_ptr<ScopedDataChannel> data_channel_weak_ptr = data_channel;
662
663 data_channel->set_on_open([this, data_channel_weak_ptr, transfer_method,
664 channel_index]() {
665 std::shared_ptr<ScopedDataChannel> data_channel =
666 data_channel_weak_ptr.lock();
667 CHECK(data_channel) << ": Subscriber got destroyed before we started.";
James Kuszmaula5822682021-12-23 18:39:28 -0800668 // Raw pointer inside the subscriber so we don't have a circular
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700669 // reference. AddListener will close it.
Austin Schuh60e77942022-05-16 17:48:24 -0700670 subscribers_[channel_index]->AddListener(data_channel, transfer_method);
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700671 });
672
673 Subscriber *subscriber = subscribers_[channel_index].get();
674 data_channel->set_on_close([subscriber, data_channel_weak_ptr]() {
675 std::shared_ptr<ScopedDataChannel> data_channel =
676 data_channel_weak_ptr.lock();
677 CHECK(data_channel) << ": Subscriber got destroyed before we finished.";
678 subscriber->RemoveListener(data_channel);
679 });
680
681 data_channel->Open(
682 connection_.connection(),
683 absl::StrCat(channel->name()->str(), "/", channel->type()->str()));
684
685 auto pair = channels_.insert({channel_index, {data_channel, true}});
686 it = pair.first;
687 }
688
689 it->second.requested = true;
690
691 VLOG(1) << "Subscribe to: " << channel->type()->str();
692 }
693
694 for (auto &it : channels_) {
695 if (!it.second.requested) {
696 it.second.data_channel->Close();
697 it.second.data_channel = nullptr;
Alex Perry5f474f22020-02-01 12:14:24 -0800698 }
699 }
Alex Perryb3b50792020-01-18 16:13:45 -0800700}
701
702} // namespace web_proxy
703} // namespace aos