1 /*
2 * libjingle
3 * Copyright 2011, Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28 #include "talk/examples/peerconnection/server/peer_channel.h"
29
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33
34 #include <algorithm>
35
36 #include "talk/examples/peerconnection/server/data_socket.h"
37 #include "talk/examples/peerconnection/server/utils.h"
38
39 // Set to the peer id of the originator when messages are being
40 // exchanged between peers, but set to the id of the receiving peer
41 // itself when notifications are sent from the server about the state
42 // of other peers.
43 //
44 // WORKAROUND: Since support for CORS varies greatly from one browser to the
45 // next, we don't use a custom name for our peer-id header (originally it was
46 // "X-Peer-Id: "). Instead, we use a "simple header", "Pragma" which should
47 // always be exposed to CORS requests. There is a special CORS header devoted
48 // to exposing proprietary headers (Access-Control-Expose-Headers), however
49 // at this point it is not working correctly in some popular browsers.
50 static const char kPeerIdHeader[] = "Pragma: ";
51
52 static const char* kRequestPaths[] = {
53 "/wait", "/sign_out", "/message",
54 };
55
56 enum RequestPathIndex {
57 kWait,
58 kSignOut,
59 kMessage,
60 };
61
62 //
63 // ChannelMember
64 //
65
66 int ChannelMember::s_member_id_ = 0;
67
ChannelMember(DataSocket * socket)68 ChannelMember::ChannelMember(DataSocket* socket)
69 : waiting_socket_(NULL), id_(++s_member_id_),
70 connected_(true), timestamp_(time(NULL)) {
71 assert(socket);
72 assert(socket->method() == DataSocket::GET);
73 assert(socket->PathEquals("/sign_in"));
74 name_ = socket->request_arguments(); // TODO: urldecode
75 if (!name_.length())
76 name_ = "peer_" + int2str(id_);
77 std::replace(name_.begin(), name_.end(), ',', '_');
78 }
79
~ChannelMember()80 ChannelMember::~ChannelMember() {
81 }
82
is_wait_request(DataSocket * ds) const83 bool ChannelMember::is_wait_request(DataSocket* ds) const {
84 return ds && ds->PathEquals(kRequestPaths[kWait]);
85 }
86
TimedOut()87 bool ChannelMember::TimedOut() {
88 return waiting_socket_ == NULL && (time(NULL) - timestamp_) > 30;
89 }
90
GetPeerIdHeader() const91 std::string ChannelMember::GetPeerIdHeader() const {
92 std::string ret(kPeerIdHeader + int2str(id_) + "\r\n");
93 return ret;
94 }
95
NotifyOfOtherMember(const ChannelMember & other)96 bool ChannelMember::NotifyOfOtherMember(const ChannelMember& other) {
97 assert(&other != this);
98 QueueResponse("200 OK", "text/plain", GetPeerIdHeader(),
99 other.GetEntry());
100 return true;
101 }
102
103 // Returns a string in the form "name,id\n".
GetEntry() const104 std::string ChannelMember::GetEntry() const {
105 char entry[1024] = {0};
106 sprintf(entry, "%s,%i,%i\n", name_.c_str(), id_, connected_); // NOLINT
107 return entry;
108 }
109
ForwardRequestToPeer(DataSocket * ds,ChannelMember * peer)110 void ChannelMember::ForwardRequestToPeer(DataSocket* ds, ChannelMember* peer) {
111 assert(peer);
112 assert(ds);
113
114 std::string extra_headers(GetPeerIdHeader());
115
116 if (peer == this) {
117 ds->Send("200 OK", true, ds->content_type(), extra_headers,
118 ds->data());
119 } else {
120 printf("Client %s sending to %s\n",
121 name_.c_str(), peer->name().c_str());
122 peer->QueueResponse("200 OK", ds->content_type(), extra_headers,
123 ds->data());
124 ds->Send("200 OK", true, "text/plain", "", "");
125 }
126 }
127
OnClosing(DataSocket * ds)128 void ChannelMember::OnClosing(DataSocket* ds) {
129 if (ds == waiting_socket_) {
130 waiting_socket_ = NULL;
131 timestamp_ = time(NULL);
132 }
133 }
134
QueueResponse(const std::string & status,const std::string & content_type,const std::string & extra_headers,const std::string & data)135 void ChannelMember::QueueResponse(const std::string& status,
136 const std::string& content_type,
137 const std::string& extra_headers,
138 const std::string& data) {
139 if (waiting_socket_) {
140 assert(queue_.size() == 0);
141 assert(waiting_socket_->method() == DataSocket::GET);
142 bool ok = waiting_socket_->Send(status, true, content_type, extra_headers,
143 data);
144 if (!ok) {
145 printf("Failed to deliver data to waiting socket\n");
146 }
147 waiting_socket_ = NULL;
148 timestamp_ = time(NULL);
149 } else {
150 QueuedResponse qr;
151 qr.status = status;
152 qr.content_type = content_type;
153 qr.extra_headers = extra_headers;
154 qr.data = data;
155 queue_.push(qr);
156 }
157 }
158
SetWaitingSocket(DataSocket * ds)159 void ChannelMember::SetWaitingSocket(DataSocket* ds) {
160 assert(ds->method() == DataSocket::GET);
161 if (ds && !queue_.empty()) {
162 assert(waiting_socket_ == NULL);
163 const QueuedResponse& response = queue_.front();
164 ds->Send(response.status, true, response.content_type,
165 response.extra_headers, response.data);
166 queue_.pop();
167 } else {
168 waiting_socket_ = ds;
169 }
170 }
171
172
173 //
174 // PeerChannel
175 //
176
177 // static
IsPeerConnection(const DataSocket * ds)178 bool PeerChannel::IsPeerConnection(const DataSocket* ds) {
179 assert(ds);
180 return (ds->method() == DataSocket::POST && ds->content_length() > 0) ||
181 (ds->method() == DataSocket::GET && ds->PathEquals("/sign_in"));
182 }
183
Lookup(DataSocket * ds) const184 ChannelMember* PeerChannel::Lookup(DataSocket* ds) const {
185 assert(ds);
186
187 if (ds->method() != DataSocket::GET && ds->method() != DataSocket::POST)
188 return NULL;
189
190 size_t i = 0;
191 for (; i < ARRAYSIZE(kRequestPaths); ++i) {
192 if (ds->PathEquals(kRequestPaths[i]))
193 break;
194 }
195
196 if (i == ARRAYSIZE(kRequestPaths))
197 return NULL;
198
199 std::string args(ds->request_arguments());
200 static const char kPeerId[] = "peer_id=";
201 size_t found = args.find(kPeerId);
202 if (found == std::string::npos)
203 return NULL;
204
205 int id = atoi(&args[found + ARRAYSIZE(kPeerId) - 1]);
206 Members::const_iterator iter = members_.begin();
207 for (; iter != members_.end(); ++iter) {
208 if (id == (*iter)->id()) {
209 if (i == kWait)
210 (*iter)->SetWaitingSocket(ds);
211 if (i == kSignOut)
212 (*iter)->set_disconnected();
213 return *iter;
214 }
215 }
216
217 return NULL;
218 }
219
IsTargetedRequest(const DataSocket * ds) const220 ChannelMember* PeerChannel::IsTargetedRequest(const DataSocket* ds) const {
221 assert(ds);
222 // Regardless of GET or POST, we look for the peer_id parameter
223 // only in the request_path.
224 const std::string& path = ds->request_path();
225 size_t args = path.find('?');
226 if (args == std::string::npos)
227 return NULL;
228 size_t found;
229 const char kTargetPeerIdParam[] = "to=";
230 do {
231 found = path.find(kTargetPeerIdParam, args);
232 if (found == std::string::npos)
233 return NULL;
234 if (found == (args + 1) || path[found - 1] == '&') {
235 found += ARRAYSIZE(kTargetPeerIdParam) - 1;
236 break;
237 }
238 args = found + ARRAYSIZE(kTargetPeerIdParam) - 1;
239 } while (true);
240 int id = atoi(&path[found]);
241 Members::const_iterator i = members_.begin();
242 for (; i != members_.end(); ++i) {
243 if ((*i)->id() == id) {
244 return *i;
245 }
246 }
247 return NULL;
248 }
249
AddMember(DataSocket * ds)250 bool PeerChannel::AddMember(DataSocket* ds) {
251 assert(IsPeerConnection(ds));
252 ChannelMember* new_guy = new ChannelMember(ds);
253 Members failures;
254 BroadcastChangedState(*new_guy, &failures);
255 HandleDeliveryFailures(&failures);
256 members_.push_back(new_guy);
257
258 printf("New member added (total=%s): %s\n",
259 size_t2str(members_.size()).c_str(), new_guy->name().c_str());
260
261 // Let the newly connected peer know about other members of the channel.
262 std::string content_type;
263 std::string response = BuildResponseForNewMember(*new_guy, &content_type);
264 ds->Send("200 Added", true, content_type, new_guy->GetPeerIdHeader(),
265 response);
266 return true;
267 }
268
CloseAll()269 void PeerChannel::CloseAll() {
270 Members::const_iterator i = members_.begin();
271 for (; i != members_.end(); ++i) {
272 (*i)->QueueResponse("200 OK", "text/plain", "", "Server shutting down");
273 }
274 DeleteAll();
275 }
276
OnClosing(DataSocket * ds)277 void PeerChannel::OnClosing(DataSocket* ds) {
278 for (Members::iterator i = members_.begin(); i != members_.end(); ++i) {
279 ChannelMember* m = (*i);
280 m->OnClosing(ds);
281 if (!m->connected()) {
282 i = members_.erase(i);
283 Members failures;
284 BroadcastChangedState(*m, &failures);
285 HandleDeliveryFailures(&failures);
286 delete m;
287 if (i == members_.end())
288 break;
289 }
290 }
291 printf("Total connected: %s\n", size_t2str(members_.size()).c_str());
292 }
293
CheckForTimeout()294 void PeerChannel::CheckForTimeout() {
295 for (Members::iterator i = members_.begin(); i != members_.end(); ++i) {
296 ChannelMember* m = (*i);
297 if (m->TimedOut()) {
298 printf("Timeout: %s\n", m->name().c_str());
299 m->set_disconnected();
300 i = members_.erase(i);
301 Members failures;
302 BroadcastChangedState(*m, &failures);
303 HandleDeliveryFailures(&failures);
304 delete m;
305 if (i == members_.end())
306 break;
307 }
308 }
309 }
310
DeleteAll()311 void PeerChannel::DeleteAll() {
312 for (Members::iterator i = members_.begin(); i != members_.end(); ++i)
313 delete (*i);
314 members_.clear();
315 }
316
BroadcastChangedState(const ChannelMember & member,Members * delivery_failures)317 void PeerChannel::BroadcastChangedState(const ChannelMember& member,
318 Members* delivery_failures) {
319 // This function should be called prior to DataSocket::Close().
320 assert(delivery_failures);
321
322 if (!member.connected()) {
323 printf("Member disconnected: %s\n", member.name().c_str());
324 }
325
326 Members::iterator i = members_.begin();
327 for (; i != members_.end(); ++i) {
328 if (&member != (*i)) {
329 if (!(*i)->NotifyOfOtherMember(member)) {
330 (*i)->set_disconnected();
331 delivery_failures->push_back(*i);
332 i = members_.erase(i);
333 if (i == members_.end())
334 break;
335 }
336 }
337 }
338 }
339
HandleDeliveryFailures(Members * failures)340 void PeerChannel::HandleDeliveryFailures(Members* failures) {
341 assert(failures);
342
343 while (!failures->empty()) {
344 Members::iterator i = failures->begin();
345 ChannelMember* member = *i;
346 assert(!member->connected());
347 failures->erase(i);
348 BroadcastChangedState(*member, failures);
349 delete member;
350 }
351 }
352
353 // Builds a simple list of "name,id\n" entries for each member.
BuildResponseForNewMember(const ChannelMember & member,std::string * content_type)354 std::string PeerChannel::BuildResponseForNewMember(const ChannelMember& member,
355 std::string* content_type) {
356 assert(content_type);
357
358 *content_type = "text/plain";
359 // The peer itself will always be the first entry.
360 std::string response(member.GetEntry());
361 for (Members::iterator i = members_.begin(); i != members_.end(); ++i) {
362 if (member.id() != (*i)->id()) {
363 assert((*i)->connected());
364 response += (*i)->GetEntry();
365 }
366 }
367
368 return response;
369 }
370