Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(745)

Side by Side Diff: remoting/protocol/jingle_session_unittest.cc

Issue 8743023: Separate Authenticator and Session unittests. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: merge Created 9 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "base/bind.h" 5 #include "base/bind.h"
6 #include "base/file_path.h"
7 #include "base/file_util.h"
8 #include "base/message_loop_proxy.h" 6 #include "base/message_loop_proxy.h"
9 #include "base/path_service.h"
10 #include "base/time.h" 7 #include "base/time.h"
11 #include "base/test/test_timeouts.h"
12 #include "crypto/nss_util.h"
13 #include "crypto/rsa_private_key.h"
14 #include "net/base/completion_callback.h"
15 #include "net/base/io_buffer.h"
16 #include "net/base/net_errors.h"
17 #include "net/socket/socket.h" 8 #include "net/socket/socket.h"
18 #include "net/socket/stream_socket.h" 9 #include "net/socket/stream_socket.h"
19 #include "remoting/base/constants.h" 10 #include "remoting/base/constants.h"
20 #include "remoting/protocol/auth_util.h"
21 #include "remoting/protocol/authenticator.h" 11 #include "remoting/protocol/authenticator.h"
22 #include "remoting/protocol/channel_authenticator.h" 12 #include "remoting/protocol/channel_authenticator.h"
13 #include "remoting/protocol/connection_tester.h"
14 #include "remoting/protocol/fake_authenticator.h"
23 #include "remoting/protocol/jingle_session.h" 15 #include "remoting/protocol/jingle_session.h"
24 #include "remoting/protocol/jingle_session_manager.h" 16 #include "remoting/protocol/jingle_session_manager.h"
25 #include "remoting/protocol/v1_authenticator.h"
26 #include "remoting/jingle_glue/jingle_thread.h" 17 #include "remoting/jingle_glue/jingle_thread.h"
27 #include "remoting/jingle_glue/fake_signal_strategy.h" 18 #include "remoting/jingle_glue/fake_signal_strategy.h"
28 #include "testing/gmock/include/gmock/gmock.h" 19 #include "testing/gmock/include/gmock/gmock.h"
29 #include "testing/gtest/include/gtest/gtest.h" 20 #include "testing/gtest/include/gtest/gtest.h"
30 #include "third_party/libjingle/source/talk/p2p/client/basicportallocator.h"
31 21
32 using testing::_; 22 using testing::_;
33 using testing::AtMost; 23 using testing::AtMost;
34 using testing::DeleteArg; 24 using testing::DeleteArg;
35 using testing::DoAll; 25 using testing::DoAll;
36 using testing::InSequence; 26 using testing::InSequence;
37 using testing::Invoke; 27 using testing::Invoke;
38 using testing::InvokeWithoutArgs; 28 using testing::InvokeWithoutArgs;
29 using testing::Mock;
39 using testing::Return; 30 using testing::Return;
40 using testing::SaveArg; 31 using testing::SaveArg;
41 using testing::SetArgumentPointee; 32 using testing::SetArgumentPointee;
42 using testing::WithArg; 33 using testing::WithArg;
43 34
44 namespace remoting { 35 namespace remoting {
45 namespace protocol { 36 namespace protocol {
46 class JingleSessionTest;
47 } // namespace protocol
48 } // namespace remoting
49
50 DISABLE_RUNNABLE_METHOD_REFCOUNT(remoting::protocol::JingleSessionTest);
51
52 namespace remoting {
53 namespace protocol {
54 37
55 namespace { 38 namespace {
56 39
57 // Send 100 messages 1024 bytes each. UDP messages are sent with 10ms delay 40 // Send 100 messages 1024 bytes each. UDP messages are sent with 10ms delay
58 // between messages (about 1 second for 100 messages). 41 // between messages (about 1 second for 100 messages).
59 const int kMessageSize = 1024; 42 const int kMessageSize = 1024;
60 const int kMessages = 100; 43 const int kMessages = 100;
61 const int kTestDataSize = kMessages * kMessageSize;
62 const int kUdpWriteDelayMs = 10; 44 const int kUdpWriteDelayMs = 10;
63 const char kChannelName[] = "test_channel"; 45 const char kChannelName[] = "test_channel";
64 46
65 const char kHostJid[] = "host1@gmail.com/123"; 47 const char kHostJid[] = "host1@gmail.com/123";
66 const char kClientJid[] = "host2@gmail.com/321"; 48 const char kClientJid[] = "host2@gmail.com/321";
67 49
68 const char kTestHostPublicKey[] =
69 "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3nk/8ILc0JBqHgOS0UCOIl4m"
70 "0GUd2FIiZ/6Fc9D/iiyUgli+FIY5dwsrSoNJ87sYGifVDh8a5fdZNV5y58CcrapI5fJI"
71 "FpXviSW4g8d/t1gcZkoz1ppmjzbgXm6ckw9Td0yRD0cHu732Ijs+eo8wT0pt4KiHkbyR"
72 "iAvjrvkNDlfiEk7tiY7YzD9zTi3146GX6KLz5GQAd/3I8I5QW3ftF1s/m93AHuc383GZ"
73 "A78Oi+IbcJf/jJUZO119VNnRKGiPsf5GZIoHyXX8O5OUQk5soKdQPeK1FwWkeZu6fuXl"
74 "QoU12I6podD6xMFa/PA/xefMwcpmuWTRhcso9bp10zVFGQIDAQAB";
75
76 const char kTestSharedSecret[] = "1234-1234-5678";
77 const char kTestSharedSecretBad[] = "0000-0000-0001";
78
79 void QuitCurrentThread() { 50 void QuitCurrentThread() {
80 MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure()); 51 MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure());
81 } 52 }
82 53
83 void OnTimeoutTerminateThread(bool* timeout) { 54 ACTION(QuitThread) {
84 *timeout = true;
85 QuitCurrentThread(); 55 QuitCurrentThread();
86 } 56 }
87 57
88 bool RunMessageLoopWithTimeout(int timeout_ms) {
89 bool timeout = false;
90 MessageLoop::current()->PostDelayedTask(
91 FROM_HERE, base::Bind(&OnTimeoutTerminateThread, &timeout), timeout_ms);
92 MessageLoop::current()->Run();
93 return !timeout;
94 }
95
96 ACTION_P(QuitThreadOnCounter, counter) { 58 ACTION_P(QuitThreadOnCounter, counter) {
97 (*counter)--; 59 (*counter)--;
98 EXPECT_GE(*counter, 0); 60 EXPECT_GE(*counter, 0);
99 if (*counter == 0) 61 if (*counter == 0)
100 QuitCurrentThread(); 62 QuitCurrentThread();
101 } 63 }
102 64
103 class MockSessionManagerListener : public SessionManager::Listener { 65 class MockSessionManagerListener : public SessionManager::Listener {
104 public: 66 public:
105 MOCK_METHOD0(OnSessionManagerInitialized, void()); 67 MOCK_METHOD0(OnSessionManagerInitialized, void());
106 MOCK_METHOD2(OnIncomingSession, 68 MOCK_METHOD2(OnIncomingSession,
107 void(Session*, 69 void(Session*,
108 SessionManager::IncomingSessionResponse*)); 70 SessionManager::IncomingSessionResponse*));
109 }; 71 };
110 72
111 class MockSessionCallback { 73 class MockSessionCallback {
112 public: 74 public:
113 MOCK_METHOD1(OnStateChange, void(Session::State)); 75 MOCK_METHOD1(OnStateChange, void(Session::State));
114 }; 76 };
115 77
116 class FakeChannelAuthenticator : public ChannelAuthenticator { 78 class MockStreamChannelCallback {
117 public: 79 public:
118 FakeChannelAuthenticator(bool accept) 80 MOCK_METHOD1(OnDone, void(net::StreamSocket* socket));
119 : accept_(accept) {
120 }
121 virtual ~FakeChannelAuthenticator() {}
122
123 virtual void SecureAndAuthenticate(
124 net::StreamSocket* socket, const DoneCallback& done_callback) OVERRIDE {
125 if (accept_) {
126 done_callback.Run(net::OK, socket);
127 } else {
128 delete socket;
129 done_callback.Run(net::ERR_FAILED, NULL);
130 }
131 }
132
133 private:
134 bool accept_;
135
136 DISALLOW_COPY_AND_ASSIGN(FakeChannelAuthenticator);
137 }; 81 };
138 82
139 class FakeClientAuthenticator : public Authenticator { 83 class MockDatagramChannelCallback {
140 public: 84 public:
141 FakeClientAuthenticator(bool accept, bool accept_channel) 85 MOCK_METHOD1(OnDone, void(net::Socket* socket));
142 : accept_(accept),
143 accept_channel_(accept_channel),
144 state_(MESSAGE_READY) {
145 }
146 virtual ~FakeClientAuthenticator() {}
147
148 virtual State state() const OVERRIDE {
149 return state_;
150 }
151
152 virtual void ProcessMessage(const buzz::XmlElement* message) OVERRIDE {
153 EXPECT_EQ(WAITING_MESSAGE, state_);
154 state_ = accept_ ? ACCEPTED : REJECTED;
155 }
156
157 virtual buzz::XmlElement* GetNextMessage() OVERRIDE {
158 EXPECT_EQ(MESSAGE_READY, state_);
159 state_ = WAITING_MESSAGE;
160 return new buzz::XmlElement(
161 buzz::QName(kChromotingXmlNamespace, "authentication"));
162 }
163
164 virtual ChannelAuthenticator* CreateChannelAuthenticator() const OVERRIDE {
165 return new FakeChannelAuthenticator(accept_channel_);
166 }
167
168 protected:
169 bool accept_;
170 bool accept_channel_;
171 State state_;
172
173 DISALLOW_COPY_AND_ASSIGN(FakeClientAuthenticator);
174 };
175
176 class FakeHostAuthenticator : public Authenticator {
177 public:
178 FakeHostAuthenticator(bool accept, bool accept_channel)
179 : accept_(accept),
180 accept_channel_(accept_channel),
181 state_(WAITING_MESSAGE) {
182 }
183 virtual ~FakeHostAuthenticator() {}
184
185 virtual State state() const OVERRIDE {
186 return state_;
187 }
188
189 virtual void ProcessMessage(const buzz::XmlElement* message) OVERRIDE {
190 EXPECT_EQ(WAITING_MESSAGE, state_);
191 state_ = MESSAGE_READY;
192 }
193
194 virtual buzz::XmlElement* GetNextMessage() OVERRIDE {
195 EXPECT_EQ(MESSAGE_READY, state_);
196 state_ = accept_ ? ACCEPTED : REJECTED;
197 return new buzz::XmlElement(
198 buzz::QName(kChromotingXmlNamespace, "authentication"));
199 }
200
201 virtual ChannelAuthenticator* CreateChannelAuthenticator() const OVERRIDE {
202 return new FakeChannelAuthenticator(accept_channel_);
203 }
204
205 protected:
206 bool accept_;
207 bool accept_channel_;
208 State state_;
209
210 DISALLOW_COPY_AND_ASSIGN(FakeHostAuthenticator);
211 };
212
213 class FakeHostAuthenticatorFactory : public AuthenticatorFactory {
214 public:
215 FakeHostAuthenticatorFactory(bool accept, bool accept_channel)
216 : accept_(accept),
217 accept_channel_(accept_channel) {
218 }
219 virtual ~FakeHostAuthenticatorFactory() {}
220
221 virtual Authenticator* CreateAuthenticator(
222 const std::string& remote_jid,
223 const buzz::XmlElement* first_message) OVERRIDE {
224 return new FakeHostAuthenticator(accept_, accept_channel_);
225 }
226
227 private:
228 bool accept_;
229 bool accept_channel_;
230
231 DISALLOW_COPY_AND_ASSIGN(FakeHostAuthenticatorFactory);
232 }; 86 };
233 87
234 } // namespace 88 } // namespace
235 89
236 class JingleSessionTest : public testing::Test { 90 class JingleSessionTest : public testing::Test {
237 public: 91 public:
238 JingleSessionTest() 92 JingleSessionTest()
239 : message_loop_(talk_base::Thread::Current()) { 93 : message_loop_(talk_base::Thread::Current()) {
240 } 94 }
241 95
(...skipping 11 matching lines...) Expand all
253 protected: 107 protected:
254 virtual void SetUp() { 108 virtual void SetUp() {
255 } 109 }
256 110
257 virtual void TearDown() { 111 virtual void TearDown() {
258 CloseSessions(); 112 CloseSessions();
259 CloseSessionManager(); 113 CloseSessionManager();
260 } 114 }
261 115
262 void CloseSessions() { 116 void CloseSessions() {
263 if (host_session_.get()) { 117 host_socket_.reset();
264 host_session_->Close(); 118 client_socket_.reset();
265 host_session_.reset(); 119 host_session_.reset();
266 } 120 client_session_.reset();
267 if (client_session_.get()) {
268 client_session_->Close();
269 client_session_.reset();
270 }
271 } 121 }
272 122
273 void CreateServerPair(bool use_fake_auth) { 123 void CreateServerPair(int auth_round_trips,
274 FilePath certs_dir; 124 FakeAuthenticator::Action auth_action) {
275 PathService::Get(base::DIR_SOURCE_ROOT, &certs_dir);
276 certs_dir = certs_dir.AppendASCII("net");
277 certs_dir = certs_dir.AppendASCII("data");
278 certs_dir = certs_dir.AppendASCII("ssl");
279 certs_dir = certs_dir.AppendASCII("certificates");
280
281 FilePath cert_path = certs_dir.AppendASCII("unittest.selfsigned.der");
282 std::string cert_der;
283 ASSERT_TRUE(file_util::ReadFileToString(cert_path, &cert_der));
284
285 FilePath key_path = certs_dir.AppendASCII("unittest.key.bin");
286 std::string key_string;
287 ASSERT_TRUE(file_util::ReadFileToString(key_path, &key_string));
288 std::vector<uint8> key_vector(
289 reinterpret_cast<const uint8*>(key_string.data()),
290 reinterpret_cast<const uint8*>(key_string.data() +
291 key_string.length()));
292 scoped_ptr<crypto::RSAPrivateKey> private_key(
293 crypto::RSAPrivateKey::CreateFromPrivateKeyInfo(key_vector));
294
295 host_signal_strategy_.reset(new FakeSignalStrategy(kHostJid)); 125 host_signal_strategy_.reset(new FakeSignalStrategy(kHostJid));
296 client_signal_strategy_.reset(new FakeSignalStrategy(kClientJid)); 126 client_signal_strategy_.reset(new FakeSignalStrategy(kClientJid));
297 FakeSignalStrategy::Connect(host_signal_strategy_.get(), 127 FakeSignalStrategy::Connect(host_signal_strategy_.get(),
298 client_signal_strategy_.get()); 128 client_signal_strategy_.get());
299 129
300 EXPECT_CALL(host_server_listener_, OnSessionManagerInitialized()) 130 EXPECT_CALL(host_server_listener_, OnSessionManagerInitialized())
301 .Times(1); 131 .Times(1);
302 host_server_.reset(new JingleSessionManager( 132 host_server_.reset(new JingleSessionManager(
303 base::MessageLoopProxy::current())); 133 base::MessageLoopProxy::current()));
304 host_server_->Init( 134 host_server_->Init(
305 kHostJid, host_signal_strategy_.get(), &host_server_listener_, false); 135 kHostJid, host_signal_strategy_.get(), &host_server_listener_, false);
306 136
307 if (use_fake_auth) { 137 host_server_->set_authenticator_factory(
308 host_server_->set_authenticator_factory( 138 new FakeHostAuthenticatorFactory(auth_round_trips, auth_action, true));
309 new FakeHostAuthenticatorFactory(true, false));
310 } else {
311 host_server_->set_authenticator_factory(
312 new V1HostAuthenticatorFactory(
313 cert_der, private_key.get(), kTestSharedSecret));
314 }
315 139
316 EXPECT_CALL(client_server_listener_, OnSessionManagerInitialized()) 140 EXPECT_CALL(client_server_listener_, OnSessionManagerInitialized())
317 .Times(1); 141 .Times(1);
318 client_server_.reset(new JingleSessionManager( 142 client_server_.reset(new JingleSessionManager(
319 base::MessageLoopProxy::current())); 143 base::MessageLoopProxy::current()));
320 client_server_->Init( 144 client_server_->Init(
321 kClientJid, client_signal_strategy_.get(), 145 kClientJid, client_signal_strategy_.get(),
322 &client_server_listener_, false); 146 &client_server_listener_, false);
323 } 147 }
324 148
325 void CloseSessionManager() { 149 void CloseSessionManager() {
326 if (host_server_.get()) { 150 if (host_server_.get()) {
327 host_server_->Close(); 151 host_server_->Close();
328 host_server_.reset(); 152 host_server_.reset();
329 } 153 }
330 if (client_server_.get()) { 154 if (client_server_.get()) {
331 client_server_->Close(); 155 client_server_->Close();
332 client_server_.reset(); 156 client_server_.reset();
333 } 157 }
334 host_signal_strategy_.reset(); 158 host_signal_strategy_.reset();
335 client_signal_strategy_.reset(); 159 client_signal_strategy_.reset();
336 } 160 }
337 161
338 bool InitiateConnection(bool use_fake_auth) { 162 void InitiateConnection(int auth_round_trips,
339 int not_connected_peers = 2; 163 FakeAuthenticator::Action auth_action,
340 164 bool expect_fail) {
341 EXPECT_CALL(host_server_listener_, OnIncomingSession(_, _)) 165 EXPECT_CALL(host_server_listener_, OnIncomingSession(_, _))
342 .WillOnce(DoAll( 166 .WillOnce(DoAll(
343 WithArg<0>(Invoke( 167 WithArg<0>(Invoke(
344 this, &JingleSessionTest::SetHostSession)), 168 this, &JingleSessionTest::SetHostSession)),
345 SetArgumentPointee<1>(protocol::SessionManager::ACCEPT))); 169 SetArgumentPointee<1>(protocol::SessionManager::ACCEPT)));
346 170
347 { 171 {
348 InSequence dummy; 172 InSequence dummy;
349 173
350 EXPECT_CALL(host_connection_callback_, 174 if (expect_fail) {
351 OnStateChange(Session::CONNECTED)) 175 EXPECT_CALL(host_connection_callback_,
352 .Times(1); 176 OnStateChange(Session::FAILED))
353 EXPECT_CALL(host_connection_callback_, 177 .Times(1);
354 OnStateChange(Session::AUTHENTICATED)) 178 } else {
355 .Times(1) 179 EXPECT_CALL(host_connection_callback_,
356 .WillOnce(QuitThreadOnCounter(&not_connected_peers)); 180 OnStateChange(Session::CONNECTED))
357 // Expect that the connection will be closed eventually. 181 .Times(1);
358 EXPECT_CALL(host_connection_callback_, 182 EXPECT_CALL(host_connection_callback_,
359 OnStateChange(Session::CLOSED)) 183 OnStateChange(Session::AUTHENTICATED))
360 .Times(AtMost(1)); 184 .Times(1);
185 }
361 } 186 }
362 187
363 { 188 {
364 InSequence dummy; 189 InSequence dummy;
365 190
366 EXPECT_CALL(client_connection_callback_, 191 EXPECT_CALL(client_connection_callback_,
367 OnStateChange(Session::CONNECTING)) 192 OnStateChange(Session::CONNECTING))
368 .Times(1); 193 .Times(1);
369 EXPECT_CALL(client_connection_callback_, 194 if (expect_fail) {
370 OnStateChange(Session::CONNECTED)) 195 EXPECT_CALL(client_connection_callback_,
371 .Times(1); 196 OnStateChange(Session::FAILED))
372 EXPECT_CALL(client_connection_callback_, 197 .Times(1);
373 OnStateChange(Session::AUTHENTICATED)) 198 } else {
374 .Times(1) 199 EXPECT_CALL(client_connection_callback_,
375 .WillOnce(QuitThreadOnCounter(&not_connected_peers)); 200 OnStateChange(Session::CONNECTED))
376 // Expect that the connection will be closed eventually. 201 .Times(1);
377 EXPECT_CALL(client_connection_callback_, 202 EXPECT_CALL(client_connection_callback_,
378 OnStateChange(Session::CLOSED)) 203 OnStateChange(Session::AUTHENTICATED))
379 .Times(AtMost(1)); 204 .Times(1);
205 }
380 } 206 }
381 207
382 Authenticator* authenticator; 208 Authenticator* authenticator = new FakeAuthenticator(
383 if (use_fake_auth) { 209 FakeAuthenticator::CLIENT, auth_round_trips, auth_action, true);
384 authenticator = new FakeClientAuthenticator(true, true); 210
385 } else {
386 authenticator = new V1ClientAuthenticator(kClientJid, kTestSharedSecret);
387 }
388 client_session_.reset(client_server_->Connect( 211 client_session_.reset(client_server_->Connect(
389 kHostJid, authenticator, 212 kHostJid, authenticator,
390 CandidateSessionConfig::CreateDefault(), 213 CandidateSessionConfig::CreateDefault(),
391 base::Bind(&MockSessionCallback::OnStateChange, 214 base::Bind(&MockSessionCallback::OnStateChange,
392 base::Unretained(&client_connection_callback_)))); 215 base::Unretained(&client_connection_callback_))));
393 216
394 return RunMessageLoopWithTimeout(TestTimeouts::action_max_timeout_ms()); 217 message_loop_.RunAllPending();
218
219 Mock::VerifyAndClearExpectations(&host_connection_callback_);
220 Mock::VerifyAndClearExpectations(&client_connection_callback_);
221
222 if (!expect_fail) {
223 // Expect that the connection will be closed eventually.
224 EXPECT_CALL(host_connection_callback_,
225 OnStateChange(Session::CLOSED))
226 .Times(AtMost(1));
227 }
228
229 if (!expect_fail) {
230 // Expect that the connection will be closed eventually.
231 EXPECT_CALL(client_connection_callback_,
232 OnStateChange(Session::CLOSED))
233 .Times(AtMost(1));
234 }
235 }
236
237 void CreateChannel() {
238 MockStreamChannelCallback client_callback;
239 MockStreamChannelCallback host_callback;
240
241 client_session_->CreateStreamChannel(kChannelName, base::Bind(
242 &MockStreamChannelCallback::OnDone,
243 base::Unretained(&host_callback)));
244 host_session_->CreateStreamChannel(kChannelName, base::Bind(
245 &MockStreamChannelCallback::OnDone,
246 base::Unretained(&client_callback)));
247
248 int counter = 2;
249 net::StreamSocket* client_socket = NULL;
250 net::StreamSocket* host_socket = NULL;
251 EXPECT_CALL(client_callback, OnDone(_))
252 .WillOnce(DoAll(SaveArg<0>(&client_socket),
253 QuitThreadOnCounter(&counter)));
254 EXPECT_CALL(host_callback, OnDone(_))
255 .WillOnce(DoAll(SaveArg<0>(&host_socket),
256 QuitThreadOnCounter(&counter)));
257 message_loop_.Run();
258
259 ASSERT_TRUE(client_socket != NULL);
260 ASSERT_TRUE(host_socket != NULL);
261
262 client_socket_.reset(client_socket);
263 host_socket_.reset(host_socket);
395 } 264 }
396 265
397 static void DoNothing() { } 266 static void DoNothing() { }
398 267
399 JingleThreadMessageLoop message_loop_; 268 JingleThreadMessageLoop message_loop_;
400 269
401 scoped_ptr<FakeSignalStrategy> host_signal_strategy_; 270 scoped_ptr<FakeSignalStrategy> host_signal_strategy_;
402 scoped_ptr<FakeSignalStrategy> client_signal_strategy_; 271 scoped_ptr<FakeSignalStrategy> client_signal_strategy_;
403 272
404 scoped_ptr<JingleSessionManager> host_server_; 273 scoped_ptr<JingleSessionManager> host_server_;
405 MockSessionManagerListener host_server_listener_; 274 MockSessionManagerListener host_server_listener_;
406 scoped_ptr<JingleSessionManager> client_server_; 275 scoped_ptr<JingleSessionManager> client_server_;
407 MockSessionManagerListener client_server_listener_; 276 MockSessionManagerListener client_server_listener_;
408 277
409 scoped_ptr<Session> host_session_; 278 scoped_ptr<Session> host_session_;
410 MockSessionCallback host_connection_callback_; 279 MockSessionCallback host_connection_callback_;
411 scoped_ptr<Session> client_session_; 280 scoped_ptr<Session> client_session_;
412 MockSessionCallback client_connection_callback_; 281 MockSessionCallback client_connection_callback_;
413 };
414 282
415 class ChannelTesterBase : public base::RefCountedThreadSafe<ChannelTesterBase> { 283 scoped_ptr<net::StreamSocket> client_socket_;
416 public: 284 scoped_ptr<net::StreamSocket> host_socket_;
417 ChannelTesterBase(Session* host_session,
418 Session* client_session)
419 : host_session_(host_session),
420 client_session_(client_session),
421 done_(false) {
422 }
423
424 virtual ~ChannelTesterBase() { }
425
426 void Start() {
427 MessageLoop::current()->PostTask(
428 FROM_HERE, base::Bind(&ChannelTesterBase::DoStart, this));
429 }
430
431 bool WaitFinished() {
432 return RunMessageLoopWithTimeout(TestTimeouts::action_max_timeout_ms());
433 }
434
435 virtual void CheckResults() = 0;
436
437 protected:
438 void DoStart() {
439 InitChannels();
440 }
441
442 virtual void InitChannels() = 0;
443
444 void Done() {
445 done_ = true;
446 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(&QuitCurrentThread));
447 }
448
449 virtual void InitBuffers() = 0;
450 virtual void DoWrite() = 0;
451 virtual void DoRead() = 0;
452
453 Session* host_session_;
454 Session* client_session_;
455 scoped_ptr<net::Socket> sockets_[2];
456 bool done_;
457 };
458
459 class TCPChannelTester : public ChannelTesterBase {
460 public:
461 TCPChannelTester(Session* host_session,
462 Session* client_session,
463 int message_size,
464 int message_count)
465 : ChannelTesterBase(host_session, client_session),
466 write_errors_(0),
467 read_errors_(0),
468 message_size_(message_size),
469 message_count_(message_count),
470 test_data_size_(message_size * message_count) {
471 }
472
473 virtual ~TCPChannelTester() { }
474
475 virtual bool did_initialization_fail() {
476 return !sockets_[0].get() || !sockets_[1].get();
477 }
478
479 virtual void CheckResults() {
480 ASSERT_FALSE(did_initialization_fail());
481
482 EXPECT_EQ(0, write_errors_);
483 EXPECT_EQ(0, read_errors_);
484
485 ASSERT_EQ(test_data_size_, input_buffer_->offset());
486
487 output_buffer_->SetOffset(0);
488 ASSERT_EQ(test_data_size_, output_buffer_->size());
489
490 EXPECT_EQ(0, memcmp(output_buffer_->data(),
491 input_buffer_->StartOfBuffer(), test_data_size_));
492 }
493
494 protected:
495 virtual void InitChannels() OVERRIDE {
496 host_session_->CreateStreamChannel(
497 kChannelName,
498 base::Bind(&TCPChannelTester::OnChannelReady,
499 base::Unretained(this), 0));
500 client_session_->CreateStreamChannel(
501 kChannelName,
502 base::Bind(&TCPChannelTester::OnChannelReady,
503 base::Unretained(this), 1));
504 }
505
506 void OnChannelReady(int id, net::StreamSocket* socket) {
507 if (!socket) {
508 host_session_->CancelChannelCreation(kChannelName);
509 client_session_->CancelChannelCreation(kChannelName);
510 Done();
511 return;
512 }
513
514 DCHECK(id >= 0 && id < 2);
515 sockets_[id].reset(socket);
516
517 if (sockets_[0].get() && sockets_[1].get()) {
518 InitBuffers();
519 DoRead();
520 DoWrite();
521 }
522 }
523
524 virtual void InitBuffers() {
525 output_buffer_ = new net::DrainableIOBuffer(
526 new net::IOBuffer(test_data_size_), test_data_size_);
527 memset(output_buffer_->data(), 123, test_data_size_);
528
529 input_buffer_ = new net::GrowableIOBuffer();
530 }
531
532 virtual void DoWrite() {
533 int result = 1;
534 while (result > 0) {
535 if (output_buffer_->BytesRemaining() == 0)
536 break;
537 int bytes_to_write = std::min(output_buffer_->BytesRemaining(),
538 message_size_);
539 result = sockets_[0]->Write(output_buffer_, bytes_to_write,
540 base::Bind(&TCPChannelTester::OnWritten,
541 base::Unretained(this)));
542 HandleWriteResult(result);
543 };
544 }
545
546 void OnWritten(int result) {
547 HandleWriteResult(result);
548 DoWrite();
549 }
550
551 void HandleWriteResult(int result) {
552 if (result <= 0 && result != net::ERR_IO_PENDING) {
553 LOG(ERROR) << "Received error " << result << " when trying to write";
554 write_errors_++;
555 Done();
556 } else if (result > 0) {
557 output_buffer_->DidConsume(result);
558 }
559 }
560
561 virtual void DoRead() {
562 int result = 1;
563 while (result > 0) {
564 input_buffer_->SetCapacity(input_buffer_->offset() + message_size_);
565 result = sockets_[1]->Read(input_buffer_, message_size_,
566 base::Bind(&TCPChannelTester::OnRead,
567 base::Unretained(this)));
568 HandleReadResult(result);
569 };
570 }
571
572 void OnRead(int result) {
573 HandleReadResult(result);
574 if (!done_)
575 DoRead(); // Don't try to read again when we are done reading.
576 }
577
578 void HandleReadResult(int result) {
579 if (result <= 0 && result != net::ERR_IO_PENDING) {
580 if (!done_) {
581 LOG(ERROR) << "Received error " << result << " when trying to read";
582 read_errors_++;
583 Done();
584 }
585 } else if (result > 0) {
586 // Allocate memory for the next read.
587 input_buffer_->set_offset(input_buffer_->offset() + result);
588 if (input_buffer_->offset() == test_data_size_)
589 Done();
590 }
591 }
592
593 scoped_refptr<net::DrainableIOBuffer> output_buffer_;
594 scoped_refptr<net::GrowableIOBuffer> input_buffer_;
595
596 int write_errors_;
597 int read_errors_;
598 int message_size_;
599 int message_count_;
600 int test_data_size_;
601 };
602
603 class ChannelSpeedTester : public TCPChannelTester {
604 public:
605 ChannelSpeedTester(Session* host_session,
606 Session* client_session,
607 int message_size)
608 : TCPChannelTester(host_session, client_session, message_size, 1) {
609 CHECK(message_size >= 8);
610 }
611
612 virtual ~ChannelSpeedTester() { }
613
614 virtual void CheckResults() {
615 }
616
617 base::TimeDelta GetElapsedTime() {
618 return base::Time::Now() - start_time_;
619 }
620
621 protected:
622 virtual void InitBuffers() {
623 TCPChannelTester::InitBuffers();
624
625 start_time_ = base::Time::Now();
626 }
627
628 base::Time start_time_;
629 };
630
631 class UDPChannelTester : public ChannelTesterBase {
632 public:
633 UDPChannelTester(Session* host_session,
634 Session* client_session)
635 : ChannelTesterBase(host_session, client_session),
636 write_errors_(0),
637 read_errors_(0),
638 packets_sent_(0),
639 packets_received_(0),
640 broken_packets_(0) {
641 }
642
643 virtual ~UDPChannelTester() { }
644
645 virtual void CheckResults() {
646 EXPECT_EQ(0, write_errors_);
647 EXPECT_EQ(0, read_errors_);
648
649 EXPECT_EQ(0, broken_packets_);
650
651 // Verify that we've received at least one packet.
652 EXPECT_GT(packets_received_, 0);
653 LOG(INFO) << "Received " << packets_received_ << " packets out of "
654 << kMessages;
655 }
656
657 protected:
658 virtual void InitChannels() OVERRIDE {
659 host_session_->CreateDatagramChannel(
660 kChannelName,
661 base::Bind(&UDPChannelTester::OnChannelReady,
662 base::Unretained(this), 0));
663 client_session_->CreateDatagramChannel(
664 kChannelName,
665 base::Bind(&UDPChannelTester::OnChannelReady,
666 base::Unretained(this), 1));
667 }
668
669 void OnChannelReady(int id, net::Socket* socket) {
670 ASSERT_TRUE(socket);
671 if (!socket) {
672 Done();
673 return;
674 }
675
676 DCHECK(id >= 0 && id < 2);
677 sockets_[id].reset(socket);
678
679 if (sockets_[0].get() && sockets_[1].get()) {
680 InitBuffers();
681 DoRead();
682 DoWrite();
683 }
684 }
685
686
687 virtual void InitBuffers() {
688 }
689
690 virtual void DoWrite() {
691 if (packets_sent_ >= kMessages) {
692 Done();
693 return;
694 }
695
696 scoped_refptr<net::IOBuffer> packet(new net::IOBuffer(kMessageSize));
697 memset(packet->data(), 123, kMessageSize);
698 sent_packets_[packets_sent_] = packet;
699 // Put index of this packet in the beginning of the packet body.
700 memcpy(packet->data(), &packets_sent_, sizeof(packets_sent_));
701
702 int result = sockets_[0]->Write(packet, kMessageSize,
703 base::Bind(&UDPChannelTester::OnWritten,
704 base::Unretained(this)));
705 HandleWriteResult(result);
706 }
707
708 void OnWritten(int result) {
709 HandleWriteResult(result);
710 }
711
712 void HandleWriteResult(int result) {
713 if (result <= 0 && result != net::ERR_IO_PENDING) {
714 LOG(ERROR) << "Received error " << result << " when trying to write";
715 write_errors_++;
716 Done();
717 } else if (result > 0) {
718 EXPECT_EQ(kMessageSize, result);
719 packets_sent_++;
720 MessageLoop::current()->PostDelayedTask(
721 FROM_HERE, base::Bind(&UDPChannelTester::DoWrite, this),
722 kUdpWriteDelayMs);
723 }
724 }
725
726 virtual void DoRead() {
727 int result = 1;
728 while (result > 0) {
729 int kReadSize = kMessageSize * 2;
730 read_buffer_ = new net::IOBuffer(kReadSize);
731
732 result = sockets_[1]->Read(read_buffer_, kReadSize,
733 base::Bind(&UDPChannelTester::OnRead,
734 base::Unretained(this)));
735 HandleReadResult(result);
736 };
737 }
738
739 void OnRead(int result) {
740 HandleReadResult(result);
741 DoRead();
742 }
743
744 void HandleReadResult(int result) {
745 if (result <= 0 && result != net::ERR_IO_PENDING) {
746 // Error will be received after the socket is closed.
747 if (!done_) {
748 LOG(ERROR) << "Received error " << result << " when trying to read";
749 read_errors_++;
750 Done();
751 }
752 } else if (result > 0) {
753 packets_received_++;
754 if (kMessageSize != result) {
755 // Invalid packet size;
756 broken_packets_++;
757 } else {
758 // Validate packet body.
759 int packet_id;
760 memcpy(&packet_id, read_buffer_->data(), sizeof(packet_id));
761 if (packet_id < 0 || packet_id >= kMessages) {
762 broken_packets_++;
763 } else {
764 if (memcmp(read_buffer_->data(), sent_packets_[packet_id]->data(),
765 kMessageSize) != 0)
766 broken_packets_++;
767 }
768 }
769 }
770 }
771
772 private:
773 scoped_refptr<net::IOBuffer> sent_packets_[kMessages];
774 scoped_refptr<net::IOBuffer> read_buffer_;
775
776 int write_errors_;
777 int read_errors_;
778 int packets_sent_;
779 int packets_received_;
780 int broken_packets_;
781 }; 285 };
782 286
783 // Verify that we can create and destory server objects without a connection. 287 // Verify that we can create and destory server objects without a connection.
784 TEST_F(JingleSessionTest, CreateAndDestoy) { 288 TEST_F(JingleSessionTest, CreateAndDestoy) {
785 CreateServerPair(false); 289 CreateServerPair(1, FakeAuthenticator::ACCEPT);
786 } 290 }
787 291
788 // Verify that incoming session can be rejected, and that the status 292 // Verify that incoming session can be rejected, and that the status
789 // of the connection is set to CLOSED in this case. 293 // of the connection is set to CLOSED in this case.
790 TEST_F(JingleSessionTest, RejectConnection) { 294 TEST_F(JingleSessionTest, RejectConnection) {
791 CreateServerPair(false); 295 CreateServerPair(1, FakeAuthenticator::ACCEPT);
792 296
793 // Reject incoming session. 297 // Reject incoming session.
794 EXPECT_CALL(host_server_listener_, OnIncomingSession(_, _)) 298 EXPECT_CALL(host_server_listener_, OnIncomingSession(_, _))
795 .WillOnce(SetArgumentPointee<1>(protocol::SessionManager::DECLINE)); 299 .WillOnce(SetArgumentPointee<1>(protocol::SessionManager::DECLINE));
796 300
797 { 301 {
798 InSequence dummy; 302 InSequence dummy;
799 303
800 EXPECT_CALL(client_connection_callback_, 304 EXPECT_CALL(client_connection_callback_,
801 OnStateChange(Session::CONNECTING)) 305 OnStateChange(Session::CONNECTING))
802 .Times(1); 306 .Times(1);
803 EXPECT_CALL(client_connection_callback_, 307 EXPECT_CALL(client_connection_callback_,
804 OnStateChange(Session::CLOSED)) 308 OnStateChange(Session::FAILED))
805 .Times(1) 309 .Times(1);
806 .WillOnce(InvokeWithoutArgs(&QuitCurrentThread));
807 } 310 }
808 311
809 Authenticator* authenticator = 312 Authenticator* authenticator = new FakeAuthenticator(
810 new V1ClientAuthenticator(kClientJid, kTestSharedSecretBad); 313 FakeAuthenticator::CLIENT, 1, FakeAuthenticator::ACCEPT, true);
811 client_session_.reset(client_server_->Connect( 314 client_session_.reset(client_server_->Connect(
812 kHostJid, authenticator, 315 kHostJid, authenticator,
813 CandidateSessionConfig::CreateDefault(), 316 CandidateSessionConfig::CreateDefault(),
814 base::Bind(&MockSessionCallback::OnStateChange, 317 base::Bind(&MockSessionCallback::OnStateChange,
815 base::Unretained(&client_connection_callback_)))); 318 base::Unretained(&client_connection_callback_))));
816 319
817 ASSERT_TRUE(RunMessageLoopWithTimeout(TestTimeouts::action_max_timeout_ms())); 320 message_loop_.RunAllPending();
818 } 321 }
819 322
820 // Verify that we can connect two endpoints. 323 // Verify that we can connect two endpoints.
821 TEST_F(JingleSessionTest, Connect) { 324 TEST_F(JingleSessionTest, Connect) {
822 CreateServerPair(false); 325 CreateServerPair(1, FakeAuthenticator::ACCEPT);
823 ASSERT_TRUE(InitiateConnection(false)); 326 InitiateConnection(1, FakeAuthenticator::ACCEPT, false);
824 } 327 }
825 328
826 // Verify that we can't connect two endpoints with mismatched secrets. 329 // Verify that we can't connect two endpoints with mismatched secrets.
330 TEST_F(JingleSessionTest, ConnectBadAuth) {
331 CreateServerPair(1, FakeAuthenticator::REJECT);
332 InitiateConnection(1, FakeAuthenticator::ACCEPT, true);
333 }
334
827 TEST_F(JingleSessionTest, ConnectBadChannelAuth) { 335 TEST_F(JingleSessionTest, ConnectBadChannelAuth) {
828 CreateServerPair(true); 336 CreateServerPair(1, FakeAuthenticator::REJECT_CHANNEL);
829 ASSERT_TRUE(InitiateConnection(true)); 337 ASSERT_NO_FATAL_FAILURE(
830 scoped_refptr<TCPChannelTester> tester( 338 InitiateConnection(1, FakeAuthenticator::ACCEPT, false));
831 new TCPChannelTester(host_session_.get(), client_session_.get(),
832 kMessageSize, kMessages));
833 tester->Start();
834 ASSERT_TRUE(tester->WaitFinished());
835 EXPECT_TRUE(tester->did_initialization_fail());
836 339
837 CloseSessions(); 340 MockStreamChannelCallback client_callback;
341 MockStreamChannelCallback host_callback;
342
343 client_session_->CreateStreamChannel(kChannelName, base::Bind(
344 &MockStreamChannelCallback::OnDone,
345 base::Unretained(&client_callback)));
346 host_session_->CreateStreamChannel(kChannelName, base::Bind(
347 &MockStreamChannelCallback::OnDone,
348 base::Unretained(&host_callback)));
349
350 EXPECT_CALL(client_callback, OnDone(_))
351 .Times(AtMost(1))
352 .WillOnce(DeleteArg<0>());
353 EXPECT_CALL(host_callback, OnDone(NULL))
354 .WillOnce(QuitThread());
355
356 message_loop_.Run();
357
358 client_session_->CancelChannelCreation(kChannelName);
359 host_session_->CancelChannelCreation(kChannelName);
838 } 360 }
839 361
840 // Verify that data can be transmitted over the event channel. 362 // Verify that data can be transmitted over the event channel.
841 TEST_F(JingleSessionTest, TestTcpChannel) { 363 TEST_F(JingleSessionTest, TestTcpChannel) {
842 CreateServerPair(false); 364 CreateServerPair(1, FakeAuthenticator::ACCEPT);
843 ASSERT_TRUE(InitiateConnection(false)); 365 ASSERT_NO_FATAL_FAILURE(
844 scoped_refptr<TCPChannelTester> tester( 366 InitiateConnection(1, FakeAuthenticator::ACCEPT, false));
845 new TCPChannelTester(host_session_.get(), client_session_.get(),
846 kMessageSize, kMessages));
847 tester->Start();
848 ASSERT_TRUE(tester->WaitFinished());
849 tester->CheckResults();
850 367
851 // Connections must be closed while |tester| still exists. 368 ASSERT_NO_FATAL_FAILURE(CreateChannel());
852 CloseSessions(); 369
370 StreamConnectionTester tester(host_socket_.get(), client_socket_.get(),
371 kMessageSize, kMessages);
372 tester.Start();
373 message_loop_.Run();
374 tester.CheckResults();
853 } 375 }
854 376
855 // Verify that data can be transmitted over the video RTP channel. 377 // Verify that data can be transmitted over the video RTP channel.
856 TEST_F(JingleSessionTest, TestUdpChannel) { 378 TEST_F(JingleSessionTest, TestUdpChannel) {
857 CreateServerPair(false); 379 CreateServerPair(1, FakeAuthenticator::ACCEPT);
858 ASSERT_TRUE(InitiateConnection(false)); 380 ASSERT_NO_FATAL_FAILURE(
859 scoped_refptr<UDPChannelTester> tester( 381 InitiateConnection(1, FakeAuthenticator::ACCEPT, false));
860 new UDPChannelTester(host_session_.get(), client_session_.get()));
861 tester->Start();
862 ASSERT_TRUE(tester->WaitFinished());
863 tester->CheckResults();
864 382
865 // Connections must be closed while |tester| still exists. 383 MockDatagramChannelCallback client_callback;
866 CloseSessions(); 384 MockDatagramChannelCallback host_callback;
867 }
868 385
869 // Send packets of different size to get the latency for sending data 386 int counter = 2;
870 // using sockets from JingleSession. 387 net::Socket* client_socket = NULL;
871 TEST_F(JingleSessionTest, FLAKY_TestSpeed) { 388 net::Socket* host_socket = NULL;
872 CreateServerPair(false); 389 EXPECT_CALL(client_callback, OnDone(_))
873 ASSERT_TRUE(InitiateConnection(false)); 390 .WillOnce(DoAll(SaveArg<0>(&client_socket),
874 scoped_refptr<ChannelSpeedTester> tester; 391 QuitThreadOnCounter(&counter)));
392 EXPECT_CALL(host_callback, OnDone(_))
393 .WillOnce(DoAll(SaveArg<0>(&host_socket),
394 QuitThreadOnCounter(&counter)));
875 395
876 tester = new ChannelSpeedTester(host_session_.get(), 396 client_session_->CreateDatagramChannel(kChannelName, base::Bind(
877 client_session_.get(), 512); 397 &MockDatagramChannelCallback::OnDone,
878 tester->Start(); 398 base::Unretained(&host_callback)));
879 ASSERT_TRUE(tester->WaitFinished()); 399 host_session_->CreateDatagramChannel(kChannelName, base::Bind(
880 LOG(INFO) << "Time for 512 bytes " 400 &MockDatagramChannelCallback::OnDone,
881 << tester->GetElapsedTime().InMilliseconds() << " ms."; 401 base::Unretained(&client_callback)));
882 402
883 CloseSessions(); 403 message_loop_.Run();
884 ASSERT_TRUE(InitiateConnection(false));
885 404
886 tester = new ChannelSpeedTester(host_session_.get(), 405 scoped_ptr<net::Socket> client_socket_ptr(client_socket);
887 client_session_.get(), 1024); 406 scoped_ptr<net::Socket> host_socket_ptr(host_socket);
888 tester->Start();
889 ASSERT_TRUE(tester->WaitFinished());
890 LOG(INFO) << "Time for 1024 bytes "
891 << tester->GetElapsedTime().InMilliseconds() << " ms.";
892 407
893 CloseSessions(); 408 ASSERT_TRUE(client_socket != NULL);
894 ASSERT_TRUE(InitiateConnection(false)); 409 ASSERT_TRUE(host_socket != NULL);
895 410
896 tester = new ChannelSpeedTester(host_session_.get(), 411 DatagramConnectionTester tester(
897 client_session_.get(), 51200); 412 client_socket, host_socket, kMessageSize, kMessages, kUdpWriteDelayMs);
898 tester->Start(); 413 tester.Start();
899 ASSERT_TRUE(tester->WaitFinished()); 414 message_loop_.Run();
900 LOG(INFO) << "Time for 50k bytes " 415 tester.CheckResults();
901 << tester->GetElapsedTime().InMilliseconds() << " ms.";
902
903 CloseSessions();
904 ASSERT_TRUE(InitiateConnection(false));
905
906 tester = new ChannelSpeedTester(host_session_.get(),
907 client_session_.get(), 512000);
908 tester->Start();
909 ASSERT_TRUE(tester->WaitFinished());
910 LOG(INFO) << "Time for 500k bytes "
911 << tester->GetElapsedTime().InMilliseconds() << " ms.";
912
913 // Connections must be closed while |tester| still exists.
914 CloseSessions();
915 } 416 }
916 417
917 } // namespace protocol 418 } // namespace protocol
918 } // namespace remoting 419 } // namespace remoting
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698