blob: f4a8ce8b58e40adcd70077b0f62e06dce2a53388 [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();
56 for (int packet_index = 0; packet_index < GetPacketCount(fetcher_->context());
57 ++packet_index) {
58 flatbuffers::Offset<MessageHeader> message =
59 PackMessage(&fbb_, fetcher_->context(), channel_index_, packet_index);
60 fbb_.Finish(message);
61
62 const flatbuffers::DetachedBuffer buffer = fbb_.Release();
63
64 webrtc::DataBuffer data_buffer(
65 rtc::CopyOnWriteBuffer(buffer.data(), buffer.size()),
66 true /* binary array */);
67 for (auto conn : channels_) {
68 conn->Send(data_buffer);
69 }
70 }
71}
72
73bool Subscriber::Compare(const Channel *channel) const {
74 return channel->name() == fetcher_->channel()->name() &&
75 channel->type() == fetcher_->channel()->type();
76}
77
78Connection::Connection(
79 ::seasocks::WebSocket *sock, ::seasocks::Server *server,
80 const std::vector<std::unique_ptr<Subscriber>> &subscribers,
81 const aos::FlatbufferDetachedBuffer<aos::Configuration> &config)
82 : sock_(sock),
83 server_(server),
84 subscribers_(subscribers),
85 config_(config) {}
Alex Perryb3b50792020-01-18 16:13:45 -080086
87// Function called for web socket data. Parses the flatbuffer and handles it
88// appropriately.
89void Connection::HandleWebSocketData(const uint8_t *data, size_t size) {
90 const WebSocketMessage *message =
91 flatbuffers::GetRoot<WebSocketMessage>(data);
92 switch (message->payload_type()) {
93 case Payload::WebSocketSdp: {
94 const WebSocketSdp *offer = message->payload_as_WebSocketSdp();
95 if (offer->type() != SdpType::OFFER) {
96 LOG(WARNING) << "Got the wrong sdp type from client";
97 break;
98 }
99 const flatbuffers::String *sdp = offer->payload();
100 webrtc::SdpParseError error;
101 std::unique_ptr<webrtc::SessionDescriptionInterface> desc =
102 CreateSessionDescription(webrtc::SdpType::kOffer, sdp->str(), &error);
103 if (!desc) {
104 LOG(WARNING) << "Failed to parse sdp description: "
105 << error.description;
106 // TODO(alex): send a message back to browser for failure.
107 break;
108 }
109
110 // We can only start creating the PeerConnection once we have something to
111 // give it, so we wait until we get an offer before starting.
112 webrtc::PeerConnectionInterface::RTCConfiguration config;
113 config.sdp_semantics = webrtc::SdpSemantics::kUnifiedPlan;
114 config.enable_dtls_srtp = true;
115
116 std::unique_ptr<rtc::Thread> signaling_thread = rtc::Thread::Create();
117 signaling_thread->SetName("signaling_thread", nullptr);
118 signaling_thread->Start();
119
120 webrtc::PeerConnectionFactoryDependencies factory_deps;
121 factory_deps.signaling_thread = signaling_thread.release();
122 rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface> factory =
123 CreateModularPeerConnectionFactory(std::move(factory_deps));
124
125 peer_connection_ =
126 factory->CreatePeerConnection(config, nullptr, nullptr, this);
127
128 peer_connection_->SetRemoteDescription(
129 DummySetSessionDescriptionObserver::Create(), desc.release());
130
131 peer_connection_->CreateAnswer(
132 this, webrtc::PeerConnectionInterface::RTCOfferAnswerOptions());
133 break;
134 }
135 case Payload::WebSocketIce: {
136 const WebSocketIce *ice = message->payload_as_WebSocketIce();
137 std::string candidate = ice->candidate()->str();
138 std::string sdpMid = ice->sdpMid()->str();
139 int sdpMLineIndex = ice->sdpMLineIndex();
140 webrtc::SdpParseError error;
141 webrtc::IceCandidateInterface *ice_candidate =
142 webrtc::CreateIceCandidate(sdpMid, sdpMLineIndex, candidate, &error);
143 if (!ice_candidate) {
144 LOG(WARNING) << "Failed to parse ice candidate: " << error.description;
145 // TODO(alex): send a message back to browser for failure.
146 break;
147 }
148 peer_connection_->AddIceCandidate(ice_candidate);
149 break;
150 }
151 default: { break; }
152 }
153}
154
Alex Perry5f474f22020-02-01 12:14:24 -0800155void Connection::Send(const ::flatbuffers::DetachedBuffer &buffer) const {
156 webrtc::DataBuffer data_buffer(
157 rtc::CopyOnWriteBuffer(buffer.data(), buffer.size()),
158 true /* binary array */);
159 data_channel_->Send(data_buffer);
160}
161
Alex Perryb3b50792020-01-18 16:13:45 -0800162void Connection::OnDataChannel(
163 rtc::scoped_refptr<webrtc::DataChannelInterface> channel) {
164 data_channel_ = channel;
165 data_channel_->RegisterObserver(this);
166}
167
168void Connection::OnIceCandidate(
169 const webrtc::IceCandidateInterface *candidate) {
170 flatbuffers::FlatBufferBuilder fbb(512);
171 std::string ice_string;
172 candidate->ToString(&ice_string);
173
174 flatbuffers::Offset<WebSocketIce> ice_fb = CreateWebSocketIceDirect(
175 fbb, ice_string.c_str(), candidate->sdp_mid().c_str(),
176 candidate->sdp_mline_index());
177 flatbuffers::Offset<WebSocketMessage> ice_message =
178 CreateWebSocketMessage(fbb, Payload::WebSocketIce, ice_fb.Union());
179 fbb.Finish(ice_message);
180
181 server_->execute(std::make_shared<UpdateData>(sock_, fbb.Release()));
182}
183
184// This is the callback for creating an sdp. We have to manually assign it
185// locally and send it to the client.
186void Connection::OnSuccess(webrtc::SessionDescriptionInterface *desc) {
187 peer_connection_->SetLocalDescription(
188 DummySetSessionDescriptionObserver::Create(), desc);
189 flatbuffers::FlatBufferBuilder fbb(512);
190 std::string answer_string;
191 desc->ToString(&answer_string);
192 flatbuffers::Offset<WebSocketSdp> sdp_fb =
193 CreateWebSocketSdpDirect(fbb, SdpType::ANSWER, answer_string.c_str());
194 flatbuffers::Offset<WebSocketMessage> answer_message =
195 CreateWebSocketMessage(fbb, Payload::WebSocketSdp, sdp_fb.Union());
196 fbb.Finish(answer_message);
197
198 server_->execute(std::make_shared<UpdateData>(sock_, fbb.Release()));
199}
200
Alex Perry5f474f22020-02-01 12:14:24 -0800201// Wait until the data channel is ready for data before sending the config.
202void Connection::OnStateChange() {
203 if (peer_connection_.get() != nullptr &&
204 data_channel_->state() == webrtc::DataChannelInterface::kOpen) {
205 Send(config_.buffer());
206 }
207}
208
209// Handle DataChannel messages. Subscribe to each listener that matches the
210// subscribe message
Alex Perryb3b50792020-01-18 16:13:45 -0800211void Connection::OnMessage(const webrtc::DataBuffer &buffer) {
Alex Perry5f474f22020-02-01 12:14:24 -0800212 const message_bridge::Connect *message =
213 flatbuffers::GetRoot<message_bridge::Connect>(buffer.data.data());
214 for (auto &subscriber : subscribers_) {
Alex Perry656dd5b2020-02-16 17:20:42 -0800215 // Make sure the subscriber is for a channel on this node.
216 if (subscriber.get() == nullptr) {
217 continue;
218 }
Alex Perry5f474f22020-02-01 12:14:24 -0800219 bool found_match = false;
220 for (auto channel : *message->channels_to_transfer()) {
221 if (subscriber->Compare(channel)) {
222 int index = subscriber->index();
223 auto it = channels_.find(index);
224 if (it == channels_.end()) {
225 auto pair = channels_.insert(
226 {index, peer_connection_->CreateDataChannel(
227 channel->name()->str() + "/" + channel->type()->str(),
228 nullptr)});
229 it = pair.first;
230 }
231 subscriber->AddListener(it->second);
232
233 VLOG(1) << "Subscribe to: " << channel->type()->str();
234 found_match = true;
235 break;
236 }
237 }
238 if (!found_match) {
239 int index = subscriber->index();
240 auto it = channels_.find(index);
241 subscriber->RemoveListener(it->second);
242 }
243 }
Alex Perryb3b50792020-01-18 16:13:45 -0800244}
245
246} // namespace web_proxy
247} // namespace aos