summaryrefslogtreecommitdiffstats
path: root/remoting/protocol/protocol_test_client.cc
blob: 6486331925cfc2e84e616e06b0926f06569f259e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "build/build_config.h"

#if !defined(OS_WIN)
extern "C" {
#include <unistd.h>
}
#endif  // !defined(OS_WIN)

#include <iostream>
#include <list>

#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/nss_util.h"
#include "base/time.h"
#include "net/base/completion_callback.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/socket/socket.h"
#include "remoting/base/constants.h"
#include "remoting/jingle_glue/jingle_client.h"
#include "remoting/jingle_glue/jingle_thread.h"
#include "remoting/protocol/jingle_session_manager.h"

using remoting::kChromotingTokenServiceName;

namespace remoting {
namespace protocol {

namespace {
const int kBufferSize = 4096;
const char kDummyAuthToken[] = "";
}  // namespace

class ProtocolTestClient;

class ProtocolTestConnection
    : public base::RefCountedThreadSafe<ProtocolTestConnection> {
 public:
  ProtocolTestConnection(ProtocolTestClient* client, MessageLoop* message_loop)
      : client_(client),
        message_loop_(message_loop),
        session_(NULL),
        ALLOW_THIS_IN_INITIALIZER_LIST(
            write_cb_(this, &ProtocolTestConnection::OnWritten)),
        pending_write_(false),
        ALLOW_THIS_IN_INITIALIZER_LIST(
            read_cb_(this, &ProtocolTestConnection::OnRead)),
        closed_event_(true, false) {
  }

  void Init(Session* session);
  void Write(const std::string& str);
  void Read();
  void Close();

  // Session::Callback interface.
  virtual void OnStateChange(Session::State state);
 private:
  void DoWrite(scoped_refptr<net::IOBuffer> buf, int size);
  void DoRead();

  void HandleReadResult(int result);

  void OnWritten(int result);
  void OnRead(int result);

  void OnFinishedClosing();

  ProtocolTestClient* client_;
  MessageLoop* message_loop_;
  scoped_refptr<Session> session_;
  net::CompletionCallbackImpl<ProtocolTestConnection> write_cb_;
  bool pending_write_;
  net::CompletionCallbackImpl<ProtocolTestConnection> read_cb_;
  scoped_refptr<net::IOBuffer> read_buffer_;
  base::WaitableEvent closed_event_;
};

class ProtocolTestClient
    : public JingleClient::Callback,
      public base::RefCountedThreadSafe<ProtocolTestClient> {
 public:
  ProtocolTestClient()
      : closed_event_(true, false) {
  }

  virtual ~ProtocolTestClient() {}

  void Run(const std::string& username, const std::string& auth_token,
           const std::string& host_jid);

  void OnConnectionClosed(ProtocolTestConnection* connection);

  // JingleClient::Callback interface.
  virtual void OnStateChange(JingleClient* client, JingleClient::State state);

  // callback for JingleSessionManager interface.
  virtual void OnNewSession(
      Session* session,
      SessionManager::IncomingSessionResponse* response);

 private:
  typedef std::list<scoped_refptr<ProtocolTestConnection> > ConnectionsList;

  void OnFinishedClosing();
  void DestroyConnection(scoped_refptr<ProtocolTestConnection> connection);

  std::string host_jid_;
  scoped_refptr<JingleClient> client_;
  scoped_refptr<JingleSessionManager> session_manager_;
  ConnectionsList connections_;
  Lock connections_lock_;
  base::WaitableEvent closed_event_;
};


void ProtocolTestConnection::Init(Session* session) {
  session_ = session;
}

void ProtocolTestConnection::Write(const std::string& str) {
  if (str.empty())
    return;

  scoped_refptr<net::IOBuffer> buf(new net::IOBuffer(str.length()));
  memcpy(buf->data(), str.c_str(), str.length());
  message_loop_->PostTask(
      FROM_HERE, NewRunnableMethod(
          this, &ProtocolTestConnection::DoWrite, buf, str.length()));
}

void ProtocolTestConnection::DoWrite(
    scoped_refptr<net::IOBuffer> buf, int size) {
  if (pending_write_) {
    LOG(ERROR) << "Cannot write because there is another pending write.";
    return;
  }

  net::Socket* channel = session_->event_channel();
  if (channel != NULL) {
    int result = channel->Write(buf, size, &write_cb_);
    if (result < 0) {
      if (result == net::ERR_IO_PENDING)
        pending_write_ = true;
      else
        LOG(ERROR) << "Write() returned error " << result;
    }
  } else {
    LOG(ERROR) << "Cannot write because the channel isn't intialized yet.";
  }
}

void ProtocolTestConnection::Read() {
  message_loop_->PostTask(
      FROM_HERE, NewRunnableMethod(
          this, &ProtocolTestConnection::DoRead));
}

void ProtocolTestConnection::DoRead() {
  read_buffer_ = new net::IOBuffer(kBufferSize);
  while (true) {
    int result = session_->event_channel()->Read(
        read_buffer_, kBufferSize, &read_cb_);
    if (result < 0) {
      if (result != net::ERR_IO_PENDING)
        LOG(ERROR) << "Read failed: " << result;
      break;
    } else {
      HandleReadResult(result);
    }
  }
}

void ProtocolTestConnection::Close() {
  session_->Close(
      NewRunnableMethod(this, &ProtocolTestConnection::OnFinishedClosing));
  closed_event_.Wait();
}

void ProtocolTestConnection::OnFinishedClosing() {
  closed_event_.Signal();
}

void ProtocolTestConnection::OnStateChange(Session::State state) {
  LOG(INFO) << "State of " << session_->jid() << " changed to " << state;
  if (state == Session::CONNECTED) {
    // Start reading after we've connected.
    Read();
  } else if (state == Session::CLOSED) {
    std::cerr << "Connection to " << session_->jid()
              << " closed" << std::endl;
    client_->OnConnectionClosed(this);
  }
}

void ProtocolTestConnection::OnWritten(int result) {
  pending_write_ = false;
  if (result < 0)
      LOG(ERROR) << "Write() returned error " << result;
}

void ProtocolTestConnection::OnRead(int result) {
  HandleReadResult(result);
  DoRead();
}

void ProtocolTestConnection::HandleReadResult(int result) {
  if (result > 0) {
    std::string str(reinterpret_cast<const char*>(read_buffer_->data()),
                    result);
    std::cout << "(" << session_->jid() << "): " << str << std::endl;
  } else {
    LOG(ERROR) << "Read() returned error " << result;
  }
}

void ProtocolTestClient::Run(const std::string& username,
                             const std::string& auth_token,
                             const std::string& host_jid) {
  remoting::JingleThread jingle_thread;
  jingle_thread.Start();
  client_ = new JingleClient(&jingle_thread);
  client_->Init(username, auth_token, kChromotingTokenServiceName, this);

  session_manager_ = new JingleSessionManager(&jingle_thread);

  host_jid_ = host_jid;

  while (true) {
    std::string line;
    std::getline(std::cin, line);

    {
      AutoLock auto_lock(connections_lock_);

      // Broadcast message to all clients.
      for (ConnectionsList::iterator it = connections_.begin();
           it != connections_.end(); ++it) {
        (*it)->Write(line);
      }
    }

    if (line == "exit")
      break;
  }

  while (!connections_.empty()) {
    connections_.front()->Close();
    connections_.pop_front();
  }

  if (session_manager_) {
    session_manager_->Close(
        NewRunnableMethod(this, &ProtocolTestClient::OnFinishedClosing));
    closed_event_.Wait();
  }

  client_->Close();
  jingle_thread.Stop();
}

void ProtocolTestClient::OnConnectionClosed(
    ProtocolTestConnection* connection) {
  client_->message_loop()->PostTask(
      FROM_HERE, NewRunnableMethod(
          this, &ProtocolTestClient::DestroyConnection,
          scoped_refptr<ProtocolTestConnection>(connection)));
}

void ProtocolTestClient::OnStateChange(
    JingleClient* client, JingleClient::State state) {
  if (state == JingleClient::CONNECTED) {
    std::cerr << "Connected as " << client->GetFullJid() << std::endl;

    session_manager_->Init(
        client_->GetFullJid(), client_->session_manager(),
        NewCallback(this, &ProtocolTestClient::OnNewSession));
    session_manager_->set_allow_local_ips(true);

    if (host_jid_ != "") {
      ProtocolTestConnection* connection =
          new ProtocolTestConnection(this, client_->message_loop());
      connection->Init(session_manager_->Connect(
          host_jid_, kDummyAuthToken, CandidateSessionConfig::CreateDefault(),
          NewCallback(connection,
                      &ProtocolTestConnection::OnStateChange)));
      connections_.push_back(make_scoped_refptr(connection));
    }
  } else if (state == JingleClient::CLOSED) {
    std::cerr << "Connection closed" << std::endl;
  }
}

void ProtocolTestClient::OnNewSession(
    Session* session,
    SessionManager::IncomingSessionResponse* response) {
  std::cerr << "Accepting connection from " << session->jid() << std::endl;

  session->set_config(SessionConfig::CreateDefault());
  *response = SessionManager::ACCEPT;

  ProtocolTestConnection* test_connection =
      new ProtocolTestConnection(this, client_->message_loop());
  session->SetStateChangeCallback(
      NewCallback(test_connection, &ProtocolTestConnection::OnStateChange));
  test_connection->Init(session);
  AutoLock auto_lock(connections_lock_);
  connections_.push_back(make_scoped_refptr(test_connection));
}

void ProtocolTestClient::OnFinishedClosing() {
  closed_event_.Signal();
}

void ProtocolTestClient::DestroyConnection(
    scoped_refptr<ProtocolTestConnection> connection) {
  connection->Close();
  AutoLock auto_lock(connections_lock_);
  for (ConnectionsList::iterator it = connections_.begin();
       it != connections_.end(); ++it) {
    if ((*it) == connection) {
      connections_.erase(it);
      return;
    }
  }
}

}  // namespace protocol
}  // namespace remoting

using remoting::protocol::ProtocolTestClient;

void usage(char* command) {
  std::cerr << "Usage: " << command << "--username=<username>" << std::endl
            << "\t--auth_token=<auth_token>" << std::endl
            << "\t[--host_jid=<host_jid>]" << std::endl;
  exit(1);
}

int main(int argc, char** argv) {
  CommandLine::Init(argc, argv);
  const CommandLine* cmd_line = CommandLine::ForCurrentProcess();

  if (!cmd_line->args().empty() || cmd_line->HasSwitch("help"))
    usage(argv[0]);

  base::AtExitManager exit_manager;

  base::EnsureNSPRInit();
  base::EnsureNSSInit();

  std::string host_jid(cmd_line->GetSwitchValueASCII("host_jid"));

  if (!cmd_line->HasSwitch("username"))
    usage(argv[0]);
  std::string username(cmd_line->GetSwitchValueASCII("username"));

  if (!cmd_line->HasSwitch("auth_token"))
    usage(argv[0]);
  std::string auth_token(cmd_line->GetSwitchValueASCII("auth_token"));

  scoped_refptr<ProtocolTestClient> client(new ProtocolTestClient());

  client->Run(username, auth_token, host_jid);

  return 0;
}