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 #include "build/build_config.h"
14 #include <sys/socket.h>
20 #include "base/callback.h"
21 #include "base/file_descriptor_posix.h"
22 #include "base/message_loop/message_loop.h"
23 #include "base/pickle.h"
24 #include "base/posix/eintr_wrapper.h"
25 #include "base/synchronization/waitable_event.h"
26 #include "ipc/ipc_message_utils.h"
27 #include "ipc/ipc_test_base.h"
31 const unsigned kNumFDsToSend
= 20;
32 const char* kDevZeroPath
= "/dev/zero";
34 class MyChannelDescriptorListenerBase
: public IPC::Listener
{
36 virtual bool OnMessageReceived(const IPC::Message
& message
) OVERRIDE
{
37 PickleIterator
iter(message
);
39 base::FileDescriptor descriptor
;
41 IPC::ParamTraits
<base::FileDescriptor
>::Read(&message
, &iter
, &descriptor
);
43 HandleFD(descriptor
.fd
);
48 virtual void HandleFD(int fd
) = 0;
51 class MyChannelDescriptorListener
: public MyChannelDescriptorListenerBase
{
53 explicit MyChannelDescriptorListener(ino_t expected_inode_num
)
54 : MyChannelDescriptorListenerBase(),
55 expected_inode_num_(expected_inode_num
),
56 num_fds_received_(0) {
59 bool GotExpectedNumberOfDescriptors() const {
60 return num_fds_received_
== kNumFDsToSend
;
63 virtual void OnChannelError() OVERRIDE
{
64 base::MessageLoop::current()->Quit();
68 virtual void HandleFD(int fd
) OVERRIDE
{
69 // Check that we can read from the FD.
71 ssize_t amt_read
= read(fd
, &buf
, 1);
72 ASSERT_EQ(amt_read
, 1);
73 ASSERT_EQ(buf
, 0); // /dev/zero always reads 0 bytes.
76 ASSERT_EQ(fstat(fd
, &st
), 0);
78 ASSERT_EQ(close(fd
), 0);
80 // Compare inode numbers to check that the file sent over the wire is
81 // actually the one expected.
82 ASSERT_EQ(expected_inode_num_
, st
.st_ino
);
85 if (num_fds_received_
== kNumFDsToSend
)
86 base::MessageLoop::current()->Quit();
90 ino_t expected_inode_num_
;
91 unsigned num_fds_received_
;
95 class IPCSendFdsTest
: public IPCTestBase
{
98 // Set up IPC channel and start client.
99 MyChannelDescriptorListener
listener(-1);
100 CreateChannel(&listener
);
101 ASSERT_TRUE(ConnectChannel());
102 ASSERT_TRUE(StartClient());
104 for (unsigned i
= 0; i
< kNumFDsToSend
; ++i
) {
105 const int fd
= open(kDevZeroPath
, O_RDONLY
);
107 base::FileDescriptor
descriptor(fd
, true);
109 IPC::Message
* message
=
110 new IPC::Message(0, 3, IPC::Message::PRIORITY_NORMAL
);
111 IPC::ParamTraits
<base::FileDescriptor
>::Write(message
, descriptor
);
112 ASSERT_TRUE(sender()->Send(message
));
116 base::MessageLoop::current()->Run();
118 // Close the channel so the client's OnChannelError() gets fired.
121 EXPECT_TRUE(WaitForClientShutdown());
126 TEST_F(IPCSendFdsTest
, DescriptorTest
) {
127 Init("SendFdsClient");
131 int SendFdsClientCommon(const std::string
& test_client_name
,
132 ino_t expected_inode_num
) {
133 base::MessageLoopForIO main_message_loop
;
134 MyChannelDescriptorListener
listener(expected_inode_num
);
136 // Set up IPC channel.
137 IPC::Channel
channel(IPCTestBase::GetChannelName(test_client_name
),
138 IPC::Channel::MODE_CLIENT
,
140 CHECK(channel
.Connect());
143 base::MessageLoop::current()->Run();
145 // Verify that the message loop was exited due to getting the correct number
146 // of descriptors, and not because of the channel closing unexpectedly.
147 CHECK(listener
.GotExpectedNumberOfDescriptors());
152 MULTIPROCESS_IPC_TEST_CLIENT_MAIN(SendFdsClient
) {
154 int fd
= open(kDevZeroPath
, O_RDONLY
);
156 EXPECT_GE(IGNORE_EINTR(close(fd
)), 0);
157 return SendFdsClientCommon("SendFdsClient", st
.st_ino
);
160 #if defined(OS_MACOSX)
161 // Test that FDs are correctly sent to a sandboxed process.
162 // TODO(port): Make this test cross-platform.
163 TEST_F(IPCSendFdsTest
, DescriptorTestSandboxed
) {
164 Init("SendFdsSandboxedClient");
168 MULTIPROCESS_IPC_TEST_CLIENT_MAIN(SendFdsSandboxedClient
) {
170 const int fd
= open(kDevZeroPath
, O_RDONLY
);
172 if (IGNORE_EINTR(close(fd
)) < 0)
175 // Enable the sandbox.
176 char* error_buff
= NULL
;
177 int error
= sandbox_init(kSBXProfilePureComputation
, SANDBOX_NAMED
,
179 bool success
= (error
== 0 && error_buff
== NULL
);
183 sandbox_free_error(error_buff
);
185 // Make sure sandbox is really enabled.
186 if (open(kDevZeroPath
, O_RDONLY
) != -1) {
187 LOG(ERROR
) << "Sandbox wasn't properly enabled";
191 // See if we can receive a file descriptor.
192 return SendFdsClientCommon("SendFdsSandboxedClient", st
.st_ino
);
194 #endif // defined(OS_MACOSX)
197 class MyCBListener
: public MyChannelDescriptorListenerBase
{
199 MyCBListener(base::Callback
<void(int)> cb
, int fds_to_send
)
200 : MyChannelDescriptorListenerBase(),
205 virtual void HandleFD(int fd
) OVERRIDE
{
209 base::Callback
<void(int)> cb_
;
212 std::pair
<int, int> make_socket_pair() {
214 CHECK_EQ(0, HANDLE_EINTR(socketpair(AF_UNIX
, SOCK_STREAM
, 0, pipe_fds
)));
215 return std::pair
<int, int>(pipe_fds
[0], pipe_fds
[1]);
218 static void null_cb(int unused_fd
) {
222 class PipeChannelHelper
{
224 PipeChannelHelper(base::Thread
* in_thread
,
225 base::Thread
* out_thread
,
226 base::Callback
<void(int)> cb
,
228 in_thread_(in_thread
),
229 out_thread_(out_thread
),
230 cb_listener_(cb
, fds_to_send
),
231 null_listener_(base::Bind(&null_cb
), 0) {
235 IPC::ChannelHandle
in_handle("IN");
236 in
.reset(new IPC::Channel(in_handle
,
237 IPC::Channel::MODE_SERVER
,
239 base::FileDescriptor
out_fd(in
->TakeClientFileDescriptor(), false);
240 IPC::ChannelHandle
out_handle("OUT", out_fd
);
241 out
.reset(new IPC::Channel(out_handle
,
242 IPC::Channel::MODE_CLIENT
,
244 // PostTask the connect calls to make sure the callbacks happens
245 // on the right threads.
246 in_thread_
->message_loop()->PostTask(
248 base::Bind(&PipeChannelHelper::Connect
, in
.get()));
249 out_thread_
->message_loop()->PostTask(
251 base::Bind(&PipeChannelHelper::Connect
, out
.get()));
254 static void DestroyChannel(scoped_ptr
<IPC::Channel
> *c
,
255 base::WaitableEvent
*event
) {
260 ~PipeChannelHelper() {
261 base::WaitableEvent
a(true, false);
262 base::WaitableEvent
b(true, false);
263 in_thread_
->message_loop()->PostTask(
265 base::Bind(&PipeChannelHelper::DestroyChannel
, &in
, &a
));
266 out_thread_
->message_loop()->PostTask(
268 base::Bind(&PipeChannelHelper::DestroyChannel
, &out
, &b
));
273 static void Connect(IPC::Channel
*channel
) {
274 EXPECT_TRUE(channel
->Connect());
278 CHECK_EQ(base::MessageLoop::current(), in_thread_
->message_loop());
281 base::FileDescriptor
descriptor(fd
, true);
283 IPC::Message
* message
=
284 new IPC::Message(0, 3, IPC::Message::PRIORITY_NORMAL
);
285 IPC::ParamTraits
<base::FileDescriptor
>::Write(message
, descriptor
);
286 ASSERT_TRUE(in
->Send(message
));
290 scoped_ptr
<IPC::Channel
> in
, out
;
291 base::Thread
* in_thread_
;
292 base::Thread
* out_thread_
;
293 MyCBListener cb_listener_
;
294 MyCBListener null_listener_
;
297 // This test is meant to provoke a kernel bug on OSX, and to prove
298 // that the workaround for it is working. It sets up two pipes and three
299 // threads, the producer thread creates socketpairs and sends one of the fds
300 // over pipe1 to the middleman thread. The middleman thread simply takes the fd
301 // sends it over pipe2 to the consumer thread. The consumer thread writes a byte
302 // to each fd it receives and then closes the pipe. The producer thread reads
303 // the bytes back from each pair of pipes and make sure that everything worked.
304 // This feedback mechanism makes sure that not too many file descriptors are
305 // in flight at the same time. For more info on the bug, see:
306 // http://crbug.com/298276
307 class IPCMultiSendingFdsTest
: public testing::Test
{
309 IPCMultiSendingFdsTest() : received_(true, false) {}
311 void Producer(PipeChannelHelper
* dest
,
314 for (int i
= 0; i
< pipes_to_send
; i
++) {
316 std::pair
<int, int> pipe_fds
= make_socket_pair();
317 t
->message_loop()->PostTask(
319 base::Bind(&PipeChannelHelper::Send
,
320 base::Unretained(dest
),
323 CHECK_EQ(1, HANDLE_EINTR(write(pipe_fds
.first
, &tmp
, 1)));
324 CHECK_EQ(0, IGNORE_EINTR(close(pipe_fds
.first
)));
329 void ConsumerHandleFD(int fd
) {
331 CHECK_EQ(1, HANDLE_EINTR(read(fd
, &tmp
, 1)));
333 CHECK_EQ(0, IGNORE_EINTR(close(fd
)));
337 base::Thread
* CreateThread(const char* name
) {
338 base::Thread
* ret
= new base::Thread(name
);
339 base::Thread::Options options
;
340 options
.message_loop_type
= base::MessageLoop::TYPE_IO
;
341 ret
->StartWithOptions(options
);
346 // On my mac, this test fails roughly 35 times per
347 // million sends with low load, but much more with high load.
348 // Unless the workaround is in place. With 10000 sends, we
349 // should see at least a 3% failure rate.
350 const int pipes_to_send
= 20000;
351 scoped_ptr
<base::Thread
> producer(CreateThread("producer"));
352 scoped_ptr
<base::Thread
> middleman(CreateThread("middleman"));
353 scoped_ptr
<base::Thread
> consumer(CreateThread("consumer"));
354 PipeChannelHelper
pipe1(
357 base::Bind(&IPCMultiSendingFdsTest::ConsumerHandleFD
,
358 base::Unretained(this)),
360 PipeChannelHelper
pipe2(
363 base::Bind(&PipeChannelHelper::Send
, base::Unretained(&pipe1
)),
367 Producer(&pipe2
, producer
.get(), pipes_to_send
);
371 base::WaitableEvent received_
;
374 TEST_F(IPCMultiSendingFdsTest
, StressTest
) {
380 #endif // defined(OS_POSIX)