blob: f4da7d977cd19289bbaf24c330b76cbcb618c3d1 [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
3#include "aos/flatbuffer_merge.h"
4#include "aos/network/connect_generated.h"
Alex Perryb3b50792020-01-18 16:13:45 -08005#include "aos/network/web_proxy_generated.h"
Alex Perry5f474f22020-02-01 12:14:24 -08006#include "aos/network/web_proxy_utils.h"
Alex Perryb3b50792020-01-18 16:13:45 -08007#include "api/create_peerconnection_factory.h"
8#include "glog/logging.h"
9
10namespace aos {
11namespace web_proxy {
12
13namespace {
14// Based on webrtc examples. In our controlled environment we expect setting sdp
15// to always succeed, and we can't do anything about a failure, so just ignore
16// everything.
17class DummySetSessionDescriptionObserver
18 : public webrtc::SetSessionDescriptionObserver {
19 public:
20 static DummySetSessionDescriptionObserver *Create() {
21 return new rtc::RefCountedObject<DummySetSessionDescriptionObserver>();
22 }
23 virtual void OnSuccess() {}
24 virtual void OnFailure(webrtc::RTCError error) {}
25};
26
27} // namespace
28
Alex Perry5f474f22020-02-01 12:14:24 -080029WebsocketHandler::WebsocketHandler(
30 ::seasocks::Server *server,
31 const std::vector<std::unique_ptr<Subscriber>> &subscribers,
32 const aos::FlatbufferDetachedBuffer<aos::Configuration> &config)
33 : server_(server), subscribers_(subscribers), config_(config) {}
Alex Perryb3b50792020-01-18 16:13:45 -080034
35void WebsocketHandler::onConnect(::seasocks::WebSocket *sock) {
36 std::unique_ptr<Connection> conn =
Alex Perry5f474f22020-02-01 12:14:24 -080037 std::make_unique<Connection>(sock, server_, subscribers_, config_);
Alex Perryb3b50792020-01-18 16:13:45 -080038 connections_.insert({sock, std::move(conn)});
39}
40
41void WebsocketHandler::onData(::seasocks::WebSocket *sock, const uint8_t *data,
42 size_t size) {
43 connections_[sock]->HandleWebSocketData(data, size);
44}
45
46void WebsocketHandler::onDisconnect(::seasocks::WebSocket *sock) {
47 connections_.erase(sock);
48}
49
Alex Perry5f474f22020-02-01 12:14:24 -080050void Subscriber::RunIteration() {
51 if (channels_.empty()) {
52 return;
53 }
54
55 fetcher_->Fetch();
Alex Perry22824d72020-02-29 17:11:43 -080056 VLOG(2) << "Sending a message with " << GetPacketCount(fetcher_->context())
57 << "packets";
Alex Perry5f474f22020-02-01 12:14:24 -080058 for (int packet_index = 0; packet_index < GetPacketCount(fetcher_->context());
59 ++packet_index) {
60 flatbuffers::Offset<MessageHeader> message =
61 PackMessage(&fbb_, fetcher_->context(), channel_index_, packet_index);
62 fbb_.Finish(message);
63
64 const flatbuffers::DetachedBuffer buffer = fbb_.Release();
65
66 webrtc::DataBuffer data_buffer(
67 rtc::CopyOnWriteBuffer(buffer.data(), buffer.size()),
68 true /* binary array */);
69 for (auto conn : channels_) {
70 conn->Send(data_buffer);
71 }
72 }
73}
74
75bool Subscriber::Compare(const Channel *channel) const {
Alex Perry22824d72020-02-29 17:11:43 -080076 return channel->name()->string_view() ==
77 fetcher_->channel()->name()->string_view() &&
78 channel->type()->string_view() ==
79 fetcher_->channel()->type()->string_view();
Alex Perry5f474f22020-02-01 12:14:24 -080080}
81
82Connection::Connection(
83 ::seasocks::WebSocket *sock, ::seasocks::Server *server,
84 const std::vector<std::unique_ptr<Subscriber>> &subscribers,
85 const aos::FlatbufferDetachedBuffer<aos::Configuration> &config)
86 : sock_(sock),
87 server_(server),
88 subscribers_(subscribers),
89 config_(config) {}
Alex Perryb3b50792020-01-18 16:13:45 -080090
91// Function called for web socket data. Parses the flatbuffer and handles it
92// appropriately.
93void Connection::HandleWebSocketData(const uint8_t *data, size_t size) {
94 const WebSocketMessage *message =
95 flatbuffers::GetRoot<WebSocketMessage>(data);
96 switch (message->payload_type()) {
97 case Payload::WebSocketSdp: {
98 const WebSocketSdp *offer = message->payload_as_WebSocketSdp();
99 if (offer->type() != SdpType::OFFER) {
100 LOG(WARNING) << "Got the wrong sdp type from client";
101 break;
102 }
103 const flatbuffers::String *sdp = offer->payload();
104 webrtc::SdpParseError error;
105 std::unique_ptr<webrtc::SessionDescriptionInterface> desc =
106 CreateSessionDescription(webrtc::SdpType::kOffer, sdp->str(), &error);
107 if (!desc) {
108 LOG(WARNING) << "Failed to parse sdp description: "
109 << error.description;
110 // TODO(alex): send a message back to browser for failure.
111 break;
112 }
113
114 // We can only start creating the PeerConnection once we have something to
115 // give it, so we wait until we get an offer before starting.
116 webrtc::PeerConnectionInterface::RTCConfiguration config;
117 config.sdp_semantics = webrtc::SdpSemantics::kUnifiedPlan;
118 config.enable_dtls_srtp = true;
119
120 std::unique_ptr<rtc::Thread> signaling_thread = rtc::Thread::Create();
121 signaling_thread->SetName("signaling_thread", nullptr);
122 signaling_thread->Start();
123
124 webrtc::PeerConnectionFactoryDependencies factory_deps;
125 factory_deps.signaling_thread = signaling_thread.release();
126 rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface> factory =
127 CreateModularPeerConnectionFactory(std::move(factory_deps));
128
129 peer_connection_ =
130 factory->CreatePeerConnection(config, nullptr, nullptr, this);
131
132 peer_connection_->SetRemoteDescription(
133 DummySetSessionDescriptionObserver::Create(), desc.release());
134
135 peer_connection_->CreateAnswer(
136 this, webrtc::PeerConnectionInterface::RTCOfferAnswerOptions());
137 break;
138 }
139 case Payload::WebSocketIce: {
140 const WebSocketIce *ice = message->payload_as_WebSocketIce();
141 std::string candidate = ice->candidate()->str();
142 std::string sdpMid = ice->sdpMid()->str();
143 int sdpMLineIndex = ice->sdpMLineIndex();
144 webrtc::SdpParseError error;
145 webrtc::IceCandidateInterface *ice_candidate =
146 webrtc::CreateIceCandidate(sdpMid, sdpMLineIndex, candidate, &error);
147 if (!ice_candidate) {
148 LOG(WARNING) << "Failed to parse ice candidate: " << error.description;
149 // TODO(alex): send a message back to browser for failure.
150 break;
151 }
152 peer_connection_->AddIceCandidate(ice_candidate);
153 break;
154 }
155 default: { break; }
156 }
157}
158
Alex Perry5f474f22020-02-01 12:14:24 -0800159void Connection::Send(const ::flatbuffers::DetachedBuffer &buffer) const {
160 webrtc::DataBuffer data_buffer(
161 rtc::CopyOnWriteBuffer(buffer.data(), buffer.size()),
162 true /* binary array */);
Alex Perry22824d72020-02-29 17:11:43 -0800163 VLOG(2) << "Sending " << buffer.size() << "bytes to a client";
Alex Perry5f474f22020-02-01 12:14:24 -0800164 data_channel_->Send(data_buffer);
165}
166
Alex Perryb3b50792020-01-18 16:13:45 -0800167void Connection::OnDataChannel(
168 rtc::scoped_refptr<webrtc::DataChannelInterface> channel) {
169 data_channel_ = channel;
170 data_channel_->RegisterObserver(this);
171}
172
173void Connection::OnIceCandidate(
174 const webrtc::IceCandidateInterface *candidate) {
175 flatbuffers::FlatBufferBuilder fbb(512);
176 std::string ice_string;
177 candidate->ToString(&ice_string);
178
179 flatbuffers::Offset<WebSocketIce> ice_fb = CreateWebSocketIceDirect(
180 fbb, ice_string.c_str(), candidate->sdp_mid().c_str(),
181 candidate->sdp_mline_index());
182 flatbuffers::Offset<WebSocketMessage> ice_message =
183 CreateWebSocketMessage(fbb, Payload::WebSocketIce, ice_fb.Union());
184 fbb.Finish(ice_message);
185
186 server_->execute(std::make_shared<UpdateData>(sock_, fbb.Release()));
187}
188
189// This is the callback for creating an sdp. We have to manually assign it
190// locally and send it to the client.
191void Connection::OnSuccess(webrtc::SessionDescriptionInterface *desc) {
192 peer_connection_->SetLocalDescription(
193 DummySetSessionDescriptionObserver::Create(), desc);
194 flatbuffers::FlatBufferBuilder fbb(512);
195 std::string answer_string;
196 desc->ToString(&answer_string);
197 flatbuffers::Offset<WebSocketSdp> sdp_fb =
198 CreateWebSocketSdpDirect(fbb, SdpType::ANSWER, answer_string.c_str());
199 flatbuffers::Offset<WebSocketMessage> answer_message =
200 CreateWebSocketMessage(fbb, Payload::WebSocketSdp, sdp_fb.Union());
201 fbb.Finish(answer_message);
202
203 server_->execute(std::make_shared<UpdateData>(sock_, fbb.Release()));
204}
205
Alex Perry5f474f22020-02-01 12:14:24 -0800206// Wait until the data channel is ready for data before sending the config.
207void Connection::OnStateChange() {
208 if (peer_connection_.get() != nullptr &&
209 data_channel_->state() == webrtc::DataChannelInterface::kOpen) {
210 Send(config_.buffer());
211 }
212}
213
214// Handle DataChannel messages. Subscribe to each listener that matches the
215// subscribe message
Alex Perryb3b50792020-01-18 16:13:45 -0800216void Connection::OnMessage(const webrtc::DataBuffer &buffer) {
Alex Perry5f474f22020-02-01 12:14:24 -0800217 const message_bridge::Connect *message =
218 flatbuffers::GetRoot<message_bridge::Connect>(buffer.data.data());
Alex Perry22824d72020-02-29 17:11:43 -0800219 VLOG(2) << "Got a connect message " << aos::FlatbufferToJson(message);
Alex Perry5f474f22020-02-01 12:14:24 -0800220 for (auto &subscriber : subscribers_) {
Alex Perry656dd5b2020-02-16 17:20:42 -0800221 // Make sure the subscriber is for a channel on this node.
222 if (subscriber.get() == nullptr) {
Alex Perry22824d72020-02-29 17:11:43 -0800223 VLOG(2) << ": Null subscriber";
Alex Perry656dd5b2020-02-16 17:20:42 -0800224 continue;
225 }
Alex Perry5f474f22020-02-01 12:14:24 -0800226 bool found_match = false;
227 for (auto channel : *message->channels_to_transfer()) {
228 if (subscriber->Compare(channel)) {
229 int index = subscriber->index();
230 auto it = channels_.find(index);
231 if (it == channels_.end()) {
232 auto pair = channels_.insert(
233 {index, peer_connection_->CreateDataChannel(
234 channel->name()->str() + "/" + channel->type()->str(),
235 nullptr)});
236 it = pair.first;
237 }
238 subscriber->AddListener(it->second);
239
240 VLOG(1) << "Subscribe to: " << channel->type()->str();
241 found_match = true;
242 break;
243 }
244 }
245 if (!found_match) {
246 int index = subscriber->index();
247 auto it = channels_.find(index);
248 subscriber->RemoveListener(it->second);
249 }
250 }
Alex Perryb3b50792020-01-18 16:13:45 -0800251}
252
253} // namespace web_proxy
254} // namespace aos