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