Fix sandbox IPC shared memory leak.
[chromium-blink-merge.git] / ipc / ipc_send_fds_test.cc
blobbe95f96269097f9b40ecabc445f4442e9ce83bad
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"
7 #if defined(OS_POSIX)
8 #if defined(OS_MACOSX)
9 extern "C" {
10 #include <sandbox.h>
12 #endif
13 #include <fcntl.h>
14 #include <sys/socket.h>
15 #include <sys/stat.h>
16 #include <unistd.h>
18 #include <queue>
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"
29 #if defined(OS_POSIX)
30 #include "base/macros.h"
31 #include "ipc/file_descriptor_set_posix.h"
32 #endif
34 namespace {
36 const unsigned kNumFDsToSend = 7; // per message
37 const unsigned kNumMessages = 20;
38 const char* kDevZeroPath = "/dev/zero";
40 #if defined(OS_POSIX)
41 COMPILE_ASSERT(kNumFDsToSend == FileDescriptorSet::kMaxDescriptorsPerMessage,
42 num_fds_to_send_must_be_the_same_as_the_max_desc_per_message);
43 #endif
45 class MyChannelDescriptorListenerBase : public IPC::Listener {
46 public:
47 bool OnMessageReceived(const IPC::Message& message) override {
48 PickleIterator iter(message);
49 base::FileDescriptor descriptor;
50 while (IPC::ParamTraits<base::FileDescriptor>::Read(
51 &message, &iter, &descriptor)) {
52 HandleFD(descriptor.fd);
54 return true;
57 protected:
58 virtual void HandleFD(int fd) = 0;
61 class MyChannelDescriptorListener : public MyChannelDescriptorListenerBase {
62 public:
63 explicit MyChannelDescriptorListener(ino_t expected_inode_num)
64 : MyChannelDescriptorListenerBase(),
65 expected_inode_num_(expected_inode_num),
66 num_fds_received_(0) {
69 bool GotExpectedNumberOfDescriptors() const {
70 return num_fds_received_ == kNumFDsToSend * kNumMessages;
73 void OnChannelError() override {
74 base::MessageLoop::current()->Quit();
77 protected:
78 void HandleFD(int fd) override {
79 ASSERT_GE(fd, 0);
80 // Check that we can read from the FD.
81 char buf;
82 ssize_t amt_read = read(fd, &buf, 1);
83 ASSERT_EQ(amt_read, 1);
84 ASSERT_EQ(buf, 0); // /dev/zero always reads 0 bytes.
86 struct stat st;
87 ASSERT_EQ(fstat(fd, &st), 0);
89 ASSERT_EQ(close(fd), 0);
91 // Compare inode numbers to check that the file sent over the wire is
92 // actually the one expected.
93 ASSERT_EQ(expected_inode_num_, st.st_ino);
95 ++num_fds_received_;
96 if (num_fds_received_ == kNumFDsToSend * kNumMessages)
97 base::MessageLoop::current()->Quit();
100 private:
101 ino_t expected_inode_num_;
102 unsigned num_fds_received_;
106 class IPCSendFdsTest : public IPCTestBase {
107 protected:
108 void RunServer() {
109 // Set up IPC channel and start client.
110 MyChannelDescriptorListener listener(-1);
111 CreateChannel(&listener);
112 ASSERT_TRUE(ConnectChannel());
113 ASSERT_TRUE(StartClient());
115 for (unsigned i = 0; i < kNumMessages; ++i) {
116 IPC::Message* message =
117 new IPC::Message(0, 3, IPC::Message::PRIORITY_NORMAL);
118 for (unsigned j = 0; j < kNumFDsToSend; ++j) {
119 const int fd = open(kDevZeroPath, O_RDONLY);
120 ASSERT_GE(fd, 0);
121 base::FileDescriptor descriptor(fd, true);
122 IPC::ParamTraits<base::FileDescriptor>::Write(message, descriptor);
124 ASSERT_TRUE(sender()->Send(message));
127 // Run message loop.
128 base::MessageLoop::current()->Run();
130 // Close the channel so the client's OnChannelError() gets fired.
131 channel()->Close();
133 EXPECT_TRUE(WaitForClientShutdown());
134 DestroyChannel();
138 TEST_F(IPCSendFdsTest, DescriptorTest) {
139 Init("SendFdsClient");
140 RunServer();
143 int SendFdsClientCommon(const std::string& test_client_name,
144 ino_t expected_inode_num) {
145 base::MessageLoopForIO main_message_loop;
146 MyChannelDescriptorListener listener(expected_inode_num);
148 // Set up IPC channel.
149 scoped_ptr<IPC::Channel> channel(IPC::Channel::CreateClient(
150 IPCTestBase::GetChannelName(test_client_name),
151 &listener));
152 CHECK(channel->Connect());
154 // Run message loop.
155 base::MessageLoop::current()->Run();
157 // Verify that the message loop was exited due to getting the correct number
158 // of descriptors, and not because of the channel closing unexpectedly.
159 CHECK(listener.GotExpectedNumberOfDescriptors());
161 return 0;
164 MULTIPROCESS_IPC_TEST_CLIENT_MAIN(SendFdsClient) {
165 struct stat st;
166 int fd = open(kDevZeroPath, O_RDONLY);
167 fstat(fd, &st);
168 EXPECT_GE(IGNORE_EINTR(close(fd)), 0);
169 return SendFdsClientCommon("SendFdsClient", st.st_ino);
172 #if defined(OS_MACOSX)
173 // Test that FDs are correctly sent to a sandboxed process.
174 // TODO(port): Make this test cross-platform.
175 TEST_F(IPCSendFdsTest, DescriptorTestSandboxed) {
176 Init("SendFdsSandboxedClient");
177 RunServer();
180 MULTIPROCESS_IPC_TEST_CLIENT_MAIN(SendFdsSandboxedClient) {
181 struct stat st;
182 const int fd = open(kDevZeroPath, O_RDONLY);
183 fstat(fd, &st);
184 if (IGNORE_EINTR(close(fd)) < 0)
185 return -1;
187 // Enable the sandbox.
188 char* error_buff = NULL;
189 int error = sandbox_init(kSBXProfilePureComputation, SANDBOX_NAMED,
190 &error_buff);
191 bool success = (error == 0 && error_buff == NULL);
192 if (!success)
193 return -1;
195 sandbox_free_error(error_buff);
197 // Make sure sandbox is really enabled.
198 if (open(kDevZeroPath, O_RDONLY) != -1) {
199 LOG(ERROR) << "Sandbox wasn't properly enabled";
200 return -1;
203 // See if we can receive a file descriptor.
204 return SendFdsClientCommon("SendFdsSandboxedClient", st.st_ino);
206 #endif // defined(OS_MACOSX)
209 class MyCBListener : public MyChannelDescriptorListenerBase {
210 public:
211 MyCBListener(base::Callback<void(int)> cb, int fds_to_send)
212 : MyChannelDescriptorListenerBase(),
213 cb_(cb) {
216 protected:
217 void HandleFD(int fd) override { cb_.Run(fd); }
218 private:
219 base::Callback<void(int)> cb_;
222 std::pair<int, int> make_socket_pair() {
223 int pipe_fds[2];
224 CHECK_EQ(0, HANDLE_EINTR(socketpair(AF_UNIX, SOCK_STREAM, 0, pipe_fds)));
225 return std::pair<int, int>(pipe_fds[0], pipe_fds[1]);
228 static void null_cb(int unused_fd) {
229 NOTREACHED();
232 class PipeChannelHelper {
233 public:
234 PipeChannelHelper(base::Thread* in_thread,
235 base::Thread* out_thread,
236 base::Callback<void(int)> cb,
237 int fds_to_send) :
238 in_thread_(in_thread),
239 out_thread_(out_thread),
240 cb_listener_(cb, fds_to_send),
241 null_listener_(base::Bind(&null_cb), 0) {
244 void Init() {
245 IPC::ChannelHandle in_handle("IN");
246 in = IPC::Channel::CreateServer(in_handle, &null_listener_);
247 IPC::ChannelHandle out_handle(
248 "OUT", base::FileDescriptor(in->TakeClientFileDescriptor()));
249 out = IPC::Channel::CreateClient(out_handle, &cb_listener_);
250 // PostTask the connect calls to make sure the callbacks happens
251 // on the right threads.
252 in_thread_->message_loop()->PostTask(
253 FROM_HERE,
254 base::Bind(&PipeChannelHelper::Connect, in.get()));
255 out_thread_->message_loop()->PostTask(
256 FROM_HERE,
257 base::Bind(&PipeChannelHelper::Connect, out.get()));
260 static void DestroyChannel(scoped_ptr<IPC::Channel> *c,
261 base::WaitableEvent *event) {
262 c->reset(0);
263 event->Signal();
266 ~PipeChannelHelper() {
267 base::WaitableEvent a(true, false);
268 base::WaitableEvent b(true, false);
269 in_thread_->message_loop()->PostTask(
270 FROM_HERE,
271 base::Bind(&PipeChannelHelper::DestroyChannel, &in, &a));
272 out_thread_->message_loop()->PostTask(
273 FROM_HERE,
274 base::Bind(&PipeChannelHelper::DestroyChannel, &out, &b));
275 a.Wait();
276 b.Wait();
279 static void Connect(IPC::Channel *channel) {
280 EXPECT_TRUE(channel->Connect());
283 void Send(int fd) {
284 CHECK_EQ(base::MessageLoop::current(), in_thread_->message_loop());
286 ASSERT_GE(fd, 0);
287 base::FileDescriptor descriptor(fd, true);
289 IPC::Message* message =
290 new IPC::Message(0, 3, IPC::Message::PRIORITY_NORMAL);
291 IPC::ParamTraits<base::FileDescriptor>::Write(message, descriptor);
292 ASSERT_TRUE(in->Send(message));
295 private:
296 scoped_ptr<IPC::Channel> in, out;
297 base::Thread* in_thread_;
298 base::Thread* out_thread_;
299 MyCBListener cb_listener_;
300 MyCBListener null_listener_;
303 // This test is meant to provoke a kernel bug on OSX, and to prove
304 // that the workaround for it is working. It sets up two pipes and three
305 // threads, the producer thread creates socketpairs and sends one of the fds
306 // over pipe1 to the middleman thread. The middleman thread simply takes the fd
307 // sends it over pipe2 to the consumer thread. The consumer thread writes a byte
308 // to each fd it receives and then closes the pipe. The producer thread reads
309 // the bytes back from each pair of pipes and make sure that everything worked.
310 // This feedback mechanism makes sure that not too many file descriptors are
311 // in flight at the same time. For more info on the bug, see:
312 // http://crbug.com/298276
313 class IPCMultiSendingFdsTest : public testing::Test {
314 public:
315 IPCMultiSendingFdsTest() : received_(true, false) {}
317 void Producer(PipeChannelHelper* dest,
318 base::Thread* t,
319 int pipes_to_send) {
320 for (int i = 0; i < pipes_to_send; i++) {
321 received_.Reset();
322 std::pair<int, int> pipe_fds = make_socket_pair();
323 t->message_loop()->PostTask(
324 FROM_HERE,
325 base::Bind(&PipeChannelHelper::Send,
326 base::Unretained(dest),
327 pipe_fds.second));
328 char tmp = 'x';
329 CHECK_EQ(1, HANDLE_EINTR(write(pipe_fds.first, &tmp, 1)));
330 CHECK_EQ(0, IGNORE_EINTR(close(pipe_fds.first)));
331 received_.Wait();
335 void ConsumerHandleFD(int fd) {
336 char tmp = 'y';
337 CHECK_EQ(1, HANDLE_EINTR(read(fd, &tmp, 1)));
338 CHECK_EQ(tmp, 'x');
339 CHECK_EQ(0, IGNORE_EINTR(close(fd)));
340 received_.Signal();
343 base::Thread* CreateThread(const char* name) {
344 base::Thread* ret = new base::Thread(name);
345 base::Thread::Options options;
346 options.message_loop_type = base::MessageLoop::TYPE_IO;
347 ret->StartWithOptions(options);
348 return ret;
351 void Run() {
352 // On my mac, this test fails roughly 35 times per
353 // million sends with low load, but much more with high load.
354 // Unless the workaround is in place. With 10000 sends, we
355 // should see at least a 3% failure rate.
356 const int pipes_to_send = 20000;
357 scoped_ptr<base::Thread> producer(CreateThread("producer"));
358 scoped_ptr<base::Thread> middleman(CreateThread("middleman"));
359 scoped_ptr<base::Thread> consumer(CreateThread("consumer"));
360 PipeChannelHelper pipe1(
361 middleman.get(),
362 consumer.get(),
363 base::Bind(&IPCMultiSendingFdsTest::ConsumerHandleFD,
364 base::Unretained(this)),
365 pipes_to_send);
366 PipeChannelHelper pipe2(
367 producer.get(),
368 middleman.get(),
369 base::Bind(&PipeChannelHelper::Send, base::Unretained(&pipe1)),
370 pipes_to_send);
371 pipe1.Init();
372 pipe2.Init();
373 Producer(&pipe2, producer.get(), pipes_to_send);
376 private:
377 base::WaitableEvent received_;
380 TEST_F(IPCMultiSendingFdsTest, StressTest) {
381 Run();
384 } // namespace
386 #endif // defined(OS_POSIX)