Update .DEPS.git
[chromium-blink-merge.git] / ipc / ipc_channel_posix_unittest.cc
blobb4ec401210b9b13bee32388a73327b71b4aa96eb
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/eintr_wrapper.h"
16 #include "base/file_path.h"
17 #include "base/file_util.h"
18 #include "base/memory/scoped_ptr.h"
19 #include "base/message_loop.h"
20 #include "base/test/multiprocess_test.h"
21 #include "base/test/test_timeouts.h"
22 #include "testing/multiprocess_func_list.h"
24 namespace {
26 static const uint32 kQuitMessage = 47;
28 class IPCChannelPosixTestListener : public IPC::Channel::Listener {
29 public:
30 enum STATUS {
31 DISCONNECTED,
32 MESSAGE_RECEIVED,
33 CHANNEL_ERROR,
34 CONNECTED,
35 DENIED,
36 LISTEN_ERROR
39 IPCChannelPosixTestListener(bool quit_only_on_message)
40 : status_(DISCONNECTED), quit_only_on_message_(quit_only_on_message) {}
42 virtual ~IPCChannelPosixTestListener() {}
44 virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE {
45 EXPECT_EQ(message.type(), kQuitMessage);
46 status_ = MESSAGE_RECEIVED;
47 QuitRunLoop();
48 return true;
51 virtual void OnChannelConnected(int32 peer_pid) OVERRIDE {
52 status_ = CONNECTED;
53 if (!quit_only_on_message_) {
54 QuitRunLoop();
58 virtual void OnChannelError() OVERRIDE {
59 status_ = CHANNEL_ERROR;
60 if (!quit_only_on_message_) {
61 QuitRunLoop();
65 virtual void OnChannelDenied() OVERRIDE {
66 status_ = DENIED;
67 if (!quit_only_on_message_) {
68 QuitRunLoop();
72 virtual void OnChannelListenError() OVERRIDE {
73 status_ = LISTEN_ERROR;
74 if (!quit_only_on_message_) {
75 QuitRunLoop();
79 STATUS status() { return status_; }
81 void QuitRunLoop() {
82 MessageLoopForIO::current()->QuitNow();
85 private:
86 // The current status of the listener.
87 STATUS status_;
88 // If |quit_only_on_message_| then the listener will only break out of
89 // the run loop when kQuitMessage is received.
90 bool quit_only_on_message_;
93 } // namespace
95 class IPCChannelPosixTest : public base::MultiProcessTest {
96 public:
97 static const char kConnectionSocketTestName[];
98 static void SetUpSocket(IPC::ChannelHandle *handle,
99 IPC::Channel::Mode mode);
100 static void SpinRunLoop(int milliseconds);
102 protected:
103 virtual void SetUp();
104 virtual void TearDown();
106 private:
107 scoped_ptr<MessageLoopForIO> message_loop_;
110 #if defined(OS_ANDROID)
111 const char IPCChannelPosixTest::kConnectionSocketTestName[] =
112 "/data/local/chrome_IPCChannelPosixTest__ConnectionSocket";
113 #else
114 const char IPCChannelPosixTest::kConnectionSocketTestName[] =
115 "/var/tmp/chrome_IPCChannelPosixTest__ConnectionSocket";
116 #endif
118 void IPCChannelPosixTest::SetUp() {
119 MultiProcessTest::SetUp();
120 // Construct a fresh IO Message loop for the duration of each test.
121 message_loop_.reset(new MessageLoopForIO());
124 void IPCChannelPosixTest::TearDown() {
125 message_loop_.reset(NULL);
126 MultiProcessTest::TearDown();
129 // Create up a socket and bind and listen to it, or connect it
130 // depending on the |mode|.
131 void IPCChannelPosixTest::SetUpSocket(IPC::ChannelHandle *handle,
132 IPC::Channel::Mode mode) {
133 const std::string& name = handle->name;
135 int socket_fd = socket(PF_UNIX, SOCK_STREAM, 0);
136 ASSERT_GE(socket_fd, 0) << name;
137 ASSERT_GE(fcntl(socket_fd, F_SETFL, O_NONBLOCK), 0);
138 struct sockaddr_un server_address = { 0 };
139 memset(&server_address, 0, sizeof(server_address));
140 server_address.sun_family = AF_UNIX;
141 int path_len = snprintf(server_address.sun_path, IPC::kMaxPipeNameLength,
142 "%s", name.c_str());
143 DCHECK_EQ(static_cast<int>(name.length()), path_len);
144 size_t server_address_len = offsetof(struct sockaddr_un,
145 sun_path) + path_len + 1;
147 if (mode == IPC::Channel::MODE_NAMED_SERVER) {
148 // Only one server at a time. Cleanup garbage if it exists.
149 unlink(name.c_str());
150 // Make sure the path we need exists.
151 FilePath path(name);
152 FilePath dir_path = path.DirName();
153 ASSERT_TRUE(file_util::CreateDirectory(dir_path));
154 ASSERT_GE(bind(socket_fd,
155 reinterpret_cast<struct sockaddr *>(&server_address),
156 server_address_len), 0) << server_address.sun_path
157 << ": " << strerror(errno)
158 << "(" << errno << ")";
159 ASSERT_GE(listen(socket_fd, SOMAXCONN), 0) << server_address.sun_path
160 << ": " << strerror(errno)
161 << "(" << errno << ")";
162 } else if (mode == IPC::Channel::MODE_NAMED_CLIENT) {
163 ASSERT_GE(connect(socket_fd,
164 reinterpret_cast<struct sockaddr *>(&server_address),
165 server_address_len), 0) << server_address.sun_path
166 << ": " << strerror(errno)
167 << "(" << errno << ")";
168 } else {
169 FAIL() << "Unknown mode " << mode;
171 handle->socket.fd = socket_fd;
174 void IPCChannelPosixTest::SpinRunLoop(int milliseconds) {
175 MessageLoopForIO *loop = MessageLoopForIO::current();
176 // Post a quit task so that this loop eventually ends and we don't hang
177 // in the case of a bad test. Usually, the run loop will quit sooner than
178 // that because all tests use a IPCChannelPosixTestListener which quits the
179 // current run loop on any channel activity.
180 loop->PostDelayedTask(
181 FROM_HERE,
182 MessageLoop::QuitClosure(),
183 base::TimeDelta::FromMilliseconds(milliseconds));
184 loop->Run();
187 TEST_F(IPCChannelPosixTest, BasicListen) {
189 #if defined(OS_ANDROID)
190 const char* kChannelName = "/data/local/IPCChannelPosixTest_BasicListen";
191 #else
192 const char* kChannelName = "/var/tmp/IPCChannelPosixTest_BasicListen";
193 #endif
194 // Test creating a socket that is listening.
195 IPC::ChannelHandle handle(kChannelName);
196 SetUpSocket(&handle, IPC::Channel::MODE_NAMED_SERVER);
197 unlink(handle.name.c_str());
198 IPC::Channel channel(handle, IPC::Channel::MODE_NAMED_SERVER, NULL);
199 ASSERT_TRUE(channel.Connect());
200 ASSERT_TRUE(channel.AcceptsConnections());
201 ASSERT_FALSE(channel.HasAcceptedConnection());
202 channel.ResetToAcceptingConnectionState();
203 ASSERT_FALSE(channel.HasAcceptedConnection());
206 TEST_F(IPCChannelPosixTest, BasicConnected) {
207 // Test creating a socket that is connected.
208 int pipe_fds[2];
209 ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, pipe_fds));
210 std::string socket_name("/var/tmp/IPCChannelPosixTest_BasicConnected");
211 ASSERT_GE(fcntl(pipe_fds[0], F_SETFL, O_NONBLOCK), 0);
213 base::FileDescriptor fd(pipe_fds[0], false);
214 IPC::ChannelHandle handle(socket_name, fd);
215 IPC::Channel channel(handle, IPC::Channel::MODE_SERVER, NULL);
216 ASSERT_TRUE(channel.Connect());
217 ASSERT_FALSE(channel.AcceptsConnections());
218 channel.Close();
219 ASSERT_TRUE(HANDLE_EINTR(close(pipe_fds[1])) == 0);
221 // Make sure that we can use the socket that is created for us by
222 // a standard channel.
223 IPC::Channel channel2(socket_name, IPC::Channel::MODE_SERVER, NULL);
224 ASSERT_TRUE(channel2.Connect());
225 ASSERT_FALSE(channel2.AcceptsConnections());
228 TEST_F(IPCChannelPosixTest, AdvancedConnected) {
229 // Test creating a connection to an external process.
230 IPCChannelPosixTestListener listener(false);
231 IPC::ChannelHandle chan_handle(kConnectionSocketTestName);
232 SetUpSocket(&chan_handle, IPC::Channel::MODE_NAMED_SERVER);
233 IPC::Channel channel(chan_handle, IPC::Channel::MODE_NAMED_SERVER, &listener);
234 ASSERT_TRUE(channel.Connect());
235 ASSERT_TRUE(channel.AcceptsConnections());
236 ASSERT_FALSE(channel.HasAcceptedConnection());
238 base::ProcessHandle handle = SpawnChild("IPCChannelPosixTestConnectionProc",
239 false);
240 ASSERT_TRUE(handle);
241 SpinRunLoop(TestTimeouts::action_max_timeout_ms());
242 ASSERT_EQ(IPCChannelPosixTestListener::CONNECTED, listener.status());
243 ASSERT_TRUE(channel.HasAcceptedConnection());
244 IPC::Message* message = new IPC::Message(0, // routing_id
245 kQuitMessage, // message type
246 IPC::Message::PRIORITY_NORMAL);
247 channel.Send(message);
248 SpinRunLoop(TestTimeouts::action_timeout_ms());
249 int exit_code = 0;
250 EXPECT_TRUE(base::WaitForExitCode(handle, &exit_code));
251 EXPECT_EQ(0, exit_code);
252 ASSERT_EQ(IPCChannelPosixTestListener::CHANNEL_ERROR, listener.status());
253 ASSERT_FALSE(channel.HasAcceptedConnection());
256 TEST_F(IPCChannelPosixTest, ResetState) {
257 // Test creating a connection to an external process. Close the connection,
258 // but continue to listen and make sure another external process can connect
259 // to us.
260 IPCChannelPosixTestListener listener(false);
261 IPC::ChannelHandle chan_handle(kConnectionSocketTestName);
262 SetUpSocket(&chan_handle, IPC::Channel::MODE_NAMED_SERVER);
263 IPC::Channel channel(chan_handle, IPC::Channel::MODE_NAMED_SERVER, &listener);
264 ASSERT_TRUE(channel.Connect());
265 ASSERT_TRUE(channel.AcceptsConnections());
266 ASSERT_FALSE(channel.HasAcceptedConnection());
268 base::ProcessHandle handle = SpawnChild("IPCChannelPosixTestConnectionProc",
269 false);
270 ASSERT_TRUE(handle);
271 SpinRunLoop(TestTimeouts::action_max_timeout_ms());
272 ASSERT_EQ(IPCChannelPosixTestListener::CONNECTED, listener.status());
273 ASSERT_TRUE(channel.HasAcceptedConnection());
274 channel.ResetToAcceptingConnectionState();
275 ASSERT_FALSE(channel.HasAcceptedConnection());
277 base::ProcessHandle handle2 = SpawnChild("IPCChannelPosixTestConnectionProc",
278 false);
279 ASSERT_TRUE(handle2);
280 SpinRunLoop(TestTimeouts::action_max_timeout_ms());
281 ASSERT_EQ(IPCChannelPosixTestListener::CONNECTED, listener.status());
282 ASSERT_TRUE(channel.HasAcceptedConnection());
283 IPC::Message* message = new IPC::Message(0, // routing_id
284 kQuitMessage, // message type
285 IPC::Message::PRIORITY_NORMAL);
286 channel.Send(message);
287 SpinRunLoop(TestTimeouts::action_timeout_ms());
288 EXPECT_TRUE(base::KillProcess(handle, 0, false));
289 int exit_code = 0;
290 EXPECT_TRUE(base::WaitForExitCode(handle2, &exit_code));
291 EXPECT_EQ(0, exit_code);
292 ASSERT_EQ(IPCChannelPosixTestListener::CHANNEL_ERROR, listener.status());
293 ASSERT_FALSE(channel.HasAcceptedConnection());
296 TEST_F(IPCChannelPosixTest, BadChannelName) {
297 // Test empty name
298 IPC::ChannelHandle handle("");
299 IPC::Channel channel(handle, IPC::Channel::MODE_NAMED_SERVER, NULL);
300 ASSERT_FALSE(channel.Connect());
302 // Test name that is too long.
303 const char *kTooLongName = "This_is_a_very_long_name_to_proactively_implement"
304 "client-centered_synergy_through_top-line"
305 "platforms_Phosfluorescently_disintermediate_"
306 "clicks-and-mortar_best_practices_without_"
307 "future-proof_growth_strategies_Continually"
308 "pontificate_proactive_potentialities_before"
309 "leading-edge_processes";
310 EXPECT_GE(strlen(kTooLongName), IPC::kMaxPipeNameLength);
311 IPC::ChannelHandle handle2(kTooLongName);
312 IPC::Channel channel2(handle2, IPC::Channel::MODE_NAMED_SERVER, NULL);
313 EXPECT_FALSE(channel2.Connect());
316 TEST_F(IPCChannelPosixTest, MultiConnection) {
317 // Test setting up a connection to an external process, and then have
318 // another external process attempt to connect to us.
319 IPCChannelPosixTestListener listener(false);
320 IPC::ChannelHandle chan_handle(kConnectionSocketTestName);
321 SetUpSocket(&chan_handle, IPC::Channel::MODE_NAMED_SERVER);
322 IPC::Channel channel(chan_handle, IPC::Channel::MODE_NAMED_SERVER, &listener);
323 ASSERT_TRUE(channel.Connect());
324 ASSERT_TRUE(channel.AcceptsConnections());
325 ASSERT_FALSE(channel.HasAcceptedConnection());
327 base::ProcessHandle handle = SpawnChild("IPCChannelPosixTestConnectionProc",
328 false);
329 ASSERT_TRUE(handle);
330 SpinRunLoop(TestTimeouts::action_max_timeout_ms());
331 ASSERT_EQ(IPCChannelPosixTestListener::CONNECTED, listener.status());
332 ASSERT_TRUE(channel.HasAcceptedConnection());
333 base::ProcessHandle handle2 = SpawnChild("IPCChannelPosixFailConnectionProc",
334 false);
335 ASSERT_TRUE(handle2);
336 SpinRunLoop(TestTimeouts::action_max_timeout_ms());
337 int exit_code = 0;
338 EXPECT_TRUE(base::WaitForExitCode(handle2, &exit_code));
339 EXPECT_EQ(exit_code, 0);
340 ASSERT_EQ(IPCChannelPosixTestListener::DENIED, listener.status());
341 ASSERT_TRUE(channel.HasAcceptedConnection());
342 IPC::Message* message = new IPC::Message(0, // routing_id
343 kQuitMessage, // message type
344 IPC::Message::PRIORITY_NORMAL);
345 channel.Send(message);
346 SpinRunLoop(TestTimeouts::action_timeout_ms());
347 EXPECT_TRUE(base::WaitForExitCode(handle, &exit_code));
348 EXPECT_EQ(exit_code, 0);
349 ASSERT_EQ(IPCChannelPosixTestListener::CHANNEL_ERROR, listener.status());
350 ASSERT_FALSE(channel.HasAcceptedConnection());
353 TEST_F(IPCChannelPosixTest, DoubleServer) {
354 // Test setting up two servers with the same name.
355 IPCChannelPosixTestListener listener(false);
356 IPCChannelPosixTestListener listener2(false);
357 IPC::ChannelHandle chan_handle(kConnectionSocketTestName);
358 IPC::Channel channel(chan_handle, IPC::Channel::MODE_SERVER, &listener);
359 IPC::Channel channel2(chan_handle, IPC::Channel::MODE_SERVER, &listener2);
360 ASSERT_TRUE(channel.Connect());
361 ASSERT_FALSE(channel2.Connect());
364 TEST_F(IPCChannelPosixTest, BadMode) {
365 // Test setting up two servers with a bad mode.
366 IPCChannelPosixTestListener listener(false);
367 IPC::ChannelHandle chan_handle(kConnectionSocketTestName);
368 IPC::Channel channel(chan_handle, IPC::Channel::MODE_NONE, &listener);
369 ASSERT_FALSE(channel.Connect());
372 TEST_F(IPCChannelPosixTest, IsNamedServerInitialized) {
373 IPCChannelPosixTestListener listener(false);
374 IPC::ChannelHandle chan_handle(kConnectionSocketTestName);
375 ASSERT_TRUE(file_util::Delete(FilePath(kConnectionSocketTestName), false));
376 ASSERT_FALSE(IPC::Channel::IsNamedServerInitialized(
377 kConnectionSocketTestName));
378 IPC::Channel channel(chan_handle, IPC::Channel::MODE_NAMED_SERVER, &listener);
379 ASSERT_TRUE(IPC::Channel::IsNamedServerInitialized(
380 kConnectionSocketTestName));
381 channel.Close();
382 ASSERT_FALSE(IPC::Channel::IsNamedServerInitialized(
383 kConnectionSocketTestName));
386 // A long running process that connects to us
387 MULTIPROCESS_TEST_MAIN(IPCChannelPosixTestConnectionProc) {
388 MessageLoopForIO message_loop;
389 IPCChannelPosixTestListener listener(true);
390 IPC::ChannelHandle handle(IPCChannelPosixTest::kConnectionSocketTestName);
391 IPCChannelPosixTest::SetUpSocket(&handle, IPC::Channel::MODE_NAMED_CLIENT);
392 IPC::Channel channel(handle, IPC::Channel::MODE_NAMED_CLIENT, &listener);
393 EXPECT_TRUE(channel.Connect());
394 IPCChannelPosixTest::SpinRunLoop(TestTimeouts::action_max_timeout_ms());
395 EXPECT_EQ(IPCChannelPosixTestListener::MESSAGE_RECEIVED, listener.status());
396 return 0;
399 // Simple external process that shouldn't be able to connect to us.
400 MULTIPROCESS_TEST_MAIN(IPCChannelPosixFailConnectionProc) {
401 MessageLoopForIO message_loop;
402 IPCChannelPosixTestListener listener(false);
403 IPC::ChannelHandle handle(IPCChannelPosixTest::kConnectionSocketTestName);
404 IPCChannelPosixTest::SetUpSocket(&handle, IPC::Channel::MODE_NAMED_CLIENT);
405 IPC::Channel channel(handle, IPC::Channel::MODE_NAMED_CLIENT, &listener);
407 // In this case connect may succeed or fail depending on if the packet
408 // actually gets sent at sendmsg. Since we never delay on send, we may not
409 // see the error. However even if connect succeeds, eventually we will get an
410 // error back since the channel will be closed when we attempt to read from
411 // it.
412 bool connected = channel.Connect();
413 if (connected) {
414 IPCChannelPosixTest::SpinRunLoop(TestTimeouts::action_max_timeout_ms());
415 EXPECT_EQ(IPCChannelPosixTestListener::CHANNEL_ERROR, listener.status());
416 } else {
417 EXPECT_EQ(IPCChannelPosixTestListener::DISCONNECTED, listener.status());
419 return 0;