blob: aac7e795257a4f0933e3ede563b5b989eedd01cd [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]3fcbd4b2012-06-05 01:54:4613#include <unistd.h>
[email protected]e45e6c02008-12-15 22:02:1714
[email protected]4af5ef42011-10-18 17:46:2215#if defined(OS_OPENBSD)
16#include <sys/uio.h>
17#endif
18
hidehiko853d6082014-11-05 23:51:5219#if !defined(OS_NACL_NONSFI)
hidehikoc2eec0d2014-10-24 03:49:2720#include <sys/un.h>
21#endif
22
[email protected]e8fce882009-01-20 22:02:5823#include <map>
[email protected]57999812013-02-24 05:40:5224#include <string>
[email protected]e8fce882009-01-20 22:02:5825
[email protected]df3c1ca12008-12-19 21:37:0126#include "base/command_line.h"
[email protected]57999812013-02-24 05:40:5227#include "base/files/file_path.h"
thestigc9e38a22014-09-13 01:02:1128#include "base/files/file_util.h"
[email protected]c62dd9d2011-09-21 18:05:4129#include "base/location.h"
[email protected]fa95fc92008-12-08 18:10:1430#include "base/logging.h"
[email protected]3b63f8f42011-03-28 01:54:1531#include "base/memory/scoped_ptr.h"
32#include "base/memory/singleton.h"
[email protected]2025d002012-11-14 20:54:3533#include "base/posix/eintr_wrapper.h"
[email protected]613eef62012-11-09 23:46:5434#include "base/posix/global_descriptors.h"
[email protected]e66ef602013-07-24 05:15:2435#include "base/process/process_handle.h"
[email protected]5c41e6e12012-03-17 02:20:4636#include "base/rand_util.h"
[email protected]7286e3fc2011-07-19 22:13:2437#include "base/stl_util.h"
[email protected]4aa794a12013-06-11 06:32:1838#include "base/strings/string_util.h"
[email protected]20305ec2011-01-21 04:55:5239#include "base/synchronization/lock.h"
[email protected]4e07f842012-11-15 22:22:1740#include "ipc/ipc_descriptors.h"
41#include "ipc/ipc_listener.h"
[email protected]946d1b22009-07-22 23:57:2142#include "ipc/ipc_logging.h"
morrita4b5c28e22015-01-14 21:17:0643#include "ipc/ipc_message_attachment_set.h"
[email protected]946d1b22009-07-22 23:57:2144#include "ipc/ipc_message_utils.h"
morrita1aa788c2015-01-31 05:45:4245#include "ipc/ipc_platform_file_attachment_posix.h"
[email protected]4e07f842012-11-15 22:22:1746#include "ipc/ipc_switches.h"
[email protected]bdf9bdc2013-03-13 04:23:1047#include "ipc/unix_domain_socket_util.h"
[email protected]d4651ff2008-12-02 16:51:5848
49namespace IPC {
50
[email protected]5f594c02009-05-01 22:37:5951// IPC channels on Windows use named pipes (CreateNamedPipe()) with
[email protected]22b42c52010-12-20 06:59:2352// channel ids as the pipe names. Channels on POSIX use sockets as
53// pipes These don't quite line up.
[email protected]5f594c02009-05-01 22:37:5954//
[email protected]22b42c52010-12-20 06:59:2355// When creating a child subprocess we use a socket pair and the parent side of
56// the fork arranges it such that the initial control channel ends up on the
[email protected]cc8f1462009-06-12 17:36:5557// magic file descriptor kPrimaryIPCChannel in the child. Future
[email protected]5f594c02009-05-01 22:37:5958// connections (file descriptors) can then be passed via that
59// connection via sendmsg().
[email protected]22b42c52010-12-20 06:59:2360//
61// A POSIX IPC channel can also be set up as a server for a bound UNIX domain
62// socket, and will handle multiple connect and disconnect sequences. Currently
63// it is limited to one connection at a time.
[email protected]5f594c02009-05-01 22:37:5964
[email protected]fa95fc92008-12-08 18:10:1465//------------------------------------------------------------------------------
[email protected]fa95fc92008-12-08 18:10:1466namespace {
67
[email protected]5f594c02009-05-01 22:37:5968// The PipeMap class works around this quirk related to unit tests:
[email protected]e8fce882009-01-20 22:02:5869//
[email protected]5f594c02009-05-01 22:37:5970// When running as a server, we install the client socket in a
[email protected]cc8f1462009-06-12 17:36:5571// specific file descriptor number (@kPrimaryIPCChannel). However, we
[email protected]5f594c02009-05-01 22:37:5972// also have to support the case where we are running unittests in the
73// same process. (We do not support forking without execing.)
[email protected]e8fce882009-01-20 22:02:5874//
75// Case 1: normal running
76// The IPC server object will install a mapping in PipeMap from the
77// name which it was given to the client pipe. When forking the client, the
78// GetClientFileDescriptorMapping will ensure that the socket is installed in
[email protected]cc8f1462009-06-12 17:36:5579// the magic slot (@kPrimaryIPCChannel). The client will search for the
[email protected]e8fce882009-01-20 22:02:5880// mapping, but it won't find any since we are in a new process. Thus the
81// magic fd number is returned. Once the client connects, the server will
[email protected]5f594c02009-05-01 22:37:5982// close its copy of the client socket and remove the mapping.
[email protected]e8fce882009-01-20 22:02:5883//
84// Case 2: unittests - client and server in the same process
85// The IPC server will install a mapping as before. The client will search
86// for a mapping and find out. It duplicates the file descriptor and
87// connects. Once the client connects, the server will close the original
88// copy of the client socket and remove the mapping. Thus, when the client
89// object closes, it will close the only remaining copy of the client socket
90// in the fd table and the server will see EOF on its side.
91//
92// TODO(port): a client process cannot connect to multiple IPC channels with
93// this scheme.
94
95class PipeMap {
96 public:
[email protected]864b5582010-12-04 23:00:1097 static PipeMap* GetInstance() {
98 return Singleton<PipeMap>::get();
99 }
100
[email protected]42ce94e2010-12-08 19:28:09101 ~PipeMap() {
102 // Shouldn't have left over pipes.
[email protected]f6b8ce32011-03-02 00:03:18103 DCHECK(map_.empty());
[email protected]42ce94e2010-12-08 19:28:09104 }
105
[email protected]e8fce882009-01-20 22:02:58106 // Lookup a given channel id. Return -1 if not found.
107 int Lookup(const std::string& channel_id) {
[email protected]20305ec2011-01-21 04:55:52108 base::AutoLock locked(lock_);
[email protected]e8fce882009-01-20 22:02:58109
110 ChannelToFDMap::const_iterator i = map_.find(channel_id);
111 if (i == map_.end())
112 return -1;
113 return i->second;
114 }
115
116 // Remove the mapping for the given channel id. No error is signaled if the
117 // channel_id doesn't exist
[email protected]2ce26c432011-09-19 17:08:12118 void Remove(const std::string& channel_id) {
[email protected]20305ec2011-01-21 04:55:52119 base::AutoLock locked(lock_);
[email protected]2ce26c432011-09-19 17:08:12120 map_.erase(channel_id);
[email protected]e8fce882009-01-20 22:02:58121 }
122
123 // Insert a mapping from @channel_id to @fd. It's a fatal error to insert a
124 // mapping if one already exists for the given channel_id
125 void Insert(const std::string& channel_id, int fd) {
[email protected]20305ec2011-01-21 04:55:52126 base::AutoLock locked(lock_);
[email protected]60ea6052011-04-18 20:07:08127 DCHECK_NE(-1, fd);
[email protected]e8fce882009-01-20 22:02:58128
129 ChannelToFDMap::const_iterator i = map_.find(channel_id);
[email protected]d2e884d2009-06-22 20:37:52130 CHECK(i == map_.end()) << "Creating second IPC server (fd " << fd << ") "
131 << "for '" << channel_id << "' while first "
132 << "(fd " << i->second << ") still exists";
[email protected]e8fce882009-01-20 22:02:58133 map_[channel_id] = fd;
134 }
135
136 private:
[email protected]20305ec2011-01-21 04:55:52137 base::Lock lock_;
[email protected]e8fce882009-01-20 22:02:58138 typedef std::map<std::string, int> ChannelToFDMap;
139 ChannelToFDMap map_;
[email protected]864b5582010-12-04 23:00:10140
141 friend struct DefaultSingletonTraits<PipeMap>;
[email protected]e097b932014-03-19 06:34:52142#if defined(OS_ANDROID)
143 friend void ::IPC::Channel::NotifyProcessForkedForTesting();
144#endif
[email protected]e8fce882009-01-20 22:02:58145};
146
[email protected]df3c1ca12008-12-19 21:37:01147//------------------------------------------------------------------------------
[email protected]fa95fc92008-12-08 18:10:14148
[email protected]86c3d9e2009-12-08 14:48:08149bool SocketWriteErrorIsRecoverable() {
150#if defined(OS_MACOSX)
151 // On OS X if sendmsg() is trying to send fds between processes and there
152 // isn't enough room in the output buffer to send the fd structure over
153 // atomically then EMSGSIZE is returned.
154 //
155 // EMSGSIZE presents a problem since the system APIs can only call us when
156 // there's room in the socket buffer and not when there is "enough" room.
157 //
158 // The current behavior is to return to the event loop when EMSGSIZE is
159 // received and hopefull service another FD. This is however still
160 // technically a busy wait since the event loop will call us right back until
161 // the receiver has read enough data to allow passing the FD over atomically.
162 return errno == EAGAIN || errno == EMSGSIZE;
163#else
164 return errno == EAGAIN;
[email protected]22b42c52010-12-20 06:59:23165#endif // OS_MACOSX
[email protected]86c3d9e2009-12-08 14:48:08166}
167
[email protected]fa95fc92008-12-08 18:10:14168} // namespace
[email protected]e097b932014-03-19 06:34:52169
170#if defined(OS_ANDROID)
171// When we fork for simple tests on Android, we can't 'exec', so we need to
172// reset these entries manually to get the expected testing behavior.
173void Channel::NotifyProcessForkedForTesting() {
174 PipeMap::GetInstance()->map_.clear();
175}
176#endif
177
[email protected]d4651ff2008-12-02 16:51:58178//------------------------------------------------------------------------------
179
perkjdbcac352014-12-11 17:27:58180#if defined(OS_LINUX)
181int ChannelPosix::global_pid_ = 0;
182#endif // OS_LINUX
183
[email protected]2f60c9b2014-06-06 20:13:51184ChannelPosix::ChannelPosix(const IPC::ChannelHandle& channel_handle,
185 Mode mode, Listener* listener)
[email protected]d805c6a2012-03-08 12:30:28186 : ChannelReader(listener),
187 mode_(mode),
[email protected]0a6fc4b2012-04-05 02:38:34188 peer_pid_(base::kNullProcessId),
[email protected]e45e6c02008-12-15 22:02:17189 is_blocked_on_write_(false),
[email protected]22b42c52010-12-20 06:59:23190 waiting_connect_(true),
[email protected]e45e6c02008-12-15 22:02:17191 message_send_bytes_written_(0),
[email protected]22b42c52010-12-20 06:59:23192 pipe_name_(channel_handle.name),
morrita2ad0be42015-01-27 20:05:53193 in_dtor_(false),
[email protected]bf84c582011-08-23 03:17:02194 must_unlink_(false) {
[email protected]df60edb2011-06-21 22:48:29195 memset(input_cmsg_buf_, 0, sizeof(input_cmsg_buf_));
[email protected]1707726c2011-02-03 20:35:09196 if (!CreatePipe(channel_handle)) {
[email protected]22b42c52010-12-20 06:59:23197 // The pipe may have been closed already.
[email protected]1707726c2011-02-03 20:35:09198 const char *modestr = (mode_ & MODE_SERVER_FLAG) ? "server" : "client";
[email protected]42ce94e2010-12-08 19:28:09199 LOG(WARNING) << "Unable to create pipe named \"" << channel_handle.name
[email protected]22b42c52010-12-20 06:59:23200 << "\" in " << modestr << " mode";
[email protected]fa95fc92008-12-08 18:10:14201 }
[email protected]d4651ff2008-12-02 16:51:58202}
203
[email protected]2f60c9b2014-06-06 20:13:51204ChannelPosix::~ChannelPosix() {
morrita2ad0be42015-01-27 20:05:53205 in_dtor_ = true;
[email protected]601858c02010-09-01 17:08:20206 Close();
207}
208
[email protected]d2e884d2009-06-22 20:37:52209bool SocketPair(int* fd1, int* fd2) {
210 int pipe_fds[2];
211 if (socketpair(AF_UNIX, SOCK_STREAM, 0, pipe_fds) != 0) {
[email protected]57b765672009-10-13 18:27:40212 PLOG(ERROR) << "socketpair()";
[email protected]d2e884d2009-06-22 20:37:52213 return false;
214 }
215
216 // Set both ends to be non-blocking.
217 if (fcntl(pipe_fds[0], F_SETFL, O_NONBLOCK) == -1 ||
218 fcntl(pipe_fds[1], F_SETFL, O_NONBLOCK) == -1) {
[email protected]57b765672009-10-13 18:27:40219 PLOG(ERROR) << "fcntl(O_NONBLOCK)";
[email protected]d89eec82013-12-03 14:10:59220 if (IGNORE_EINTR(close(pipe_fds[0])) < 0)
[email protected]70eb6572010-06-23 00:37:46221 PLOG(ERROR) << "close";
[email protected]d89eec82013-12-03 14:10:59222 if (IGNORE_EINTR(close(pipe_fds[1])) < 0)
[email protected]70eb6572010-06-23 00:37:46223 PLOG(ERROR) << "close";
[email protected]d2e884d2009-06-22 20:37:52224 return false;
225 }
226
227 *fd1 = pipe_fds[0];
228 *fd2 = pipe_fds[1];
229
230 return true;
231}
232
[email protected]2f60c9b2014-06-06 20:13:51233bool ChannelPosix::CreatePipe(
[email protected]1707726c2011-02-03 20:35:09234 const IPC::ChannelHandle& channel_handle) {
morritace44fef2014-09-29 22:25:54235 DCHECK(!server_listen_pipe_.is_valid() && !pipe_.is_valid());
[email protected]22b42c52010-12-20 06:59:23236
237 // Four possible cases:
238 // 1) It's a channel wrapping a pipe that is given to us.
239 // 2) It's for a named channel, so we create it.
240 // 3) It's for a client that we implement ourself. This is used
[email protected]e097b932014-03-19 06:34:52241 // in single-process unittesting.
[email protected]22b42c52010-12-20 06:59:23242 // 4) It's the initial IPC channel:
243 // 4a) Client side: Pull the pipe out of the GlobalDescriptors set.
244 // 4b) Server side: create the pipe.
245
morritace44fef2014-09-29 22:25:54246 base::ScopedFD local_pipe;
[email protected]22b42c52010-12-20 06:59:23247 if (channel_handle.socket.fd != -1) {
248 // Case 1 from comment above.
morritace44fef2014-09-29 22:25:54249 local_pipe.reset(channel_handle.socket.fd);
[email protected]22b42c52010-12-20 06:59:23250#if defined(IPC_USES_READWRITE)
251 // Test the socket passed into us to make sure it is nonblocking.
252 // We don't want to call read/write on a blocking socket.
morritace44fef2014-09-29 22:25:54253 int value = fcntl(local_pipe.get(), F_GETFL);
[email protected]22b42c52010-12-20 06:59:23254 if (value == -1) {
255 PLOG(ERROR) << "fcntl(F_GETFL) " << pipe_name_;
256 return false;
257 }
258 if (!(value & O_NONBLOCK)) {
259 LOG(ERROR) << "Socket " << pipe_name_ << " must be O_NONBLOCK";
260 return false;
261 }
262#endif // IPC_USES_READWRITE
[email protected]1707726c2011-02-03 20:35:09263 } else if (mode_ & MODE_NAMED_FLAG) {
hidehiko853d6082014-11-05 23:51:52264#if defined(OS_NACL_NONSFI)
hidehikoc2eec0d2014-10-24 03:49:27265 LOG(FATAL)
266 << "IPC channels in nacl_helper_nonsfi should not be in NAMED mode.";
267#else
[email protected]22b42c52010-12-20 06:59:23268 // Case 2 from comment above.
morritace44fef2014-09-29 22:25:54269 int local_pipe_fd = -1;
270
[email protected]1707726c2011-02-03 20:35:09271 if (mode_ & MODE_SERVER_FLAG) {
[email protected]bdf9bdc2013-03-13 04:23:10272 if (!CreateServerUnixDomainSocket(base::FilePath(pipe_name_),
morritace44fef2014-09-29 22:25:54273 &local_pipe_fd)) {
[email protected]df3c1ca12008-12-19 21:37:01274 return false;
275 }
morritace44fef2014-09-29 22:25:54276
[email protected]56f0f262011-02-24 17:14:36277 must_unlink_ = true;
[email protected]1707726c2011-02-03 20:35:09278 } else if (mode_ & MODE_CLIENT_FLAG) {
[email protected]bdf9bdc2013-03-13 04:23:10279 if (!CreateClientUnixDomainSocket(base::FilePath(pipe_name_),
morritace44fef2014-09-29 22:25:54280 &local_pipe_fd)) {
[email protected]df3c1ca12008-12-19 21:37:01281 return false;
282 }
[email protected]1707726c2011-02-03 20:35:09283 } else {
[email protected]6aad23f92011-03-02 22:27:14284 LOG(ERROR) << "Bad mode: " << mode_;
[email protected]1707726c2011-02-03 20:35:09285 return false;
[email protected]fa95fc92008-12-08 18:10:14286 }
morritace44fef2014-09-29 22:25:54287
288 local_pipe.reset(local_pipe_fd);
hidehiko853d6082014-11-05 23:51:52289#endif // !defined(OS_NACL_NONSFI)
[email protected]fa95fc92008-12-08 18:10:14290 } else {
morritace44fef2014-09-29 22:25:54291 local_pipe.reset(PipeMap::GetInstance()->Lookup(pipe_name_));
[email protected]1707726c2011-02-03 20:35:09292 if (mode_ & MODE_CLIENT_FLAG) {
morritace44fef2014-09-29 22:25:54293 if (local_pipe.is_valid()) {
[email protected]22b42c52010-12-20 06:59:23294 // Case 3 from comment above.
295 // We only allow one connection.
morritace44fef2014-09-29 22:25:54296 local_pipe.reset(HANDLE_EINTR(dup(local_pipe.release())));
[email protected]2ce26c432011-09-19 17:08:12297 PipeMap::GetInstance()->Remove(pipe_name_);
[email protected]d2e884d2009-06-22 20:37:52298 } else {
[email protected]22b42c52010-12-20 06:59:23299 // Case 4a from comment above.
[email protected]554a8852009-11-30 22:14:37300 // Guard against inappropriate reuse of the initial IPC channel. If
301 // an IPC channel closes and someone attempts to reuse it by name, the
302 // initial channel must not be recycled here. http://crbug.com/26754.
303 static bool used_initial_channel = false;
304 if (used_initial_channel) {
[email protected]9f816f72010-03-16 20:31:10305 LOG(FATAL) << "Denying attempt to reuse initial IPC channel for "
306 << pipe_name_;
[email protected]554a8852009-11-30 22:14:37307 return false;
308 }
309 used_initial_channel = true;
310
morritace44fef2014-09-29 22:25:54311 local_pipe.reset(
312 base::GlobalDescriptors::GetInstance()->Get(kPrimaryIPCChannel));
[email protected]df3c1ca12008-12-19 21:37:01313 }
[email protected]1707726c2011-02-03 20:35:09314 } else if (mode_ & MODE_SERVER_FLAG) {
[email protected]22b42c52010-12-20 06:59:23315 // Case 4b from comment above.
morritace44fef2014-09-29 22:25:54316 if (local_pipe.is_valid()) {
[email protected]22b42c52010-12-20 06:59:23317 LOG(ERROR) << "Server already exists for " << pipe_name_;
morritace44fef2014-09-29 22:25:54318 // This is a client side pipe registered by other server and
319 // shouldn't be closed.
320 ignore_result(local_pipe.release());
[email protected]baf556a2009-09-04 21:34:05321 return false;
322 }
[email protected]2ce26c432011-09-19 17:08:12323 base::AutoLock lock(client_pipe_lock_);
morritace44fef2014-09-29 22:25:54324 int local_pipe_fd = -1, client_pipe_fd = -1;
325 if (!SocketPair(&local_pipe_fd, &client_pipe_fd))
[email protected]22b42c52010-12-20 06:59:23326 return false;
morritace44fef2014-09-29 22:25:54327 local_pipe.reset(local_pipe_fd);
328 client_pipe_.reset(client_pipe_fd);
329 PipeMap::GetInstance()->Insert(pipe_name_, client_pipe_fd);
[email protected]22b42c52010-12-20 06:59:23330 } else {
[email protected]6aad23f92011-03-02 22:27:14331 LOG(ERROR) << "Bad mode: " << mode_;
[email protected]22b42c52010-12-20 06:59:23332 return false;
[email protected]baf556a2009-09-04 21:34:05333 }
334 }
[email protected]22b42c52010-12-20 06:59:23335
[email protected]22b42c52010-12-20 06:59:23336#if defined(IPC_USES_READWRITE)
337 // Create a dedicated socketpair() for exchanging file descriptors.
338 // See comments for IPC_USES_READWRITE for details.
[email protected]1707726c2011-02-03 20:35:09339 if (mode_ & MODE_CLIENT_FLAG) {
morritace44fef2014-09-29 22:25:54340 int fd_pipe_fd = 1, remote_fd_pipe_fd = -1;
341 if (!SocketPair(&fd_pipe_fd, &remote_fd_pipe_fd)) {
[email protected]22b42c52010-12-20 06:59:23342 return false;
343 }
morritace44fef2014-09-29 22:25:54344
345 fd_pipe_.reset(fd_pipe_fd);
346 remote_fd_pipe_.reset(remote_fd_pipe_fd);
[email protected]22b42c52010-12-20 06:59:23347 }
348#endif // IPC_USES_READWRITE
349
hidehikoc2eec0d2014-10-24 03:49:27350 if ((mode_ & MODE_SERVER_FLAG) && (mode_ & MODE_NAMED_FLAG)) {
hidehiko853d6082014-11-05 23:51:52351#if defined(OS_NACL_NONSFI)
hidehikoc2eec0d2014-10-24 03:49:27352 LOG(FATAL) << "IPC channels in nacl_helper_nonsfi "
353 << "should not be in NAMED or SERVER mode.";
354#else
morritace44fef2014-09-29 22:25:54355 server_listen_pipe_.reset(local_pipe.release());
hidehikoc2eec0d2014-10-24 03:49:27356#endif
357 } else {
morritace44fef2014-09-29 22:25:54358 pipe_.reset(local_pipe.release());
hidehikoc2eec0d2014-10-24 03:49:27359 }
[email protected]fa95fc92008-12-08 18:10:14360 return true;
[email protected]d4651ff2008-12-02 16:51:58361}
362
[email protected]2f60c9b2014-06-06 20:13:51363bool ChannelPosix::Connect() {
morritace44fef2014-09-29 22:25:54364 if (!server_listen_pipe_.is_valid() && !pipe_.is_valid()) {
[email protected]0e8a7912014-02-21 00:18:29365 DLOG(WARNING) << "Channel creation failed: " << pipe_name_;
[email protected]22b42c52010-12-20 06:59:23366 return false;
367 }
368
369 bool did_connect = true;
morritace44fef2014-09-29 22:25:54370 if (server_listen_pipe_.is_valid()) {
hidehiko853d6082014-11-05 23:51:52371#if defined(OS_NACL_NONSFI)
hidehikoc2eec0d2014-10-24 03:49:27372 LOG(FATAL) << "IPC channels in nacl_helper_nonsfi "
373 << "should always be in client mode.";
374#else
[email protected]22b42c52010-12-20 06:59:23375 // Watch the pipe for connections, and turn any connections into
376 // active sockets.
[email protected]fd0a773a2013-04-30 20:55:03377 base::MessageLoopForIO::current()->WatchFileDescriptor(
morritace44fef2014-09-29 22:25:54378 server_listen_pipe_.get(),
[email protected]e45e6c02008-12-15 22:02:17379 true,
[email protected]fd0a773a2013-04-30 20:55:03380 base::MessageLoopForIO::WATCH_READ,
[email protected]e45e6c02008-12-15 22:02:17381 &server_listen_connection_watcher_,
382 this);
hidehikoc2eec0d2014-10-24 03:49:27383#endif
[email protected]fa95fc92008-12-08 18:10:14384 } else {
[email protected]22b42c52010-12-20 06:59:23385 did_connect = AcceptConnection();
[email protected]fa95fc92008-12-08 18:10:14386 }
[email protected]22b42c52010-12-20 06:59:23387 return did_connect;
[email protected]d4651ff2008-12-02 16:51:58388}
[email protected]fa95fc92008-12-08 18:10:14389
[email protected]2f60c9b2014-06-06 20:13:51390void ChannelPosix::CloseFileDescriptors(Message* msg) {
[email protected]dc875dc2013-10-15 00:07:00391#if defined(OS_MACOSX)
392 // There is a bug on OSX which makes it dangerous to close
393 // a file descriptor while it is in transit. So instead we
394 // store the file descriptor in a set and send a message to
395 // the recipient, which is queued AFTER the message that
396 // sent the FD. The recipient will reply to the message,
397 // letting us know that it is now safe to close the file
398 // descriptor. For more information, see:
399 // http://crbug.com/298276
400 std::vector<int> to_close;
morrita4b5c28e22015-01-14 21:17:06401 msg->attachment_set()->ReleaseFDsToClose(&to_close);
[email protected]dc875dc2013-10-15 00:07:00402 for (size_t i = 0; i < to_close.size(); i++) {
403 fds_to_close_.insert(to_close[i]);
404 QueueCloseFDMessage(to_close[i], 2);
405 }
406#else
morrita4b5c28e22015-01-14 21:17:06407 msg->attachment_set()->CommitAll();
[email protected]dc875dc2013-10-15 00:07:00408#endif
409}
410
[email protected]2f60c9b2014-06-06 20:13:51411bool ChannelPosix::ProcessOutgoingMessages() {
[email protected]fa95fc92008-12-08 18:10:14412 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
413 // no connection?
[email protected]22b42c52010-12-20 06:59:23414 if (output_queue_.empty())
[email protected]c7f91e82010-12-20 06:39:44415 return true;
[email protected]c7f91e82010-12-20 06:39:44416
morritace44fef2014-09-29 22:25:54417 if (!pipe_.is_valid())
[email protected]fa95fc92008-12-08 18:10:14418 return false;
419
[email protected]fa95fc92008-12-08 18:10:14420 // Write out all the messages we can till the write blocks or there are no
421 // more outgoing messages.
422 while (!output_queue_.empty()) {
423 Message* msg = output_queue_.front();
424
425 size_t amt_to_write = msg->size() - message_send_bytes_written_;
[email protected]60ea6052011-04-18 20:07:08426 DCHECK_NE(0U, amt_to_write);
[email protected]baf556a2009-09-04 21:34:05427 const char* out_bytes = reinterpret_cast<const char*>(msg->data()) +
[email protected]fa95fc92008-12-08 18:10:14428 message_send_bytes_written_;
[email protected]526776c2009-02-07 00:39:26429
[email protected]157c61b2009-05-01 21:37:31430 struct msghdr msgh = {0};
431 struct iovec iov = {const_cast<char*>(out_bytes), amt_to_write};
432 msgh.msg_iov = &iov;
433 msgh.msg_iovlen = 1;
morrita4b5c28e22015-01-14 21:17:06434 char buf[CMSG_SPACE(sizeof(int) *
435 MessageAttachmentSet::kMaxDescriptorsPerMessage)];
[email protected]526776c2009-02-07 00:39:26436
[email protected]baf556a2009-09-04 21:34:05437 ssize_t bytes_written = 1;
438 int fd_written = -1;
439
morrita4b5c28e22015-01-14 21:17:06440 if (message_send_bytes_written_ == 0 && !msg->attachment_set()->empty()) {
[email protected]157c61b2009-05-01 21:37:31441 // This is the first chunk of a message which has descriptors to send
442 struct cmsghdr *cmsg;
morrita4b5c28e22015-01-14 21:17:06443 const unsigned num_fds = msg->attachment_set()->size();
[email protected]526776c2009-02-07 00:39:26444
morrita4b5c28e22015-01-14 21:17:06445 DCHECK(num_fds <= MessageAttachmentSet::kMaxDescriptorsPerMessage);
446 if (msg->attachment_set()->ContainsDirectoryDescriptor()) {
[email protected]aac449e2010-06-10 21:39:04447 LOG(FATAL) << "Panic: attempting to transport directory descriptor over"
448 " IPC. Aborting to maintain sandbox isolation.";
449 // If you have hit this then something tried to send a file descriptor
450 // to a directory over an IPC channel. Since IPC channels span
451 // sandboxes this is very bad: the receiving process can use openat
452 // with ".." elements in the path in order to reach the real
453 // filesystem.
454 }
[email protected]526776c2009-02-07 00:39:26455
[email protected]157c61b2009-05-01 21:37:31456 msgh.msg_control = buf;
457 msgh.msg_controllen = CMSG_SPACE(sizeof(int) * num_fds);
458 cmsg = CMSG_FIRSTHDR(&msgh);
459 cmsg->cmsg_level = SOL_SOCKET;
460 cmsg->cmsg_type = SCM_RIGHTS;
461 cmsg->cmsg_len = CMSG_LEN(sizeof(int) * num_fds);
morrita4b5c28e22015-01-14 21:17:06462 msg->attachment_set()->PeekDescriptors(
[email protected]157c61b2009-05-01 21:37:31463 reinterpret_cast<int*>(CMSG_DATA(cmsg)));
464 msgh.msg_controllen = cmsg->cmsg_len;
[email protected]526776c2009-02-07 00:39:26465
[email protected]168ae922009-12-04 18:08:45466 // DCHECK_LE above already checks that
[email protected]05094a32011-09-01 00:50:13467 // num_fds < kMaxDescriptorsPerMessage so no danger of overflow.
[email protected]168ae922009-12-04 18:08:45468 msg->header()->num_fds = static_cast<uint16>(num_fds);
[email protected]baf556a2009-09-04 21:34:05469
[email protected]e40f5a0b2010-12-08 21:22:24470#if defined(IPC_USES_READWRITE)
[email protected]d805c6a2012-03-08 12:30:28471 if (!IsHelloMessage(*msg)) {
[email protected]baf556a2009-09-04 21:34:05472 // Only the Hello message sends the file descriptor with the message.
473 // Subsequently, we can send file descriptors on the dedicated
474 // fd_pipe_ which makes Seccomp sandbox operation more efficient.
475 struct iovec fd_pipe_iov = { const_cast<char *>(""), 1 };
476 msgh.msg_iov = &fd_pipe_iov;
morritace44fef2014-09-29 22:25:54477 fd_written = fd_pipe_.get();
478 bytes_written =
479 HANDLE_EINTR(sendmsg(fd_pipe_.get(), &msgh, MSG_DONTWAIT));
[email protected]baf556a2009-09-04 21:34:05480 msgh.msg_iov = &iov;
481 msgh.msg_controllen = 0;
482 if (bytes_written > 0) {
[email protected]dc875dc2013-10-15 00:07:00483 CloseFileDescriptors(msg);
[email protected]baf556a2009-09-04 21:34:05484 }
485 }
[email protected]22b42c52010-12-20 06:59:23486#endif // IPC_USES_READWRITE
[email protected]157c61b2009-05-01 21:37:31487 }
488
[email protected]baf556a2009-09-04 21:34:05489 if (bytes_written == 1) {
morritace44fef2014-09-29 22:25:54490 fd_written = pipe_.get();
[email protected]e40f5a0b2010-12-08 21:22:24491#if defined(IPC_USES_READWRITE)
[email protected]d805c6a2012-03-08 12:30:28492 if ((mode_ & MODE_CLIENT_FLAG) && IsHelloMessage(*msg)) {
morrita4b5c28e22015-01-14 21:17:06493 DCHECK_EQ(msg->attachment_set()->size(), 1U);
[email protected]baf556a2009-09-04 21:34:05494 }
[email protected]22b42c52010-12-20 06:59:23495 if (!msgh.msg_controllen) {
morritace44fef2014-09-29 22:25:54496 bytes_written =
497 HANDLE_EINTR(write(pipe_.get(), out_bytes, amt_to_write));
[email protected]baf556a2009-09-04 21:34:05498 } else
[email protected]22b42c52010-12-20 06:59:23499#endif // IPC_USES_READWRITE
[email protected]baf556a2009-09-04 21:34:05500 {
morritace44fef2014-09-29 22:25:54501 bytes_written = HANDLE_EINTR(sendmsg(pipe_.get(), &msgh, MSG_DONTWAIT));
[email protected]baf556a2009-09-04 21:34:05502 }
503 }
[email protected]157c61b2009-05-01 21:37:31504 if (bytes_written > 0)
[email protected]dc875dc2013-10-15 00:07:00505 CloseFileDescriptors(msg);
[email protected]fa95fc92008-12-08 18:10:14506
[email protected]86c3d9e2009-12-08 14:48:08507 if (bytes_written < 0 && !SocketWriteErrorIsRecoverable()) {
[email protected]0e8a7912014-02-21 00:18:29508 // We can't close the pipe here, because calling OnChannelError
509 // may destroy this object, and that would be bad if we are
510 // called from Send(). Instead, we return false and hope the
511 // caller will close the pipe. If they do not, the pipe will
512 // still be closed next time OnFileCanReadWithoutBlocking is
513 // called.
[email protected]cb38c0b22009-05-27 18:29:48514#if defined(OS_MACOSX)
515 // On OSX writing to a pipe with no listener returns EPERM.
516 if (errno == EPERM) {
[email protected]cb38c0b22009-05-27 18:29:48517 return false;
518 }
519#endif // OS_MACOSX
[email protected]7bf54f5e2009-10-23 01:48:21520 if (errno == EPIPE) {
[email protected]7bf54f5e2009-10-23 01:48:21521 return false;
522 }
[email protected]780ae942009-12-03 13:35:46523 PLOG(ERROR) << "pipe error on "
524 << fd_written
[email protected]9fbc2f2f2011-02-11 08:43:52525 << " Currently writing message of size: "
[email protected]86c3d9e2009-12-08 14:48:08526 << msg->size();
[email protected]fa95fc92008-12-08 18:10:14527 return false;
528 }
529
530 if (static_cast<size_t>(bytes_written) != amt_to_write) {
[email protected]3d1b6662009-01-29 17:03:11531 if (bytes_written > 0) {
532 // If write() fails with EAGAIN then bytes_written will be -1.
533 message_send_bytes_written_ += bytes_written;
534 }
[email protected]fa95fc92008-12-08 18:10:14535
536 // Tell libevent to call us back once things are unblocked.
[email protected]e45e6c02008-12-15 22:02:17537 is_blocked_on_write_ = true;
[email protected]fd0a773a2013-04-30 20:55:03538 base::MessageLoopForIO::current()->WatchFileDescriptor(
morritace44fef2014-09-29 22:25:54539 pipe_.get(),
[email protected]e45e6c02008-12-15 22:02:17540 false, // One shot
[email protected]fd0a773a2013-04-30 20:55:03541 base::MessageLoopForIO::WATCH_WRITE,
[email protected]e45e6c02008-12-15 22:02:17542 &write_watcher_,
543 this);
[email protected]3d1b6662009-01-29 17:03:11544 return true;
[email protected]fa95fc92008-12-08 18:10:14545 } else {
546 message_send_bytes_written_ = 0;
547
548 // Message sent OK!
[email protected]2a9d601b2010-10-19 23:50:00549 DVLOG(2) << "sent message @" << msg << " on channel @" << this
morritace44fef2014-09-29 22:25:54550 << " with type " << msg->type() << " on fd " << pipe_.get();
[email protected]baf556a2009-09-04 21:34:05551 delete output_queue_.front();
[email protected]fa95fc92008-12-08 18:10:14552 output_queue_.pop();
[email protected]fa95fc92008-12-08 18:10:14553 }
554 }
555 return true;
556}
557
[email protected]2f60c9b2014-06-06 20:13:51558bool ChannelPosix::Send(Message* message) {
morrita81b17e02015-02-06 00:58:30559 DCHECK(!message->HasMojoHandles());
[email protected]2a9d601b2010-10-19 23:50:00560 DVLOG(2) << "sending message @" << message << " on channel @" << this
561 << " with type " << message->type()
562 << " (" << output_queue_.size() << " in queue)";
[email protected]fa95fc92008-12-08 18:10:14563
[email protected]4c2c1db2009-03-20 20:56:55564#ifdef IPC_MESSAGE_LOG_ENABLED
[email protected]8e8bb6d2010-12-13 08:18:55565 Logging::GetInstance()->OnSendMessage(message, "");
[email protected]22b42c52010-12-20 06:59:23566#endif // IPC_MESSAGE_LOG_ENABLED
[email protected]fa95fc92008-12-08 18:10:14567
[email protected]2c391df2012-09-18 03:41:29568 message->TraceMessageBegin();
[email protected]fa95fc92008-12-08 18:10:14569 output_queue_.push(message);
[email protected]22b42c52010-12-20 06:59:23570 if (!is_blocked_on_write_ && !waiting_connect_) {
[email protected]13ffc272014-02-18 17:42:20571 return ProcessOutgoingMessages();
[email protected]fa95fc92008-12-08 18:10:14572 }
573
574 return true;
575}
576
[email protected]2f60c9b2014-06-06 20:13:51577int ChannelPosix::GetClientFileDescriptor() const {
[email protected]2ce26c432011-09-19 17:08:12578 base::AutoLock lock(client_pipe_lock_);
morritace44fef2014-09-29 22:25:54579 return client_pipe_.get();
[email protected]df3c1ca12008-12-19 21:37:01580}
581
morritaa409ccc2014-10-20 23:53:25582base::ScopedFD ChannelPosix::TakeClientFileDescriptor() {
[email protected]2ce26c432011-09-19 17:08:12583 base::AutoLock lock(client_pipe_lock_);
morritace44fef2014-09-29 22:25:54584 if (!client_pipe_.is_valid())
morritaa409ccc2014-10-20 23:53:25585 return base::ScopedFD();
morritace44fef2014-09-29 22:25:54586 PipeMap::GetInstance()->Remove(pipe_name_);
morritaa409ccc2014-10-20 23:53:25587 return client_pipe_.Pass();
[email protected]2ce26c432011-09-19 17:08:12588}
589
[email protected]2f60c9b2014-06-06 20:13:51590void ChannelPosix::CloseClientFileDescriptor() {
[email protected]2ce26c432011-09-19 17:08:12591 base::AutoLock lock(client_pipe_lock_);
morritace44fef2014-09-29 22:25:54592 if (!client_pipe_.is_valid())
593 return;
594 PipeMap::GetInstance()->Remove(pipe_name_);
595 client_pipe_.reset();
[email protected]2ce26c432011-09-19 17:08:12596}
597
[email protected]2f60c9b2014-06-06 20:13:51598bool ChannelPosix::AcceptsConnections() const {
morritace44fef2014-09-29 22:25:54599 return server_listen_pipe_.is_valid();
[email protected]22b42c52010-12-20 06:59:23600}
[email protected]9a44a4db62010-12-20 06:19:07601
[email protected]2f60c9b2014-06-06 20:13:51602bool ChannelPosix::HasAcceptedConnection() const {
morritace44fef2014-09-29 22:25:54603 return AcceptsConnections() && pipe_.is_valid();
[email protected]22b42c52010-12-20 06:59:23604}
[email protected]9a44a4db62010-12-20 06:19:07605
hidehiko853d6082014-11-05 23:51:52606#if !defined(OS_NACL_NONSFI)
hidehikoc2eec0d2014-10-24 03:49:27607// GetPeerEuid is not supported in nacl_helper_nonsfi.
[email protected]2f60c9b2014-06-06 20:13:51608bool ChannelPosix::GetPeerEuid(uid_t* peer_euid) const {
[email protected]bdf9bdc2013-03-13 04:23:10609 DCHECK(!(mode_ & MODE_SERVER) || HasAcceptedConnection());
morritace44fef2014-09-29 22:25:54610 return IPC::GetPeerEuid(pipe_.get(), peer_euid);
[email protected]8ec3fbe2011-04-06 12:01:44611}
hidehikoc2eec0d2014-10-24 03:49:27612#endif
[email protected]8ec3fbe2011-04-06 12:01:44613
[email protected]2f60c9b2014-06-06 20:13:51614void ChannelPosix::ResetToAcceptingConnectionState() {
[email protected]22b42c52010-12-20 06:59:23615 // Unregister libevent for the unix domain socket and close it.
616 read_watcher_.StopWatchingFileDescriptor();
617 write_watcher_.StopWatchingFileDescriptor();
morrita2ad0be42015-01-27 20:05:53618 ResetSafely(&pipe_);
[email protected]22b42c52010-12-20 06:59:23619#if defined(IPC_USES_READWRITE)
morritace44fef2014-09-29 22:25:54620 fd_pipe_.reset();
621 remote_fd_pipe_.reset();
[email protected]22b42c52010-12-20 06:59:23622#endif // IPC_USES_READWRITE
[email protected]c7f91e82010-12-20 06:39:44623
[email protected]22b42c52010-12-20 06:59:23624 while (!output_queue_.empty()) {
625 Message* m = output_queue_.front();
626 output_queue_.pop();
627 delete m;
[email protected]c7f91e82010-12-20 06:39:44628 }
629
[email protected]22b42c52010-12-20 06:59:23630 // Close any outstanding, received file descriptors.
[email protected]334f3022012-02-29 22:48:14631 ClearInputFDs();
[email protected]dc875dc2013-10-15 00:07:00632
633#if defined(OS_MACOSX)
634 // Clear any outstanding, sent file descriptors.
635 for (std::set<int>::iterator i = fds_to_close_.begin();
636 i != fds_to_close_.end();
637 ++i) {
[email protected]d89eec82013-12-03 14:10:59638 if (IGNORE_EINTR(close(*i)) < 0)
[email protected]dc875dc2013-10-15 00:07:00639 PLOG(ERROR) << "close";
640 }
641 fds_to_close_.clear();
642#endif
[email protected]22b42c52010-12-20 06:59:23643}
644
[email protected]313c00e52011-08-09 06:46:06645// static
[email protected]2f60c9b2014-06-06 20:13:51646bool ChannelPosix::IsNamedServerInitialized(
[email protected]313c00e52011-08-09 06:46:06647 const std::string& channel_id) {
[email protected]7567484142013-07-11 17:36:07648 return base::PathExists(base::FilePath(channel_id));
[email protected]313c00e52011-08-09 06:46:06649}
650
perkjdbcac352014-12-11 17:27:58651#if defined(OS_LINUX)
652// static
653void ChannelPosix::SetGlobalPid(int pid) {
654 global_pid_ = pid;
655}
656#endif // OS_LINUX
657
[email protected]22b42c52010-12-20 06:59:23658// Called by libevent when we can read from the pipe without blocking.
[email protected]2f60c9b2014-06-06 20:13:51659void ChannelPosix::OnFileCanReadWithoutBlocking(int fd) {
morritace44fef2014-09-29 22:25:54660 if (fd == server_listen_pipe_.get()) {
hidehiko853d6082014-11-05 23:51:52661#if defined(OS_NACL_NONSFI)
hidehikoc2eec0d2014-10-24 03:49:27662 LOG(FATAL)
663 << "IPC channels in nacl_helper_nonsfi should not be SERVER mode.";
664#else
[email protected]22b42c52010-12-20 06:59:23665 int new_pipe = 0;
morritace44fef2014-09-29 22:25:54666 if (!ServerAcceptConnection(server_listen_pipe_.get(), &new_pipe) ||
[email protected]bdf9bdc2013-03-13 04:23:10667 new_pipe < 0) {
[email protected]c7f91e82010-12-20 06:39:44668 Close();
[email protected]d805c6a2012-03-08 12:30:28669 listener()->OnChannelListenError();
[email protected]22b42c52010-12-20 06:59:23670 }
671
morritace44fef2014-09-29 22:25:54672 if (pipe_.is_valid()) {
[email protected]22b42c52010-12-20 06:59:23673 // We already have a connection. We only handle one at a time.
674 // close our new descriptor.
675 if (HANDLE_EINTR(shutdown(new_pipe, SHUT_RDWR)) < 0)
[email protected]334f3022012-02-29 22:48:14676 DPLOG(ERROR) << "shutdown " << pipe_name_;
[email protected]d89eec82013-12-03 14:10:59677 if (IGNORE_EINTR(close(new_pipe)) < 0)
[email protected]334f3022012-02-29 22:48:14678 DPLOG(ERROR) << "close " << pipe_name_;
[email protected]d805c6a2012-03-08 12:30:28679 listener()->OnChannelDenied();
[email protected]c7f91e82010-12-20 06:39:44680 return;
[email protected]9a44a4db62010-12-20 06:19:07681 }
morritace44fef2014-09-29 22:25:54682 pipe_.reset(new_pipe);
[email protected]22b42c52010-12-20 06:59:23683
[email protected]8ec3fbe2011-04-06 12:01:44684 if ((mode_ & MODE_OPEN_ACCESS_FLAG) == 0) {
685 // Verify that the IPC channel peer is running as the same user.
686 uid_t client_euid;
[email protected]bdf9bdc2013-03-13 04:23:10687 if (!GetPeerEuid(&client_euid)) {
[email protected]334f3022012-02-29 22:48:14688 DLOG(ERROR) << "Unable to query client euid";
[email protected]8ec3fbe2011-04-06 12:01:44689 ResetToAcceptingConnectionState();
690 return;
691 }
692 if (client_euid != geteuid()) {
[email protected]334f3022012-02-29 22:48:14693 DLOG(WARNING) << "Client euid is not authorised";
[email protected]8ec3fbe2011-04-06 12:01:44694 ResetToAcceptingConnectionState();
695 return;
696 }
697 }
698
[email protected]22b42c52010-12-20 06:59:23699 if (!AcceptConnection()) {
700 NOTREACHED() << "AcceptConnection should not fail on server";
701 }
[email protected]22b42c52010-12-20 06:59:23702 waiting_connect_ = false;
hidehikoc2eec0d2014-10-24 03:49:27703#endif
[email protected]22b42c52010-12-20 06:59:23704 } else if (fd == pipe_) {
[email protected]1707726c2011-02-03 20:35:09705 if (waiting_connect_ && (mode_ & MODE_SERVER_FLAG)) {
[email protected]22b42c52010-12-20 06:59:23706 waiting_connect_ = false;
707 }
708 if (!ProcessIncomingMessages()) {
[email protected]887250a2011-02-28 20:30:47709 // ClosePipeOnError may delete this object, so we mustn't call
710 // ProcessOutgoingMessages.
[email protected]22b42c52010-12-20 06:59:23711 ClosePipeOnError();
[email protected]dc875dc2013-10-15 00:07:00712 return;
[email protected]22b42c52010-12-20 06:59:23713 }
714 } else {
715 NOTREACHED() << "Unknown pipe " << fd;
[email protected]fa95fc92008-12-08 18:10:14716 }
717
718 // If we're a server and handshaking, then we want to make sure that we
719 // only send our handshake message after we've processed the client's.
720 // This gives us a chance to kill the client if the incoming handshake
[email protected]0e8a7912014-02-21 00:18:29721 // is invalid. This also flushes any closefd messages.
[email protected]dc875dc2013-10-15 00:07:00722 if (!is_blocked_on_write_) {
723 if (!ProcessOutgoingMessages()) {
724 ClosePipeOnError();
725 }
[email protected]fa95fc92008-12-08 18:10:14726 }
727}
728
729// Called by libevent when we can write to the pipe without blocking.
[email protected]2f60c9b2014-06-06 20:13:51730void ChannelPosix::OnFileCanWriteWithoutBlocking(int fd) {
morritace44fef2014-09-29 22:25:54731 DCHECK_EQ(pipe_.get(), fd);
[email protected]22b42c52010-12-20 06:59:23732 is_blocked_on_write_ = false;
[email protected]fa95fc92008-12-08 18:10:14733 if (!ProcessOutgoingMessages()) {
[email protected]22b42c52010-12-20 06:59:23734 ClosePipeOnError();
[email protected]9a44a4db62010-12-20 06:19:07735 }
736}
737
[email protected]2f60c9b2014-06-06 20:13:51738bool ChannelPosix::AcceptConnection() {
[email protected]fd0a773a2013-04-30 20:55:03739 base::MessageLoopForIO::current()->WatchFileDescriptor(
morritace44fef2014-09-29 22:25:54740 pipe_.get(),
741 true,
742 base::MessageLoopForIO::WATCH_READ,
743 &read_watcher_,
744 this);
[email protected]22b42c52010-12-20 06:59:23745 QueueHelloMessage();
746
[email protected]1707726c2011-02-03 20:35:09747 if (mode_ & MODE_CLIENT_FLAG) {
[email protected]22b42c52010-12-20 06:59:23748 // If we are a client we want to send a hello message out immediately.
749 // In server mode we will send a hello message when we receive one from a
750 // client.
751 waiting_connect_ = false;
[email protected]13ffc272014-02-18 17:42:20752 return ProcessOutgoingMessages();
[email protected]1707726c2011-02-03 20:35:09753 } else if (mode_ & MODE_SERVER_FLAG) {
[email protected]22b42c52010-12-20 06:59:23754 waiting_connect_ = true;
755 return true;
[email protected]1707726c2011-02-03 20:35:09756 } else {
757 NOTREACHED();
758 return false;
[email protected]22b42c52010-12-20 06:59:23759 }
760}
761
[email protected]2f60c9b2014-06-06 20:13:51762void ChannelPosix::ClosePipeOnError() {
[email protected]22b42c52010-12-20 06:59:23763 if (HasAcceptedConnection()) {
764 ResetToAcceptingConnectionState();
[email protected]d805c6a2012-03-08 12:30:28765 listener()->OnChannelError();
[email protected]22b42c52010-12-20 06:59:23766 } else {
767 Close();
768 if (AcceptsConnections()) {
[email protected]d805c6a2012-03-08 12:30:28769 listener()->OnChannelListenError();
[email protected]22b42c52010-12-20 06:59:23770 } else {
[email protected]d805c6a2012-03-08 12:30:28771 listener()->OnChannelError();
[email protected]22b42c52010-12-20 06:59:23772 }
773 }
774}
775
[email protected]64860882014-08-04 23:44:17776int ChannelPosix::GetHelloMessageProcId() const {
hidehiko763f8be2015-02-03 07:24:34777#if defined(OS_NACL_NONSFI)
778 // In nacl_helper_nonsfi, getpid() invoked by GetCurrentProcId() is not
779 // allowed and would cause a SIGSYS crash because of the seccomp sandbox.
780 return -1;
781#else
perkjdbcac352014-12-11 17:27:58782 int pid = base::GetCurrentProcId();
783#if defined(OS_LINUX)
784 // Our process may be in a sandbox with a separate PID namespace.
785 if (global_pid_) {
786 pid = global_pid_;
787 }
hidehiko763f8be2015-02-03 07:24:34788#endif // defined(OS_LINUX)
perkjdbcac352014-12-11 17:27:58789 return pid;
hidehiko763f8be2015-02-03 07:24:34790#endif // defined(OS_NACL_NONSFI)
[email protected]e1d67a882011-08-31 21:11:04791}
792
[email protected]2f60c9b2014-06-06 20:13:51793void ChannelPosix::QueueHelloMessage() {
[email protected]22b42c52010-12-20 06:59:23794 // Create the Hello message
795 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
[email protected]753bb252013-11-04 22:28:12796 HELLO_MESSAGE_TYPE,
797 IPC::Message::PRIORITY_NORMAL));
[email protected]e1d67a882011-08-31 21:11:04798 if (!msg->WriteInt(GetHelloMessageProcId())) {
[email protected]22b42c52010-12-20 06:59:23799 NOTREACHED() << "Unable to pickle hello message proc id";
800 }
801#if defined(IPC_USES_READWRITE)
802 scoped_ptr<Message> hello;
morritace44fef2014-09-29 22:25:54803 if (remote_fd_pipe_.is_valid()) {
morrita1aa788c2015-01-31 05:45:42804 if (!msg->WriteAttachment(
805 new internal::PlatformFileAttachment(remote_fd_pipe_.get()))) {
[email protected]22b42c52010-12-20 06:59:23806 NOTREACHED() << "Unable to pickle hello message file descriptors";
807 }
morrita4b5c28e22015-01-14 21:17:06808 DCHECK_EQ(msg->attachment_set()->size(), 1U);
[email protected]22b42c52010-12-20 06:59:23809 }
810#endif // IPC_USES_READWRITE
811 output_queue_.push(msg.release());
812}
813
[email protected]2f60c9b2014-06-06 20:13:51814ChannelPosix::ReadState ChannelPosix::ReadData(
[email protected]3d5a60b2012-03-01 21:41:47815 char* buffer,
816 int buffer_len,
817 int* bytes_read) {
morritace44fef2014-09-29 22:25:54818 if (!pipe_.is_valid())
[email protected]3d5a60b2012-03-01 21:41:47819 return READ_FAILED;
820
[email protected]334f3022012-02-29 22:48:14821 struct msghdr msg = {0};
822
[email protected]3fcbd4b2012-06-05 01:54:46823 struct iovec iov = {buffer, static_cast<size_t>(buffer_len)};
[email protected]334f3022012-02-29 22:48:14824 msg.msg_iov = &iov;
825 msg.msg_iovlen = 1;
826
827 msg.msg_control = input_cmsg_buf_;
828
829 // recvmsg() returns 0 if the connection has closed or EAGAIN if no data
830 // is waiting on the pipe.
[email protected]334f3022012-02-29 22:48:14831#if defined(IPC_USES_READWRITE)
morritace44fef2014-09-29 22:25:54832 if (fd_pipe_.is_valid()) {
833 *bytes_read = HANDLE_EINTR(read(pipe_.get(), buffer, buffer_len));
[email protected]334f3022012-02-29 22:48:14834 msg.msg_controllen = 0;
835 } else
836#endif // IPC_USES_READWRITE
837 {
838 msg.msg_controllen = sizeof(input_cmsg_buf_);
morritace44fef2014-09-29 22:25:54839 *bytes_read = HANDLE_EINTR(recvmsg(pipe_.get(), &msg, MSG_DONTWAIT));
[email protected]334f3022012-02-29 22:48:14840 }
[email protected]3d5a60b2012-03-01 21:41:47841 if (*bytes_read < 0) {
[email protected]334f3022012-02-29 22:48:14842 if (errno == EAGAIN) {
[email protected]3d5a60b2012-03-01 21:41:47843 return READ_PENDING;
[email protected]334f3022012-02-29 22:48:14844#if defined(OS_MACOSX)
845 } else if (errno == EPERM) {
846 // On OSX, reading from a pipe with no listener returns EPERM
847 // treat this as a special case to prevent spurious error messages
848 // to the console.
[email protected]3d5a60b2012-03-01 21:41:47849 return READ_FAILED;
[email protected]334f3022012-02-29 22:48:14850#endif // OS_MACOSX
851 } else if (errno == ECONNRESET || errno == EPIPE) {
[email protected]3d5a60b2012-03-01 21:41:47852 return READ_FAILED;
[email protected]334f3022012-02-29 22:48:14853 } else {
morritace44fef2014-09-29 22:25:54854 PLOG(ERROR) << "pipe error (" << pipe_.get() << ")";
[email protected]3d5a60b2012-03-01 21:41:47855 return READ_FAILED;
[email protected]334f3022012-02-29 22:48:14856 }
[email protected]3d5a60b2012-03-01 21:41:47857 } else if (*bytes_read == 0) {
[email protected]334f3022012-02-29 22:48:14858 // The pipe has closed...
[email protected]3d5a60b2012-03-01 21:41:47859 return READ_FAILED;
[email protected]334f3022012-02-29 22:48:14860 }
[email protected]3d5a60b2012-03-01 21:41:47861 DCHECK(*bytes_read);
[email protected]334f3022012-02-29 22:48:14862
863 CloseClientFileDescriptor();
864
865 // Read any file descriptors from the message.
866 if (!ExtractFileDescriptorsFromMsghdr(&msg))
[email protected]3d5a60b2012-03-01 21:41:47867 return READ_FAILED;
868 return READ_SUCCEEDED;
[email protected]334f3022012-02-29 22:48:14869}
870
871#if defined(IPC_USES_READWRITE)
[email protected]2f60c9b2014-06-06 20:13:51872bool ChannelPosix::ReadFileDescriptorsFromFDPipe() {
[email protected]334f3022012-02-29 22:48:14873 char dummy;
874 struct iovec fd_pipe_iov = { &dummy, 1 };
875
876 struct msghdr msg = { 0 };
877 msg.msg_iov = &fd_pipe_iov;
878 msg.msg_iovlen = 1;
879 msg.msg_control = input_cmsg_buf_;
880 msg.msg_controllen = sizeof(input_cmsg_buf_);
morritace44fef2014-09-29 22:25:54881 ssize_t bytes_received =
882 HANDLE_EINTR(recvmsg(fd_pipe_.get(), &msg, MSG_DONTWAIT));
[email protected]334f3022012-02-29 22:48:14883
884 if (bytes_received != 1)
885 return true; // No message waiting.
886
887 if (!ExtractFileDescriptorsFromMsghdr(&msg))
888 return false;
889 return true;
890}
891#endif
892
[email protected]d805c6a2012-03-08 12:30:28893// On Posix, we need to fix up the file descriptors before the input message
894// is dispatched.
895//
896// This will read from the input_fds_ (READWRITE mode only) and read more
897// handles from the FD pipe if necessary.
[email protected]2f60c9b2014-06-06 20:13:51898bool ChannelPosix::WillDispatchInputMessage(Message* msg) {
[email protected]334f3022012-02-29 22:48:14899 uint16 header_fds = msg->header()->num_fds;
900 if (!header_fds)
901 return true; // Nothing to do.
902
903 // The message has file descriptors.
904 const char* error = NULL;
905 if (header_fds > input_fds_.size()) {
906 // The message has been completely received, but we didn't get
907 // enough file descriptors.
908#if defined(IPC_USES_READWRITE)
909 if (!ReadFileDescriptorsFromFDPipe())
910 return false;
911 if (header_fds > input_fds_.size())
912#endif // IPC_USES_READWRITE
913 error = "Message needs unreceived descriptors";
914 }
915
morrita4b5c28e22015-01-14 21:17:06916 if (header_fds > MessageAttachmentSet::kMaxDescriptorsPerMessage)
[email protected]334f3022012-02-29 22:48:14917 error = "Message requires an excessive number of descriptors";
918
919 if (error) {
920 LOG(WARNING) << error
921 << " channel:" << this
922 << " message-type:" << msg->type()
923 << " header()->num_fds:" << header_fds;
[email protected]334f3022012-02-29 22:48:14924 // Abort the connection.
925 ClearInputFDs();
926 return false;
927 }
928
[email protected]7e9eecb62012-04-09 21:40:44929 // The shenaniganery below with &foo.front() requires input_fds_ to have
930 // contiguous underlying storage (such as a simple array or a std::vector).
931 // This is why the header warns not to make input_fds_ a deque<>.
morrita4b5c28e22015-01-14 21:17:06932 msg->attachment_set()->AddDescriptorsToOwn(&input_fds_.front(), header_fds);
[email protected]334f3022012-02-29 22:48:14933 input_fds_.erase(input_fds_.begin(), input_fds_.begin() + header_fds);
934 return true;
935}
936
[email protected]2f60c9b2014-06-06 20:13:51937bool ChannelPosix::DidEmptyInputBuffers() {
[email protected]3d5a60b2012-03-01 21:41:47938 // When the input data buffer is empty, the fds should be too. If this is
939 // not the case, we probably have a rogue renderer which is trying to fill
940 // our descriptor table.
941 return input_fds_.empty();
942}
943
[email protected]2f60c9b2014-06-06 20:13:51944bool ChannelPosix::ExtractFileDescriptorsFromMsghdr(msghdr* msg) {
[email protected]334f3022012-02-29 22:48:14945 // Check that there are any control messages. On OSX, CMSG_FIRSTHDR will
946 // return an invalid non-NULL pointer in the case that controllen == 0.
947 if (msg->msg_controllen == 0)
948 return true;
949
950 for (cmsghdr* cmsg = CMSG_FIRSTHDR(msg);
951 cmsg;
952 cmsg = CMSG_NXTHDR(msg, cmsg)) {
953 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
954 unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0);
955 DCHECK_EQ(0U, payload_len % sizeof(int));
956 const int* file_descriptors = reinterpret_cast<int*>(CMSG_DATA(cmsg));
957 unsigned num_file_descriptors = payload_len / 4;
958 input_fds_.insert(input_fds_.end(),
959 file_descriptors,
960 file_descriptors + num_file_descriptors);
961
962 // Check this after adding the FDs so we don't leak them.
963 if (msg->msg_flags & MSG_CTRUNC) {
964 ClearInputFDs();
965 return false;
966 }
967
968 return true;
969 }
970 }
971
972 // No file descriptors found, but that's OK.
973 return true;
974}
975
[email protected]2f60c9b2014-06-06 20:13:51976void ChannelPosix::ClearInputFDs() {
[email protected]7e9eecb62012-04-09 21:40:44977 for (size_t i = 0; i < input_fds_.size(); ++i) {
[email protected]d89eec82013-12-03 14:10:59978 if (IGNORE_EINTR(close(input_fds_[i])) < 0)
[email protected]334f3022012-02-29 22:48:14979 PLOG(ERROR) << "close ";
[email protected]334f3022012-02-29 22:48:14980 }
[email protected]7e9eecb62012-04-09 21:40:44981 input_fds_.clear();
[email protected]334f3022012-02-29 22:48:14982}
983
[email protected]2f60c9b2014-06-06 20:13:51984void ChannelPosix::QueueCloseFDMessage(int fd, int hops) {
[email protected]dc875dc2013-10-15 00:07:00985 switch (hops) {
986 case 1:
987 case 2: {
988 // Create the message
989 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
[email protected]753bb252013-11-04 22:28:12990 CLOSE_FD_MESSAGE_TYPE,
991 IPC::Message::PRIORITY_NORMAL));
[email protected]dc875dc2013-10-15 00:07:00992 if (!msg->WriteInt(hops - 1) || !msg->WriteInt(fd)) {
993 NOTREACHED() << "Unable to pickle close fd.";
994 }
995 // Send(msg.release());
996 output_queue_.push(msg.release());
997 break;
998 }
999
1000 default:
1001 NOTREACHED();
1002 break;
1003 }
1004}
1005
[email protected]2f60c9b2014-06-06 20:13:511006void ChannelPosix::HandleInternalMessage(const Message& msg) {
[email protected]334f3022012-02-29 22:48:141007 // The Hello message contains only the process id.
[email protected]ce208f872012-03-07 20:42:561008 PickleIterator iter(msg);
[email protected]dc875dc2013-10-15 00:07:001009
1010 switch (msg.type()) {
1011 default:
1012 NOTREACHED();
1013 break;
1014
1015 case Channel::HELLO_MESSAGE_TYPE:
1016 int pid;
avi48fc13b2014-12-28 23:31:481017 if (!iter.ReadInt(&pid))
[email protected]dc875dc2013-10-15 00:07:001018 NOTREACHED();
[email protected]334f3022012-02-29 22:48:141019
1020#if defined(IPC_USES_READWRITE)
[email protected]dc875dc2013-10-15 00:07:001021 if (mode_ & MODE_SERVER_FLAG) {
1022 // With IPC_USES_READWRITE, the Hello message from the client to the
1023 // server also contains the fd_pipe_, which will be used for all
1024 // subsequent file descriptor passing.
morrita4b5c28e22015-01-14 21:17:061025 DCHECK_EQ(msg.attachment_set()->size(), 1U);
morrita1aa788c2015-01-31 05:45:421026 scoped_refptr<MessageAttachment> attachment;
1027 if (!msg.ReadAttachment(&iter, &attachment)) {
[email protected]dc875dc2013-10-15 00:07:001028 NOTREACHED();
1029 }
morrita1aa788c2015-01-31 05:45:421030 fd_pipe_.reset(attachment->TakePlatformFile());
[email protected]dc875dc2013-10-15 00:07:001031 }
[email protected]787f5e462013-10-11 04:22:341032#endif // IPC_USES_READWRITE
[email protected]dc875dc2013-10-15 00:07:001033 peer_pid_ = pid;
1034 listener()->OnChannelConnected(pid);
1035 break;
1036
1037#if defined(OS_MACOSX)
1038 case Channel::CLOSE_FD_MESSAGE_TYPE:
1039 int fd, hops;
avi48fc13b2014-12-28 23:31:481040 if (!iter.ReadInt(&hops))
[email protected]dc875dc2013-10-15 00:07:001041 NOTREACHED();
avi48fc13b2014-12-28 23:31:481042 if (!iter.ReadInt(&fd))
[email protected]dc875dc2013-10-15 00:07:001043 NOTREACHED();
1044 if (hops == 0) {
1045 if (fds_to_close_.erase(fd) > 0) {
[email protected]d89eec82013-12-03 14:10:591046 if (IGNORE_EINTR(close(fd)) < 0)
[email protected]dc875dc2013-10-15 00:07:001047 PLOG(ERROR) << "close";
1048 } else {
1049 NOTREACHED();
1050 }
1051 } else {
1052 QueueCloseFDMessage(fd, hops);
1053 }
1054 break;
1055#endif
1056 }
[email protected]334f3022012-02-29 22:48:141057}
1058
[email protected]2f60c9b2014-06-06 20:13:511059void ChannelPosix::Close() {
[email protected]fa95fc92008-12-08 18:10:141060 // Close can be called multiple time, so we need to make sure we're
1061 // idempotent.
1062
[email protected]22b42c52010-12-20 06:59:231063 ResetToAcceptingConnectionState();
[email protected]fa95fc92008-12-08 18:10:141064
[email protected]22b42c52010-12-20 06:59:231065 if (must_unlink_) {
1066 unlink(pipe_name_.c_str());
1067 must_unlink_ = false;
1068 }
morritace44fef2014-09-29 22:25:541069
1070 if (server_listen_pipe_.is_valid()) {
hidehiko853d6082014-11-05 23:51:521071#if defined(OS_NACL_NONSFI)
hidehikoc2eec0d2014-10-24 03:49:271072 LOG(FATAL)
1073 << "IPC channels in nacl_helper_nonsfi should not be SERVER mode.";
1074#else
morritace44fef2014-09-29 22:25:541075 server_listen_pipe_.reset();
[email protected]22b42c52010-12-20 06:59:231076 // Unregister libevent for the listening socket and close it.
1077 server_listen_connection_watcher_.StopWatchingFileDescriptor();
hidehikoc2eec0d2014-10-24 03:49:271078#endif
[email protected]fa95fc92008-12-08 18:10:141079 }
1080
[email protected]2ce26c432011-09-19 17:08:121081 CloseClientFileDescriptor();
[email protected]fa95fc92008-12-08 18:10:141082}
1083
[email protected]2f60c9b2014-06-06 20:13:511084base::ProcessId ChannelPosix::GetPeerPID() const {
1085 return peer_pid_;
1086}
1087
[email protected]64860882014-08-04 23:44:171088base::ProcessId ChannelPosix::GetSelfPID() const {
1089 return GetHelloMessageProcId();
1090}
1091
morrita2ad0be42015-01-27 20:05:531092void ChannelPosix::ResetSafely(base::ScopedFD* fd) {
1093 if (!in_dtor_) {
1094 fd->reset();
1095 return;
1096 }
1097
1098 // crbug.com/449233
1099 // The CL [1] tightened the error check for closing FDs, but it turned
1100 // out that there are existing cases that hit the newly added check.
1101 // ResetSafely() is the workaround for that crash, turning it from
1102 // from PCHECK() to DPCHECK() so that it doesn't crash in production.
1103 // [1] https://crrev.com/ce44fef5fd60dd2be5c587d4b084bdcd36adcee4
1104 int fd_to_close = fd->release();
1105 if (-1 != fd_to_close) {
1106 int rv = IGNORE_EINTR(close(fd_to_close));
1107 DPCHECK(0 == rv);
1108 }
1109}
1110
[email protected]514411fc2008-12-10 22:28:111111//------------------------------------------------------------------------------
[email protected]2f60c9b2014-06-06 20:13:511112// Channel's methods
[email protected]22b42c52010-12-20 06:59:231113
[email protected]313c00e52011-08-09 06:46:061114// static
[email protected]2f60c9b2014-06-06 20:13:511115scoped_ptr<Channel> Channel::Create(
1116 const IPC::ChannelHandle &channel_handle, Mode mode, Listener* listener) {
dchengecc340f2014-10-17 00:43:541117 return make_scoped_ptr(new ChannelPosix(channel_handle, mode, listener));
[email protected]313c00e52011-08-09 06:46:061118}
1119
[email protected]5c41e6e12012-03-17 02:20:461120// static
1121std::string Channel::GenerateVerifiedChannelID(const std::string& prefix) {
1122 // A random name is sufficient validation on posix systems, so we don't need
1123 // an additional shared secret.
1124
1125 std::string id = prefix;
1126 if (!id.empty())
1127 id.append(".");
1128
1129 return id.append(GenerateUniqueRandomChannelID());
1130}
1131
1132
[email protected]2f60c9b2014-06-06 20:13:511133bool Channel::IsNamedServerInitialized(
1134 const std::string& channel_id) {
1135 return ChannelPosix::IsNamedServerInitialized(channel_id);
1136}
1137
perkjdbcac352014-12-11 17:27:581138#if defined(OS_LINUX)
1139// static
1140void Channel::SetGlobalPid(int pid) {
1141 ChannelPosix::SetGlobalPid(pid);
1142}
1143#endif // OS_LINUX
1144
[email protected]d4651ff2008-12-02 16:51:581145} // namespace IPC