1 /*
2 * Copyright 2011 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11 #include "webrtc/examples/peerconnection/server/peer_channel.h"
12
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16
17 #include <algorithm>
18
19 #include "webrtc/examples/peerconnection/server/data_socket.h"
20 #include "webrtc/examples/peerconnection/server/utils.h"
21 #include "webrtc/base/stringutils.h"
22 #include "webrtc/base/urlencode.h"
23
24 using rtc::sprintfn;
25
26 // Set to the peer id of the originator when messages are being
27 // exchanged between peers, but set to the id of the receiving peer
28 // itself when notifications are sent from the server about the state
29 // of other peers.
30 //
31 // WORKAROUND: Since support for CORS varies greatly from one browser to the
32 // next, we don't use a custom name for our peer-id header (originally it was
33 // "X-Peer-Id: "). Instead, we use a "simple header", "Pragma" which should
34 // always be exposed to CORS requests. There is a special CORS header devoted
35 // to exposing proprietary headers (Access-Control-Expose-Headers), however
36 // at this point it is not working correctly in some popular browsers.
37 static const char kPeerIdHeader[] = "Pragma: ";
38
39 static const char* kRequestPaths[] = {
40 "/wait", "/sign_out", "/message",
41 };
42
43 enum RequestPathIndex {
44 kWait,
45 kSignOut,
46 kMessage,
47 };
48
49 const size_t kMaxNameLength = 512;
50
51 //
52 // ChannelMember
53 //
54
55 int ChannelMember::s_member_id_ = 0;
56
ChannelMember(DataSocket * socket)57 ChannelMember::ChannelMember(DataSocket* socket)
58 : waiting_socket_(NULL), id_(++s_member_id_),
59 connected_(true), timestamp_(time(NULL)) {
60 assert(socket);
61 assert(socket->method() == DataSocket::GET);
62 assert(socket->PathEquals("/sign_in"));
63 name_ = rtc::UrlDecodeString(socket->request_arguments());
64 if (name_.empty())
65 name_ = "peer_" + int2str(id_);
66 else if (name_.length() > kMaxNameLength)
67 name_.resize(kMaxNameLength);
68
69 std::replace(name_.begin(), name_.end(), ',', '_');
70 }
71
~ChannelMember()72 ChannelMember::~ChannelMember() {
73 }
74
is_wait_request(DataSocket * ds) const75 bool ChannelMember::is_wait_request(DataSocket* ds) const {
76 return ds && ds->PathEquals(kRequestPaths[kWait]);
77 }
78
TimedOut()79 bool ChannelMember::TimedOut() {
80 return waiting_socket_ == NULL && (time(NULL) - timestamp_) > 30;
81 }
82
GetPeerIdHeader() const83 std::string ChannelMember::GetPeerIdHeader() const {
84 std::string ret(kPeerIdHeader + int2str(id_) + "\r\n");
85 return ret;
86 }
87
NotifyOfOtherMember(const ChannelMember & other)88 bool ChannelMember::NotifyOfOtherMember(const ChannelMember& other) {
89 assert(&other != this);
90 QueueResponse("200 OK", "text/plain", GetPeerIdHeader(),
91 other.GetEntry());
92 return true;
93 }
94
95 // Returns a string in the form "name,id,connected\n".
GetEntry() const96 std::string ChannelMember::GetEntry() const {
97 assert(name_.length() <= kMaxNameLength);
98
99 // name, 11-digit int, 1-digit bool, newline, null
100 char entry[kMaxNameLength + 15];
101 sprintfn(entry, sizeof(entry), "%s,%d,%d\n",
102 name_.substr(0, kMaxNameLength).c_str(), id_, connected_);
103 return entry;
104 }
105
ForwardRequestToPeer(DataSocket * ds,ChannelMember * peer)106 void ChannelMember::ForwardRequestToPeer(DataSocket* ds, ChannelMember* peer) {
107 assert(peer);
108 assert(ds);
109
110 std::string extra_headers(GetPeerIdHeader());
111
112 if (peer == this) {
113 ds->Send("200 OK", true, ds->content_type(), extra_headers,
114 ds->data());
115 } else {
116 printf("Client %s sending to %s\n",
117 name_.c_str(), peer->name().c_str());
118 peer->QueueResponse("200 OK", ds->content_type(), extra_headers,
119 ds->data());
120 ds->Send("200 OK", true, "text/plain", "", "");
121 }
122 }
123
OnClosing(DataSocket * ds)124 void ChannelMember::OnClosing(DataSocket* ds) {
125 if (ds == waiting_socket_) {
126 waiting_socket_ = NULL;
127 timestamp_ = time(NULL);
128 }
129 }
130
QueueResponse(const std::string & status,const std::string & content_type,const std::string & extra_headers,const std::string & data)131 void ChannelMember::QueueResponse(const std::string& status,
132 const std::string& content_type,
133 const std::string& extra_headers,
134 const std::string& data) {
135 if (waiting_socket_) {
136 assert(queue_.size() == 0);
137 assert(waiting_socket_->method() == DataSocket::GET);
138 bool ok = waiting_socket_->Send(status, true, content_type, extra_headers,
139 data);
140 if (!ok) {
141 printf("Failed to deliver data to waiting socket\n");
142 }
143 waiting_socket_ = NULL;
144 timestamp_ = time(NULL);
145 } else {
146 QueuedResponse qr;
147 qr.status = status;
148 qr.content_type = content_type;
149 qr.extra_headers = extra_headers;
150 qr.data = data;
151 queue_.push(qr);
152 }
153 }
154
SetWaitingSocket(DataSocket * ds)155 void ChannelMember::SetWaitingSocket(DataSocket* ds) {
156 assert(ds->method() == DataSocket::GET);
157 if (ds && !queue_.empty()) {
158 assert(waiting_socket_ == NULL);
159 const QueuedResponse& response = queue_.front();
160 ds->Send(response.status, true, response.content_type,
161 response.extra_headers, response.data);
162 queue_.pop();
163 } else {
164 waiting_socket_ = ds;
165 }
166 }
167
168 //
169 // PeerChannel
170 //
171
172 // static
IsPeerConnection(const DataSocket * ds)173 bool PeerChannel::IsPeerConnection(const DataSocket* ds) {
174 assert(ds);
175 return (ds->method() == DataSocket::POST && ds->content_length() > 0) ||
176 (ds->method() == DataSocket::GET && ds->PathEquals("/sign_in"));
177 }
178
Lookup(DataSocket * ds) const179 ChannelMember* PeerChannel::Lookup(DataSocket* ds) const {
180 assert(ds);
181
182 if (ds->method() != DataSocket::GET && ds->method() != DataSocket::POST)
183 return NULL;
184
185 size_t i = 0;
186 for (; i < ARRAYSIZE(kRequestPaths); ++i) {
187 if (ds->PathEquals(kRequestPaths[i]))
188 break;
189 }
190
191 if (i == ARRAYSIZE(kRequestPaths))
192 return NULL;
193
194 std::string args(ds->request_arguments());
195 static const char kPeerId[] = "peer_id=";
196 size_t found = args.find(kPeerId);
197 if (found == std::string::npos)
198 return NULL;
199
200 int id = atoi(&args[found + ARRAYSIZE(kPeerId) - 1]);
201 Members::const_iterator iter = members_.begin();
202 for (; iter != members_.end(); ++iter) {
203 if (id == (*iter)->id()) {
204 if (i == kWait)
205 (*iter)->SetWaitingSocket(ds);
206 if (i == kSignOut)
207 (*iter)->set_disconnected();
208 return *iter;
209 }
210 }
211
212 return NULL;
213 }
214
IsTargetedRequest(const DataSocket * ds) const215 ChannelMember* PeerChannel::IsTargetedRequest(const DataSocket* ds) const {
216 assert(ds);
217 // Regardless of GET or POST, we look for the peer_id parameter
218 // only in the request_path.
219 const std::string& path = ds->request_path();
220 size_t args = path.find('?');
221 if (args == std::string::npos)
222 return NULL;
223 size_t found;
224 const char kTargetPeerIdParam[] = "to=";
225 do {
226 found = path.find(kTargetPeerIdParam, args);
227 if (found == std::string::npos)
228 return NULL;
229 if (found == (args + 1) || path[found - 1] == '&') {
230 found += ARRAYSIZE(kTargetPeerIdParam) - 1;
231 break;
232 }
233 args = found + ARRAYSIZE(kTargetPeerIdParam) - 1;
234 } while (true);
235 int id = atoi(&path[found]);
236 Members::const_iterator i = members_.begin();
237 for (; i != members_.end(); ++i) {
238 if ((*i)->id() == id) {
239 return *i;
240 }
241 }
242 return NULL;
243 }
244
AddMember(DataSocket * ds)245 bool PeerChannel::AddMember(DataSocket* ds) {
246 assert(IsPeerConnection(ds));
247 ChannelMember* new_guy = new ChannelMember(ds);
248 Members failures;
249 BroadcastChangedState(*new_guy, &failures);
250 HandleDeliveryFailures(&failures);
251 members_.push_back(new_guy);
252
253 printf("New member added (total=%s): %s\n",
254 size_t2str(members_.size()).c_str(), new_guy->name().c_str());
255
256 // Let the newly connected peer know about other members of the channel.
257 std::string content_type;
258 std::string response = BuildResponseForNewMember(*new_guy, &content_type);
259 ds->Send("200 Added", true, content_type, new_guy->GetPeerIdHeader(),
260 response);
261 return true;
262 }
263
CloseAll()264 void PeerChannel::CloseAll() {
265 Members::const_iterator i = members_.begin();
266 for (; i != members_.end(); ++i) {
267 (*i)->QueueResponse("200 OK", "text/plain", "", "Server shutting down");
268 }
269 DeleteAll();
270 }
271
OnClosing(DataSocket * ds)272 void PeerChannel::OnClosing(DataSocket* ds) {
273 for (Members::iterator i = members_.begin(); i != members_.end(); ++i) {
274 ChannelMember* m = (*i);
275 m->OnClosing(ds);
276 if (!m->connected()) {
277 i = members_.erase(i);
278 Members failures;
279 BroadcastChangedState(*m, &failures);
280 HandleDeliveryFailures(&failures);
281 delete m;
282 if (i == members_.end())
283 break;
284 }
285 }
286 printf("Total connected: %s\n", size_t2str(members_.size()).c_str());
287 }
288
CheckForTimeout()289 void PeerChannel::CheckForTimeout() {
290 for (Members::iterator i = members_.begin(); i != members_.end(); ++i) {
291 ChannelMember* m = (*i);
292 if (m->TimedOut()) {
293 printf("Timeout: %s\n", m->name().c_str());
294 m->set_disconnected();
295 i = members_.erase(i);
296 Members failures;
297 BroadcastChangedState(*m, &failures);
298 HandleDeliveryFailures(&failures);
299 delete m;
300 if (i == members_.end())
301 break;
302 }
303 }
304 }
305
DeleteAll()306 void PeerChannel::DeleteAll() {
307 for (Members::iterator i = members_.begin(); i != members_.end(); ++i)
308 delete (*i);
309 members_.clear();
310 }
311
BroadcastChangedState(const ChannelMember & member,Members * delivery_failures)312 void PeerChannel::BroadcastChangedState(const ChannelMember& member,
313 Members* delivery_failures) {
314 // This function should be called prior to DataSocket::Close().
315 assert(delivery_failures);
316
317 if (!member.connected()) {
318 printf("Member disconnected: %s\n", member.name().c_str());
319 }
320
321 Members::iterator i = members_.begin();
322 for (; i != members_.end(); ++i) {
323 if (&member != (*i)) {
324 if (!(*i)->NotifyOfOtherMember(member)) {
325 (*i)->set_disconnected();
326 delivery_failures->push_back(*i);
327 i = members_.erase(i);
328 if (i == members_.end())
329 break;
330 }
331 }
332 }
333 }
334
HandleDeliveryFailures(Members * failures)335 void PeerChannel::HandleDeliveryFailures(Members* failures) {
336 assert(failures);
337
338 while (!failures->empty()) {
339 Members::iterator i = failures->begin();
340 ChannelMember* member = *i;
341 assert(!member->connected());
342 failures->erase(i);
343 BroadcastChangedState(*member, failures);
344 delete member;
345 }
346 }
347
348 // Builds a simple list of "name,id\n" entries for each member.
BuildResponseForNewMember(const ChannelMember & member,std::string * content_type)349 std::string PeerChannel::BuildResponseForNewMember(const ChannelMember& member,
350 std::string* content_type) {
351 assert(content_type);
352
353 *content_type = "text/plain";
354 // The peer itself will always be the first entry.
355 std::string response(member.GetEntry());
356 for (Members::iterator i = members_.begin(); i != members_.end(); ++i) {
357 if (member.id() != (*i)->id()) {
358 assert((*i)->connected());
359 response += (*i)->GetEntry();
360 }
361 }
362
363 return response;
364 }
365