blob: 17b3641f577d5605bd0aa1763ea6fa79fd12ada7 [file] [log] [blame]
[email protected]11307022012-01-25 23:53:061// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]d4651ff2008-12-02 16:51:582// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]946d1b22009-07-22 23:57:215#include "ipc/ipc_channel_posix.h"
[email protected]d4651ff2008-12-02 16:51:586
[email protected]c3110742008-12-11 00:36:477#include <errno.h>
[email protected]fa95fc92008-12-08 18:10:148#include <fcntl.h>
[email protected]e45e6c02008-12-15 22:02:179#include <stddef.h>
[email protected]fa95fc92008-12-08 18:10:1410#include <sys/socket.h>
11#include <sys/stat.h>
[email protected]57999812013-02-24 05:40:5212#include <sys/types.h>
[email protected]e45e6c02008-12-15 22:02:1713#include <sys/un.h>
[email protected]3fcbd4b2012-06-05 01:54:4614#include <unistd.h>
[email protected]e45e6c02008-12-15 22:02:1715
[email protected]4af5ef42011-10-18 17:46:2216#if defined(OS_OPENBSD)
17#include <sys/uio.h>
18#endif
19
[email protected]e8fce882009-01-20 22:02:5820#include <map>
[email protected]57999812013-02-24 05:40:5221#include <string>
[email protected]e8fce882009-01-20 22:02:5822
[email protected]df3c1ca12008-12-19 21:37:0123#include "base/command_line.h"
[email protected]22b42c52010-12-20 06:59:2324#include "base/file_util.h"
[email protected]57999812013-02-24 05:40:5225#include "base/files/file_path.h"
[email protected]c62dd9d2011-09-21 18:05:4126#include "base/location.h"
[email protected]fa95fc92008-12-08 18:10:1427#include "base/logging.h"
[email protected]3b63f8f42011-03-28 01:54:1528#include "base/memory/scoped_ptr.h"
29#include "base/memory/singleton.h"
[email protected]2025d002012-11-14 20:54:3530#include "base/posix/eintr_wrapper.h"
[email protected]613eef62012-11-09 23:46:5431#include "base/posix/global_descriptors.h"
[email protected]fa95fc92008-12-08 18:10:1432#include "base/process_util.h"
[email protected]5c41e6e12012-03-17 02:20:4633#include "base/rand_util.h"
[email protected]7286e3fc2011-07-19 22:13:2434#include "base/stl_util.h"
[email protected]946d1b22009-07-22 23:57:2135#include "base/string_util.h"
[email protected]20305ec2011-01-21 04:55:5236#include "base/synchronization/lock.h"
[email protected]946d1b22009-07-22 23:57:2137#include "ipc/file_descriptor_set_posix.h"
[email protected]4e07f842012-11-15 22:22:1738#include "ipc/ipc_descriptors.h"
39#include "ipc/ipc_listener.h"
[email protected]946d1b22009-07-22 23:57:2140#include "ipc/ipc_logging.h"
41#include "ipc/ipc_message_utils.h"
[email protected]4e07f842012-11-15 22:22:1742#include "ipc/ipc_switches.h"
[email protected]d4651ff2008-12-02 16:51:5843
44namespace IPC {
45
[email protected]5f594c02009-05-01 22:37:5946// IPC channels on Windows use named pipes (CreateNamedPipe()) with
[email protected]22b42c52010-12-20 06:59:2347// channel ids as the pipe names. Channels on POSIX use sockets as
48// pipes These don't quite line up.
[email protected]5f594c02009-05-01 22:37:5949//
[email protected]22b42c52010-12-20 06:59:2350// When creating a child subprocess we use a socket pair and the parent side of
51// the fork arranges it such that the initial control channel ends up on the
[email protected]cc8f1462009-06-12 17:36:5552// magic file descriptor kPrimaryIPCChannel in the child. Future
[email protected]5f594c02009-05-01 22:37:5953// connections (file descriptors) can then be passed via that
54// connection via sendmsg().
[email protected]22b42c52010-12-20 06:59:2355//
56// A POSIX IPC channel can also be set up as a server for a bound UNIX domain
57// socket, and will handle multiple connect and disconnect sequences. Currently
58// it is limited to one connection at a time.
[email protected]5f594c02009-05-01 22:37:5959
[email protected]fa95fc92008-12-08 18:10:1460//------------------------------------------------------------------------------
[email protected]fa95fc92008-12-08 18:10:1461namespace {
62
[email protected]5f594c02009-05-01 22:37:5963// The PipeMap class works around this quirk related to unit tests:
[email protected]e8fce882009-01-20 22:02:5864//
[email protected]5f594c02009-05-01 22:37:5965// When running as a server, we install the client socket in a
[email protected]cc8f1462009-06-12 17:36:5566// specific file descriptor number (@kPrimaryIPCChannel). However, we
[email protected]5f594c02009-05-01 22:37:5967// also have to support the case where we are running unittests in the
68// same process. (We do not support forking without execing.)
[email protected]e8fce882009-01-20 22:02:5869//
70// Case 1: normal running
71// The IPC server object will install a mapping in PipeMap from the
72// name which it was given to the client pipe. When forking the client, the
73// GetClientFileDescriptorMapping will ensure that the socket is installed in
[email protected]cc8f1462009-06-12 17:36:5574// the magic slot (@kPrimaryIPCChannel). The client will search for the
[email protected]e8fce882009-01-20 22:02:5875// mapping, but it won't find any since we are in a new process. Thus the
76// magic fd number is returned. Once the client connects, the server will
[email protected]5f594c02009-05-01 22:37:5977// close its copy of the client socket and remove the mapping.
[email protected]e8fce882009-01-20 22:02:5878//
79// Case 2: unittests - client and server in the same process
80// The IPC server will install a mapping as before. The client will search
81// for a mapping and find out. It duplicates the file descriptor and
82// connects. Once the client connects, the server will close the original
83// copy of the client socket and remove the mapping. Thus, when the client
84// object closes, it will close the only remaining copy of the client socket
85// in the fd table and the server will see EOF on its side.
86//
87// TODO(port): a client process cannot connect to multiple IPC channels with
88// this scheme.
89
90class PipeMap {
91 public:
[email protected]864b5582010-12-04 23:00:1092 static PipeMap* GetInstance() {
93 return Singleton<PipeMap>::get();
94 }
95
[email protected]42ce94e2010-12-08 19:28:0996 ~PipeMap() {
97 // Shouldn't have left over pipes.
[email protected]f6b8ce32011-03-02 00:03:1898 DCHECK(map_.empty());
[email protected]42ce94e2010-12-08 19:28:0999 }
100
[email protected]e8fce882009-01-20 22:02:58101 // Lookup a given channel id. Return -1 if not found.
102 int Lookup(const std::string& channel_id) {
[email protected]20305ec2011-01-21 04:55:52103 base::AutoLock locked(lock_);
[email protected]e8fce882009-01-20 22:02:58104
105 ChannelToFDMap::const_iterator i = map_.find(channel_id);
106 if (i == map_.end())
107 return -1;
108 return i->second;
109 }
110
111 // Remove the mapping for the given channel id. No error is signaled if the
112 // channel_id doesn't exist
[email protected]2ce26c432011-09-19 17:08:12113 void Remove(const std::string& channel_id) {
[email protected]20305ec2011-01-21 04:55:52114 base::AutoLock locked(lock_);
[email protected]2ce26c432011-09-19 17:08:12115 map_.erase(channel_id);
[email protected]e8fce882009-01-20 22:02:58116 }
117
118 // Insert a mapping from @channel_id to @fd. It's a fatal error to insert a
119 // mapping if one already exists for the given channel_id
120 void Insert(const std::string& channel_id, int fd) {
[email protected]20305ec2011-01-21 04:55:52121 base::AutoLock locked(lock_);
[email protected]60ea6052011-04-18 20:07:08122 DCHECK_NE(-1, fd);
[email protected]e8fce882009-01-20 22:02:58123
124 ChannelToFDMap::const_iterator i = map_.find(channel_id);
[email protected]d2e884d2009-06-22 20:37:52125 CHECK(i == map_.end()) << "Creating second IPC server (fd " << fd << ") "
126 << "for '" << channel_id << "' while first "
127 << "(fd " << i->second << ") still exists";
[email protected]e8fce882009-01-20 22:02:58128 map_[channel_id] = fd;
129 }
130
131 private:
[email protected]20305ec2011-01-21 04:55:52132 base::Lock lock_;
[email protected]e8fce882009-01-20 22:02:58133 typedef std::map<std::string, int> ChannelToFDMap;
134 ChannelToFDMap map_;
[email protected]864b5582010-12-04 23:00:10135
136 friend struct DefaultSingletonTraits<PipeMap>;
[email protected]e8fce882009-01-20 22:02:58137};
138
[email protected]df3c1ca12008-12-19 21:37:01139//------------------------------------------------------------------------------
[email protected]22b42c52010-12-20 06:59:23140// Verify that kMaxPipeNameLength is a decent size.
[email protected]cffa687f2010-12-08 20:33:46141COMPILE_ASSERT(sizeof(((sockaddr_un*)0)->sun_path) >= kMaxPipeNameLength,
142 BAD_SUN_PATH_LENGTH);
[email protected]fa95fc92008-12-08 18:10:14143
[email protected]22b42c52010-12-20 06:59:23144// Creates a unix domain socket bound to the specified name that is listening
145// for connections.
146bool CreateServerUnixDomainSocket(const std::string& pipe_name,
147 int* server_listen_fd) {
[email protected]fa95fc92008-12-08 18:10:14148 DCHECK(server_listen_fd);
[email protected]fa95fc92008-12-08 18:10:14149
[email protected]02d66512009-03-17 01:48:35150 if (pipe_name.length() == 0 || pipe_name.length() >= kMaxPipeNameLength) {
[email protected]3c524252011-08-25 14:14:05151 DLOG(ERROR) << "pipe_name.length() == " << pipe_name.length();
[email protected]fa95fc92008-12-08 18:10:14152 return false;
153 }
154
155 // Create socket.
156 int fd = socket(AF_UNIX, SOCK_STREAM, 0);
157 if (fd < 0) {
158 return false;
159 }
160
161 // Make socket non-blocking
162 if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
[email protected]22b42c52010-12-20 06:59:23163 PLOG(ERROR) << "fcntl(O_NONBLOCK) " << pipe_name;
[email protected]70eb6572010-06-23 00:37:46164 if (HANDLE_EINTR(close(fd)) < 0)
[email protected]5484722e2010-12-09 01:13:12165 PLOG(ERROR) << "close " << pipe_name;
[email protected]fa95fc92008-12-08 18:10:14166 return false;
167 }
168
169 // Delete any old FS instances.
170 unlink(pipe_name.c_str());
171
[email protected]6bef6c82011-01-20 21:42:08172 // Make sure the path we need exists.
[email protected]6d4b67a2013-02-10 04:49:30173 base::FilePath path(pipe_name);
174 base::FilePath dir_path = path.DirName();
[email protected]22b42c52010-12-20 06:59:23175 if (!file_util::CreateDirectory(dir_path)) {
[email protected]a1923e62011-12-21 22:12:58176 if (HANDLE_EINTR(close(fd)) < 0)
177 PLOG(ERROR) << "close " << pipe_name;
[email protected]22b42c52010-12-20 06:59:23178 return false;
179 }
180
[email protected]6bef6c82011-01-20 21:42:08181 // Create unix_addr structure.
[email protected]fa95fc92008-12-08 18:10:14182 struct sockaddr_un unix_addr;
183 memset(&unix_addr, 0, sizeof(unix_addr));
184 unix_addr.sun_family = AF_UNIX;
[email protected]22b42c52010-12-20 06:59:23185 int path_len = snprintf(unix_addr.sun_path, IPC::kMaxPipeNameLength,
186 "%s", pipe_name.c_str());
187 DCHECK_EQ(static_cast<int>(pipe_name.length()), path_len);
188 size_t unix_addr_len = offsetof(struct sockaddr_un,
189 sun_path) + path_len + 1;
[email protected]fa95fc92008-12-08 18:10:14190
191 // Bind the socket.
192 if (bind(fd, reinterpret_cast<const sockaddr*>(&unix_addr),
193 unix_addr_len) != 0) {
[email protected]5484722e2010-12-09 01:13:12194 PLOG(ERROR) << "bind " << pipe_name;
[email protected]70eb6572010-06-23 00:37:46195 if (HANDLE_EINTR(close(fd)) < 0)
[email protected]5484722e2010-12-09 01:13:12196 PLOG(ERROR) << "close " << pipe_name;
[email protected]fa95fc92008-12-08 18:10:14197 return false;
198 }
199
200 // Start listening on the socket.
201 const int listen_queue_length = 1;
202 if (listen(fd, listen_queue_length) != 0) {
[email protected]5484722e2010-12-09 01:13:12203 PLOG(ERROR) << "listen " << pipe_name;
[email protected]70eb6572010-06-23 00:37:46204 if (HANDLE_EINTR(close(fd)) < 0)
[email protected]5484722e2010-12-09 01:13:12205 PLOG(ERROR) << "close " << pipe_name;
[email protected]fa95fc92008-12-08 18:10:14206 return false;
207 }
208
209 *server_listen_fd = fd;
210 return true;
211}
212
[email protected]22b42c52010-12-20 06:59:23213// Accept a connection on a socket we are listening to.
214bool ServerAcceptConnection(int server_listen_fd, int* server_socket) {
[email protected]fa95fc92008-12-08 18:10:14215 DCHECK(server_socket);
216
[email protected]157c61b2009-05-01 21:37:31217 int accept_fd = HANDLE_EINTR(accept(server_listen_fd, NULL, 0));
[email protected]fa95fc92008-12-08 18:10:14218 if (accept_fd < 0)
219 return false;
[email protected]3af21262008-12-16 21:49:34220 if (fcntl(accept_fd, F_SETFL, O_NONBLOCK) == -1) {
[email protected]22b42c52010-12-20 06:59:23221 PLOG(ERROR) << "fcntl(O_NONBLOCK) " << accept_fd;
[email protected]70eb6572010-06-23 00:37:46222 if (HANDLE_EINTR(close(accept_fd)) < 0)
[email protected]5484722e2010-12-09 01:13:12223 PLOG(ERROR) << "close " << accept_fd;
[email protected]3af21262008-12-16 21:49:34224 return false;
225 }
[email protected]fa95fc92008-12-08 18:10:14226
227 *server_socket = accept_fd;
228 return true;
229}
230
[email protected]22b42c52010-12-20 06:59:23231bool CreateClientUnixDomainSocket(const std::string& pipe_name,
232 int* client_socket) {
[email protected]fa95fc92008-12-08 18:10:14233 DCHECK(client_socket);
[email protected]5484722e2010-12-09 01:13:12234 DCHECK_GT(pipe_name.length(), 0u);
[email protected]02d66512009-03-17 01:48:35235 DCHECK_LT(pipe_name.length(), kMaxPipeNameLength);
[email protected]fa95fc92008-12-08 18:10:14236
[email protected]5484722e2010-12-09 01:13:12237 if (pipe_name.length() == 0 || pipe_name.length() >= kMaxPipeNameLength) {
238 return false;
239 }
240
[email protected]fa95fc92008-12-08 18:10:14241 // Create socket.
242 int fd = socket(AF_UNIX, SOCK_STREAM, 0);
243 if (fd < 0) {
[email protected]5484722e2010-12-09 01:13:12244 PLOG(ERROR) << "socket " << pipe_name;
[email protected]fa95fc92008-12-08 18:10:14245 return false;
246 }
247
248 // Make socket non-blocking
249 if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
[email protected]22b42c52010-12-20 06:59:23250 PLOG(ERROR) << "fcntl(O_NONBLOCK) " << pipe_name;
[email protected]70eb6572010-06-23 00:37:46251 if (HANDLE_EINTR(close(fd)) < 0)
[email protected]5484722e2010-12-09 01:13:12252 PLOG(ERROR) << "close " << pipe_name;
[email protected]fa95fc92008-12-08 18:10:14253 return false;
254 }
255
256 // Create server side of socket.
[email protected]5484722e2010-12-09 01:13:12257 struct sockaddr_un server_unix_addr;
[email protected]fa95fc92008-12-08 18:10:14258 memset(&server_unix_addr, 0, sizeof(server_unix_addr));
259 server_unix_addr.sun_family = AF_UNIX;
[email protected]22b42c52010-12-20 06:59:23260 int path_len = snprintf(server_unix_addr.sun_path, IPC::kMaxPipeNameLength,
261 "%s", pipe_name.c_str());
262 DCHECK_EQ(static_cast<int>(pipe_name.length()), path_len);
263 size_t server_unix_addr_len = offsetof(struct sockaddr_un,
264 sun_path) + path_len + 1;
[email protected]fa95fc92008-12-08 18:10:14265
[email protected]157c61b2009-05-01 21:37:31266 if (HANDLE_EINTR(connect(fd, reinterpret_cast<sockaddr*>(&server_unix_addr),
267 server_unix_addr_len)) != 0) {
[email protected]5484722e2010-12-09 01:13:12268 PLOG(ERROR) << "connect " << pipe_name;
[email protected]70eb6572010-06-23 00:37:46269 if (HANDLE_EINTR(close(fd)) < 0)
[email protected]5484722e2010-12-09 01:13:12270 PLOG(ERROR) << "close " << pipe_name;
[email protected]fa95fc92008-12-08 18:10:14271 return false;
272 }
273
274 *client_socket = fd;
275 return true;
276}
277
[email protected]86c3d9e2009-12-08 14:48:08278bool SocketWriteErrorIsRecoverable() {
279#if defined(OS_MACOSX)
280 // On OS X if sendmsg() is trying to send fds between processes and there
281 // isn't enough room in the output buffer to send the fd structure over
282 // atomically then EMSGSIZE is returned.
283 //
284 // EMSGSIZE presents a problem since the system APIs can only call us when
285 // there's room in the socket buffer and not when there is "enough" room.
286 //
287 // The current behavior is to return to the event loop when EMSGSIZE is
288 // received and hopefull service another FD. This is however still
289 // technically a busy wait since the event loop will call us right back until
290 // the receiver has read enough data to allow passing the FD over atomically.
291 return errno == EAGAIN || errno == EMSGSIZE;
292#else
293 return errno == EAGAIN;
[email protected]22b42c52010-12-20 06:59:23294#endif // OS_MACOSX
[email protected]86c3d9e2009-12-08 14:48:08295}
296
[email protected]fa95fc92008-12-08 18:10:14297} // namespace
[email protected]d4651ff2008-12-02 16:51:58298//------------------------------------------------------------------------------
299
[email protected]e1d67a882011-08-31 21:11:04300#if defined(OS_LINUX)
301int Channel::ChannelImpl::global_pid_ = 0;
302#endif // OS_LINUX
303
[email protected]42ce94e2010-12-08 19:28:09304Channel::ChannelImpl::ChannelImpl(const IPC::ChannelHandle& channel_handle,
305 Mode mode, Listener* listener)
[email protected]d805c6a2012-03-08 12:30:28306 : ChannelReader(listener),
307 mode_(mode),
[email protected]0a6fc4b2012-04-05 02:38:34308 peer_pid_(base::kNullProcessId),
[email protected]e45e6c02008-12-15 22:02:17309 is_blocked_on_write_(false),
[email protected]22b42c52010-12-20 06:59:23310 waiting_connect_(true),
[email protected]e45e6c02008-12-15 22:02:17311 message_send_bytes_written_(0),
312 server_listen_pipe_(-1),
313 pipe_(-1),
[email protected]df3c1ca12008-12-19 21:37:01314 client_pipe_(-1),
[email protected]e40f5a0b2010-12-08 21:22:24315#if defined(IPC_USES_READWRITE)
[email protected]baf556a2009-09-04 21:34:05316 fd_pipe_(-1),
317 remote_fd_pipe_(-1),
[email protected]22b42c52010-12-20 06:59:23318#endif // IPC_USES_READWRITE
319 pipe_name_(channel_handle.name),
[email protected]bf84c582011-08-23 03:17:02320 must_unlink_(false) {
[email protected]df60edb2011-06-21 22:48:29321 memset(input_cmsg_buf_, 0, sizeof(input_cmsg_buf_));
[email protected]1707726c2011-02-03 20:35:09322 if (!CreatePipe(channel_handle)) {
[email protected]22b42c52010-12-20 06:59:23323 // The pipe may have been closed already.
[email protected]1707726c2011-02-03 20:35:09324 const char *modestr = (mode_ & MODE_SERVER_FLAG) ? "server" : "client";
[email protected]42ce94e2010-12-08 19:28:09325 LOG(WARNING) << "Unable to create pipe named \"" << channel_handle.name
[email protected]22b42c52010-12-20 06:59:23326 << "\" in " << modestr << " mode";
[email protected]fa95fc92008-12-08 18:10:14327 }
[email protected]d4651ff2008-12-02 16:51:58328}
329
[email protected]601858c02010-09-01 17:08:20330Channel::ChannelImpl::~ChannelImpl() {
331 Close();
332}
333
[email protected]d2e884d2009-06-22 20:37:52334bool SocketPair(int* fd1, int* fd2) {
335 int pipe_fds[2];
336 if (socketpair(AF_UNIX, SOCK_STREAM, 0, pipe_fds) != 0) {
[email protected]57b765672009-10-13 18:27:40337 PLOG(ERROR) << "socketpair()";
[email protected]d2e884d2009-06-22 20:37:52338 return false;
339 }
340
341 // Set both ends to be non-blocking.
342 if (fcntl(pipe_fds[0], F_SETFL, O_NONBLOCK) == -1 ||
343 fcntl(pipe_fds[1], F_SETFL, O_NONBLOCK) == -1) {
[email protected]57b765672009-10-13 18:27:40344 PLOG(ERROR) << "fcntl(O_NONBLOCK)";
[email protected]70eb6572010-06-23 00:37:46345 if (HANDLE_EINTR(close(pipe_fds[0])) < 0)
346 PLOG(ERROR) << "close";
347 if (HANDLE_EINTR(close(pipe_fds[1])) < 0)
348 PLOG(ERROR) << "close";
[email protected]d2e884d2009-06-22 20:37:52349 return false;
350 }
351
352 *fd1 = pipe_fds[0];
353 *fd2 = pipe_fds[1];
354
355 return true;
356}
357
[email protected]1707726c2011-02-03 20:35:09358bool Channel::ChannelImpl::CreatePipe(
359 const IPC::ChannelHandle& channel_handle) {
[email protected]fa95fc92008-12-08 18:10:14360 DCHECK(server_listen_pipe_ == -1 && pipe_ == -1);
[email protected]22b42c52010-12-20 06:59:23361
362 // Four possible cases:
363 // 1) It's a channel wrapping a pipe that is given to us.
364 // 2) It's for a named channel, so we create it.
365 // 3) It's for a client that we implement ourself. This is used
366 // in unittesting.
367 // 4) It's the initial IPC channel:
368 // 4a) Client side: Pull the pipe out of the GlobalDescriptors set.
369 // 4b) Server side: create the pipe.
370
[email protected]6aad23f92011-03-02 22:27:14371 int local_pipe = -1;
[email protected]22b42c52010-12-20 06:59:23372 if (channel_handle.socket.fd != -1) {
373 // Case 1 from comment above.
[email protected]6aad23f92011-03-02 22:27:14374 local_pipe = channel_handle.socket.fd;
[email protected]22b42c52010-12-20 06:59:23375#if defined(IPC_USES_READWRITE)
376 // Test the socket passed into us to make sure it is nonblocking.
377 // We don't want to call read/write on a blocking socket.
[email protected]6aad23f92011-03-02 22:27:14378 int value = fcntl(local_pipe, F_GETFL);
[email protected]22b42c52010-12-20 06:59:23379 if (value == -1) {
380 PLOG(ERROR) << "fcntl(F_GETFL) " << pipe_name_;
381 return false;
382 }
383 if (!(value & O_NONBLOCK)) {
384 LOG(ERROR) << "Socket " << pipe_name_ << " must be O_NONBLOCK";
385 return false;
386 }
387#endif // IPC_USES_READWRITE
[email protected]1707726c2011-02-03 20:35:09388 } else if (mode_ & MODE_NAMED_FLAG) {
[email protected]22b42c52010-12-20 06:59:23389 // Case 2 from comment above.
[email protected]1707726c2011-02-03 20:35:09390 if (mode_ & MODE_SERVER_FLAG) {
[email protected]6aad23f92011-03-02 22:27:14391 if (!CreateServerUnixDomainSocket(pipe_name_, &local_pipe)) {
[email protected]df3c1ca12008-12-19 21:37:01392 return false;
393 }
[email protected]56f0f262011-02-24 17:14:36394 must_unlink_ = true;
[email protected]1707726c2011-02-03 20:35:09395 } else if (mode_ & MODE_CLIENT_FLAG) {
[email protected]6aad23f92011-03-02 22:27:14396 if (!CreateClientUnixDomainSocket(pipe_name_, &local_pipe)) {
[email protected]df3c1ca12008-12-19 21:37:01397 return false;
398 }
[email protected]1707726c2011-02-03 20:35:09399 } else {
[email protected]6aad23f92011-03-02 22:27:14400 LOG(ERROR) << "Bad mode: " << mode_;
[email protected]1707726c2011-02-03 20:35:09401 return false;
[email protected]fa95fc92008-12-08 18:10:14402 }
403 } else {
[email protected]6aad23f92011-03-02 22:27:14404 local_pipe = PipeMap::GetInstance()->Lookup(pipe_name_);
[email protected]1707726c2011-02-03 20:35:09405 if (mode_ & MODE_CLIENT_FLAG) {
[email protected]6aad23f92011-03-02 22:27:14406 if (local_pipe != -1) {
[email protected]22b42c52010-12-20 06:59:23407 // Case 3 from comment above.
408 // We only allow one connection.
[email protected]6aad23f92011-03-02 22:27:14409 local_pipe = HANDLE_EINTR(dup(local_pipe));
[email protected]2ce26c432011-09-19 17:08:12410 PipeMap::GetInstance()->Remove(pipe_name_);
[email protected]d2e884d2009-06-22 20:37:52411 } else {
[email protected]22b42c52010-12-20 06:59:23412 // Case 4a from comment above.
[email protected]554a8852009-11-30 22:14:37413 // Guard against inappropriate reuse of the initial IPC channel. If
414 // an IPC channel closes and someone attempts to reuse it by name, the
415 // initial channel must not be recycled here. http://crbug.com/26754.
416 static bool used_initial_channel = false;
417 if (used_initial_channel) {
[email protected]9f816f72010-03-16 20:31:10418 LOG(FATAL) << "Denying attempt to reuse initial IPC channel for "
419 << pipe_name_;
[email protected]554a8852009-11-30 22:14:37420 return false;
421 }
422 used_initial_channel = true;
423
[email protected]6aad23f92011-03-02 22:27:14424 local_pipe =
425 base::GlobalDescriptors::GetInstance()->Get(kPrimaryIPCChannel);
[email protected]df3c1ca12008-12-19 21:37:01426 }
[email protected]1707726c2011-02-03 20:35:09427 } else if (mode_ & MODE_SERVER_FLAG) {
[email protected]22b42c52010-12-20 06:59:23428 // Case 4b from comment above.
[email protected]6aad23f92011-03-02 22:27:14429 if (local_pipe != -1) {
[email protected]22b42c52010-12-20 06:59:23430 LOG(ERROR) << "Server already exists for " << pipe_name_;
[email protected]baf556a2009-09-04 21:34:05431 return false;
432 }
[email protected]2ce26c432011-09-19 17:08:12433 base::AutoLock lock(client_pipe_lock_);
[email protected]6aad23f92011-03-02 22:27:14434 if (!SocketPair(&local_pipe, &client_pipe_))
[email protected]22b42c52010-12-20 06:59:23435 return false;
436 PipeMap::GetInstance()->Insert(pipe_name_, client_pipe_);
437 } else {
[email protected]6aad23f92011-03-02 22:27:14438 LOG(ERROR) << "Bad mode: " << mode_;
[email protected]22b42c52010-12-20 06:59:23439 return false;
[email protected]baf556a2009-09-04 21:34:05440 }
441 }
[email protected]22b42c52010-12-20 06:59:23442
[email protected]22b42c52010-12-20 06:59:23443#if defined(IPC_USES_READWRITE)
444 // Create a dedicated socketpair() for exchanging file descriptors.
445 // See comments for IPC_USES_READWRITE for details.
[email protected]1707726c2011-02-03 20:35:09446 if (mode_ & MODE_CLIENT_FLAG) {
[email protected]22b42c52010-12-20 06:59:23447 if (!SocketPair(&fd_pipe_, &remote_fd_pipe_)) {
448 return false;
449 }
450 }
451#endif // IPC_USES_READWRITE
452
[email protected]6aad23f92011-03-02 22:27:14453 if ((mode_ & MODE_SERVER_FLAG) && (mode_ & MODE_NAMED_FLAG)) {
454 server_listen_pipe_ = local_pipe;
455 local_pipe = -1;
456 }
457
458 pipe_ = local_pipe;
[email protected]fa95fc92008-12-08 18:10:14459 return true;
[email protected]d4651ff2008-12-02 16:51:58460}
461
[email protected]514411fc2008-12-10 22:28:11462bool Channel::ChannelImpl::Connect() {
[email protected]22b42c52010-12-20 06:59:23463 if (server_listen_pipe_ == -1 && pipe_ == -1) {
[email protected]6aad23f92011-03-02 22:27:14464 DLOG(INFO) << "Channel creation failed: " << pipe_name_;
[email protected]22b42c52010-12-20 06:59:23465 return false;
466 }
467
468 bool did_connect = true;
469 if (server_listen_pipe_ != -1) {
470 // Watch the pipe for connections, and turn any connections into
471 // active sockets.
[email protected]e45e6c02008-12-15 22:02:17472 MessageLoopForIO::current()->WatchFileDescriptor(
473 server_listen_pipe_,
474 true,
475 MessageLoopForIO::WATCH_READ,
476 &server_listen_connection_watcher_,
477 this);
[email protected]fa95fc92008-12-08 18:10:14478 } else {
[email protected]22b42c52010-12-20 06:59:23479 did_connect = AcceptConnection();
[email protected]fa95fc92008-12-08 18:10:14480 }
[email protected]22b42c52010-12-20 06:59:23481 return did_connect;
[email protected]d4651ff2008-12-02 16:51:58482}
[email protected]fa95fc92008-12-08 18:10:14483
[email protected]514411fc2008-12-10 22:28:11484bool Channel::ChannelImpl::ProcessOutgoingMessages() {
[email protected]fa95fc92008-12-08 18:10:14485 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
486 // no connection?
[email protected]22b42c52010-12-20 06:59:23487 if (output_queue_.empty())
[email protected]c7f91e82010-12-20 06:39:44488 return true;
[email protected]c7f91e82010-12-20 06:39:44489
[email protected]22b42c52010-12-20 06:59:23490 if (pipe_ == -1)
[email protected]fa95fc92008-12-08 18:10:14491 return false;
492
[email protected]fa95fc92008-12-08 18:10:14493 // Write out all the messages we can till the write blocks or there are no
494 // more outgoing messages.
495 while (!output_queue_.empty()) {
496 Message* msg = output_queue_.front();
497
498 size_t amt_to_write = msg->size() - message_send_bytes_written_;
[email protected]60ea6052011-04-18 20:07:08499 DCHECK_NE(0U, amt_to_write);
[email protected]baf556a2009-09-04 21:34:05500 const char* out_bytes = reinterpret_cast<const char*>(msg->data()) +
[email protected]fa95fc92008-12-08 18:10:14501 message_send_bytes_written_;
[email protected]526776c2009-02-07 00:39:26502
[email protected]157c61b2009-05-01 21:37:31503 struct msghdr msgh = {0};
504 struct iovec iov = {const_cast<char*>(out_bytes), amt_to_write};
505 msgh.msg_iov = &iov;
506 msgh.msg_iovlen = 1;
507 char buf[CMSG_SPACE(
[email protected]05094a32011-09-01 00:50:13508 sizeof(int) * FileDescriptorSet::kMaxDescriptorsPerMessage)];
[email protected]526776c2009-02-07 00:39:26509
[email protected]baf556a2009-09-04 21:34:05510 ssize_t bytes_written = 1;
511 int fd_written = -1;
512
[email protected]157c61b2009-05-01 21:37:31513 if (message_send_bytes_written_ == 0 &&
514 !msg->file_descriptor_set()->empty()) {
515 // This is the first chunk of a message which has descriptors to send
516 struct cmsghdr *cmsg;
517 const unsigned num_fds = msg->file_descriptor_set()->size();
[email protected]526776c2009-02-07 00:39:26518
[email protected]05094a32011-09-01 00:50:13519 DCHECK(num_fds <= FileDescriptorSet::kMaxDescriptorsPerMessage);
[email protected]aac449e2010-06-10 21:39:04520 if (msg->file_descriptor_set()->ContainsDirectoryDescriptor()) {
521 LOG(FATAL) << "Panic: attempting to transport directory descriptor over"
522 " IPC. Aborting to maintain sandbox isolation.";
523 // If you have hit this then something tried to send a file descriptor
524 // to a directory over an IPC channel. Since IPC channels span
525 // sandboxes this is very bad: the receiving process can use openat
526 // with ".." elements in the path in order to reach the real
527 // filesystem.
528 }
[email protected]526776c2009-02-07 00:39:26529
[email protected]157c61b2009-05-01 21:37:31530 msgh.msg_control = buf;
531 msgh.msg_controllen = CMSG_SPACE(sizeof(int) * num_fds);
532 cmsg = CMSG_FIRSTHDR(&msgh);
533 cmsg->cmsg_level = SOL_SOCKET;
534 cmsg->cmsg_type = SCM_RIGHTS;
535 cmsg->cmsg_len = CMSG_LEN(sizeof(int) * num_fds);
536 msg->file_descriptor_set()->GetDescriptors(
537 reinterpret_cast<int*>(CMSG_DATA(cmsg)));
538 msgh.msg_controllen = cmsg->cmsg_len;
[email protected]526776c2009-02-07 00:39:26539
[email protected]168ae922009-12-04 18:08:45540 // DCHECK_LE above already checks that
[email protected]05094a32011-09-01 00:50:13541 // num_fds < kMaxDescriptorsPerMessage so no danger of overflow.
[email protected]168ae922009-12-04 18:08:45542 msg->header()->num_fds = static_cast<uint16>(num_fds);
[email protected]baf556a2009-09-04 21:34:05543
[email protected]e40f5a0b2010-12-08 21:22:24544#if defined(IPC_USES_READWRITE)
[email protected]d805c6a2012-03-08 12:30:28545 if (!IsHelloMessage(*msg)) {
[email protected]baf556a2009-09-04 21:34:05546 // Only the Hello message sends the file descriptor with the message.
547 // Subsequently, we can send file descriptors on the dedicated
548 // fd_pipe_ which makes Seccomp sandbox operation more efficient.
549 struct iovec fd_pipe_iov = { const_cast<char *>(""), 1 };
550 msgh.msg_iov = &fd_pipe_iov;
551 fd_written = fd_pipe_;
552 bytes_written = HANDLE_EINTR(sendmsg(fd_pipe_, &msgh, MSG_DONTWAIT));
553 msgh.msg_iov = &iov;
554 msgh.msg_controllen = 0;
555 if (bytes_written > 0) {
556 msg->file_descriptor_set()->CommitAll();
557 }
558 }
[email protected]22b42c52010-12-20 06:59:23559#endif // IPC_USES_READWRITE
[email protected]157c61b2009-05-01 21:37:31560 }
561
[email protected]baf556a2009-09-04 21:34:05562 if (bytes_written == 1) {
563 fd_written = pipe_;
[email protected]e40f5a0b2010-12-08 21:22:24564#if defined(IPC_USES_READWRITE)
[email protected]d805c6a2012-03-08 12:30:28565 if ((mode_ & MODE_CLIENT_FLAG) && IsHelloMessage(*msg)) {
[email protected]7ee1a44c2010-07-23 14:18:59566 DCHECK_EQ(msg->file_descriptor_set()->size(), 1U);
[email protected]baf556a2009-09-04 21:34:05567 }
[email protected]22b42c52010-12-20 06:59:23568 if (!msgh.msg_controllen) {
[email protected]baf556a2009-09-04 21:34:05569 bytes_written = HANDLE_EINTR(write(pipe_, out_bytes, amt_to_write));
570 } else
[email protected]22b42c52010-12-20 06:59:23571#endif // IPC_USES_READWRITE
[email protected]baf556a2009-09-04 21:34:05572 {
573 bytes_written = HANDLE_EINTR(sendmsg(pipe_, &msgh, MSG_DONTWAIT));
574 }
575 }
[email protected]157c61b2009-05-01 21:37:31576 if (bytes_written > 0)
577 msg->file_descriptor_set()->CommitAll();
[email protected]fa95fc92008-12-08 18:10:14578
[email protected]86c3d9e2009-12-08 14:48:08579 if (bytes_written < 0 && !SocketWriteErrorIsRecoverable()) {
[email protected]cb38c0b22009-05-27 18:29:48580#if defined(OS_MACOSX)
581 // On OSX writing to a pipe with no listener returns EPERM.
582 if (errno == EPERM) {
583 Close();
584 return false;
585 }
586#endif // OS_MACOSX
[email protected]7bf54f5e2009-10-23 01:48:21587 if (errno == EPIPE) {
588 Close();
589 return false;
590 }
[email protected]780ae942009-12-03 13:35:46591 PLOG(ERROR) << "pipe error on "
592 << fd_written
[email protected]9fbc2f2f2011-02-11 08:43:52593 << " Currently writing message of size: "
[email protected]86c3d9e2009-12-08 14:48:08594 << msg->size();
[email protected]fa95fc92008-12-08 18:10:14595 return false;
596 }
597
598 if (static_cast<size_t>(bytes_written) != amt_to_write) {
[email protected]3d1b6662009-01-29 17:03:11599 if (bytes_written > 0) {
600 // If write() fails with EAGAIN then bytes_written will be -1.
601 message_send_bytes_written_ += bytes_written;
602 }
[email protected]fa95fc92008-12-08 18:10:14603
604 // Tell libevent to call us back once things are unblocked.
[email protected]e45e6c02008-12-15 22:02:17605 is_blocked_on_write_ = true;
606 MessageLoopForIO::current()->WatchFileDescriptor(
607 pipe_,
608 false, // One shot
609 MessageLoopForIO::WATCH_WRITE,
610 &write_watcher_,
611 this);
[email protected]3d1b6662009-01-29 17:03:11612 return true;
[email protected]fa95fc92008-12-08 18:10:14613 } else {
614 message_send_bytes_written_ = 0;
615
616 // Message sent OK!
[email protected]2a9d601b2010-10-19 23:50:00617 DVLOG(2) << "sent message @" << msg << " on channel @" << this
[email protected]5484722e2010-12-09 01:13:12618 << " with type " << msg->type() << " on fd " << pipe_;
[email protected]baf556a2009-09-04 21:34:05619 delete output_queue_.front();
[email protected]fa95fc92008-12-08 18:10:14620 output_queue_.pop();
[email protected]fa95fc92008-12-08 18:10:14621 }
622 }
623 return true;
624}
625
[email protected]514411fc2008-12-10 22:28:11626bool Channel::ChannelImpl::Send(Message* message) {
[email protected]2a9d601b2010-10-19 23:50:00627 DVLOG(2) << "sending message @" << message << " on channel @" << this
628 << " with type " << message->type()
629 << " (" << output_queue_.size() << " in queue)";
[email protected]fa95fc92008-12-08 18:10:14630
[email protected]4c2c1db2009-03-20 20:56:55631#ifdef IPC_MESSAGE_LOG_ENABLED
[email protected]8e8bb6d2010-12-13 08:18:55632 Logging::GetInstance()->OnSendMessage(message, "");
[email protected]22b42c52010-12-20 06:59:23633#endif // IPC_MESSAGE_LOG_ENABLED
[email protected]fa95fc92008-12-08 18:10:14634
[email protected]2c391df2012-09-18 03:41:29635 message->TraceMessageBegin();
[email protected]fa95fc92008-12-08 18:10:14636 output_queue_.push(message);
[email protected]22b42c52010-12-20 06:59:23637 if (!is_blocked_on_write_ && !waiting_connect_) {
638 return ProcessOutgoingMessages();
[email protected]fa95fc92008-12-08 18:10:14639 }
640
641 return true;
642}
643
[email protected]2ce26c432011-09-19 17:08:12644int Channel::ChannelImpl::GetClientFileDescriptor() {
645 base::AutoLock lock(client_pipe_lock_);
[email protected]cc8f1462009-06-12 17:36:55646 return client_pipe_;
[email protected]df3c1ca12008-12-19 21:37:01647}
648
[email protected]2ce26c432011-09-19 17:08:12649int Channel::ChannelImpl::TakeClientFileDescriptor() {
650 base::AutoLock lock(client_pipe_lock_);
651 int fd = client_pipe_;
652 if (client_pipe_ != -1) {
653 PipeMap::GetInstance()->Remove(pipe_name_);
654 client_pipe_ = -1;
655 }
656 return fd;
657}
658
659void Channel::ChannelImpl::CloseClientFileDescriptor() {
660 base::AutoLock lock(client_pipe_lock_);
661 if (client_pipe_ != -1) {
662 PipeMap::GetInstance()->Remove(pipe_name_);
663 if (HANDLE_EINTR(close(client_pipe_)) < 0)
664 PLOG(ERROR) << "close " << pipe_name_;
665 client_pipe_ = -1;
666 }
667}
668
[email protected]22b42c52010-12-20 06:59:23669bool Channel::ChannelImpl::AcceptsConnections() const {
670 return server_listen_pipe_ != -1;
671}
[email protected]9a44a4db62010-12-20 06:19:07672
[email protected]22b42c52010-12-20 06:59:23673bool Channel::ChannelImpl::HasAcceptedConnection() const {
674 return AcceptsConnections() && pipe_ != -1;
675}
[email protected]9a44a4db62010-12-20 06:19:07676
[email protected]8ec3fbe2011-04-06 12:01:44677bool Channel::ChannelImpl::GetClientEuid(uid_t* client_euid) const {
678 DCHECK(HasAcceptedConnection());
[email protected]4af5ef42011-10-18 17:46:22679#if defined(OS_MACOSX) || defined(OS_OPENBSD)
[email protected]8ec3fbe2011-04-06 12:01:44680 uid_t peer_euid;
681 gid_t peer_gid;
682 if (getpeereid(pipe_, &peer_euid, &peer_gid) != 0) {
683 PLOG(ERROR) << "getpeereid " << pipe_;
684 return false;
685 }
686 *client_euid = peer_euid;
687 return true;
[email protected]94f8c952011-06-25 04:54:41688#elif defined(OS_SOLARIS)
689 return false;
[email protected]8ec3fbe2011-04-06 12:01:44690#else
691 struct ucred cred;
692 socklen_t cred_len = sizeof(cred);
693 if (getsockopt(pipe_, SOL_SOCKET, SO_PEERCRED, &cred, &cred_len) != 0) {
694 PLOG(ERROR) << "getsockopt " << pipe_;
695 return false;
696 }
[email protected]11307022012-01-25 23:53:06697 if (static_cast<unsigned>(cred_len) < sizeof(cred)) {
[email protected]8ec3fbe2011-04-06 12:01:44698 NOTREACHED() << "Truncated ucred from SO_PEERCRED?";
699 return false;
700 }
701 *client_euid = cred.uid;
702 return true;
703#endif
704}
705
[email protected]22b42c52010-12-20 06:59:23706void Channel::ChannelImpl::ResetToAcceptingConnectionState() {
707 // Unregister libevent for the unix domain socket and close it.
708 read_watcher_.StopWatchingFileDescriptor();
709 write_watcher_.StopWatchingFileDescriptor();
710 if (pipe_ != -1) {
711 if (HANDLE_EINTR(close(pipe_)) < 0)
712 PLOG(ERROR) << "close pipe_ " << pipe_name_;
713 pipe_ = -1;
714 }
715#if defined(IPC_USES_READWRITE)
716 if (fd_pipe_ != -1) {
717 if (HANDLE_EINTR(close(fd_pipe_)) < 0)
718 PLOG(ERROR) << "close fd_pipe_ " << pipe_name_;
719 fd_pipe_ = -1;
720 }
721 if (remote_fd_pipe_ != -1) {
722 if (HANDLE_EINTR(close(remote_fd_pipe_)) < 0)
723 PLOG(ERROR) << "close remote_fd_pipe_ " << pipe_name_;
724 remote_fd_pipe_ = -1;
725 }
726#endif // IPC_USES_READWRITE
[email protected]c7f91e82010-12-20 06:39:44727
[email protected]22b42c52010-12-20 06:59:23728 while (!output_queue_.empty()) {
729 Message* m = output_queue_.front();
730 output_queue_.pop();
731 delete m;
[email protected]c7f91e82010-12-20 06:39:44732 }
733
[email protected]22b42c52010-12-20 06:59:23734 // Close any outstanding, received file descriptors.
[email protected]334f3022012-02-29 22:48:14735 ClearInputFDs();
[email protected]22b42c52010-12-20 06:59:23736}
737
[email protected]313c00e52011-08-09 06:46:06738// static
739bool Channel::ChannelImpl::IsNamedServerInitialized(
740 const std::string& channel_id) {
[email protected]6d4b67a2013-02-10 04:49:30741 return file_util::PathExists(base::FilePath(channel_id));
[email protected]313c00e52011-08-09 06:46:06742}
743
[email protected]e1d67a882011-08-31 21:11:04744#if defined(OS_LINUX)
745// static
746void Channel::ChannelImpl::SetGlobalPid(int pid) {
747 global_pid_ = pid;
748}
749#endif // OS_LINUX
750
[email protected]22b42c52010-12-20 06:59:23751// Called by libevent when we can read from the pipe without blocking.
752void Channel::ChannelImpl::OnFileCanReadWithoutBlocking(int fd) {
753 bool send_server_hello_msg = false;
754 if (fd == server_listen_pipe_) {
755 int new_pipe = 0;
756 if (!ServerAcceptConnection(server_listen_pipe_, &new_pipe)) {
[email protected]c7f91e82010-12-20 06:39:44757 Close();
[email protected]d805c6a2012-03-08 12:30:28758 listener()->OnChannelListenError();
[email protected]22b42c52010-12-20 06:59:23759 }
760
761 if (pipe_ != -1) {
762 // We already have a connection. We only handle one at a time.
763 // close our new descriptor.
764 if (HANDLE_EINTR(shutdown(new_pipe, SHUT_RDWR)) < 0)
[email protected]334f3022012-02-29 22:48:14765 DPLOG(ERROR) << "shutdown " << pipe_name_;
[email protected]22b42c52010-12-20 06:59:23766 if (HANDLE_EINTR(close(new_pipe)) < 0)
[email protected]334f3022012-02-29 22:48:14767 DPLOG(ERROR) << "close " << pipe_name_;
[email protected]d805c6a2012-03-08 12:30:28768 listener()->OnChannelDenied();
[email protected]c7f91e82010-12-20 06:39:44769 return;
[email protected]9a44a4db62010-12-20 06:19:07770 }
[email protected]22b42c52010-12-20 06:59:23771 pipe_ = new_pipe;
772
[email protected]8ec3fbe2011-04-06 12:01:44773 if ((mode_ & MODE_OPEN_ACCESS_FLAG) == 0) {
774 // Verify that the IPC channel peer is running as the same user.
775 uid_t client_euid;
776 if (!GetClientEuid(&client_euid)) {
[email protected]334f3022012-02-29 22:48:14777 DLOG(ERROR) << "Unable to query client euid";
[email protected]8ec3fbe2011-04-06 12:01:44778 ResetToAcceptingConnectionState();
779 return;
780 }
781 if (client_euid != geteuid()) {
[email protected]334f3022012-02-29 22:48:14782 DLOG(WARNING) << "Client euid is not authorised";
[email protected]8ec3fbe2011-04-06 12:01:44783 ResetToAcceptingConnectionState();
784 return;
785 }
786 }
787
[email protected]22b42c52010-12-20 06:59:23788 if (!AcceptConnection()) {
789 NOTREACHED() << "AcceptConnection should not fail on server";
790 }
791 send_server_hello_msg = true;
792 waiting_connect_ = false;
793 } else if (fd == pipe_) {
[email protected]1707726c2011-02-03 20:35:09794 if (waiting_connect_ && (mode_ & MODE_SERVER_FLAG)) {
[email protected]22b42c52010-12-20 06:59:23795 send_server_hello_msg = true;
796 waiting_connect_ = false;
797 }
798 if (!ProcessIncomingMessages()) {
[email protected]887250a2011-02-28 20:30:47799 // ClosePipeOnError may delete this object, so we mustn't call
800 // ProcessOutgoingMessages.
801 send_server_hello_msg = false;
[email protected]22b42c52010-12-20 06:59:23802 ClosePipeOnError();
803 }
804 } else {
805 NOTREACHED() << "Unknown pipe " << fd;
[email protected]fa95fc92008-12-08 18:10:14806 }
807
808 // If we're a server and handshaking, then we want to make sure that we
809 // only send our handshake message after we've processed the client's.
810 // This gives us a chance to kill the client if the incoming handshake
811 // is invalid.
812 if (send_server_hello_msg) {
813 ProcessOutgoingMessages();
814 }
815}
816
817// Called by libevent when we can write to the pipe without blocking.
[email protected]e45e6c02008-12-15 22:02:17818void Channel::ChannelImpl::OnFileCanWriteWithoutBlocking(int fd) {
[email protected]60ea6052011-04-18 20:07:08819 DCHECK_EQ(pipe_, fd);
[email protected]22b42c52010-12-20 06:59:23820 is_blocked_on_write_ = false;
[email protected]fa95fc92008-12-08 18:10:14821 if (!ProcessOutgoingMessages()) {
[email protected]22b42c52010-12-20 06:59:23822 ClosePipeOnError();
[email protected]9a44a4db62010-12-20 06:19:07823 }
824}
825
[email protected]22b42c52010-12-20 06:59:23826bool Channel::ChannelImpl::AcceptConnection() {
827 MessageLoopForIO::current()->WatchFileDescriptor(pipe_,
828 true,
829 MessageLoopForIO::WATCH_READ,
830 &read_watcher_,
831 this);
832 QueueHelloMessage();
833
[email protected]1707726c2011-02-03 20:35:09834 if (mode_ & MODE_CLIENT_FLAG) {
[email protected]22b42c52010-12-20 06:59:23835 // If we are a client we want to send a hello message out immediately.
836 // In server mode we will send a hello message when we receive one from a
837 // client.
838 waiting_connect_ = false;
839 return ProcessOutgoingMessages();
[email protected]1707726c2011-02-03 20:35:09840 } else if (mode_ & MODE_SERVER_FLAG) {
[email protected]22b42c52010-12-20 06:59:23841 waiting_connect_ = true;
842 return true;
[email protected]1707726c2011-02-03 20:35:09843 } else {
844 NOTREACHED();
845 return false;
[email protected]22b42c52010-12-20 06:59:23846 }
847}
848
849void Channel::ChannelImpl::ClosePipeOnError() {
850 if (HasAcceptedConnection()) {
851 ResetToAcceptingConnectionState();
[email protected]d805c6a2012-03-08 12:30:28852 listener()->OnChannelError();
[email protected]22b42c52010-12-20 06:59:23853 } else {
854 Close();
855 if (AcceptsConnections()) {
[email protected]d805c6a2012-03-08 12:30:28856 listener()->OnChannelListenError();
[email protected]22b42c52010-12-20 06:59:23857 } else {
[email protected]d805c6a2012-03-08 12:30:28858 listener()->OnChannelError();
[email protected]22b42c52010-12-20 06:59:23859 }
860 }
861}
862
[email protected]e1d67a882011-08-31 21:11:04863int Channel::ChannelImpl::GetHelloMessageProcId() {
864 int pid = base::GetCurrentProcId();
865#if defined(OS_LINUX)
866 // Our process may be in a sandbox with a separate PID namespace.
867 if (global_pid_) {
868 pid = global_pid_;
869 }
870#endif
871 return pid;
872}
873
[email protected]22b42c52010-12-20 06:59:23874void Channel::ChannelImpl::QueueHelloMessage() {
875 // Create the Hello message
876 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
877 HELLO_MESSAGE_TYPE,
878 IPC::Message::PRIORITY_NORMAL));
[email protected]e1d67a882011-08-31 21:11:04879 if (!msg->WriteInt(GetHelloMessageProcId())) {
[email protected]22b42c52010-12-20 06:59:23880 NOTREACHED() << "Unable to pickle hello message proc id";
881 }
882#if defined(IPC_USES_READWRITE)
883 scoped_ptr<Message> hello;
884 if (remote_fd_pipe_ != -1) {
885 if (!msg->WriteFileDescriptor(base::FileDescriptor(remote_fd_pipe_,
886 false))) {
887 NOTREACHED() << "Unable to pickle hello message file descriptors";
888 }
889 DCHECK_EQ(msg->file_descriptor_set()->size(), 1U);
890 }
891#endif // IPC_USES_READWRITE
892 output_queue_.push(msg.release());
893}
894
[email protected]3d5a60b2012-03-01 21:41:47895Channel::ChannelImpl::ReadState Channel::ChannelImpl::ReadData(
896 char* buffer,
897 int buffer_len,
898 int* bytes_read) {
899 if (pipe_ == -1)
900 return READ_FAILED;
901
[email protected]334f3022012-02-29 22:48:14902 struct msghdr msg = {0};
903
[email protected]3fcbd4b2012-06-05 01:54:46904 struct iovec iov = {buffer, static_cast<size_t>(buffer_len)};
[email protected]334f3022012-02-29 22:48:14905 msg.msg_iov = &iov;
906 msg.msg_iovlen = 1;
907
908 msg.msg_control = input_cmsg_buf_;
909
910 // recvmsg() returns 0 if the connection has closed or EAGAIN if no data
911 // is waiting on the pipe.
[email protected]334f3022012-02-29 22:48:14912#if defined(IPC_USES_READWRITE)
913 if (fd_pipe_ >= 0) {
[email protected]3d5a60b2012-03-01 21:41:47914 *bytes_read = HANDLE_EINTR(read(pipe_, buffer, buffer_len));
[email protected]334f3022012-02-29 22:48:14915 msg.msg_controllen = 0;
916 } else
917#endif // IPC_USES_READWRITE
918 {
919 msg.msg_controllen = sizeof(input_cmsg_buf_);
[email protected]3d5a60b2012-03-01 21:41:47920 *bytes_read = HANDLE_EINTR(recvmsg(pipe_, &msg, MSG_DONTWAIT));
[email protected]334f3022012-02-29 22:48:14921 }
[email protected]3d5a60b2012-03-01 21:41:47922 if (*bytes_read < 0) {
[email protected]334f3022012-02-29 22:48:14923 if (errno == EAGAIN) {
[email protected]3d5a60b2012-03-01 21:41:47924 return READ_PENDING;
[email protected]334f3022012-02-29 22:48:14925#if defined(OS_MACOSX)
926 } else if (errno == EPERM) {
927 // On OSX, reading from a pipe with no listener returns EPERM
928 // treat this as a special case to prevent spurious error messages
929 // to the console.
[email protected]3d5a60b2012-03-01 21:41:47930 return READ_FAILED;
[email protected]334f3022012-02-29 22:48:14931#endif // OS_MACOSX
932 } else if (errno == ECONNRESET || errno == EPIPE) {
[email protected]3d5a60b2012-03-01 21:41:47933 return READ_FAILED;
[email protected]334f3022012-02-29 22:48:14934 } else {
935 PLOG(ERROR) << "pipe error (" << pipe_ << ")";
[email protected]3d5a60b2012-03-01 21:41:47936 return READ_FAILED;
[email protected]334f3022012-02-29 22:48:14937 }
[email protected]3d5a60b2012-03-01 21:41:47938 } else if (*bytes_read == 0) {
[email protected]334f3022012-02-29 22:48:14939 // The pipe has closed...
[email protected]3d5a60b2012-03-01 21:41:47940 return READ_FAILED;
[email protected]334f3022012-02-29 22:48:14941 }
[email protected]3d5a60b2012-03-01 21:41:47942 DCHECK(*bytes_read);
[email protected]334f3022012-02-29 22:48:14943
944 CloseClientFileDescriptor();
945
946 // Read any file descriptors from the message.
947 if (!ExtractFileDescriptorsFromMsghdr(&msg))
[email protected]3d5a60b2012-03-01 21:41:47948 return READ_FAILED;
949 return READ_SUCCEEDED;
[email protected]334f3022012-02-29 22:48:14950}
951
952#if defined(IPC_USES_READWRITE)
953bool Channel::ChannelImpl::ReadFileDescriptorsFromFDPipe() {
954 char dummy;
955 struct iovec fd_pipe_iov = { &dummy, 1 };
956
957 struct msghdr msg = { 0 };
958 msg.msg_iov = &fd_pipe_iov;
959 msg.msg_iovlen = 1;
960 msg.msg_control = input_cmsg_buf_;
961 msg.msg_controllen = sizeof(input_cmsg_buf_);
962 ssize_t bytes_received = HANDLE_EINTR(recvmsg(fd_pipe_, &msg, MSG_DONTWAIT));
963
964 if (bytes_received != 1)
965 return true; // No message waiting.
966
967 if (!ExtractFileDescriptorsFromMsghdr(&msg))
968 return false;
969 return true;
970}
971#endif
972
[email protected]d805c6a2012-03-08 12:30:28973// On Posix, we need to fix up the file descriptors before the input message
974// is dispatched.
975//
976// This will read from the input_fds_ (READWRITE mode only) and read more
977// handles from the FD pipe if necessary.
[email protected]3d5a60b2012-03-01 21:41:47978bool Channel::ChannelImpl::WillDispatchInputMessage(Message* msg) {
[email protected]334f3022012-02-29 22:48:14979 uint16 header_fds = msg->header()->num_fds;
980 if (!header_fds)
981 return true; // Nothing to do.
982
983 // The message has file descriptors.
984 const char* error = NULL;
985 if (header_fds > input_fds_.size()) {
986 // The message has been completely received, but we didn't get
987 // enough file descriptors.
988#if defined(IPC_USES_READWRITE)
989 if (!ReadFileDescriptorsFromFDPipe())
990 return false;
991 if (header_fds > input_fds_.size())
992#endif // IPC_USES_READWRITE
993 error = "Message needs unreceived descriptors";
994 }
995
996 if (header_fds > FileDescriptorSet::kMaxDescriptorsPerMessage)
997 error = "Message requires an excessive number of descriptors";
998
999 if (error) {
1000 LOG(WARNING) << error
1001 << " channel:" << this
1002 << " message-type:" << msg->type()
1003 << " header()->num_fds:" << header_fds;
1004#if defined(CHROMIUM_SELINUX)
1005 LOG(WARNING) << "In the case of SELinux this can be caused when "
1006 "using a --user-data-dir to which the default "
1007 "policy doesn't give the renderer access to. ";
1008#endif // CHROMIUM_SELINUX
1009 // Abort the connection.
1010 ClearInputFDs();
1011 return false;
1012 }
1013
[email protected]7e9eecb62012-04-09 21:40:441014 // The shenaniganery below with &foo.front() requires input_fds_ to have
1015 // contiguous underlying storage (such as a simple array or a std::vector).
1016 // This is why the header warns not to make input_fds_ a deque<>.
[email protected]334f3022012-02-29 22:48:141017 msg->file_descriptor_set()->SetDescriptors(&input_fds_.front(),
1018 header_fds);
1019 input_fds_.erase(input_fds_.begin(), input_fds_.begin() + header_fds);
1020 return true;
1021}
1022
[email protected]3d5a60b2012-03-01 21:41:471023bool Channel::ChannelImpl::DidEmptyInputBuffers() {
1024 // When the input data buffer is empty, the fds should be too. If this is
1025 // not the case, we probably have a rogue renderer which is trying to fill
1026 // our descriptor table.
1027 return input_fds_.empty();
1028}
1029
[email protected]334f3022012-02-29 22:48:141030bool Channel::ChannelImpl::ExtractFileDescriptorsFromMsghdr(msghdr* msg) {
1031 // Check that there are any control messages. On OSX, CMSG_FIRSTHDR will
1032 // return an invalid non-NULL pointer in the case that controllen == 0.
1033 if (msg->msg_controllen == 0)
1034 return true;
1035
1036 for (cmsghdr* cmsg = CMSG_FIRSTHDR(msg);
1037 cmsg;
1038 cmsg = CMSG_NXTHDR(msg, cmsg)) {
1039 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
1040 unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0);
1041 DCHECK_EQ(0U, payload_len % sizeof(int));
1042 const int* file_descriptors = reinterpret_cast<int*>(CMSG_DATA(cmsg));
1043 unsigned num_file_descriptors = payload_len / 4;
1044 input_fds_.insert(input_fds_.end(),
1045 file_descriptors,
1046 file_descriptors + num_file_descriptors);
1047
1048 // Check this after adding the FDs so we don't leak them.
1049 if (msg->msg_flags & MSG_CTRUNC) {
1050 ClearInputFDs();
1051 return false;
1052 }
1053
1054 return true;
1055 }
1056 }
1057
1058 // No file descriptors found, but that's OK.
1059 return true;
1060}
1061
1062void Channel::ChannelImpl::ClearInputFDs() {
[email protected]7e9eecb62012-04-09 21:40:441063 for (size_t i = 0; i < input_fds_.size(); ++i) {
1064 if (HANDLE_EINTR(close(input_fds_[i])) < 0)
[email protected]334f3022012-02-29 22:48:141065 PLOG(ERROR) << "close ";
[email protected]334f3022012-02-29 22:48:141066 }
[email protected]7e9eecb62012-04-09 21:40:441067 input_fds_.clear();
[email protected]334f3022012-02-29 22:48:141068}
1069
1070void Channel::ChannelImpl::HandleHelloMessage(const Message& msg) {
1071 // The Hello message contains only the process id.
[email protected]ce208f872012-03-07 20:42:561072 PickleIterator iter(msg);
[email protected]334f3022012-02-29 22:48:141073 int pid;
1074 if (!msg.ReadInt(&iter, &pid))
1075 NOTREACHED();
1076
1077#if defined(IPC_USES_READWRITE)
1078 if (mode_ & MODE_SERVER_FLAG) {
1079 // With IPC_USES_READWRITE, the Hello message from the client to the
1080 // server also contains the fd_pipe_, which will be used for all
1081 // subsequent file descriptor passing.
1082 DCHECK_EQ(msg.file_descriptor_set()->size(), 1U);
1083 base::FileDescriptor descriptor;
1084 if (!msg.ReadFileDescriptor(&iter, &descriptor)) {
1085 NOTREACHED();
1086 }
1087 fd_pipe_ = descriptor.fd;
1088 CHECK(descriptor.auto_close);
1089 }
1090#endif // IPC_USES_READWRITE
[email protected]0a6fc4b2012-04-05 02:38:341091 peer_pid_ = pid;
[email protected]d805c6a2012-03-08 12:30:281092 listener()->OnChannelConnected(pid);
[email protected]334f3022012-02-29 22:48:141093}
1094
[email protected]514411fc2008-12-10 22:28:111095void Channel::ChannelImpl::Close() {
[email protected]fa95fc92008-12-08 18:10:141096 // Close can be called multiple time, so we need to make sure we're
1097 // idempotent.
1098
[email protected]22b42c52010-12-20 06:59:231099 ResetToAcceptingConnectionState();
[email protected]fa95fc92008-12-08 18:10:141100
[email protected]22b42c52010-12-20 06:59:231101 if (must_unlink_) {
1102 unlink(pipe_name_.c_str());
1103 must_unlink_ = false;
1104 }
[email protected]fa95fc92008-12-08 18:10:141105 if (server_listen_pipe_ != -1) {
[email protected]70eb6572010-06-23 00:37:461106 if (HANDLE_EINTR(close(server_listen_pipe_)) < 0)
[email protected]334f3022012-02-29 22:48:141107 DPLOG(ERROR) << "close " << server_listen_pipe_;
[email protected]fa95fc92008-12-08 18:10:141108 server_listen_pipe_ = -1;
[email protected]22b42c52010-12-20 06:59:231109 // Unregister libevent for the listening socket and close it.
1110 server_listen_connection_watcher_.StopWatchingFileDescriptor();
[email protected]fa95fc92008-12-08 18:10:141111 }
1112
[email protected]2ce26c432011-09-19 17:08:121113 CloseClientFileDescriptor();
[email protected]fa95fc92008-12-08 18:10:141114}
1115
[email protected]514411fc2008-12-10 22:28:111116//------------------------------------------------------------------------------
1117// Channel's methods simply call through to ChannelImpl.
[email protected]42ce94e2010-12-08 19:28:091118Channel::Channel(const IPC::ChannelHandle& channel_handle, Mode mode,
[email protected]514411fc2008-12-10 22:28:111119 Listener* listener)
[email protected]42ce94e2010-12-08 19:28:091120 : channel_impl_(new ChannelImpl(channel_handle, mode, listener)) {
[email protected]514411fc2008-12-10 22:28:111121}
1122
1123Channel::~Channel() {
1124 delete channel_impl_;
1125}
1126
1127bool Channel::Connect() {
1128 return channel_impl_->Connect();
1129}
1130
1131void Channel::Close() {
[email protected]5fc7ec592012-05-16 18:58:321132 if (channel_impl_)
1133 channel_impl_->Close();
[email protected]514411fc2008-12-10 22:28:111134}
1135
[email protected]0a6fc4b2012-04-05 02:38:341136base::ProcessId Channel::peer_pid() const {
1137 return channel_impl_->peer_pid();
1138}
1139
[email protected]514411fc2008-12-10 22:28:111140bool Channel::Send(Message* message) {
1141 return channel_impl_->Send(message);
1142}
1143
[email protected]cc8f1462009-06-12 17:36:551144int Channel::GetClientFileDescriptor() const {
1145 return channel_impl_->GetClientFileDescriptor();
[email protected]df3c1ca12008-12-19 21:37:011146}
1147
[email protected]2ce26c432011-09-19 17:08:121148int Channel::TakeClientFileDescriptor() {
1149 return channel_impl_->TakeClientFileDescriptor();
1150}
1151
[email protected]22b42c52010-12-20 06:59:231152bool Channel::AcceptsConnections() const {
1153 return channel_impl_->AcceptsConnections();
1154}
1155
1156bool Channel::HasAcceptedConnection() const {
1157 return channel_impl_->HasAcceptedConnection();
1158}
1159
[email protected]8ec3fbe2011-04-06 12:01:441160bool Channel::GetClientEuid(uid_t* client_euid) const {
1161 return channel_impl_->GetClientEuid(client_euid);
1162}
1163
[email protected]22b42c52010-12-20 06:59:231164void Channel::ResetToAcceptingConnectionState() {
1165 channel_impl_->ResetToAcceptingConnectionState();
1166}
1167
[email protected]313c00e52011-08-09 06:46:061168// static
1169bool Channel::IsNamedServerInitialized(const std::string& channel_id) {
1170 return ChannelImpl::IsNamedServerInitialized(channel_id);
1171}
1172
[email protected]5c41e6e12012-03-17 02:20:461173// static
1174std::string Channel::GenerateVerifiedChannelID(const std::string& prefix) {
1175 // A random name is sufficient validation on posix systems, so we don't need
1176 // an additional shared secret.
1177
1178 std::string id = prefix;
1179 if (!id.empty())
1180 id.append(".");
1181
1182 return id.append(GenerateUniqueRandomChannelID());
1183}
1184
1185
[email protected]e1d67a882011-08-31 21:11:041186#if defined(OS_LINUX)
1187// static
1188void Channel::SetGlobalPid(int pid) {
1189 ChannelImpl::SetGlobalPid(pid);
1190}
1191#endif // OS_LINUX
1192
[email protected]d4651ff2008-12-02 16:51:581193} // namespace IPC