blob: db7fb5bc729b5deb2b7b4dbe0dcfbd15aa485ed6 [file] [log] [blame]
Alex Perryb3b50792020-01-18 16:13:45 -08001#ifndef AOS_NETWORK_WEB_PROXY_H_
2#define AOS_NETWORK_WEB_PROXY_H_
Austin Schuh52e5e3a2021-04-24 22:30:02 -07003
4#include <deque>
Alex Perryb3b50792020-01-18 16:13:45 -08005#include <map>
James Kuszmaule524ed02023-12-09 13:21:03 -08006#include <optional>
Alex Perryb3b50792020-01-18 16:13:45 -08007#include <set>
Austin Schuh52e5e3a2021-04-24 22:30:02 -07008
Philipp Schrader790cb542023-07-05 21:06:52 -07009#include "flatbuffers/flatbuffers.h"
10
James Kuszmaul7ad91522020-09-01 19:15:35 -070011#include "aos/events/event_loop.h"
James Kuszmaul71a81932020-12-15 21:08:01 -080012#include "aos/events/shm_event_loop.h"
James Kuszmaul8d928d02020-12-25 17:47:49 -080013#include "aos/mutex/mutex.h"
Alex Perry5f474f22020-02-01 12:14:24 -080014#include "aos/network/connect_generated.h"
Austin Schuh52e5e3a2021-04-24 22:30:02 -070015#include "aos/network/rawrtc.h"
Alex Perry5f474f22020-02-01 12:14:24 -080016#include "aos/network/web_proxy_generated.h"
Alex Perryb3b50792020-01-18 16:13:45 -080017#include "aos/seasocks/seasocks_logger.h"
Alex Perryb3b50792020-01-18 16:13:45 -080018#include "seasocks/Server.h"
19#include "seasocks/StringUtil.h"
20#include "seasocks/WebSocket.h"
21
Alex Perryb3b50792020-01-18 16:13:45 -080022namespace aos {
23namespace web_proxy {
24
25class Connection;
Alex Perry5f474f22020-02-01 12:14:24 -080026class Subscriber;
Austin Schuh52e5e3a2021-04-24 22:30:02 -070027class ApplicationConnection;
Alex Perryb3b50792020-01-18 16:13:45 -080028
James Kuszmaul1a29c082022-02-03 14:02:47 -080029enum class StoreHistory {
30 kNo,
31 kYes,
32};
33
Alex Perryb3b50792020-01-18 16:13:45 -080034// Basic class that handles receiving new websocket connections. Creates a new
35// Connection to manage the rest of the negotiation and data passing. When the
36// websocket closes, it deletes the Connection.
37class WebsocketHandler : public ::seasocks::WebSocket::Handler {
38 public:
James Kuszmaul71a81932020-12-15 21:08:01 -080039 WebsocketHandler(::seasocks::Server *server, aos::EventLoop *event_loop,
James Kuszmaul1a29c082022-02-03 14:02:47 -080040 StoreHistory store_history,
41 int per_channel_buffer_size_bytes);
Alex Perryb3b50792020-01-18 16:13:45 -080042 void onConnect(::seasocks::WebSocket *sock) override;
43 void onData(::seasocks::WebSocket *sock, const uint8_t *data,
44 size_t size) override;
45 void onDisconnect(::seasocks::WebSocket *sock) override;
James Kuszmaul147b4c12022-07-13 20:35:27 -070046 // Stops recording data, even if the event loop continues running. This allows
47 // us to continue serving the webserver + websocket server, without having to
48 // load more actual data.
49 void StopRecording() { recording_ = false; }
Alex Perryb3b50792020-01-18 16:13:45 -080050
51 private:
Alex Perryb3b50792020-01-18 16:13:45 -080052 ::seasocks::Server *server_;
James Kuszmaul7ad91522020-09-01 19:15:35 -070053 std::vector<std::unique_ptr<Subscriber>> subscribers_;
54 const aos::FlatbufferDetachedBuffer<aos::Configuration> config_;
James Kuszmaul71a81932020-12-15 21:08:01 -080055
Austin Schuh52e5e3a2021-04-24 22:30:02 -070056 std::map<::seasocks::WebSocket *, std::unique_ptr<ApplicationConnection>>
57 connections_;
58
59 EventLoop *const event_loop_;
James Kuszmaul147b4c12022-07-13 20:35:27 -070060 // Whether to pay attention to new messages.
61 bool recording_ = true;
James Kuszmaul71a81932020-12-15 21:08:01 -080062};
63
64// Wrapper class that manages the seasocks server and WebsocketHandler.
65class WebProxy {
66 public:
James Kuszmaul1a29c082022-02-03 14:02:47 -080067 // Constructs a WebProxy object for interacting with a webpage. store_history
68 // and per_channel_buffer_size_bytes specify how we manage delivering LOSSLESS
69 // messages to the client:
70 // * store_history specifies whether we should always buffer up data for all
71 // channels--even for messages that are played prior to the client
72 // connecting. This is mostly useful for log replay where the client
73 // will typically connect after the logfile has been fully loaded/replayed.
74 // * per_channel_buffer_size_bytes is the maximum amount of data to buffer
75 // up per channel (-1 will indicate infinite data, which is used during log
76 // replay). This is divided by the max_size per channel to determine
77 // how many messages to queue up.
78 WebProxy(aos::EventLoop *event_loop, StoreHistory store_history,
79 int per_channel_buffer_size_bytes);
80 WebProxy(aos::ShmEventLoop *event_loop, StoreHistory store_history,
81 int per_channel_buffer_size_bytes);
James Kuszmaulb67409b2022-06-20 16:25:03 -070082 WebProxy(aos::EventLoop *event_loop, aos::internal::EPoll *epoll,
83 StoreHistory store_history, int per_channel_buffer_size_bytes);
James Kuszmaul71a81932020-12-15 21:08:01 -080084 ~WebProxy();
85
86 void SetDataPath(const char *path) { server_.setStaticPath(path); }
87
James Kuszmaul147b4c12022-07-13 20:35:27 -070088 // Stops recording data. Useful for setting end times in log replay.
89 void StopRecording();
90
James Kuszmaul71a81932020-12-15 21:08:01 -080091 private:
James Kuszmaul71a81932020-12-15 21:08:01 -080092 aos::internal::EPoll internal_epoll_;
93 aos::internal::EPoll *const epoll_;
94 ::seasocks::Server server_;
95 std::shared_ptr<WebsocketHandler> websocket_handler_;
Alex Perryb3b50792020-01-18 16:13:45 -080096};
97
98// Seasocks requires that sends happen on the correct thread. This class takes a
99// detached buffer to send on a specific websocket connection and sends it when
100// seasocks is ready.
101class UpdateData : public ::seasocks::Server::Runnable {
102 public:
103 UpdateData(::seasocks::WebSocket *websocket,
Alex Perry5f474f22020-02-01 12:14:24 -0800104 flatbuffers::DetachedBuffer &&buffer)
Alex Perryb3b50792020-01-18 16:13:45 -0800105 : sock_(websocket), buffer_(std::move(buffer)) {}
106 ~UpdateData() override = default;
107 UpdateData(const UpdateData &) = delete;
108 UpdateData &operator=(const UpdateData &) = delete;
109
110 void run() override { sock_->send(buffer_.data(), buffer_.size()); }
111
112 private:
113 ::seasocks::WebSocket *sock_;
Alex Perry5f474f22020-02-01 12:14:24 -0800114 const flatbuffers::DetachedBuffer buffer_;
115};
116
117// Represents a fetcher and all the Connections that care about it.
118// Handles building the message and telling each connection to send it.
119// indexed by location of the channel it handles in the config.
James Kuszmaul71a81932020-12-15 21:08:01 -0800120// Subscriber also uses an internal buffer to store past messages. This is
121// primarily meant for use in offline log replay/simulation where we want to be
122// able to store infinite buffers. In the future, we will probably want to be
123// able to specify *which* channels to store buffers for so that we aren't just
124// loading the entire logfile into memory.
Alex Perry5f474f22020-02-01 12:14:24 -0800125class Subscriber {
126 public:
James Kuszmaul71a81932020-12-15 21:08:01 -0800127 Subscriber(std::unique_ptr<RawFetcher> fetcher, int channel_index,
James Kuszmaul1a29c082022-02-03 14:02:47 -0800128 StoreHistory store_history, int buffer_size)
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700129 : fetcher_(std::move(fetcher)),
James Kuszmaul71a81932020-12-15 21:08:01 -0800130 channel_index_(channel_index),
James Kuszmaul1a29c082022-02-03 14:02:47 -0800131 store_history_(store_history == StoreHistory::kYes),
James Kuszmaul71a81932020-12-15 21:08:01 -0800132 buffer_size_(buffer_size) {}
Alex Perry5f474f22020-02-01 12:14:24 -0800133
James Kuszmaul147b4c12022-07-13 20:35:27 -0700134 // Runs a single iteration of going through and fetching new data as needed
135 // and servicing any WebRTC channels that are requesting messages.
136 // fetch_new specifies whether we should actually attempt to retrieve new data
137 // on the channel--if false, will only worry about sending existing data to
138 // any clients.
139 void RunIteration(bool fetch_new);
Alex Perry5f474f22020-02-01 12:14:24 -0800140
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700141 void AddListener(std::shared_ptr<ScopedDataChannel> data_channel,
142 TransferMethod transfer_method);
Alex Perry5f474f22020-02-01 12:14:24 -0800143
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700144 void RemoveListener(std::shared_ptr<ScopedDataChannel> data_channel);
Alex Perry5f474f22020-02-01 12:14:24 -0800145
146 private:
James Kuszmaul71a81932020-12-15 21:08:01 -0800147 struct ChannelInformation {
148 TransferMethod transfer_method;
James Kuszmaula5822682021-12-23 18:39:28 -0800149 // Queue index (same as the queue index within the AOS channel) of the
150 // message that we are currently sending or, if we are between messages,
151 // the next message we will send.
James Kuszmaul71a81932020-12-15 21:08:01 -0800152 uint32_t current_queue_index = 0;
James Kuszmaula5822682021-12-23 18:39:28 -0800153 // Index of the next packet to send within current_queue_index (large
154 // messages are broken into multiple packets, as we have encountered
155 // issues with how some WebRTC implementations handle large packets).
James Kuszmaul71a81932020-12-15 21:08:01 -0800156 size_t next_packet_number = 0;
James Kuszmaula5822682021-12-23 18:39:28 -0800157 // The last queue/packet index reported by the client.
158 uint32_t reported_queue_index = 0;
159 size_t reported_packet_index = 0;
James Kuszmaule524ed02023-12-09 13:21:03 -0800160 std::optional<aos::monotonic_clock::time_point> last_report = std::nullopt;
James Kuszmaul71a81932020-12-15 21:08:01 -0800161 };
162 struct Message {
163 uint32_t index = 0xffffffff;
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700164 std::vector<std::shared_ptr<struct mbuf>> data;
James Kuszmaul71a81932020-12-15 21:08:01 -0800165 };
166
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700167 std::shared_ptr<struct mbuf> NextBuffer(ChannelInformation *channel);
James Kuszmaul71a81932020-12-15 21:08:01 -0800168 void SkipToLastMessage(ChannelInformation *channel);
169
Alex Perry5f474f22020-02-01 12:14:24 -0800170 std::unique_ptr<RawFetcher> fetcher_;
171 int channel_index_;
James Kuszmaul1a29c082022-02-03 14:02:47 -0800172 // If set, will always build up a buffer of the most recent buffer_size_
173 // messages. If store_history_ is *not* set we will only buffer up messages
174 // while there is an active listener.
175 bool store_history_;
James Kuszmaul71a81932020-12-15 21:08:01 -0800176 int buffer_size_;
177 std::deque<Message> message_buffer_;
James Kuszmaula5822682021-12-23 18:39:28 -0800178 // The ScopedDataChannel that we use for actually sending data over WebRTC
179 // is stored using a weak_ptr because:
180 // (a) There are some dangers of accidentally creating circular dependencies
181 // that prevent a ScopedDataChannel from ever being destroyed.
182 // (b) The inter-dependencies involved are complicated enough that we want
183 // to be able to check whether someone has destroyed the ScopedDataChannel
184 // before using it (if it has been destroyed and the Subscriber still
185 // wants to use it, that is a bug, but checking for bugs is useful).
186 // This particular location *may* be able to get away with a shared_ptr, but
187 // because the ScopedDataChannel effectively destroys itself (see
188 // ScopedDataChannel::StaticDataChannelCloseHandler) while also potentially
189 // holding references to other objects (e.g., through the various handlers
190 // that can be registered), creating unnecessary shared_ptr's is dubious.
191 std::vector<std::pair<std::weak_ptr<ScopedDataChannel>, ChannelInformation>>
192 channels_;
Alex Perryb3b50792020-01-18 16:13:45 -0800193};
194
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700195// Class to manage a WebRTC connection to a browser.
196class ApplicationConnection {
Alex Perryb3b50792020-01-18 16:13:45 -0800197 public:
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700198 ApplicationConnection(
199 ::seasocks::Server *server, ::seasocks::WebSocket *sock,
200 const std::vector<std::unique_ptr<Subscriber>> &subscribers,
201 const aos::FlatbufferDetachedBuffer<aos::Configuration> &config,
202 const EventLoop *event_loop);
Alex Perry5f474f22020-02-01 12:14:24 -0800203
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700204 ~ApplicationConnection();
Alex Perryb3b50792020-01-18 16:13:45 -0800205
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700206 // Handles a SDP sent through the negotiation channel.
207 void OnSdp(const char *sdp);
208 // Handles a ICE candidate sent through the negotiation channel.
209 void OnIce(const WebSocketIce *ice);
Alex Perryb3b50792020-01-18 16:13:45 -0800210
211 private:
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700212 void LocalCandidate(
213 struct rawrtc_peer_connection_ice_candidate *const candidate,
214 char const *const url);
Alex Perry5f474f22020-02-01 12:14:24 -0800215
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700216 // Handles a signaling channel being made.
217 void OnDataChannel(std::shared_ptr<ScopedDataChannel> channel);
218
219 // Handles data coming in on the signaling channel requesting subscription.
220 void HandleSignallingData(
221 struct mbuf *const
222 buffer, // nullable (in case partial delivery has been requested)
223 const enum rawrtc_data_channel_message_flag /*flags*/);
224
225 RawRTCConnection connection_;
226
227 ::seasocks::Server *server_;
228 ::seasocks::WebSocket *sock_;
229
230 struct ChannelState {
231 std::shared_ptr<ScopedDataChannel> data_channel;
232 bool requested = true;
233 };
234
James Kuszmaul9776b392023-01-14 14:08:08 -0800235 std::map<size_t, ChannelState> channels_;
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700236 const std::vector<std::unique_ptr<Subscriber>> &subscribers_;
237
238 const std::vector<FlatbufferDetachedBuffer<MessageHeader>> config_headers_;
James Kuszmaul71a81932020-12-15 21:08:01 -0800239
240 const EventLoop *const event_loop_;
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700241
242 std::shared_ptr<ScopedDataChannel> channel_;
Alex Perryb3b50792020-01-18 16:13:45 -0800243};
244
245} // namespace web_proxy
246} // namespace aos
247
248#endif // AOS_NETWORK_WEB_PROXY_H_