blob: e38dcea71bc0f11b14b612c2f106ed0acf55b201 [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>
6#include <set>
Austin Schuh52e5e3a2021-04-24 22:30:02 -07007
James Kuszmaul7ad91522020-09-01 19:15:35 -07008#include "aos/events/event_loop.h"
James Kuszmaul71a81932020-12-15 21:08:01 -08009#include "aos/events/shm_event_loop.h"
James Kuszmaul8d928d02020-12-25 17:47:49 -080010#include "aos/mutex/mutex.h"
Alex Perry5f474f22020-02-01 12:14:24 -080011#include "aos/network/connect_generated.h"
Austin Schuh52e5e3a2021-04-24 22:30:02 -070012#include "aos/network/rawrtc.h"
Alex Perry5f474f22020-02-01 12:14:24 -080013#include "aos/network/web_proxy_generated.h"
Alex Perryb3b50792020-01-18 16:13:45 -080014#include "aos/seasocks/seasocks_logger.h"
15#include "flatbuffers/flatbuffers.h"
16#include "seasocks/Server.h"
17#include "seasocks/StringUtil.h"
18#include "seasocks/WebSocket.h"
19
Alex Perryb3b50792020-01-18 16:13:45 -080020namespace aos {
21namespace web_proxy {
22
23class Connection;
Alex Perry5f474f22020-02-01 12:14:24 -080024class Subscriber;
Austin Schuh52e5e3a2021-04-24 22:30:02 -070025class ApplicationConnection;
Alex Perryb3b50792020-01-18 16:13:45 -080026
James Kuszmaul1a29c082022-02-03 14:02:47 -080027enum class StoreHistory {
28 kNo,
29 kYes,
30};
31
Alex Perryb3b50792020-01-18 16:13:45 -080032// Basic class that handles receiving new websocket connections. Creates a new
33// Connection to manage the rest of the negotiation and data passing. When the
34// websocket closes, it deletes the Connection.
35class WebsocketHandler : public ::seasocks::WebSocket::Handler {
36 public:
James Kuszmaul71a81932020-12-15 21:08:01 -080037 WebsocketHandler(::seasocks::Server *server, aos::EventLoop *event_loop,
James Kuszmaul1a29c082022-02-03 14:02:47 -080038 StoreHistory store_history,
39 int per_channel_buffer_size_bytes);
Alex Perryb3b50792020-01-18 16:13:45 -080040 void onConnect(::seasocks::WebSocket *sock) override;
41 void onData(::seasocks::WebSocket *sock, const uint8_t *data,
42 size_t size) override;
43 void onDisconnect(::seasocks::WebSocket *sock) override;
James Kuszmaul147b4c12022-07-13 20:35:27 -070044 // Stops recording data, even if the event loop continues running. This allows
45 // us to continue serving the webserver + websocket server, without having to
46 // load more actual data.
47 void StopRecording() { recording_ = false; }
Alex Perryb3b50792020-01-18 16:13:45 -080048
49 private:
Alex Perryb3b50792020-01-18 16:13:45 -080050 ::seasocks::Server *server_;
James Kuszmaul7ad91522020-09-01 19:15:35 -070051 std::vector<std::unique_ptr<Subscriber>> subscribers_;
52 const aos::FlatbufferDetachedBuffer<aos::Configuration> config_;
James Kuszmaul71a81932020-12-15 21:08:01 -080053
Austin Schuh52e5e3a2021-04-24 22:30:02 -070054 std::map<::seasocks::WebSocket *, std::unique_ptr<ApplicationConnection>>
55 connections_;
56
57 EventLoop *const event_loop_;
James Kuszmaul147b4c12022-07-13 20:35:27 -070058 // Whether to pay attention to new messages.
59 bool recording_ = true;
James Kuszmaul71a81932020-12-15 21:08:01 -080060};
61
62// Wrapper class that manages the seasocks server and WebsocketHandler.
63class WebProxy {
64 public:
James Kuszmaul1a29c082022-02-03 14:02:47 -080065 // Constructs a WebProxy object for interacting with a webpage. store_history
66 // and per_channel_buffer_size_bytes specify how we manage delivering LOSSLESS
67 // messages to the client:
68 // * store_history specifies whether we should always buffer up data for all
69 // channels--even for messages that are played prior to the client
70 // connecting. This is mostly useful for log replay where the client
71 // will typically connect after the logfile has been fully loaded/replayed.
72 // * per_channel_buffer_size_bytes is the maximum amount of data to buffer
73 // up per channel (-1 will indicate infinite data, which is used during log
74 // replay). This is divided by the max_size per channel to determine
75 // how many messages to queue up.
76 WebProxy(aos::EventLoop *event_loop, StoreHistory store_history,
77 int per_channel_buffer_size_bytes);
78 WebProxy(aos::ShmEventLoop *event_loop, StoreHistory store_history,
79 int per_channel_buffer_size_bytes);
James Kuszmaulb67409b2022-06-20 16:25:03 -070080 WebProxy(aos::EventLoop *event_loop, aos::internal::EPoll *epoll,
81 StoreHistory store_history, int per_channel_buffer_size_bytes);
James Kuszmaul71a81932020-12-15 21:08:01 -080082 ~WebProxy();
83
84 void SetDataPath(const char *path) { server_.setStaticPath(path); }
85
James Kuszmaul147b4c12022-07-13 20:35:27 -070086 // Stops recording data. Useful for setting end times in log replay.
87 void StopRecording();
88
James Kuszmaul71a81932020-12-15 21:08:01 -080089 private:
James Kuszmaul71a81932020-12-15 21:08:01 -080090 aos::internal::EPoll internal_epoll_;
91 aos::internal::EPoll *const epoll_;
92 ::seasocks::Server server_;
93 std::shared_ptr<WebsocketHandler> websocket_handler_;
Alex Perryb3b50792020-01-18 16:13:45 -080094};
95
96// Seasocks requires that sends happen on the correct thread. This class takes a
97// detached buffer to send on a specific websocket connection and sends it when
98// seasocks is ready.
99class UpdateData : public ::seasocks::Server::Runnable {
100 public:
101 UpdateData(::seasocks::WebSocket *websocket,
Alex Perry5f474f22020-02-01 12:14:24 -0800102 flatbuffers::DetachedBuffer &&buffer)
Alex Perryb3b50792020-01-18 16:13:45 -0800103 : sock_(websocket), buffer_(std::move(buffer)) {}
104 ~UpdateData() override = default;
105 UpdateData(const UpdateData &) = delete;
106 UpdateData &operator=(const UpdateData &) = delete;
107
108 void run() override { sock_->send(buffer_.data(), buffer_.size()); }
109
110 private:
111 ::seasocks::WebSocket *sock_;
Alex Perry5f474f22020-02-01 12:14:24 -0800112 const flatbuffers::DetachedBuffer buffer_;
113};
114
115// Represents a fetcher and all the Connections that care about it.
116// Handles building the message and telling each connection to send it.
117// indexed by location of the channel it handles in the config.
James Kuszmaul71a81932020-12-15 21:08:01 -0800118// Subscriber also uses an internal buffer to store past messages. This is
119// primarily meant for use in offline log replay/simulation where we want to be
120// able to store infinite buffers. In the future, we will probably want to be
121// able to specify *which* channels to store buffers for so that we aren't just
122// loading the entire logfile into memory.
Alex Perry5f474f22020-02-01 12:14:24 -0800123class Subscriber {
124 public:
James Kuszmaul71a81932020-12-15 21:08:01 -0800125 Subscriber(std::unique_ptr<RawFetcher> fetcher, int channel_index,
James Kuszmaul1a29c082022-02-03 14:02:47 -0800126 StoreHistory store_history, int buffer_size)
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700127 : fetcher_(std::move(fetcher)),
James Kuszmaul71a81932020-12-15 21:08:01 -0800128 channel_index_(channel_index),
James Kuszmaul1a29c082022-02-03 14:02:47 -0800129 store_history_(store_history == StoreHistory::kYes),
James Kuszmaul71a81932020-12-15 21:08:01 -0800130 buffer_size_(buffer_size) {}
Alex Perry5f474f22020-02-01 12:14:24 -0800131
James Kuszmaul147b4c12022-07-13 20:35:27 -0700132 // Runs a single iteration of going through and fetching new data as needed
133 // and servicing any WebRTC channels that are requesting messages.
134 // fetch_new specifies whether we should actually attempt to retrieve new data
135 // on the channel--if false, will only worry about sending existing data to
136 // any clients.
137 void RunIteration(bool fetch_new);
Alex Perry5f474f22020-02-01 12:14:24 -0800138
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700139 void AddListener(std::shared_ptr<ScopedDataChannel> data_channel,
140 TransferMethod transfer_method);
Alex Perry5f474f22020-02-01 12:14:24 -0800141
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700142 void RemoveListener(std::shared_ptr<ScopedDataChannel> data_channel);
Alex Perry5f474f22020-02-01 12:14:24 -0800143
144 private:
James Kuszmaul71a81932020-12-15 21:08:01 -0800145 struct ChannelInformation {
146 TransferMethod transfer_method;
James Kuszmaula5822682021-12-23 18:39:28 -0800147 // Queue index (same as the queue index within the AOS channel) of the
148 // message that we are currently sending or, if we are between messages,
149 // the next message we will send.
James Kuszmaul71a81932020-12-15 21:08:01 -0800150 uint32_t current_queue_index = 0;
James Kuszmaula5822682021-12-23 18:39:28 -0800151 // Index of the next packet to send within current_queue_index (large
152 // messages are broken into multiple packets, as we have encountered
153 // issues with how some WebRTC implementations handle large packets).
James Kuszmaul71a81932020-12-15 21:08:01 -0800154 size_t next_packet_number = 0;
James Kuszmaula5822682021-12-23 18:39:28 -0800155 // The last queue/packet index reported by the client.
156 uint32_t reported_queue_index = 0;
157 size_t reported_packet_index = 0;
James Kuszmaul71a81932020-12-15 21:08:01 -0800158 };
159 struct Message {
160 uint32_t index = 0xffffffff;
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700161 std::vector<std::shared_ptr<struct mbuf>> data;
James Kuszmaul71a81932020-12-15 21:08:01 -0800162 };
163
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700164 std::shared_ptr<struct mbuf> NextBuffer(ChannelInformation *channel);
James Kuszmaul71a81932020-12-15 21:08:01 -0800165 void SkipToLastMessage(ChannelInformation *channel);
166
Alex Perry5f474f22020-02-01 12:14:24 -0800167 std::unique_ptr<RawFetcher> fetcher_;
168 int channel_index_;
James Kuszmaul1a29c082022-02-03 14:02:47 -0800169 // If set, will always build up a buffer of the most recent buffer_size_
170 // messages. If store_history_ is *not* set we will only buffer up messages
171 // while there is an active listener.
172 bool store_history_;
James Kuszmaul71a81932020-12-15 21:08:01 -0800173 int buffer_size_;
174 std::deque<Message> message_buffer_;
James Kuszmaula5822682021-12-23 18:39:28 -0800175 // The ScopedDataChannel that we use for actually sending data over WebRTC
176 // is stored using a weak_ptr because:
177 // (a) There are some dangers of accidentally creating circular dependencies
178 // that prevent a ScopedDataChannel from ever being destroyed.
179 // (b) The inter-dependencies involved are complicated enough that we want
180 // to be able to check whether someone has destroyed the ScopedDataChannel
181 // before using it (if it has been destroyed and the Subscriber still
182 // wants to use it, that is a bug, but checking for bugs is useful).
183 // This particular location *may* be able to get away with a shared_ptr, but
184 // because the ScopedDataChannel effectively destroys itself (see
185 // ScopedDataChannel::StaticDataChannelCloseHandler) while also potentially
186 // holding references to other objects (e.g., through the various handlers
187 // that can be registered), creating unnecessary shared_ptr's is dubious.
188 std::vector<std::pair<std::weak_ptr<ScopedDataChannel>, ChannelInformation>>
189 channels_;
Alex Perryb3b50792020-01-18 16:13:45 -0800190};
191
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700192// Class to manage a WebRTC connection to a browser.
193class ApplicationConnection {
Alex Perryb3b50792020-01-18 16:13:45 -0800194 public:
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700195 ApplicationConnection(
196 ::seasocks::Server *server, ::seasocks::WebSocket *sock,
197 const std::vector<std::unique_ptr<Subscriber>> &subscribers,
198 const aos::FlatbufferDetachedBuffer<aos::Configuration> &config,
199 const EventLoop *event_loop);
Alex Perry5f474f22020-02-01 12:14:24 -0800200
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700201 ~ApplicationConnection();
Alex Perryb3b50792020-01-18 16:13:45 -0800202
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700203 // Handles a SDP sent through the negotiation channel.
204 void OnSdp(const char *sdp);
205 // Handles a ICE candidate sent through the negotiation channel.
206 void OnIce(const WebSocketIce *ice);
Alex Perryb3b50792020-01-18 16:13:45 -0800207
208 private:
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700209 void LocalCandidate(
210 struct rawrtc_peer_connection_ice_candidate *const candidate,
211 char const *const url);
Alex Perry5f474f22020-02-01 12:14:24 -0800212
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700213 // Handles a signaling channel being made.
214 void OnDataChannel(std::shared_ptr<ScopedDataChannel> channel);
215
216 // Handles data coming in on the signaling channel requesting subscription.
217 void HandleSignallingData(
218 struct mbuf *const
219 buffer, // nullable (in case partial delivery has been requested)
220 const enum rawrtc_data_channel_message_flag /*flags*/);
221
222 RawRTCConnection connection_;
223
224 ::seasocks::Server *server_;
225 ::seasocks::WebSocket *sock_;
226
227 struct ChannelState {
228 std::shared_ptr<ScopedDataChannel> data_channel;
229 bool requested = true;
230 };
231
James Kuszmaul9776b392023-01-14 14:08:08 -0800232 std::map<size_t, ChannelState> channels_;
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700233 const std::vector<std::unique_ptr<Subscriber>> &subscribers_;
234
235 const std::vector<FlatbufferDetachedBuffer<MessageHeader>> config_headers_;
James Kuszmaul71a81932020-12-15 21:08:01 -0800236
237 const EventLoop *const event_loop_;
Austin Schuh52e5e3a2021-04-24 22:30:02 -0700238
239 std::shared_ptr<ScopedDataChannel> channel_;
Alex Perryb3b50792020-01-18 16:13:45 -0800240};
241
242} // namespace web_proxy
243} // namespace aos
244
245#endif // AOS_NETWORK_WEB_PROXY_H_