Add scoped_ptr-safe base::Value to Dictionary/List conversion functions.
[chromium-blink-merge.git] / ipc / ipc_channel_posix_unittest.cc
blobeb78b7c2cfb9afd0551e98cb7875234080e37007
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // These tests are POSIX only.
7 #include "ipc/ipc_channel_posix.h"
9 #include <fcntl.h>
10 #include <stdint.h>
11 #include <sys/socket.h>
12 #include <sys/un.h>
13 #include <unistd.h>
15 #include "base/basictypes.h"
16 #include "base/files/file_path.h"
17 #include "base/files/file_util.h"
18 #include "base/location.h"
19 #include "base/memory/scoped_ptr.h"
20 #include "base/path_service.h"
21 #include "base/posix/eintr_wrapper.h"
22 #include "base/process/process.h"
23 #include "base/single_thread_task_runner.h"
24 #include "base/test/multiprocess_test.h"
25 #include "base/test/test_timeouts.h"
26 #include "ipc/ipc_listener.h"
27 #include "ipc/unix_domain_socket_util.h"
28 #include "testing/multiprocess_func_list.h"
30 namespace {
32 static const uint32_t kQuitMessage = 47;
34 class IPCChannelPosixTestListener : public IPC::Listener {
35 public:
36 enum STATUS {
37 DISCONNECTED,
38 MESSAGE_RECEIVED,
39 CHANNEL_ERROR,
40 CONNECTED,
41 DENIED,
42 LISTEN_ERROR
45 IPCChannelPosixTestListener(bool quit_only_on_message)
46 : status_(DISCONNECTED),
47 quit_only_on_message_(quit_only_on_message) {
50 ~IPCChannelPosixTestListener() override {}
52 bool OnMessageReceived(const IPC::Message& message) override {
53 EXPECT_EQ(message.type(), kQuitMessage);
54 status_ = MESSAGE_RECEIVED;
55 QuitRunLoop();
56 return true;
59 void OnChannelConnected(int32_t peer_pid) override {
60 status_ = CONNECTED;
61 if (!quit_only_on_message_) {
62 QuitRunLoop();
66 void OnChannelError() override {
67 status_ = CHANNEL_ERROR;
68 QuitRunLoop();
71 void OnChannelDenied() override {
72 status_ = DENIED;
73 if (!quit_only_on_message_) {
74 QuitRunLoop();
78 void OnChannelListenError() override {
79 status_ = LISTEN_ERROR;
80 if (!quit_only_on_message_) {
81 QuitRunLoop();
85 STATUS status() { return status_; }
87 void QuitRunLoop() {
88 base::MessageLoopForIO* loop = base::MessageLoopForIO::current();
89 if (loop->is_running()) {
90 loop->QuitNow();
91 } else {
92 // Die as soon as Run is called.
93 loop->task_runner()->PostTask(FROM_HERE, loop->QuitClosure());
97 private:
98 // The current status of the listener.
99 STATUS status_;
100 // If |quit_only_on_message_| then the listener will only break out of
101 // the run loop when kQuitMessage is received.
102 bool quit_only_on_message_;
105 class IPCChannelPosixTest : public base::MultiProcessTest {
106 public:
107 static void SetUpSocket(IPC::ChannelHandle *handle,
108 IPC::Channel::Mode mode);
109 static void SpinRunLoop(base::TimeDelta delay);
110 static const std::string GetConnectionSocketName();
111 static const std::string GetChannelDirName();
113 protected:
114 void SetUp() override;
115 void TearDown() override;
117 private:
118 scoped_ptr<base::MessageLoopForIO> message_loop_;
121 const std::string IPCChannelPosixTest::GetChannelDirName() {
122 base::FilePath tmp_dir;
123 PathService::Get(base::DIR_TEMP, &tmp_dir);
124 return tmp_dir.value();
127 const std::string IPCChannelPosixTest::GetConnectionSocketName() {
128 return GetChannelDirName() + "/chrome_IPCChannelPosixTest__ConnectionSocket";
131 void IPCChannelPosixTest::SetUp() {
132 MultiProcessTest::SetUp();
133 // Construct a fresh IO Message loop for the duration of each test.
134 message_loop_.reset(new base::MessageLoopForIO());
137 void IPCChannelPosixTest::TearDown() {
138 message_loop_.reset(NULL);
139 MultiProcessTest::TearDown();
142 // Create up a socket and bind and listen to it, or connect it
143 // depending on the |mode|.
144 void IPCChannelPosixTest::SetUpSocket(IPC::ChannelHandle *handle,
145 IPC::Channel::Mode mode) {
146 const std::string& name = handle->name;
148 int socket_fd = socket(PF_UNIX, SOCK_STREAM, 0);
149 ASSERT_GE(socket_fd, 0) << name;
150 ASSERT_GE(fcntl(socket_fd, F_SETFL, O_NONBLOCK), 0);
151 struct sockaddr_un server_address = { 0 };
152 memset(&server_address, 0, sizeof(server_address));
153 server_address.sun_family = AF_UNIX;
154 int path_len = snprintf(server_address.sun_path, IPC::kMaxSocketNameLength,
155 "%s", name.c_str());
156 DCHECK_EQ(static_cast<int>(name.length()), path_len);
157 size_t server_address_len = offsetof(struct sockaddr_un,
158 sun_path) + path_len + 1;
160 if (mode == IPC::Channel::MODE_NAMED_SERVER) {
161 // Only one server at a time. Cleanup garbage if it exists.
162 unlink(name.c_str());
163 // Make sure the path we need exists.
164 base::FilePath path(name);
165 base::FilePath dir_path = path.DirName();
166 ASSERT_TRUE(base::CreateDirectory(dir_path));
167 ASSERT_GE(bind(socket_fd,
168 reinterpret_cast<struct sockaddr *>(&server_address),
169 server_address_len), 0) << server_address.sun_path
170 << ": " << strerror(errno)
171 << "(" << errno << ")";
172 ASSERT_GE(listen(socket_fd, SOMAXCONN), 0) << server_address.sun_path
173 << ": " << strerror(errno)
174 << "(" << errno << ")";
175 } else if (mode == IPC::Channel::MODE_NAMED_CLIENT) {
176 ASSERT_GE(connect(socket_fd,
177 reinterpret_cast<struct sockaddr *>(&server_address),
178 server_address_len), 0) << server_address.sun_path
179 << ": " << strerror(errno)
180 << "(" << errno << ")";
181 } else {
182 FAIL() << "Unknown mode " << mode;
184 handle->socket.fd = socket_fd;
187 void IPCChannelPosixTest::SpinRunLoop(base::TimeDelta delay) {
188 base::MessageLoopForIO* loop = base::MessageLoopForIO::current();
189 // Post a quit task so that this loop eventually ends and we don't hang
190 // in the case of a bad test. Usually, the run loop will quit sooner than
191 // that because all tests use a IPCChannelPosixTestListener which quits the
192 // current run loop on any channel activity.
193 loop->task_runner()->PostDelayedTask(FROM_HERE, loop->QuitClosure(), delay);
194 loop->Run();
197 TEST_F(IPCChannelPosixTest, BasicListen) {
198 const std::string kChannelName =
199 GetChannelDirName() + "/IPCChannelPosixTest_BasicListen";
201 // Test creating a socket that is listening.
202 IPC::ChannelHandle handle(kChannelName);
203 SetUpSocket(&handle, IPC::Channel::MODE_NAMED_SERVER);
204 unlink(handle.name.c_str());
205 scoped_ptr<IPC::ChannelPosix> channel(new IPC::ChannelPosix(
206 handle, IPC::Channel::MODE_NAMED_SERVER, NULL, nullptr));
207 ASSERT_TRUE(channel->Connect());
208 ASSERT_TRUE(channel->AcceptsConnections());
209 ASSERT_FALSE(channel->HasAcceptedConnection());
210 channel->ResetToAcceptingConnectionState();
211 ASSERT_FALSE(channel->HasAcceptedConnection());
212 unlink(handle.name.c_str());
215 TEST_F(IPCChannelPosixTest, BasicConnected) {
216 // Test creating a socket that is connected.
217 int pipe_fds[2];
218 ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, pipe_fds));
219 std::string socket_name("/var/tmp/IPCChannelPosixTest_BasicConnected");
220 ASSERT_GE(fcntl(pipe_fds[0], F_SETFL, O_NONBLOCK), 0);
222 base::FileDescriptor fd(pipe_fds[0], false);
223 IPC::ChannelHandle handle(socket_name, fd);
224 scoped_ptr<IPC::ChannelPosix> channel(
225 new IPC::ChannelPosix(handle, IPC::Channel::MODE_SERVER, NULL, nullptr));
226 ASSERT_TRUE(channel->Connect());
227 ASSERT_FALSE(channel->AcceptsConnections());
228 channel->Close();
229 ASSERT_TRUE(IGNORE_EINTR(close(pipe_fds[1])) == 0);
231 // Make sure that we can use the socket that is created for us by
232 // a standard channel.
233 scoped_ptr<IPC::ChannelPosix> channel2(new IPC::ChannelPosix(
234 socket_name, IPC::Channel::MODE_SERVER, NULL, nullptr));
235 ASSERT_TRUE(channel2->Connect());
236 ASSERT_FALSE(channel2->AcceptsConnections());
239 // If a connection closes right before a Send() call, we may end up closing
240 // the connection without notifying the listener, which can cause hangs in
241 // sync_message_filter and others. Make sure the listener is notified.
242 TEST_F(IPCChannelPosixTest, SendHangTest) {
243 IPCChannelPosixTestListener out_listener(true);
244 IPCChannelPosixTestListener in_listener(true);
245 IPC::ChannelHandle in_handle("IN");
246 scoped_ptr<IPC::ChannelPosix> in_chan(new IPC::ChannelPosix(
247 in_handle, IPC::Channel::MODE_SERVER, &in_listener, nullptr));
248 IPC::ChannelHandle out_handle(
249 "OUT", base::FileDescriptor(in_chan->TakeClientFileDescriptor()));
250 scoped_ptr<IPC::ChannelPosix> out_chan(new IPC::ChannelPosix(
251 out_handle, IPC::Channel::MODE_CLIENT, &out_listener, nullptr));
252 ASSERT_TRUE(in_chan->Connect());
253 ASSERT_TRUE(out_chan->Connect());
254 in_chan->Close(); // simulate remote process dying at an unfortunate time.
255 // Send will fail, because it cannot write the message.
256 ASSERT_FALSE(out_chan->Send(new IPC::Message(
257 0, // routing_id
258 kQuitMessage, // message type
259 IPC::Message::PRIORITY_NORMAL)));
260 SpinRunLoop(TestTimeouts::action_max_timeout());
261 ASSERT_EQ(IPCChannelPosixTestListener::CHANNEL_ERROR, out_listener.status());
264 // If a connection closes right before a Connect() call, we may end up closing
265 // the connection without notifying the listener, which can cause hangs in
266 // sync_message_filter and others. Make sure the listener is notified.
267 TEST_F(IPCChannelPosixTest, AcceptHangTest) {
268 IPCChannelPosixTestListener out_listener(true);
269 IPCChannelPosixTestListener in_listener(true);
270 IPC::ChannelHandle in_handle("IN");
271 scoped_ptr<IPC::ChannelPosix> in_chan(new IPC::ChannelPosix(
272 in_handle, IPC::Channel::MODE_SERVER, &in_listener, nullptr));
273 IPC::ChannelHandle out_handle(
274 "OUT", base::FileDescriptor(in_chan->TakeClientFileDescriptor()));
275 scoped_ptr<IPC::ChannelPosix> out_chan(new IPC::ChannelPosix(
276 out_handle, IPC::Channel::MODE_CLIENT, &out_listener, nullptr));
277 ASSERT_TRUE(in_chan->Connect());
278 in_chan->Close(); // simulate remote process dying at an unfortunate time.
279 ASSERT_FALSE(out_chan->Connect());
280 SpinRunLoop(TestTimeouts::action_max_timeout());
281 ASSERT_EQ(IPCChannelPosixTestListener::CHANNEL_ERROR, out_listener.status());
284 #if defined(OS_ANDROID)
285 #define MAYBE_AdvancedConnected DISABLED_AdvancedConnected
286 #else
287 #define MAYBE_AdvancedConnected AdvancedConnected
288 #endif
289 TEST_F(IPCChannelPosixTest, MAYBE_AdvancedConnected) {
290 // Test creating a connection to an external process.
291 IPCChannelPosixTestListener listener(false);
292 IPC::ChannelHandle chan_handle(GetConnectionSocketName());
293 SetUpSocket(&chan_handle, IPC::Channel::MODE_NAMED_SERVER);
294 scoped_ptr<IPC::ChannelPosix> channel(new IPC::ChannelPosix(
295 chan_handle, IPC::Channel::MODE_NAMED_SERVER, &listener, nullptr));
296 ASSERT_TRUE(channel->Connect());
297 ASSERT_TRUE(channel->AcceptsConnections());
298 ASSERT_FALSE(channel->HasAcceptedConnection());
300 base::Process process = SpawnChild("IPCChannelPosixTestConnectionProc");
301 ASSERT_TRUE(process.IsValid());
302 SpinRunLoop(TestTimeouts::action_max_timeout());
303 ASSERT_EQ(IPCChannelPosixTestListener::CONNECTED, listener.status());
304 ASSERT_TRUE(channel->HasAcceptedConnection());
305 IPC::Message* message = new IPC::Message(0, // routing_id
306 kQuitMessage, // message type
307 IPC::Message::PRIORITY_NORMAL);
308 channel->Send(message);
309 SpinRunLoop(TestTimeouts::action_timeout());
310 int exit_code = 0;
311 EXPECT_TRUE(process.WaitForExit(&exit_code));
312 EXPECT_EQ(0, exit_code);
313 ASSERT_EQ(IPCChannelPosixTestListener::CHANNEL_ERROR, listener.status());
314 ASSERT_FALSE(channel->HasAcceptedConnection());
315 unlink(chan_handle.name.c_str());
318 #if defined(OS_ANDROID)
319 #define MAYBE_ResetState DISABLED_ResetState
320 #else
321 #define MAYBE_ResetState ResetState
322 #endif
323 TEST_F(IPCChannelPosixTest, MAYBE_ResetState) {
324 // Test creating a connection to an external process. Close the connection,
325 // but continue to listen and make sure another external process can connect
326 // to us.
327 IPCChannelPosixTestListener listener(false);
328 IPC::ChannelHandle chan_handle(GetConnectionSocketName());
329 SetUpSocket(&chan_handle, IPC::Channel::MODE_NAMED_SERVER);
330 scoped_ptr<IPC::ChannelPosix> channel(new IPC::ChannelPosix(
331 chan_handle, IPC::Channel::MODE_NAMED_SERVER, &listener, nullptr));
332 ASSERT_TRUE(channel->Connect());
333 ASSERT_TRUE(channel->AcceptsConnections());
334 ASSERT_FALSE(channel->HasAcceptedConnection());
336 base::Process process = SpawnChild("IPCChannelPosixTestConnectionProc");
337 ASSERT_TRUE(process.IsValid());
338 SpinRunLoop(TestTimeouts::action_max_timeout());
339 ASSERT_EQ(IPCChannelPosixTestListener::CONNECTED, listener.status());
340 ASSERT_TRUE(channel->HasAcceptedConnection());
341 channel->ResetToAcceptingConnectionState();
342 ASSERT_FALSE(channel->HasAcceptedConnection());
344 base::Process process2 = SpawnChild("IPCChannelPosixTestConnectionProc");
345 ASSERT_TRUE(process2.IsValid());
346 SpinRunLoop(TestTimeouts::action_max_timeout());
347 ASSERT_EQ(IPCChannelPosixTestListener::CONNECTED, listener.status());
348 ASSERT_TRUE(channel->HasAcceptedConnection());
349 IPC::Message* message = new IPC::Message(0, // routing_id
350 kQuitMessage, // message type
351 IPC::Message::PRIORITY_NORMAL);
352 channel->Send(message);
353 SpinRunLoop(TestTimeouts::action_timeout());
354 EXPECT_TRUE(process.Terminate(0, false));
355 int exit_code = 0;
356 EXPECT_TRUE(process2.WaitForExit(&exit_code));
357 EXPECT_EQ(0, exit_code);
358 ASSERT_EQ(IPCChannelPosixTestListener::CHANNEL_ERROR, listener.status());
359 ASSERT_FALSE(channel->HasAcceptedConnection());
360 unlink(chan_handle.name.c_str());
363 TEST_F(IPCChannelPosixTest, BadChannelName) {
364 // Test empty name
365 IPC::ChannelHandle handle("");
366 scoped_ptr<IPC::ChannelPosix> channel(new IPC::ChannelPosix(
367 handle, IPC::Channel::MODE_NAMED_SERVER, NULL, nullptr));
368 ASSERT_FALSE(channel->Connect());
370 // Test name that is too long.
371 const char *kTooLongName = "This_is_a_very_long_name_to_proactively_implement"
372 "client-centered_synergy_through_top-line"
373 "platforms_Phosfluorescently_disintermediate_"
374 "clicks-and-mortar_best_practices_without_"
375 "future-proof_growth_strategies_Continually"
376 "pontificate_proactive_potentialities_before"
377 "leading-edge_processes";
378 EXPECT_GE(strlen(kTooLongName), IPC::kMaxSocketNameLength);
379 IPC::ChannelHandle handle2(kTooLongName);
380 scoped_ptr<IPC::ChannelPosix> channel2(new IPC::ChannelPosix(
381 handle2, IPC::Channel::MODE_NAMED_SERVER, NULL, nullptr));
382 EXPECT_FALSE(channel2->Connect());
385 #if defined(OS_ANDROID)
386 #define MAYBE_MultiConnection DISABLED_MultiConnection
387 #else
388 #define MAYBE_MultiConnection MultiConnection
389 #endif
390 TEST_F(IPCChannelPosixTest, MAYBE_MultiConnection) {
391 // Test setting up a connection to an external process, and then have
392 // another external process attempt to connect to us.
393 IPCChannelPosixTestListener listener(false);
394 IPC::ChannelHandle chan_handle(GetConnectionSocketName());
395 SetUpSocket(&chan_handle, IPC::Channel::MODE_NAMED_SERVER);
396 scoped_ptr<IPC::ChannelPosix> channel(new IPC::ChannelPosix(
397 chan_handle, IPC::Channel::MODE_NAMED_SERVER, &listener, nullptr));
398 ASSERT_TRUE(channel->Connect());
399 ASSERT_TRUE(channel->AcceptsConnections());
400 ASSERT_FALSE(channel->HasAcceptedConnection());
402 base::Process process = SpawnChild("IPCChannelPosixTestConnectionProc");
403 ASSERT_TRUE(process.IsValid());
404 SpinRunLoop(TestTimeouts::action_max_timeout());
405 ASSERT_EQ(IPCChannelPosixTestListener::CONNECTED, listener.status());
406 ASSERT_TRUE(channel->HasAcceptedConnection());
407 base::Process process2 = SpawnChild("IPCChannelPosixFailConnectionProc");
408 ASSERT_TRUE(process2.IsValid());
409 SpinRunLoop(TestTimeouts::action_max_timeout());
410 int exit_code = 0;
411 EXPECT_TRUE(process2.WaitForExit(&exit_code));
412 EXPECT_EQ(exit_code, 0);
413 ASSERT_EQ(IPCChannelPosixTestListener::DENIED, listener.status());
414 ASSERT_TRUE(channel->HasAcceptedConnection());
415 IPC::Message* message = new IPC::Message(0, // routing_id
416 kQuitMessage, // message type
417 IPC::Message::PRIORITY_NORMAL);
418 channel->Send(message);
419 SpinRunLoop(TestTimeouts::action_timeout());
420 EXPECT_TRUE(process.WaitForExit(&exit_code));
421 EXPECT_EQ(exit_code, 0);
422 ASSERT_EQ(IPCChannelPosixTestListener::CHANNEL_ERROR, listener.status());
423 ASSERT_FALSE(channel->HasAcceptedConnection());
424 unlink(chan_handle.name.c_str());
427 TEST_F(IPCChannelPosixTest, DoubleServer) {
428 // Test setting up two servers with the same name.
429 IPCChannelPosixTestListener listener(false);
430 IPCChannelPosixTestListener listener2(false);
431 IPC::ChannelHandle chan_handle(GetConnectionSocketName());
432 scoped_ptr<IPC::ChannelPosix> channel(new IPC::ChannelPosix(
433 chan_handle, IPC::Channel::MODE_SERVER, &listener, nullptr));
434 scoped_ptr<IPC::ChannelPosix> channel2(new IPC::ChannelPosix(
435 chan_handle, IPC::Channel::MODE_SERVER, &listener2, nullptr));
436 ASSERT_TRUE(channel->Connect());
437 ASSERT_FALSE(channel2->Connect());
440 TEST_F(IPCChannelPosixTest, BadMode) {
441 // Test setting up two servers with a bad mode.
442 IPCChannelPosixTestListener listener(false);
443 IPC::ChannelHandle chan_handle(GetConnectionSocketName());
444 scoped_ptr<IPC::ChannelPosix> channel(new IPC::ChannelPosix(
445 chan_handle, IPC::Channel::MODE_NONE, &listener, nullptr));
446 ASSERT_FALSE(channel->Connect());
449 TEST_F(IPCChannelPosixTest, IsNamedServerInitialized) {
450 const std::string& connection_socket_name = GetConnectionSocketName();
451 IPCChannelPosixTestListener listener(false);
452 IPC::ChannelHandle chan_handle(connection_socket_name);
453 ASSERT_TRUE(base::DeleteFile(base::FilePath(connection_socket_name), false));
454 ASSERT_FALSE(IPC::Channel::IsNamedServerInitialized(
455 connection_socket_name));
456 scoped_ptr<IPC::ChannelPosix> channel(new IPC::ChannelPosix(
457 chan_handle, IPC::Channel::MODE_NAMED_SERVER, &listener, nullptr));
458 ASSERT_TRUE(IPC::Channel::IsNamedServerInitialized(
459 connection_socket_name));
460 channel->Close();
461 ASSERT_FALSE(IPC::Channel::IsNamedServerInitialized(
462 connection_socket_name));
463 unlink(chan_handle.name.c_str());
466 // A long running process that connects to us
467 MULTIPROCESS_TEST_MAIN(IPCChannelPosixTestConnectionProc) {
468 base::MessageLoopForIO message_loop;
469 IPCChannelPosixTestListener listener(true);
470 IPC::ChannelHandle handle(IPCChannelPosixTest::GetConnectionSocketName());
471 IPCChannelPosixTest::SetUpSocket(&handle, IPC::Channel::MODE_NAMED_CLIENT);
472 scoped_ptr<IPC::ChannelPosix> channel(new IPC::ChannelPosix(
473 handle, IPC::Channel::MODE_NAMED_CLIENT, &listener, nullptr));
474 EXPECT_TRUE(channel->Connect());
475 IPCChannelPosixTest::SpinRunLoop(TestTimeouts::action_max_timeout());
476 EXPECT_EQ(IPCChannelPosixTestListener::MESSAGE_RECEIVED, listener.status());
477 return 0;
480 // Simple external process that shouldn't be able to connect to us.
481 MULTIPROCESS_TEST_MAIN(IPCChannelPosixFailConnectionProc) {
482 base::MessageLoopForIO message_loop;
483 IPCChannelPosixTestListener listener(false);
484 IPC::ChannelHandle handle(IPCChannelPosixTest::GetConnectionSocketName());
485 IPCChannelPosixTest::SetUpSocket(&handle, IPC::Channel::MODE_NAMED_CLIENT);
486 scoped_ptr<IPC::ChannelPosix> channel(new IPC::ChannelPosix(
487 handle, IPC::Channel::MODE_NAMED_CLIENT, &listener, nullptr));
489 // In this case connect may succeed or fail depending on if the packet
490 // actually gets sent at sendmsg. Since we never delay on send, we may not
491 // see the error. However even if connect succeeds, eventually we will get an
492 // error back since the channel will be closed when we attempt to read from
493 // it.
494 bool connected = channel->Connect();
495 if (connected) {
496 IPCChannelPosixTest::SpinRunLoop(TestTimeouts::action_max_timeout());
497 EXPECT_EQ(IPCChannelPosixTestListener::CHANNEL_ERROR, listener.status());
498 } else {
499 EXPECT_EQ(IPCChannelPosixTestListener::DISCONNECTED, listener.status());
501 return 0;
504 } // namespace