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"
10 #include <sys/socket.h>
14 #include "base/basictypes.h"
15 #include "base/file_util.h"
16 #include "base/files/file_path.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/kill.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"
30 static const uint32 kQuitMessage
= 47;
32 class IPCChannelPosixTestListener
: public IPC::Listener
{
43 IPCChannelPosixTestListener(bool quit_only_on_message
)
44 : status_(DISCONNECTED
),
45 quit_only_on_message_(quit_only_on_message
) {
48 virtual ~IPCChannelPosixTestListener() {}
50 virtual bool OnMessageReceived(const IPC::Message
& message
) OVERRIDE
{
51 EXPECT_EQ(message
.type(), kQuitMessage
);
52 status_
= MESSAGE_RECEIVED
;
57 virtual void OnChannelConnected(int32 peer_pid
) OVERRIDE
{
59 if (!quit_only_on_message_
) {
64 virtual void OnChannelError() OVERRIDE
{
65 status_
= CHANNEL_ERROR
;
69 virtual void OnChannelDenied() OVERRIDE
{
71 if (!quit_only_on_message_
) {
76 virtual void OnChannelListenError() OVERRIDE
{
77 status_
= LISTEN_ERROR
;
78 if (!quit_only_on_message_
) {
83 STATUS
status() { return status_
; }
86 base::MessageLoopForIO
* loop
= base::MessageLoopForIO::current();
87 if (loop
->is_running()) {
90 // Die as soon as Run is called.
91 loop
->PostTask(FROM_HERE
, loop
->QuitClosure());
96 // The current status of the listener.
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
{
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();
112 virtual void SetUp();
113 virtual void TearDown();
116 scoped_ptr
<base::MessageLoopForIO
> message_loop_
;
119 const std::string
IPCChannelPosixTest::GetChannelDirName() {
120 #if defined(OS_ANDROID)
121 base::FilePath tmp_dir
;
122 PathService::Get(base::DIR_CACHE
, &tmp_dir
);
123 return tmp_dir
.value();
129 const std::string
IPCChannelPosixTest::GetConnectionSocketName() {
130 return GetChannelDirName() + "/chrome_IPCChannelPosixTest__ConnectionSocket";
133 void IPCChannelPosixTest::SetUp() {
134 MultiProcessTest::SetUp();
135 // Construct a fresh IO Message loop for the duration of each test.
136 message_loop_
.reset(new base::MessageLoopForIO());
139 void IPCChannelPosixTest::TearDown() {
140 message_loop_
.reset(NULL
);
141 MultiProcessTest::TearDown();
144 // Create up a socket and bind and listen to it, or connect it
145 // depending on the |mode|.
146 void IPCChannelPosixTest::SetUpSocket(IPC::ChannelHandle
*handle
,
147 IPC::Channel::Mode mode
) {
148 const std::string
& name
= handle
->name
;
150 int socket_fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
151 ASSERT_GE(socket_fd
, 0) << name
;
152 ASSERT_GE(fcntl(socket_fd
, F_SETFL
, O_NONBLOCK
), 0);
153 struct sockaddr_un server_address
= { 0 };
154 memset(&server_address
, 0, sizeof(server_address
));
155 server_address
.sun_family
= AF_UNIX
;
156 int path_len
= snprintf(server_address
.sun_path
, IPC::kMaxSocketNameLength
,
158 DCHECK_EQ(static_cast<int>(name
.length()), path_len
);
159 size_t server_address_len
= offsetof(struct sockaddr_un
,
160 sun_path
) + path_len
+ 1;
162 if (mode
== IPC::Channel::MODE_NAMED_SERVER
) {
163 // Only one server at a time. Cleanup garbage if it exists.
164 unlink(name
.c_str());
165 // Make sure the path we need exists.
166 base::FilePath
path(name
);
167 base::FilePath dir_path
= path
.DirName();
168 ASSERT_TRUE(base::CreateDirectory(dir_path
));
169 ASSERT_GE(bind(socket_fd
,
170 reinterpret_cast<struct sockaddr
*>(&server_address
),
171 server_address_len
), 0) << server_address
.sun_path
172 << ": " << strerror(errno
)
173 << "(" << errno
<< ")";
174 ASSERT_GE(listen(socket_fd
, SOMAXCONN
), 0) << server_address
.sun_path
175 << ": " << strerror(errno
)
176 << "(" << errno
<< ")";
177 } else if (mode
== IPC::Channel::MODE_NAMED_CLIENT
) {
178 ASSERT_GE(connect(socket_fd
,
179 reinterpret_cast<struct sockaddr
*>(&server_address
),
180 server_address_len
), 0) << server_address
.sun_path
181 << ": " << strerror(errno
)
182 << "(" << errno
<< ")";
184 FAIL() << "Unknown mode " << mode
;
186 handle
->socket
.fd
= socket_fd
;
189 void IPCChannelPosixTest::SpinRunLoop(base::TimeDelta delay
) {
190 base::MessageLoopForIO
* loop
= base::MessageLoopForIO::current();
191 // Post a quit task so that this loop eventually ends and we don't hang
192 // in the case of a bad test. Usually, the run loop will quit sooner than
193 // that because all tests use a IPCChannelPosixTestListener which quits the
194 // current run loop on any channel activity.
195 loop
->PostDelayedTask(FROM_HERE
, loop
->QuitClosure(), delay
);
199 TEST_F(IPCChannelPosixTest
, BasicListen
) {
200 const std::string kChannelName
=
201 GetChannelDirName() + "/IPCChannelPosixTest_BasicListen";
203 // Test creating a socket that is listening.
204 IPC::ChannelHandle
handle(kChannelName
);
205 SetUpSocket(&handle
, IPC::Channel::MODE_NAMED_SERVER
);
206 unlink(handle
.name
.c_str());
207 scoped_ptr
<IPC::Channel
> channel(
208 IPC::Channel::CreateNamedServer(handle
, NULL
));
209 ASSERT_TRUE(channel
->Connect());
210 ASSERT_TRUE(channel
->AcceptsConnections());
211 ASSERT_FALSE(channel
->HasAcceptedConnection());
212 channel
->ResetToAcceptingConnectionState();
213 ASSERT_FALSE(channel
->HasAcceptedConnection());
216 TEST_F(IPCChannelPosixTest
, BasicConnected
) {
217 // Test creating a socket that is connected.
219 ASSERT_EQ(0, socketpair(AF_UNIX
, SOCK_STREAM
, 0, pipe_fds
));
220 std::string
socket_name("/var/tmp/IPCChannelPosixTest_BasicConnected");
221 ASSERT_GE(fcntl(pipe_fds
[0], F_SETFL
, O_NONBLOCK
), 0);
223 base::FileDescriptor
fd(pipe_fds
[0], false);
224 IPC::ChannelHandle
handle(socket_name
, fd
);
225 scoped_ptr
<IPC::Channel
> channel(IPC::Channel::CreateServer(handle
, NULL
));
226 ASSERT_TRUE(channel
->Connect());
227 ASSERT_FALSE(channel
->AcceptsConnections());
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::Channel
> channel2(
234 IPC::Channel::CreateServer(socket_name
, NULL
));
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::Channel
> in_chan(
247 IPC::Channel::CreateServer(in_handle
, &in_listener
));
248 base::FileDescriptor
out_fd(
249 in_chan
->TakeClientFileDescriptor(), false);
250 IPC::ChannelHandle
out_handle("OUT", out_fd
);
251 scoped_ptr
<IPC::Channel
> out_chan(
252 IPC::Channel::CreateClient(out_handle
, &out_listener
));
253 ASSERT_TRUE(in_chan
->Connect());
254 ASSERT_TRUE(out_chan
->Connect());
255 in_chan
->Close(); // simulate remote process dying at an unfortunate time.
256 // Send will fail, because it cannot write the message.
257 ASSERT_FALSE(out_chan
->Send(new IPC::Message(
259 kQuitMessage
, // message type
260 IPC::Message::PRIORITY_NORMAL
)));
261 SpinRunLoop(TestTimeouts::action_max_timeout());
262 ASSERT_EQ(IPCChannelPosixTestListener::CHANNEL_ERROR
, out_listener
.status());
265 // If a connection closes right before a Connect() call, we may end up closing
266 // the connection without notifying the listener, which can cause hangs in
267 // sync_message_filter and others. Make sure the listener is notified.
268 TEST_F(IPCChannelPosixTest
, AcceptHangTest
) {
269 IPCChannelPosixTestListener
out_listener(true);
270 IPCChannelPosixTestListener
in_listener(true);
271 IPC::ChannelHandle
in_handle("IN");
272 scoped_ptr
<IPC::Channel
> in_chan(
273 IPC::Channel::CreateServer(in_handle
, &in_listener
));
274 base::FileDescriptor
out_fd(
275 in_chan
->TakeClientFileDescriptor(), false);
276 IPC::ChannelHandle
out_handle("OUT", out_fd
);
277 scoped_ptr
<IPC::Channel
> out_chan(
278 IPC::Channel::CreateClient(out_handle
, &out_listener
));
279 ASSERT_TRUE(in_chan
->Connect());
280 in_chan
->Close(); // simulate remote process dying at an unfortunate time.
281 ASSERT_FALSE(out_chan
->Connect());
282 SpinRunLoop(TestTimeouts::action_max_timeout());
283 ASSERT_EQ(IPCChannelPosixTestListener::CHANNEL_ERROR
, out_listener
.status());
286 TEST_F(IPCChannelPosixTest
, AdvancedConnected
) {
287 // Test creating a connection to an external process.
288 IPCChannelPosixTestListener
listener(false);
289 IPC::ChannelHandle
chan_handle(GetConnectionSocketName());
290 SetUpSocket(&chan_handle
, IPC::Channel::MODE_NAMED_SERVER
);
291 scoped_ptr
<IPC::Channel
> channel(
292 IPC::Channel::CreateNamedServer(chan_handle
, &listener
));
293 ASSERT_TRUE(channel
->Connect());
294 ASSERT_TRUE(channel
->AcceptsConnections());
295 ASSERT_FALSE(channel
->HasAcceptedConnection());
297 base::ProcessHandle handle
= SpawnChild("IPCChannelPosixTestConnectionProc");
299 SpinRunLoop(TestTimeouts::action_max_timeout());
300 ASSERT_EQ(IPCChannelPosixTestListener::CONNECTED
, listener
.status());
301 ASSERT_TRUE(channel
->HasAcceptedConnection());
302 IPC::Message
* message
= new IPC::Message(0, // routing_id
303 kQuitMessage
, // message type
304 IPC::Message::PRIORITY_NORMAL
);
305 channel
->Send(message
);
306 SpinRunLoop(TestTimeouts::action_timeout());
308 EXPECT_TRUE(base::WaitForExitCode(handle
, &exit_code
));
309 EXPECT_EQ(0, exit_code
);
310 ASSERT_EQ(IPCChannelPosixTestListener::CHANNEL_ERROR
, listener
.status());
311 ASSERT_FALSE(channel
->HasAcceptedConnection());
314 TEST_F(IPCChannelPosixTest
, ResetState
) {
315 // Test creating a connection to an external process. Close the connection,
316 // but continue to listen and make sure another external process can connect
318 IPCChannelPosixTestListener
listener(false);
319 IPC::ChannelHandle
chan_handle(GetConnectionSocketName());
320 SetUpSocket(&chan_handle
, IPC::Channel::MODE_NAMED_SERVER
);
321 scoped_ptr
<IPC::Channel
> channel(
322 IPC::Channel::CreateNamedServer(chan_handle
, &listener
));
323 ASSERT_TRUE(channel
->Connect());
324 ASSERT_TRUE(channel
->AcceptsConnections());
325 ASSERT_FALSE(channel
->HasAcceptedConnection());
327 base::ProcessHandle handle
= SpawnChild("IPCChannelPosixTestConnectionProc");
329 SpinRunLoop(TestTimeouts::action_max_timeout());
330 ASSERT_EQ(IPCChannelPosixTestListener::CONNECTED
, listener
.status());
331 ASSERT_TRUE(channel
->HasAcceptedConnection());
332 channel
->ResetToAcceptingConnectionState();
333 ASSERT_FALSE(channel
->HasAcceptedConnection());
335 base::ProcessHandle handle2
= SpawnChild("IPCChannelPosixTestConnectionProc");
336 ASSERT_TRUE(handle2
);
337 SpinRunLoop(TestTimeouts::action_max_timeout());
338 ASSERT_EQ(IPCChannelPosixTestListener::CONNECTED
, listener
.status());
339 ASSERT_TRUE(channel
->HasAcceptedConnection());
340 IPC::Message
* message
= new IPC::Message(0, // routing_id
341 kQuitMessage
, // message type
342 IPC::Message::PRIORITY_NORMAL
);
343 channel
->Send(message
);
344 SpinRunLoop(TestTimeouts::action_timeout());
345 EXPECT_TRUE(base::KillProcess(handle
, 0, false));
347 EXPECT_TRUE(base::WaitForExitCode(handle2
, &exit_code
));
348 EXPECT_EQ(0, exit_code
);
349 ASSERT_EQ(IPCChannelPosixTestListener::CHANNEL_ERROR
, listener
.status());
350 ASSERT_FALSE(channel
->HasAcceptedConnection());
353 TEST_F(IPCChannelPosixTest
, BadChannelName
) {
355 IPC::ChannelHandle
handle("");
356 scoped_ptr
<IPC::Channel
> channel(
357 IPC::Channel::CreateNamedServer(handle
, NULL
));
358 ASSERT_FALSE(channel
->Connect());
360 // Test name that is too long.
361 const char *kTooLongName
= "This_is_a_very_long_name_to_proactively_implement"
362 "client-centered_synergy_through_top-line"
363 "platforms_Phosfluorescently_disintermediate_"
364 "clicks-and-mortar_best_practices_without_"
365 "future-proof_growth_strategies_Continually"
366 "pontificate_proactive_potentialities_before"
367 "leading-edge_processes";
368 EXPECT_GE(strlen(kTooLongName
), IPC::kMaxSocketNameLength
);
369 IPC::ChannelHandle
handle2(kTooLongName
);
370 scoped_ptr
<IPC::Channel
> channel2(
371 IPC::Channel::CreateNamedServer(handle2
, NULL
));
372 EXPECT_FALSE(channel2
->Connect());
375 TEST_F(IPCChannelPosixTest
, MultiConnection
) {
376 // Test setting up a connection to an external process, and then have
377 // another external process attempt to connect to us.
378 IPCChannelPosixTestListener
listener(false);
379 IPC::ChannelHandle
chan_handle(GetConnectionSocketName());
380 SetUpSocket(&chan_handle
, IPC::Channel::MODE_NAMED_SERVER
);
381 scoped_ptr
<IPC::Channel
> channel(
382 IPC::Channel::CreateNamedServer(chan_handle
, &listener
));
383 ASSERT_TRUE(channel
->Connect());
384 ASSERT_TRUE(channel
->AcceptsConnections());
385 ASSERT_FALSE(channel
->HasAcceptedConnection());
387 base::ProcessHandle handle
= SpawnChild("IPCChannelPosixTestConnectionProc");
389 SpinRunLoop(TestTimeouts::action_max_timeout());
390 ASSERT_EQ(IPCChannelPosixTestListener::CONNECTED
, listener
.status());
391 ASSERT_TRUE(channel
->HasAcceptedConnection());
392 base::ProcessHandle handle2
= SpawnChild("IPCChannelPosixFailConnectionProc");
393 ASSERT_TRUE(handle2
);
394 SpinRunLoop(TestTimeouts::action_max_timeout());
396 EXPECT_TRUE(base::WaitForExitCode(handle2
, &exit_code
));
397 EXPECT_EQ(exit_code
, 0);
398 ASSERT_EQ(IPCChannelPosixTestListener::DENIED
, listener
.status());
399 ASSERT_TRUE(channel
->HasAcceptedConnection());
400 IPC::Message
* message
= new IPC::Message(0, // routing_id
401 kQuitMessage
, // message type
402 IPC::Message::PRIORITY_NORMAL
);
403 channel
->Send(message
);
404 SpinRunLoop(TestTimeouts::action_timeout());
405 EXPECT_TRUE(base::WaitForExitCode(handle
, &exit_code
));
406 EXPECT_EQ(exit_code
, 0);
407 ASSERT_EQ(IPCChannelPosixTestListener::CHANNEL_ERROR
, listener
.status());
408 ASSERT_FALSE(channel
->HasAcceptedConnection());
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::Channel
> channel(
417 IPC::Channel::CreateServer(chan_handle
, &listener
));
418 scoped_ptr
<IPC::Channel
> channel2(
419 IPC::Channel::CreateServer(chan_handle
, &listener2
));
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::Channel
> channel(IPC::Channel::Create(
429 chan_handle
, IPC::Channel::MODE_NONE
, &listener
));
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::Channel
> channel(
441 IPC::Channel::CreateNamedServer(chan_handle
, &listener
));
442 ASSERT_TRUE(IPC::Channel::IsNamedServerInitialized(
443 connection_socket_name
));
445 ASSERT_FALSE(IPC::Channel::IsNamedServerInitialized(
446 connection_socket_name
));
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::Channel
> channel(
456 IPC::Channel::CreateNamedClient(handle
, &listener
));
457 EXPECT_TRUE(channel
->Connect());
458 IPCChannelPosixTest::SpinRunLoop(TestTimeouts::action_max_timeout());
459 EXPECT_EQ(IPCChannelPosixTestListener::MESSAGE_RECEIVED
, listener
.status());
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::Channel
> channel(
470 IPC::Channel::CreateNamedClient(handle
, &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
477 bool connected
= channel
->Connect();
479 IPCChannelPosixTest::SpinRunLoop(TestTimeouts::action_max_timeout());
480 EXPECT_EQ(IPCChannelPosixTestListener::CHANNEL_ERROR
, listener
.status());
482 EXPECT_EQ(IPCChannelPosixTestListener::DISCONNECTED
, listener
.status());