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