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.
50static const char kPeerIdHeader[] = "Pragma: ";
51
52static const char* kRequestPaths[] = {
53  "/wait", "/sign_out", "/message",
54};
55
56enum RequestPathIndex {
57  kWait,
58  kSignOut,
59  kMessage,
60};
61
62const size_t kMaxNameLength = 512;
63
64//
65// ChannelMember
66//
67
68int ChannelMember::s_member_id_ = 0;
69
70ChannelMember::ChannelMember(DataSocket* socket)
71  : waiting_socket_(NULL), id_(++s_member_id_),
72    connected_(true), timestamp_(time(NULL)) {
73  assert(socket);
74  assert(socket->method() == DataSocket::GET);
75  assert(socket->PathEquals("/sign_in"));
76  name_ = socket->request_arguments();  // TODO: urldecode
77  if (name_.empty())
78    name_ = "peer_" + int2str(id_);
79  else if (name_.length() > kMaxNameLength)
80    name_.resize(kMaxNameLength);
81
82  std::replace(name_.begin(), name_.end(), ',', '_');
83}
84
85ChannelMember::~ChannelMember() {
86}
87
88bool ChannelMember::is_wait_request(DataSocket* ds) const {
89  return ds && ds->PathEquals(kRequestPaths[kWait]);
90}
91
92bool ChannelMember::TimedOut() {
93  return waiting_socket_ == NULL && (time(NULL) - timestamp_) > 30;
94}
95
96std::string ChannelMember::GetPeerIdHeader() const {
97  std::string ret(kPeerIdHeader + int2str(id_) + "\r\n");
98  return ret;
99}
100
101bool ChannelMember::NotifyOfOtherMember(const ChannelMember& other) {
102  assert(&other != this);
103  QueueResponse("200 OK", "text/plain", GetPeerIdHeader(),
104                other.GetEntry());
105  return true;
106}
107
108// Returns a string in the form "name,id,connected\n".
109std::string ChannelMember::GetEntry() const {
110  assert(name_.length() <= kMaxNameLength);
111  char entry[1024] = {0};
112  sprintf(entry, "%s,%i,%i\n", name_.c_str(), id_, connected_);  // NOLINT
113  return entry;
114}
115
116void ChannelMember::ForwardRequestToPeer(DataSocket* ds, ChannelMember* peer) {
117  assert(peer);
118  assert(ds);
119
120  std::string extra_headers(GetPeerIdHeader());
121
122  if (peer == this) {
123    ds->Send("200 OK", true, ds->content_type(), extra_headers,
124             ds->data());
125  } else {
126    printf("Client %s sending to %s\n",
127        name_.c_str(), peer->name().c_str());
128    peer->QueueResponse("200 OK", ds->content_type(), extra_headers,
129                        ds->data());
130    ds->Send("200 OK", true, "text/plain", "", "");
131  }
132}
133
134void ChannelMember::OnClosing(DataSocket* ds) {
135  if (ds == waiting_socket_) {
136    waiting_socket_ = NULL;
137    timestamp_ = time(NULL);
138  }
139}
140
141void ChannelMember::QueueResponse(const std::string& status,
142                                  const std::string& content_type,
143                                  const std::string& extra_headers,
144                                  const std::string& data) {
145  if (waiting_socket_) {
146    assert(queue_.size() == 0);
147    assert(waiting_socket_->method() == DataSocket::GET);
148    bool ok = waiting_socket_->Send(status, true, content_type, extra_headers,
149                                    data);
150    if (!ok) {
151      printf("Failed to deliver data to waiting socket\n");
152    }
153    waiting_socket_ = NULL;
154    timestamp_ = time(NULL);
155  } else {
156    QueuedResponse qr;
157    qr.status = status;
158    qr.content_type = content_type;
159    qr.extra_headers = extra_headers;
160    qr.data = data;
161    queue_.push(qr);
162  }
163}
164
165void ChannelMember::SetWaitingSocket(DataSocket* ds) {
166  assert(ds->method() == DataSocket::GET);
167  if (ds && !queue_.empty()) {
168    assert(waiting_socket_ == NULL);
169    const QueuedResponse& response = queue_.front();
170    ds->Send(response.status, true, response.content_type,
171             response.extra_headers, response.data);
172    queue_.pop();
173  } else {
174    waiting_socket_ = ds;
175  }
176}
177
178//
179// PeerChannel
180//
181
182// static
183bool PeerChannel::IsPeerConnection(const DataSocket* ds) {
184  assert(ds);
185  return (ds->method() == DataSocket::POST && ds->content_length() > 0) ||
186         (ds->method() == DataSocket::GET && ds->PathEquals("/sign_in"));
187}
188
189ChannelMember* PeerChannel::Lookup(DataSocket* ds) const {
190  assert(ds);
191
192  if (ds->method() != DataSocket::GET && ds->method() != DataSocket::POST)
193    return NULL;
194
195  size_t i = 0;
196  for (; i < ARRAYSIZE(kRequestPaths); ++i) {
197    if (ds->PathEquals(kRequestPaths[i]))
198      break;
199  }
200
201  if (i == ARRAYSIZE(kRequestPaths))
202    return NULL;
203
204  std::string args(ds->request_arguments());
205  static const char kPeerId[] = "peer_id=";
206  size_t found = args.find(kPeerId);
207  if (found == std::string::npos)
208    return NULL;
209
210  int id = atoi(&args[found + ARRAYSIZE(kPeerId) - 1]);
211  Members::const_iterator iter = members_.begin();
212  for (; iter != members_.end(); ++iter) {
213    if (id == (*iter)->id()) {
214      if (i == kWait)
215        (*iter)->SetWaitingSocket(ds);
216      if (i == kSignOut)
217        (*iter)->set_disconnected();
218      return *iter;
219    }
220  }
221
222  return NULL;
223}
224
225ChannelMember* PeerChannel::IsTargetedRequest(const DataSocket* ds) const {
226  assert(ds);
227  // Regardless of GET or POST, we look for the peer_id parameter
228  // only in the request_path.
229  const std::string& path = ds->request_path();
230  size_t args = path.find('?');
231  if (args == std::string::npos)
232    return NULL;
233  size_t found;
234  const char kTargetPeerIdParam[] = "to=";
235  do {
236    found = path.find(kTargetPeerIdParam, args);
237    if (found == std::string::npos)
238      return NULL;
239    if (found == (args + 1) || path[found - 1] == '&') {
240      found += ARRAYSIZE(kTargetPeerIdParam) - 1;
241      break;
242    }
243    args = found + ARRAYSIZE(kTargetPeerIdParam) - 1;
244  } while (true);
245  int id = atoi(&path[found]);
246  Members::const_iterator i = members_.begin();
247  for (; i != members_.end(); ++i) {
248    if ((*i)->id() == id) {
249      return *i;
250    }
251  }
252  return NULL;
253}
254
255bool PeerChannel::AddMember(DataSocket* ds) {
256  assert(IsPeerConnection(ds));
257  ChannelMember* new_guy = new ChannelMember(ds);
258  Members failures;
259  BroadcastChangedState(*new_guy, &failures);
260  HandleDeliveryFailures(&failures);
261  members_.push_back(new_guy);
262
263  printf("New member added (total=%s): %s\n",
264      size_t2str(members_.size()).c_str(), new_guy->name().c_str());
265
266  // Let the newly connected peer know about other members of the channel.
267  std::string content_type;
268  std::string response = BuildResponseForNewMember(*new_guy, &content_type);
269  ds->Send("200 Added", true, content_type, new_guy->GetPeerIdHeader(),
270           response);
271  return true;
272}
273
274void PeerChannel::CloseAll() {
275  Members::const_iterator i = members_.begin();
276  for (; i != members_.end(); ++i) {
277    (*i)->QueueResponse("200 OK", "text/plain", "", "Server shutting down");
278  }
279  DeleteAll();
280}
281
282void PeerChannel::OnClosing(DataSocket* ds) {
283  for (Members::iterator i = members_.begin(); i != members_.end(); ++i) {
284    ChannelMember* m = (*i);
285    m->OnClosing(ds);
286    if (!m->connected()) {
287      i = members_.erase(i);
288      Members failures;
289      BroadcastChangedState(*m, &failures);
290      HandleDeliveryFailures(&failures);
291      delete m;
292      if (i == members_.end())
293        break;
294    }
295  }
296  printf("Total connected: %s\n", size_t2str(members_.size()).c_str());
297}
298
299void PeerChannel::CheckForTimeout() {
300  for (Members::iterator i = members_.begin(); i != members_.end(); ++i) {
301    ChannelMember* m = (*i);
302    if (m->TimedOut()) {
303      printf("Timeout: %s\n", m->name().c_str());
304      m->set_disconnected();
305      i = members_.erase(i);
306      Members failures;
307      BroadcastChangedState(*m, &failures);
308      HandleDeliveryFailures(&failures);
309      delete m;
310      if (i == members_.end())
311        break;
312    }
313  }
314}
315
316void PeerChannel::DeleteAll() {
317  for (Members::iterator i = members_.begin(); i != members_.end(); ++i)
318    delete (*i);
319  members_.clear();
320}
321
322void PeerChannel::BroadcastChangedState(const ChannelMember& member,
323                                        Members* delivery_failures) {
324  // This function should be called prior to DataSocket::Close().
325  assert(delivery_failures);
326
327  if (!member.connected()) {
328    printf("Member disconnected: %s\n", member.name().c_str());
329  }
330
331  Members::iterator i = members_.begin();
332  for (; i != members_.end(); ++i) {
333    if (&member != (*i)) {
334      if (!(*i)->NotifyOfOtherMember(member)) {
335        (*i)->set_disconnected();
336        delivery_failures->push_back(*i);
337        i = members_.erase(i);
338        if (i == members_.end())
339          break;
340      }
341    }
342  }
343}
344
345void PeerChannel::HandleDeliveryFailures(Members* failures) {
346  assert(failures);
347
348  while (!failures->empty()) {
349    Members::iterator i = failures->begin();
350    ChannelMember* member = *i;
351    assert(!member->connected());
352    failures->erase(i);
353    BroadcastChangedState(*member, failures);
354    delete member;
355  }
356}
357
358// Builds a simple list of "name,id\n" entries for each member.
359std::string PeerChannel::BuildResponseForNewMember(const ChannelMember& member,
360                                                   std::string* content_type) {
361  assert(content_type);
362
363  *content_type = "text/plain";
364  // The peer itself will always be the first entry.
365  std::string response(member.GetEntry());
366  for (Members::iterator i = members_.begin(); i != members_.end(); ++i) {
367    if (member.id() != (*i)->id()) {
368      assert((*i)->connected());
369      response += (*i)->GetEntry();
370    }
371  }
372
373  return response;
374}
375