Migrate SiteSettingsPreferencesTest from ChromeShell to ChromePublic.
[chromium-blink-merge.git] / ipc / ipc_send_fds_test.cc
blob7669c8fd1cf72b7664e1a94ef7f9063cd9094a4e
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/location.h"
23 #include "base/pickle.h"
24 #include "base/posix/eintr_wrapper.h"
25 #include "base/single_thread_task_runner.h"
26 #include "base/synchronization/waitable_event.h"
27 #include "ipc/ipc_message_attachment_set.h"
28 #include "ipc/ipc_message_utils.h"
29 #include "ipc/ipc_test_base.h"
31 #if defined(OS_POSIX)
32 #include "base/macros.h"
33 #endif
35 namespace {
37 const unsigned kNumFDsToSend = 7; // per message
38 const unsigned kNumMessages = 20;
39 const char* kDevZeroPath = "/dev/zero";
41 #if defined(OS_POSIX)
42 static_assert(kNumFDsToSend ==
43 IPC::MessageAttachmentSet::kMaxDescriptorsPerMessage,
44 "The number of FDs to send must be kMaxDescriptorsPerMessage.");
45 #endif
47 class MyChannelDescriptorListenerBase : public IPC::Listener {
48 public:
49 bool OnMessageReceived(const IPC::Message& message) override {
50 base::PickleIterator iter(message);
51 base::FileDescriptor descriptor;
52 while (IPC::ParamTraits<base::FileDescriptor>::Read(
53 &message, &iter, &descriptor)) {
54 HandleFD(descriptor.fd);
56 return true;
59 protected:
60 virtual void HandleFD(int fd) = 0;
63 class MyChannelDescriptorListener : public MyChannelDescriptorListenerBase {
64 public:
65 explicit MyChannelDescriptorListener(ino_t expected_inode_num)
66 : MyChannelDescriptorListenerBase(),
67 expected_inode_num_(expected_inode_num),
68 num_fds_received_(0) {
71 bool GotExpectedNumberOfDescriptors() const {
72 return num_fds_received_ == kNumFDsToSend * kNumMessages;
75 void OnChannelError() override {
76 base::MessageLoop::current()->Quit();
79 protected:
80 void HandleFD(int fd) override {
81 ASSERT_GE(fd, 0);
82 // Check that we can read from the FD.
83 char buf;
84 ssize_t amt_read = read(fd, &buf, 1);
85 ASSERT_EQ(amt_read, 1);
86 ASSERT_EQ(buf, 0); // /dev/zero always reads 0 bytes.
88 struct stat st;
89 ASSERT_EQ(fstat(fd, &st), 0);
91 ASSERT_EQ(close(fd), 0);
93 // Compare inode numbers to check that the file sent over the wire is
94 // actually the one expected.
95 ASSERT_EQ(expected_inode_num_, st.st_ino);
97 ++num_fds_received_;
98 if (num_fds_received_ == kNumFDsToSend * kNumMessages)
99 base::MessageLoop::current()->Quit();
102 private:
103 ino_t expected_inode_num_;
104 unsigned num_fds_received_;
108 class IPCSendFdsTest : public IPCTestBase {
109 protected:
110 void RunServer() {
111 // Set up IPC channel and start client.
112 MyChannelDescriptorListener listener(-1);
113 CreateChannel(&listener);
114 ASSERT_TRUE(ConnectChannel());
115 ASSERT_TRUE(StartClient());
117 for (unsigned i = 0; i < kNumMessages; ++i) {
118 IPC::Message* message =
119 new IPC::Message(0, 3, IPC::Message::PRIORITY_NORMAL);
120 for (unsigned j = 0; j < kNumFDsToSend; ++j) {
121 const int fd = open(kDevZeroPath, O_RDONLY);
122 ASSERT_GE(fd, 0);
123 base::FileDescriptor descriptor(fd, true);
124 IPC::ParamTraits<base::FileDescriptor>::Write(message, descriptor);
126 ASSERT_TRUE(sender()->Send(message));
129 // Run message loop.
130 base::MessageLoop::current()->Run();
132 // Close the channel so the client's OnChannelError() gets fired.
133 channel()->Close();
135 EXPECT_TRUE(WaitForClientShutdown());
136 DestroyChannel();
140 TEST_F(IPCSendFdsTest, DescriptorTest) {
141 Init("SendFdsClient");
142 RunServer();
145 int SendFdsClientCommon(const std::string& test_client_name,
146 ino_t expected_inode_num) {
147 base::MessageLoopForIO main_message_loop;
148 MyChannelDescriptorListener listener(expected_inode_num);
150 // Set up IPC channel.
151 scoped_ptr<IPC::Channel> channel(IPC::Channel::CreateClient(
152 IPCTestBase::GetChannelName(test_client_name), &listener, nullptr));
153 CHECK(channel->Connect());
155 // Run message loop.
156 base::MessageLoop::current()->Run();
158 // Verify that the message loop was exited due to getting the correct number
159 // of descriptors, and not because of the channel closing unexpectedly.
160 CHECK(listener.GotExpectedNumberOfDescriptors());
162 return 0;
165 MULTIPROCESS_IPC_TEST_CLIENT_MAIN(SendFdsClient) {
166 struct stat st;
167 int fd = open(kDevZeroPath, O_RDONLY);
168 fstat(fd, &st);
169 EXPECT_GE(IGNORE_EINTR(close(fd)), 0);
170 return SendFdsClientCommon("SendFdsClient", st.st_ino);
173 #if defined(OS_MACOSX)
174 // Test that FDs are correctly sent to a sandboxed process.
175 // TODO(port): Make this test cross-platform.
176 TEST_F(IPCSendFdsTest, DescriptorTestSandboxed) {
177 Init("SendFdsSandboxedClient");
178 RunServer();
181 MULTIPROCESS_IPC_TEST_CLIENT_MAIN(SendFdsSandboxedClient) {
182 struct stat st;
183 const int fd = open(kDevZeroPath, O_RDONLY);
184 fstat(fd, &st);
185 if (IGNORE_EINTR(close(fd)) < 0)
186 return -1;
188 // Enable the sandbox.
189 char* error_buff = NULL;
190 int error = sandbox_init(kSBXProfilePureComputation, SANDBOX_NAMED,
191 &error_buff);
192 bool success = (error == 0 && error_buff == NULL);
193 if (!success)
194 return -1;
196 sandbox_free_error(error_buff);
198 // Make sure sandbox is really enabled.
199 if (open(kDevZeroPath, O_RDONLY) != -1) {
200 LOG(ERROR) << "Sandbox wasn't properly enabled";
201 return -1;
204 // See if we can receive a file descriptor.
205 return SendFdsClientCommon("SendFdsSandboxedClient", st.st_ino);
207 #endif // defined(OS_MACOSX)
210 class MyCBListener : public MyChannelDescriptorListenerBase {
211 public:
212 MyCBListener(base::Callback<void(int)> cb, int fds_to_send)
213 : MyChannelDescriptorListenerBase(),
214 cb_(cb) {
217 protected:
218 void HandleFD(int fd) override { cb_.Run(fd); }
219 private:
220 base::Callback<void(int)> cb_;
223 std::pair<int, int> make_socket_pair() {
224 int pipe_fds[2];
225 CHECK_EQ(0, HANDLE_EINTR(socketpair(AF_UNIX, SOCK_STREAM, 0, pipe_fds)));
226 return std::pair<int, int>(pipe_fds[0], pipe_fds[1]);
229 static void null_cb(int unused_fd) {
230 NOTREACHED();
233 class PipeChannelHelper {
234 public:
235 PipeChannelHelper(base::Thread* in_thread,
236 base::Thread* out_thread,
237 base::Callback<void(int)> cb,
238 int fds_to_send) :
239 in_thread_(in_thread),
240 out_thread_(out_thread),
241 cb_listener_(cb, fds_to_send),
242 null_listener_(base::Bind(&null_cb), 0) {
245 void Init() {
246 IPC::ChannelHandle in_handle("IN");
247 in = IPC::Channel::CreateServer(in_handle, &null_listener_, nullptr);
248 IPC::ChannelHandle out_handle(
249 "OUT", base::FileDescriptor(in->TakeClientFileDescriptor()));
250 out = IPC::Channel::CreateClient(out_handle, &cb_listener_, nullptr);
251 // PostTask the connect calls to make sure the callbacks happens
252 // on the right threads.
253 in_thread_->task_runner()->PostTask(
254 FROM_HERE, base::Bind(&PipeChannelHelper::Connect, in.get()));
255 out_thread_->task_runner()->PostTask(
256 FROM_HERE, base::Bind(&PipeChannelHelper::Connect, out.get()));
259 static void DestroyChannel(scoped_ptr<IPC::Channel> *c,
260 base::WaitableEvent *event) {
261 c->reset(0);
262 event->Signal();
265 ~PipeChannelHelper() {
266 base::WaitableEvent a(true, false);
267 base::WaitableEvent b(true, false);
268 in_thread_->task_runner()->PostTask(
269 FROM_HERE, base::Bind(&PipeChannelHelper::DestroyChannel, &in, &a));
270 out_thread_->task_runner()->PostTask(
271 FROM_HERE, base::Bind(&PipeChannelHelper::DestroyChannel, &out, &b));
272 a.Wait();
273 b.Wait();
276 static void Connect(IPC::Channel *channel) {
277 EXPECT_TRUE(channel->Connect());
280 void Send(int fd) {
281 CHECK_EQ(base::MessageLoop::current(), in_thread_->message_loop());
283 ASSERT_GE(fd, 0);
284 base::FileDescriptor descriptor(fd, true);
286 IPC::Message* message =
287 new IPC::Message(0, 3, IPC::Message::PRIORITY_NORMAL);
288 IPC::ParamTraits<base::FileDescriptor>::Write(message, descriptor);
289 ASSERT_TRUE(in->Send(message));
292 private:
293 scoped_ptr<IPC::Channel> in, out;
294 base::Thread* in_thread_;
295 base::Thread* out_thread_;
296 MyCBListener cb_listener_;
297 MyCBListener null_listener_;
300 // This test is meant to provoke a kernel bug on OSX, and to prove
301 // that the workaround for it is working. It sets up two pipes and three
302 // threads, the producer thread creates socketpairs and sends one of the fds
303 // over pipe1 to the middleman thread. The middleman thread simply takes the fd
304 // sends it over pipe2 to the consumer thread. The consumer thread writes a byte
305 // to each fd it receives and then closes the pipe. The producer thread reads
306 // the bytes back from each pair of pipes and make sure that everything worked.
307 // This feedback mechanism makes sure that not too many file descriptors are
308 // in flight at the same time. For more info on the bug, see:
309 // http://crbug.com/298276
310 class IPCMultiSendingFdsTest : public testing::Test {
311 public:
312 IPCMultiSendingFdsTest() : received_(true, false) {}
314 void Producer(PipeChannelHelper* dest,
315 base::Thread* t,
316 int pipes_to_send) {
317 for (int i = 0; i < pipes_to_send; i++) {
318 received_.Reset();
319 std::pair<int, int> pipe_fds = make_socket_pair();
320 t->task_runner()->PostTask(
321 FROM_HERE, base::Bind(&PipeChannelHelper::Send,
322 base::Unretained(dest), pipe_fds.second));
323 char tmp = 'x';
324 CHECK_EQ(1, HANDLE_EINTR(write(pipe_fds.first, &tmp, 1)));
325 CHECK_EQ(0, IGNORE_EINTR(close(pipe_fds.first)));
326 received_.Wait();
330 void ConsumerHandleFD(int fd) {
331 char tmp = 'y';
332 CHECK_EQ(1, HANDLE_EINTR(read(fd, &tmp, 1)));
333 CHECK_EQ(tmp, 'x');
334 CHECK_EQ(0, IGNORE_EINTR(close(fd)));
335 received_.Signal();
338 base::Thread* CreateThread(const char* name) {
339 base::Thread* ret = new base::Thread(name);
340 base::Thread::Options options;
341 options.message_loop_type = base::MessageLoop::TYPE_IO;
342 ret->StartWithOptions(options);
343 return ret;
346 void Run() {
347 // On my mac, this test fails roughly 35 times per
348 // million sends with low load, but much more with high load.
349 // Unless the workaround is in place. With 10000 sends, we
350 // should see at least a 3% failure rate.
351 const int pipes_to_send = 20000;
352 scoped_ptr<base::Thread> producer(CreateThread("producer"));
353 scoped_ptr<base::Thread> middleman(CreateThread("middleman"));
354 scoped_ptr<base::Thread> consumer(CreateThread("consumer"));
355 PipeChannelHelper pipe1(
356 middleman.get(),
357 consumer.get(),
358 base::Bind(&IPCMultiSendingFdsTest::ConsumerHandleFD,
359 base::Unretained(this)),
360 pipes_to_send);
361 PipeChannelHelper pipe2(
362 producer.get(),
363 middleman.get(),
364 base::Bind(&PipeChannelHelper::Send, base::Unretained(&pipe1)),
365 pipes_to_send);
366 pipe1.Init();
367 pipe2.Init();
368 Producer(&pipe2, producer.get(), pipes_to_send);
371 private:
372 base::WaitableEvent received_;
375 TEST_F(IPCMultiSendingFdsTest, StressTest) {
376 Run();
379 } // namespace
381 #endif // defined(OS_POSIX)