blob: 3972788772eed771ecc1b3df6250492e4fece7dd [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]e66ef602013-07-24 05:15:2432#include "base/process/process_handle.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]4aa794a12013-06-11 06:32:1835#include "base/strings/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]bdf9bdc2013-03-13 04:23:1043#include "ipc/unix_domain_socket_util.h"
[email protected]d4651ff2008-12-02 16:51:5844
45namespace IPC {
46
[email protected]5f594c02009-05-01 22:37:5947// IPC channels on Windows use named pipes (CreateNamedPipe()) with
[email protected]22b42c52010-12-20 06:59:2348// channel ids as the pipe names. Channels on POSIX use sockets as
49// pipes These don't quite line up.
[email protected]5f594c02009-05-01 22:37:5950//
[email protected]22b42c52010-12-20 06:59:2351// When creating a child subprocess we use a socket pair and the parent side of
52// the fork arranges it such that the initial control channel ends up on the
[email protected]cc8f1462009-06-12 17:36:5553// magic file descriptor kPrimaryIPCChannel in the child. Future
[email protected]5f594c02009-05-01 22:37:5954// connections (file descriptors) can then be passed via that
55// connection via sendmsg().
[email protected]22b42c52010-12-20 06:59:2356//
57// A POSIX IPC channel can also be set up as a server for a bound UNIX domain
58// socket, and will handle multiple connect and disconnect sequences. Currently
59// it is limited to one connection at a time.
[email protected]5f594c02009-05-01 22:37:5960
[email protected]fa95fc92008-12-08 18:10:1461//------------------------------------------------------------------------------
[email protected]fa95fc92008-12-08 18:10:1462namespace {
63
[email protected]5f594c02009-05-01 22:37:5964// The PipeMap class works around this quirk related to unit tests:
[email protected]e8fce882009-01-20 22:02:5865//
[email protected]5f594c02009-05-01 22:37:5966// When running as a server, we install the client socket in a
[email protected]cc8f1462009-06-12 17:36:5567// specific file descriptor number (@kPrimaryIPCChannel). However, we
[email protected]5f594c02009-05-01 22:37:5968// also have to support the case where we are running unittests in the
69// same process. (We do not support forking without execing.)
[email protected]e8fce882009-01-20 22:02:5870//
71// Case 1: normal running
72// The IPC server object will install a mapping in PipeMap from the
73// name which it was given to the client pipe. When forking the client, the
74// GetClientFileDescriptorMapping will ensure that the socket is installed in
[email protected]cc8f1462009-06-12 17:36:5575// the magic slot (@kPrimaryIPCChannel). The client will search for the
[email protected]e8fce882009-01-20 22:02:5876// mapping, but it won't find any since we are in a new process. Thus the
77// magic fd number is returned. Once the client connects, the server will
[email protected]5f594c02009-05-01 22:37:5978// close its copy of the client socket and remove the mapping.
[email protected]e8fce882009-01-20 22:02:5879//
80// Case 2: unittests - client and server in the same process
81// The IPC server will install a mapping as before. The client will search
82// for a mapping and find out. It duplicates the file descriptor and
83// connects. Once the client connects, the server will close the original
84// copy of the client socket and remove the mapping. Thus, when the client
85// object closes, it will close the only remaining copy of the client socket
86// in the fd table and the server will see EOF on its side.
87//
88// TODO(port): a client process cannot connect to multiple IPC channels with
89// this scheme.
90
91class PipeMap {
92 public:
[email protected]864b5582010-12-04 23:00:1093 static PipeMap* GetInstance() {
94 return Singleton<PipeMap>::get();
95 }
96
[email protected]42ce94e2010-12-08 19:28:0997 ~PipeMap() {
98 // Shouldn't have left over pipes.
[email protected]f6b8ce32011-03-02 00:03:1899 DCHECK(map_.empty());
[email protected]42ce94e2010-12-08 19:28:09100 }
101
[email protected]e8fce882009-01-20 22:02:58102 // Lookup a given channel id. Return -1 if not found.
103 int Lookup(const std::string& channel_id) {
[email protected]20305ec2011-01-21 04:55:52104 base::AutoLock locked(lock_);
[email protected]e8fce882009-01-20 22:02:58105
106 ChannelToFDMap::const_iterator i = map_.find(channel_id);
107 if (i == map_.end())
108 return -1;
109 return i->second;
110 }
111
112 // Remove the mapping for the given channel id. No error is signaled if the
113 // channel_id doesn't exist
[email protected]2ce26c432011-09-19 17:08:12114 void Remove(const std::string& channel_id) {
[email protected]20305ec2011-01-21 04:55:52115 base::AutoLock locked(lock_);
[email protected]2ce26c432011-09-19 17:08:12116 map_.erase(channel_id);
[email protected]e8fce882009-01-20 22:02:58117 }
118
119 // Insert a mapping from @channel_id to @fd. It's a fatal error to insert a
120 // mapping if one already exists for the given channel_id
121 void Insert(const std::string& channel_id, int fd) {
[email protected]20305ec2011-01-21 04:55:52122 base::AutoLock locked(lock_);
[email protected]60ea6052011-04-18 20:07:08123 DCHECK_NE(-1, fd);
[email protected]e8fce882009-01-20 22:02:58124
125 ChannelToFDMap::const_iterator i = map_.find(channel_id);
[email protected]d2e884d2009-06-22 20:37:52126 CHECK(i == map_.end()) << "Creating second IPC server (fd " << fd << ") "
127 << "for '" << channel_id << "' while first "
128 << "(fd " << i->second << ") still exists";
[email protected]e8fce882009-01-20 22:02:58129 map_[channel_id] = fd;
130 }
131
132 private:
[email protected]20305ec2011-01-21 04:55:52133 base::Lock lock_;
[email protected]e8fce882009-01-20 22:02:58134 typedef std::map<std::string, int> ChannelToFDMap;
135 ChannelToFDMap map_;
[email protected]864b5582010-12-04 23:00:10136
137 friend struct DefaultSingletonTraits<PipeMap>;
[email protected]e097b932014-03-19 06:34:52138#if defined(OS_ANDROID)
139 friend void ::IPC::Channel::NotifyProcessForkedForTesting();
140#endif
[email protected]e8fce882009-01-20 22:02:58141};
142
[email protected]df3c1ca12008-12-19 21:37:01143//------------------------------------------------------------------------------
[email protected]fa95fc92008-12-08 18:10:14144
[email protected]86c3d9e2009-12-08 14:48:08145bool SocketWriteErrorIsRecoverable() {
146#if defined(OS_MACOSX)
147 // On OS X if sendmsg() is trying to send fds between processes and there
148 // isn't enough room in the output buffer to send the fd structure over
149 // atomically then EMSGSIZE is returned.
150 //
151 // EMSGSIZE presents a problem since the system APIs can only call us when
152 // there's room in the socket buffer and not when there is "enough" room.
153 //
154 // The current behavior is to return to the event loop when EMSGSIZE is
155 // received and hopefull service another FD. This is however still
156 // technically a busy wait since the event loop will call us right back until
157 // the receiver has read enough data to allow passing the FD over atomically.
158 return errno == EAGAIN || errno == EMSGSIZE;
159#else
160 return errno == EAGAIN;
[email protected]22b42c52010-12-20 06:59:23161#endif // OS_MACOSX
[email protected]86c3d9e2009-12-08 14:48:08162}
163
[email protected]fa95fc92008-12-08 18:10:14164} // namespace
[email protected]e097b932014-03-19 06:34:52165
166#if defined(OS_ANDROID)
167// When we fork for simple tests on Android, we can't 'exec', so we need to
168// reset these entries manually to get the expected testing behavior.
169void Channel::NotifyProcessForkedForTesting() {
170 PipeMap::GetInstance()->map_.clear();
171}
172#endif
173
[email protected]d4651ff2008-12-02 16:51:58174//------------------------------------------------------------------------------
175
[email protected]e1d67a882011-08-31 21:11:04176#if defined(OS_LINUX)
[email protected]2f60c9b2014-06-06 20:13:51177int ChannelPosix::global_pid_ = 0;
[email protected]e1d67a882011-08-31 21:11:04178#endif // OS_LINUX
179
[email protected]2f60c9b2014-06-06 20:13:51180ChannelPosix::ChannelPosix(const IPC::ChannelHandle& channel_handle,
181 Mode mode, Listener* listener)
[email protected]d805c6a2012-03-08 12:30:28182 : ChannelReader(listener),
183 mode_(mode),
[email protected]0a6fc4b2012-04-05 02:38:34184 peer_pid_(base::kNullProcessId),
[email protected]e45e6c02008-12-15 22:02:17185 is_blocked_on_write_(false),
[email protected]22b42c52010-12-20 06:59:23186 waiting_connect_(true),
[email protected]e45e6c02008-12-15 22:02:17187 message_send_bytes_written_(0),
188 server_listen_pipe_(-1),
189 pipe_(-1),
[email protected]df3c1ca12008-12-19 21:37:01190 client_pipe_(-1),
[email protected]e40f5a0b2010-12-08 21:22:24191#if defined(IPC_USES_READWRITE)
[email protected]baf556a2009-09-04 21:34:05192 fd_pipe_(-1),
193 remote_fd_pipe_(-1),
[email protected]22b42c52010-12-20 06:59:23194#endif // IPC_USES_READWRITE
195 pipe_name_(channel_handle.name),
[email protected]bf84c582011-08-23 03:17:02196 must_unlink_(false) {
[email protected]df60edb2011-06-21 22:48:29197 memset(input_cmsg_buf_, 0, sizeof(input_cmsg_buf_));
[email protected]1707726c2011-02-03 20:35:09198 if (!CreatePipe(channel_handle)) {
[email protected]22b42c52010-12-20 06:59:23199 // The pipe may have been closed already.
[email protected]1707726c2011-02-03 20:35:09200 const char *modestr = (mode_ & MODE_SERVER_FLAG) ? "server" : "client";
[email protected]42ce94e2010-12-08 19:28:09201 LOG(WARNING) << "Unable to create pipe named \"" << channel_handle.name
[email protected]22b42c52010-12-20 06:59:23202 << "\" in " << modestr << " mode";
[email protected]fa95fc92008-12-08 18:10:14203 }
[email protected]d4651ff2008-12-02 16:51:58204}
205
[email protected]2f60c9b2014-06-06 20:13:51206ChannelPosix::~ChannelPosix() {
[email protected]601858c02010-09-01 17:08:20207 Close();
208}
209
[email protected]d2e884d2009-06-22 20:37:52210bool SocketPair(int* fd1, int* fd2) {
211 int pipe_fds[2];
212 if (socketpair(AF_UNIX, SOCK_STREAM, 0, pipe_fds) != 0) {
[email protected]57b765672009-10-13 18:27:40213 PLOG(ERROR) << "socketpair()";
[email protected]d2e884d2009-06-22 20:37:52214 return false;
215 }
216
217 // Set both ends to be non-blocking.
218 if (fcntl(pipe_fds[0], F_SETFL, O_NONBLOCK) == -1 ||
219 fcntl(pipe_fds[1], F_SETFL, O_NONBLOCK) == -1) {
[email protected]57b765672009-10-13 18:27:40220 PLOG(ERROR) << "fcntl(O_NONBLOCK)";
[email protected]d89eec82013-12-03 14:10:59221 if (IGNORE_EINTR(close(pipe_fds[0])) < 0)
[email protected]70eb6572010-06-23 00:37:46222 PLOG(ERROR) << "close";
[email protected]d89eec82013-12-03 14:10:59223 if (IGNORE_EINTR(close(pipe_fds[1])) < 0)
[email protected]70eb6572010-06-23 00:37:46224 PLOG(ERROR) << "close";
[email protected]d2e884d2009-06-22 20:37:52225 return false;
226 }
227
228 *fd1 = pipe_fds[0];
229 *fd2 = pipe_fds[1];
230
231 return true;
232}
233
[email protected]2f60c9b2014-06-06 20:13:51234bool ChannelPosix::CreatePipe(
[email protected]1707726c2011-02-03 20:35:09235 const IPC::ChannelHandle& channel_handle) {
[email protected]fa95fc92008-12-08 18:10:14236 DCHECK(server_listen_pipe_ == -1 && pipe_ == -1);
[email protected]22b42c52010-12-20 06:59:23237
238 // Four possible cases:
239 // 1) It's a channel wrapping a pipe that is given to us.
240 // 2) It's for a named channel, so we create it.
241 // 3) It's for a client that we implement ourself. This is used
[email protected]e097b932014-03-19 06:34:52242 // in single-process unittesting.
[email protected]22b42c52010-12-20 06:59:23243 // 4) It's the initial IPC channel:
244 // 4a) Client side: Pull the pipe out of the GlobalDescriptors set.
245 // 4b) Server side: create the pipe.
246
[email protected]6aad23f92011-03-02 22:27:14247 int local_pipe = -1;
[email protected]22b42c52010-12-20 06:59:23248 if (channel_handle.socket.fd != -1) {
249 // Case 1 from comment above.
[email protected]6aad23f92011-03-02 22:27:14250 local_pipe = channel_handle.socket.fd;
[email protected]22b42c52010-12-20 06:59:23251#if defined(IPC_USES_READWRITE)
252 // Test the socket passed into us to make sure it is nonblocking.
253 // We don't want to call read/write on a blocking socket.
[email protected]6aad23f92011-03-02 22:27:14254 int value = fcntl(local_pipe, F_GETFL);
[email protected]22b42c52010-12-20 06:59:23255 if (value == -1) {
256 PLOG(ERROR) << "fcntl(F_GETFL) " << pipe_name_;
257 return false;
258 }
259 if (!(value & O_NONBLOCK)) {
260 LOG(ERROR) << "Socket " << pipe_name_ << " must be O_NONBLOCK";
261 return false;
262 }
263#endif // IPC_USES_READWRITE
[email protected]1707726c2011-02-03 20:35:09264 } else if (mode_ & MODE_NAMED_FLAG) {
[email protected]22b42c52010-12-20 06:59:23265 // Case 2 from comment above.
[email protected]1707726c2011-02-03 20:35:09266 if (mode_ & MODE_SERVER_FLAG) {
[email protected]bdf9bdc2013-03-13 04:23:10267 if (!CreateServerUnixDomainSocket(base::FilePath(pipe_name_),
268 &local_pipe)) {
[email protected]df3c1ca12008-12-19 21:37:01269 return false;
270 }
[email protected]56f0f262011-02-24 17:14:36271 must_unlink_ = true;
[email protected]1707726c2011-02-03 20:35:09272 } else if (mode_ & MODE_CLIENT_FLAG) {
[email protected]bdf9bdc2013-03-13 04:23:10273 if (!CreateClientUnixDomainSocket(base::FilePath(pipe_name_),
274 &local_pipe)) {
[email protected]df3c1ca12008-12-19 21:37:01275 return false;
276 }
[email protected]1707726c2011-02-03 20:35:09277 } else {
[email protected]6aad23f92011-03-02 22:27:14278 LOG(ERROR) << "Bad mode: " << mode_;
[email protected]1707726c2011-02-03 20:35:09279 return false;
[email protected]fa95fc92008-12-08 18:10:14280 }
281 } else {
[email protected]6aad23f92011-03-02 22:27:14282 local_pipe = PipeMap::GetInstance()->Lookup(pipe_name_);
[email protected]1707726c2011-02-03 20:35:09283 if (mode_ & MODE_CLIENT_FLAG) {
[email protected]6aad23f92011-03-02 22:27:14284 if (local_pipe != -1) {
[email protected]22b42c52010-12-20 06:59:23285 // Case 3 from comment above.
286 // We only allow one connection.
[email protected]6aad23f92011-03-02 22:27:14287 local_pipe = HANDLE_EINTR(dup(local_pipe));
[email protected]2ce26c432011-09-19 17:08:12288 PipeMap::GetInstance()->Remove(pipe_name_);
[email protected]d2e884d2009-06-22 20:37:52289 } else {
[email protected]22b42c52010-12-20 06:59:23290 // Case 4a from comment above.
[email protected]554a8852009-11-30 22:14:37291 // Guard against inappropriate reuse of the initial IPC channel. If
292 // an IPC channel closes and someone attempts to reuse it by name, the
293 // initial channel must not be recycled here. http://crbug.com/26754.
294 static bool used_initial_channel = false;
295 if (used_initial_channel) {
[email protected]9f816f72010-03-16 20:31:10296 LOG(FATAL) << "Denying attempt to reuse initial IPC channel for "
297 << pipe_name_;
[email protected]554a8852009-11-30 22:14:37298 return false;
299 }
300 used_initial_channel = true;
301
[email protected]6aad23f92011-03-02 22:27:14302 local_pipe =
303 base::GlobalDescriptors::GetInstance()->Get(kPrimaryIPCChannel);
[email protected]df3c1ca12008-12-19 21:37:01304 }
[email protected]1707726c2011-02-03 20:35:09305 } else if (mode_ & MODE_SERVER_FLAG) {
[email protected]22b42c52010-12-20 06:59:23306 // Case 4b from comment above.
[email protected]6aad23f92011-03-02 22:27:14307 if (local_pipe != -1) {
[email protected]22b42c52010-12-20 06:59:23308 LOG(ERROR) << "Server already exists for " << pipe_name_;
[email protected]baf556a2009-09-04 21:34:05309 return false;
310 }
[email protected]2ce26c432011-09-19 17:08:12311 base::AutoLock lock(client_pipe_lock_);
[email protected]6aad23f92011-03-02 22:27:14312 if (!SocketPair(&local_pipe, &client_pipe_))
[email protected]22b42c52010-12-20 06:59:23313 return false;
314 PipeMap::GetInstance()->Insert(pipe_name_, client_pipe_);
315 } else {
[email protected]6aad23f92011-03-02 22:27:14316 LOG(ERROR) << "Bad mode: " << mode_;
[email protected]22b42c52010-12-20 06:59:23317 return false;
[email protected]baf556a2009-09-04 21:34:05318 }
319 }
[email protected]22b42c52010-12-20 06:59:23320
[email protected]22b42c52010-12-20 06:59:23321#if defined(IPC_USES_READWRITE)
322 // Create a dedicated socketpair() for exchanging file descriptors.
323 // See comments for IPC_USES_READWRITE for details.
[email protected]1707726c2011-02-03 20:35:09324 if (mode_ & MODE_CLIENT_FLAG) {
[email protected]22b42c52010-12-20 06:59:23325 if (!SocketPair(&fd_pipe_, &remote_fd_pipe_)) {
326 return false;
327 }
328 }
329#endif // IPC_USES_READWRITE
330
[email protected]6aad23f92011-03-02 22:27:14331 if ((mode_ & MODE_SERVER_FLAG) && (mode_ & MODE_NAMED_FLAG)) {
332 server_listen_pipe_ = local_pipe;
333 local_pipe = -1;
334 }
335
336 pipe_ = local_pipe;
[email protected]fa95fc92008-12-08 18:10:14337 return true;
[email protected]d4651ff2008-12-02 16:51:58338}
339
[email protected]2f60c9b2014-06-06 20:13:51340bool ChannelPosix::Connect() {
[email protected]22b42c52010-12-20 06:59:23341 if (server_listen_pipe_ == -1 && pipe_ == -1) {
[email protected]0e8a7912014-02-21 00:18:29342 DLOG(WARNING) << "Channel creation failed: " << pipe_name_;
[email protected]22b42c52010-12-20 06:59:23343 return false;
344 }
345
346 bool did_connect = true;
347 if (server_listen_pipe_ != -1) {
348 // Watch the pipe for connections, and turn any connections into
349 // active sockets.
[email protected]fd0a773a2013-04-30 20:55:03350 base::MessageLoopForIO::current()->WatchFileDescriptor(
[email protected]e45e6c02008-12-15 22:02:17351 server_listen_pipe_,
352 true,
[email protected]fd0a773a2013-04-30 20:55:03353 base::MessageLoopForIO::WATCH_READ,
[email protected]e45e6c02008-12-15 22:02:17354 &server_listen_connection_watcher_,
355 this);
[email protected]fa95fc92008-12-08 18:10:14356 } else {
[email protected]22b42c52010-12-20 06:59:23357 did_connect = AcceptConnection();
[email protected]fa95fc92008-12-08 18:10:14358 }
[email protected]22b42c52010-12-20 06:59:23359 return did_connect;
[email protected]d4651ff2008-12-02 16:51:58360}
[email protected]fa95fc92008-12-08 18:10:14361
[email protected]2f60c9b2014-06-06 20:13:51362void ChannelPosix::CloseFileDescriptors(Message* msg) {
[email protected]dc875dc2013-10-15 00:07:00363#if defined(OS_MACOSX)
364 // There is a bug on OSX which makes it dangerous to close
365 // a file descriptor while it is in transit. So instead we
366 // store the file descriptor in a set and send a message to
367 // the recipient, which is queued AFTER the message that
368 // sent the FD. The recipient will reply to the message,
369 // letting us know that it is now safe to close the file
370 // descriptor. For more information, see:
371 // http://crbug.com/298276
372 std::vector<int> to_close;
373 msg->file_descriptor_set()->ReleaseFDsToClose(&to_close);
374 for (size_t i = 0; i < to_close.size(); i++) {
375 fds_to_close_.insert(to_close[i]);
376 QueueCloseFDMessage(to_close[i], 2);
377 }
378#else
379 msg->file_descriptor_set()->CommitAll();
380#endif
381}
382
[email protected]2f60c9b2014-06-06 20:13:51383bool ChannelPosix::ProcessOutgoingMessages() {
[email protected]fa95fc92008-12-08 18:10:14384 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
385 // no connection?
[email protected]22b42c52010-12-20 06:59:23386 if (output_queue_.empty())
[email protected]c7f91e82010-12-20 06:39:44387 return true;
[email protected]c7f91e82010-12-20 06:39:44388
[email protected]22b42c52010-12-20 06:59:23389 if (pipe_ == -1)
[email protected]fa95fc92008-12-08 18:10:14390 return false;
391
[email protected]fa95fc92008-12-08 18:10:14392 // Write out all the messages we can till the write blocks or there are no
393 // more outgoing messages.
394 while (!output_queue_.empty()) {
395 Message* msg = output_queue_.front();
396
397 size_t amt_to_write = msg->size() - message_send_bytes_written_;
[email protected]60ea6052011-04-18 20:07:08398 DCHECK_NE(0U, amt_to_write);
[email protected]baf556a2009-09-04 21:34:05399 const char* out_bytes = reinterpret_cast<const char*>(msg->data()) +
[email protected]fa95fc92008-12-08 18:10:14400 message_send_bytes_written_;
[email protected]526776c2009-02-07 00:39:26401
[email protected]157c61b2009-05-01 21:37:31402 struct msghdr msgh = {0};
403 struct iovec iov = {const_cast<char*>(out_bytes), amt_to_write};
404 msgh.msg_iov = &iov;
405 msgh.msg_iovlen = 1;
406 char buf[CMSG_SPACE(
[email protected]05094a32011-09-01 00:50:13407 sizeof(int) * FileDescriptorSet::kMaxDescriptorsPerMessage)];
[email protected]526776c2009-02-07 00:39:26408
[email protected]baf556a2009-09-04 21:34:05409 ssize_t bytes_written = 1;
410 int fd_written = -1;
411
[email protected]157c61b2009-05-01 21:37:31412 if (message_send_bytes_written_ == 0 &&
413 !msg->file_descriptor_set()->empty()) {
414 // This is the first chunk of a message which has descriptors to send
415 struct cmsghdr *cmsg;
416 const unsigned num_fds = msg->file_descriptor_set()->size();
[email protected]526776c2009-02-07 00:39:26417
[email protected]05094a32011-09-01 00:50:13418 DCHECK(num_fds <= FileDescriptorSet::kMaxDescriptorsPerMessage);
[email protected]aac449e2010-06-10 21:39:04419 if (msg->file_descriptor_set()->ContainsDirectoryDescriptor()) {
420 LOG(FATAL) << "Panic: attempting to transport directory descriptor over"
421 " IPC. Aborting to maintain sandbox isolation.";
422 // If you have hit this then something tried to send a file descriptor
423 // to a directory over an IPC channel. Since IPC channels span
424 // sandboxes this is very bad: the receiving process can use openat
425 // with ".." elements in the path in order to reach the real
426 // filesystem.
427 }
[email protected]526776c2009-02-07 00:39:26428
[email protected]157c61b2009-05-01 21:37:31429 msgh.msg_control = buf;
430 msgh.msg_controllen = CMSG_SPACE(sizeof(int) * num_fds);
431 cmsg = CMSG_FIRSTHDR(&msgh);
432 cmsg->cmsg_level = SOL_SOCKET;
433 cmsg->cmsg_type = SCM_RIGHTS;
434 cmsg->cmsg_len = CMSG_LEN(sizeof(int) * num_fds);
435 msg->file_descriptor_set()->GetDescriptors(
436 reinterpret_cast<int*>(CMSG_DATA(cmsg)));
437 msgh.msg_controllen = cmsg->cmsg_len;
[email protected]526776c2009-02-07 00:39:26438
[email protected]168ae922009-12-04 18:08:45439 // DCHECK_LE above already checks that
[email protected]05094a32011-09-01 00:50:13440 // num_fds < kMaxDescriptorsPerMessage so no danger of overflow.
[email protected]168ae922009-12-04 18:08:45441 msg->header()->num_fds = static_cast<uint16>(num_fds);
[email protected]baf556a2009-09-04 21:34:05442
[email protected]e40f5a0b2010-12-08 21:22:24443#if defined(IPC_USES_READWRITE)
[email protected]d805c6a2012-03-08 12:30:28444 if (!IsHelloMessage(*msg)) {
[email protected]baf556a2009-09-04 21:34:05445 // Only the Hello message sends the file descriptor with the message.
446 // Subsequently, we can send file descriptors on the dedicated
447 // fd_pipe_ which makes Seccomp sandbox operation more efficient.
448 struct iovec fd_pipe_iov = { const_cast<char *>(""), 1 };
449 msgh.msg_iov = &fd_pipe_iov;
450 fd_written = fd_pipe_;
451 bytes_written = HANDLE_EINTR(sendmsg(fd_pipe_, &msgh, MSG_DONTWAIT));
452 msgh.msg_iov = &iov;
453 msgh.msg_controllen = 0;
454 if (bytes_written > 0) {
[email protected]dc875dc2013-10-15 00:07:00455 CloseFileDescriptors(msg);
[email protected]baf556a2009-09-04 21:34:05456 }
457 }
[email protected]22b42c52010-12-20 06:59:23458#endif // IPC_USES_READWRITE
[email protected]157c61b2009-05-01 21:37:31459 }
460
[email protected]baf556a2009-09-04 21:34:05461 if (bytes_written == 1) {
462 fd_written = pipe_;
[email protected]e40f5a0b2010-12-08 21:22:24463#if defined(IPC_USES_READWRITE)
[email protected]d805c6a2012-03-08 12:30:28464 if ((mode_ & MODE_CLIENT_FLAG) && IsHelloMessage(*msg)) {
[email protected]7ee1a44c2010-07-23 14:18:59465 DCHECK_EQ(msg->file_descriptor_set()->size(), 1U);
[email protected]baf556a2009-09-04 21:34:05466 }
[email protected]22b42c52010-12-20 06:59:23467 if (!msgh.msg_controllen) {
[email protected]baf556a2009-09-04 21:34:05468 bytes_written = HANDLE_EINTR(write(pipe_, out_bytes, amt_to_write));
469 } else
[email protected]22b42c52010-12-20 06:59:23470#endif // IPC_USES_READWRITE
[email protected]baf556a2009-09-04 21:34:05471 {
472 bytes_written = HANDLE_EINTR(sendmsg(pipe_, &msgh, MSG_DONTWAIT));
473 }
474 }
[email protected]157c61b2009-05-01 21:37:31475 if (bytes_written > 0)
[email protected]dc875dc2013-10-15 00:07:00476 CloseFileDescriptors(msg);
[email protected]fa95fc92008-12-08 18:10:14477
[email protected]86c3d9e2009-12-08 14:48:08478 if (bytes_written < 0 && !SocketWriteErrorIsRecoverable()) {
[email protected]0e8a7912014-02-21 00:18:29479 // We can't close the pipe here, because calling OnChannelError
480 // may destroy this object, and that would be bad if we are
481 // called from Send(). Instead, we return false and hope the
482 // caller will close the pipe. If they do not, the pipe will
483 // still be closed next time OnFileCanReadWithoutBlocking is
484 // called.
[email protected]cb38c0b22009-05-27 18:29:48485#if defined(OS_MACOSX)
486 // On OSX writing to a pipe with no listener returns EPERM.
487 if (errno == EPERM) {
[email protected]cb38c0b22009-05-27 18:29:48488 return false;
489 }
490#endif // OS_MACOSX
[email protected]7bf54f5e2009-10-23 01:48:21491 if (errno == EPIPE) {
[email protected]7bf54f5e2009-10-23 01:48:21492 return false;
493 }
[email protected]780ae942009-12-03 13:35:46494 PLOG(ERROR) << "pipe error on "
495 << fd_written
[email protected]9fbc2f2f2011-02-11 08:43:52496 << " Currently writing message of size: "
[email protected]86c3d9e2009-12-08 14:48:08497 << msg->size();
[email protected]fa95fc92008-12-08 18:10:14498 return false;
499 }
500
501 if (static_cast<size_t>(bytes_written) != amt_to_write) {
[email protected]3d1b6662009-01-29 17:03:11502 if (bytes_written > 0) {
503 // If write() fails with EAGAIN then bytes_written will be -1.
504 message_send_bytes_written_ += bytes_written;
505 }
[email protected]fa95fc92008-12-08 18:10:14506
507 // Tell libevent to call us back once things are unblocked.
[email protected]e45e6c02008-12-15 22:02:17508 is_blocked_on_write_ = true;
[email protected]fd0a773a2013-04-30 20:55:03509 base::MessageLoopForIO::current()->WatchFileDescriptor(
[email protected]e45e6c02008-12-15 22:02:17510 pipe_,
511 false, // One shot
[email protected]fd0a773a2013-04-30 20:55:03512 base::MessageLoopForIO::WATCH_WRITE,
[email protected]e45e6c02008-12-15 22:02:17513 &write_watcher_,
514 this);
[email protected]3d1b6662009-01-29 17:03:11515 return true;
[email protected]fa95fc92008-12-08 18:10:14516 } else {
517 message_send_bytes_written_ = 0;
518
519 // Message sent OK!
[email protected]2a9d601b2010-10-19 23:50:00520 DVLOG(2) << "sent message @" << msg << " on channel @" << this
[email protected]5484722e2010-12-09 01:13:12521 << " with type " << msg->type() << " on fd " << pipe_;
[email protected]baf556a2009-09-04 21:34:05522 delete output_queue_.front();
[email protected]fa95fc92008-12-08 18:10:14523 output_queue_.pop();
[email protected]fa95fc92008-12-08 18:10:14524 }
525 }
526 return true;
527}
528
[email protected]2f60c9b2014-06-06 20:13:51529bool ChannelPosix::Send(Message* message) {
[email protected]2a9d601b2010-10-19 23:50:00530 DVLOG(2) << "sending message @" << message << " on channel @" << this
531 << " with type " << message->type()
532 << " (" << output_queue_.size() << " in queue)";
[email protected]fa95fc92008-12-08 18:10:14533
[email protected]4c2c1db2009-03-20 20:56:55534#ifdef IPC_MESSAGE_LOG_ENABLED
[email protected]8e8bb6d2010-12-13 08:18:55535 Logging::GetInstance()->OnSendMessage(message, "");
[email protected]22b42c52010-12-20 06:59:23536#endif // IPC_MESSAGE_LOG_ENABLED
[email protected]fa95fc92008-12-08 18:10:14537
[email protected]2c391df2012-09-18 03:41:29538 message->TraceMessageBegin();
[email protected]fa95fc92008-12-08 18:10:14539 output_queue_.push(message);
[email protected]22b42c52010-12-20 06:59:23540 if (!is_blocked_on_write_ && !waiting_connect_) {
[email protected]13ffc272014-02-18 17:42:20541 return ProcessOutgoingMessages();
[email protected]fa95fc92008-12-08 18:10:14542 }
543
544 return true;
545}
546
[email protected]2f60c9b2014-06-06 20:13:51547int ChannelPosix::GetClientFileDescriptor() const {
[email protected]2ce26c432011-09-19 17:08:12548 base::AutoLock lock(client_pipe_lock_);
[email protected]cc8f1462009-06-12 17:36:55549 return client_pipe_;
[email protected]df3c1ca12008-12-19 21:37:01550}
551
[email protected]2f60c9b2014-06-06 20:13:51552int ChannelPosix::TakeClientFileDescriptor() {
[email protected]2ce26c432011-09-19 17:08:12553 base::AutoLock lock(client_pipe_lock_);
554 int fd = client_pipe_;
555 if (client_pipe_ != -1) {
556 PipeMap::GetInstance()->Remove(pipe_name_);
557 client_pipe_ = -1;
558 }
559 return fd;
560}
561
[email protected]2f60c9b2014-06-06 20:13:51562void ChannelPosix::CloseClientFileDescriptor() {
[email protected]2ce26c432011-09-19 17:08:12563 base::AutoLock lock(client_pipe_lock_);
564 if (client_pipe_ != -1) {
565 PipeMap::GetInstance()->Remove(pipe_name_);
[email protected]d89eec82013-12-03 14:10:59566 if (IGNORE_EINTR(close(client_pipe_)) < 0)
[email protected]2ce26c432011-09-19 17:08:12567 PLOG(ERROR) << "close " << pipe_name_;
568 client_pipe_ = -1;
569 }
570}
571
[email protected]2f60c9b2014-06-06 20:13:51572bool ChannelPosix::AcceptsConnections() const {
[email protected]22b42c52010-12-20 06:59:23573 return server_listen_pipe_ != -1;
574}
[email protected]9a44a4db62010-12-20 06:19:07575
[email protected]2f60c9b2014-06-06 20:13:51576bool ChannelPosix::HasAcceptedConnection() const {
[email protected]22b42c52010-12-20 06:59:23577 return AcceptsConnections() && pipe_ != -1;
578}
[email protected]9a44a4db62010-12-20 06:19:07579
[email protected]2f60c9b2014-06-06 20:13:51580bool ChannelPosix::GetPeerEuid(uid_t* peer_euid) const {
[email protected]bdf9bdc2013-03-13 04:23:10581 DCHECK(!(mode_ & MODE_SERVER) || HasAcceptedConnection());
582 return IPC::GetPeerEuid(pipe_, peer_euid);
[email protected]8ec3fbe2011-04-06 12:01:44583}
584
[email protected]2f60c9b2014-06-06 20:13:51585void ChannelPosix::ResetToAcceptingConnectionState() {
[email protected]22b42c52010-12-20 06:59:23586 // Unregister libevent for the unix domain socket and close it.
587 read_watcher_.StopWatchingFileDescriptor();
588 write_watcher_.StopWatchingFileDescriptor();
589 if (pipe_ != -1) {
[email protected]d89eec82013-12-03 14:10:59590 if (IGNORE_EINTR(close(pipe_)) < 0)
[email protected]22b42c52010-12-20 06:59:23591 PLOG(ERROR) << "close pipe_ " << pipe_name_;
592 pipe_ = -1;
593 }
594#if defined(IPC_USES_READWRITE)
595 if (fd_pipe_ != -1) {
[email protected]d89eec82013-12-03 14:10:59596 if (IGNORE_EINTR(close(fd_pipe_)) < 0)
[email protected]22b42c52010-12-20 06:59:23597 PLOG(ERROR) << "close fd_pipe_ " << pipe_name_;
598 fd_pipe_ = -1;
599 }
600 if (remote_fd_pipe_ != -1) {
[email protected]d89eec82013-12-03 14:10:59601 if (IGNORE_EINTR(close(remote_fd_pipe_)) < 0)
[email protected]22b42c52010-12-20 06:59:23602 PLOG(ERROR) << "close remote_fd_pipe_ " << pipe_name_;
603 remote_fd_pipe_ = -1;
604 }
605#endif // IPC_USES_READWRITE
[email protected]c7f91e82010-12-20 06:39:44606
[email protected]22b42c52010-12-20 06:59:23607 while (!output_queue_.empty()) {
608 Message* m = output_queue_.front();
609 output_queue_.pop();
610 delete m;
[email protected]c7f91e82010-12-20 06:39:44611 }
612
[email protected]22b42c52010-12-20 06:59:23613 // Close any outstanding, received file descriptors.
[email protected]334f3022012-02-29 22:48:14614 ClearInputFDs();
[email protected]dc875dc2013-10-15 00:07:00615
616#if defined(OS_MACOSX)
617 // Clear any outstanding, sent file descriptors.
618 for (std::set<int>::iterator i = fds_to_close_.begin();
619 i != fds_to_close_.end();
620 ++i) {
[email protected]d89eec82013-12-03 14:10:59621 if (IGNORE_EINTR(close(*i)) < 0)
[email protected]dc875dc2013-10-15 00:07:00622 PLOG(ERROR) << "close";
623 }
624 fds_to_close_.clear();
625#endif
[email protected]22b42c52010-12-20 06:59:23626}
627
[email protected]313c00e52011-08-09 06:46:06628// static
[email protected]2f60c9b2014-06-06 20:13:51629bool ChannelPosix::IsNamedServerInitialized(
[email protected]313c00e52011-08-09 06:46:06630 const std::string& channel_id) {
[email protected]7567484142013-07-11 17:36:07631 return base::PathExists(base::FilePath(channel_id));
[email protected]313c00e52011-08-09 06:46:06632}
633
[email protected]e1d67a882011-08-31 21:11:04634#if defined(OS_LINUX)
635// static
[email protected]2f60c9b2014-06-06 20:13:51636void ChannelPosix::SetGlobalPid(int pid) {
[email protected]e1d67a882011-08-31 21:11:04637 global_pid_ = pid;
638}
639#endif // OS_LINUX
640
[email protected]22b42c52010-12-20 06:59:23641// Called by libevent when we can read from the pipe without blocking.
[email protected]2f60c9b2014-06-06 20:13:51642void ChannelPosix::OnFileCanReadWithoutBlocking(int fd) {
[email protected]22b42c52010-12-20 06:59:23643 if (fd == server_listen_pipe_) {
644 int new_pipe = 0;
[email protected]bdf9bdc2013-03-13 04:23:10645 if (!ServerAcceptConnection(server_listen_pipe_, &new_pipe) ||
646 new_pipe < 0) {
[email protected]c7f91e82010-12-20 06:39:44647 Close();
[email protected]d805c6a2012-03-08 12:30:28648 listener()->OnChannelListenError();
[email protected]22b42c52010-12-20 06:59:23649 }
650
651 if (pipe_ != -1) {
652 // We already have a connection. We only handle one at a time.
653 // close our new descriptor.
654 if (HANDLE_EINTR(shutdown(new_pipe, SHUT_RDWR)) < 0)
[email protected]334f3022012-02-29 22:48:14655 DPLOG(ERROR) << "shutdown " << pipe_name_;
[email protected]d89eec82013-12-03 14:10:59656 if (IGNORE_EINTR(close(new_pipe)) < 0)
[email protected]334f3022012-02-29 22:48:14657 DPLOG(ERROR) << "close " << pipe_name_;
[email protected]d805c6a2012-03-08 12:30:28658 listener()->OnChannelDenied();
[email protected]c7f91e82010-12-20 06:39:44659 return;
[email protected]9a44a4db62010-12-20 06:19:07660 }
[email protected]22b42c52010-12-20 06:59:23661 pipe_ = new_pipe;
662
[email protected]8ec3fbe2011-04-06 12:01:44663 if ((mode_ & MODE_OPEN_ACCESS_FLAG) == 0) {
664 // Verify that the IPC channel peer is running as the same user.
665 uid_t client_euid;
[email protected]bdf9bdc2013-03-13 04:23:10666 if (!GetPeerEuid(&client_euid)) {
[email protected]334f3022012-02-29 22:48:14667 DLOG(ERROR) << "Unable to query client euid";
[email protected]8ec3fbe2011-04-06 12:01:44668 ResetToAcceptingConnectionState();
669 return;
670 }
671 if (client_euid != geteuid()) {
[email protected]334f3022012-02-29 22:48:14672 DLOG(WARNING) << "Client euid is not authorised";
[email protected]8ec3fbe2011-04-06 12:01:44673 ResetToAcceptingConnectionState();
674 return;
675 }
676 }
677
[email protected]22b42c52010-12-20 06:59:23678 if (!AcceptConnection()) {
679 NOTREACHED() << "AcceptConnection should not fail on server";
680 }
[email protected]22b42c52010-12-20 06:59:23681 waiting_connect_ = false;
682 } else if (fd == pipe_) {
[email protected]1707726c2011-02-03 20:35:09683 if (waiting_connect_ && (mode_ & MODE_SERVER_FLAG)) {
[email protected]22b42c52010-12-20 06:59:23684 waiting_connect_ = false;
685 }
686 if (!ProcessIncomingMessages()) {
[email protected]887250a2011-02-28 20:30:47687 // ClosePipeOnError may delete this object, so we mustn't call
688 // ProcessOutgoingMessages.
[email protected]22b42c52010-12-20 06:59:23689 ClosePipeOnError();
[email protected]dc875dc2013-10-15 00:07:00690 return;
[email protected]22b42c52010-12-20 06:59:23691 }
692 } else {
693 NOTREACHED() << "Unknown pipe " << fd;
[email protected]fa95fc92008-12-08 18:10:14694 }
695
696 // If we're a server and handshaking, then we want to make sure that we
697 // only send our handshake message after we've processed the client's.
698 // This gives us a chance to kill the client if the incoming handshake
[email protected]0e8a7912014-02-21 00:18:29699 // is invalid. This also flushes any closefd messages.
[email protected]dc875dc2013-10-15 00:07:00700 if (!is_blocked_on_write_) {
701 if (!ProcessOutgoingMessages()) {
702 ClosePipeOnError();
703 }
[email protected]fa95fc92008-12-08 18:10:14704 }
705}
706
707// Called by libevent when we can write to the pipe without blocking.
[email protected]2f60c9b2014-06-06 20:13:51708void ChannelPosix::OnFileCanWriteWithoutBlocking(int fd) {
[email protected]60ea6052011-04-18 20:07:08709 DCHECK_EQ(pipe_, fd);
[email protected]22b42c52010-12-20 06:59:23710 is_blocked_on_write_ = false;
[email protected]fa95fc92008-12-08 18:10:14711 if (!ProcessOutgoingMessages()) {
[email protected]22b42c52010-12-20 06:59:23712 ClosePipeOnError();
[email protected]9a44a4db62010-12-20 06:19:07713 }
714}
715
[email protected]2f60c9b2014-06-06 20:13:51716bool ChannelPosix::AcceptConnection() {
[email protected]fd0a773a2013-04-30 20:55:03717 base::MessageLoopForIO::current()->WatchFileDescriptor(
718 pipe_, true, base::MessageLoopForIO::WATCH_READ, &read_watcher_, this);
[email protected]22b42c52010-12-20 06:59:23719 QueueHelloMessage();
720
[email protected]1707726c2011-02-03 20:35:09721 if (mode_ & MODE_CLIENT_FLAG) {
[email protected]22b42c52010-12-20 06:59:23722 // If we are a client we want to send a hello message out immediately.
723 // In server mode we will send a hello message when we receive one from a
724 // client.
725 waiting_connect_ = false;
[email protected]13ffc272014-02-18 17:42:20726 return ProcessOutgoingMessages();
[email protected]1707726c2011-02-03 20:35:09727 } else if (mode_ & MODE_SERVER_FLAG) {
[email protected]22b42c52010-12-20 06:59:23728 waiting_connect_ = true;
729 return true;
[email protected]1707726c2011-02-03 20:35:09730 } else {
731 NOTREACHED();
732 return false;
[email protected]22b42c52010-12-20 06:59:23733 }
734}
735
[email protected]2f60c9b2014-06-06 20:13:51736void ChannelPosix::ClosePipeOnError() {
[email protected]22b42c52010-12-20 06:59:23737 if (HasAcceptedConnection()) {
738 ResetToAcceptingConnectionState();
[email protected]d805c6a2012-03-08 12:30:28739 listener()->OnChannelError();
[email protected]22b42c52010-12-20 06:59:23740 } else {
741 Close();
742 if (AcceptsConnections()) {
[email protected]d805c6a2012-03-08 12:30:28743 listener()->OnChannelListenError();
[email protected]22b42c52010-12-20 06:59:23744 } else {
[email protected]d805c6a2012-03-08 12:30:28745 listener()->OnChannelError();
[email protected]22b42c52010-12-20 06:59:23746 }
747 }
748}
749
[email protected]2f60c9b2014-06-06 20:13:51750int ChannelPosix::GetHelloMessageProcId() {
[email protected]e1d67a882011-08-31 21:11:04751 int pid = base::GetCurrentProcId();
752#if defined(OS_LINUX)
753 // Our process may be in a sandbox with a separate PID namespace.
754 if (global_pid_) {
755 pid = global_pid_;
756 }
757#endif
758 return pid;
759}
760
[email protected]2f60c9b2014-06-06 20:13:51761void ChannelPosix::QueueHelloMessage() {
[email protected]22b42c52010-12-20 06:59:23762 // Create the Hello message
763 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
[email protected]753bb252013-11-04 22:28:12764 HELLO_MESSAGE_TYPE,
765 IPC::Message::PRIORITY_NORMAL));
[email protected]e1d67a882011-08-31 21:11:04766 if (!msg->WriteInt(GetHelloMessageProcId())) {
[email protected]22b42c52010-12-20 06:59:23767 NOTREACHED() << "Unable to pickle hello message proc id";
768 }
769#if defined(IPC_USES_READWRITE)
770 scoped_ptr<Message> hello;
771 if (remote_fd_pipe_ != -1) {
772 if (!msg->WriteFileDescriptor(base::FileDescriptor(remote_fd_pipe_,
773 false))) {
774 NOTREACHED() << "Unable to pickle hello message file descriptors";
775 }
776 DCHECK_EQ(msg->file_descriptor_set()->size(), 1U);
777 }
778#endif // IPC_USES_READWRITE
779 output_queue_.push(msg.release());
780}
781
[email protected]2f60c9b2014-06-06 20:13:51782ChannelPosix::ReadState ChannelPosix::ReadData(
[email protected]3d5a60b2012-03-01 21:41:47783 char* buffer,
784 int buffer_len,
785 int* bytes_read) {
786 if (pipe_ == -1)
787 return READ_FAILED;
788
[email protected]334f3022012-02-29 22:48:14789 struct msghdr msg = {0};
790
[email protected]3fcbd4b2012-06-05 01:54:46791 struct iovec iov = {buffer, static_cast<size_t>(buffer_len)};
[email protected]334f3022012-02-29 22:48:14792 msg.msg_iov = &iov;
793 msg.msg_iovlen = 1;
794
795 msg.msg_control = input_cmsg_buf_;
796
797 // recvmsg() returns 0 if the connection has closed or EAGAIN if no data
798 // is waiting on the pipe.
[email protected]334f3022012-02-29 22:48:14799#if defined(IPC_USES_READWRITE)
800 if (fd_pipe_ >= 0) {
[email protected]3d5a60b2012-03-01 21:41:47801 *bytes_read = HANDLE_EINTR(read(pipe_, buffer, buffer_len));
[email protected]334f3022012-02-29 22:48:14802 msg.msg_controllen = 0;
803 } else
804#endif // IPC_USES_READWRITE
805 {
806 msg.msg_controllen = sizeof(input_cmsg_buf_);
[email protected]3d5a60b2012-03-01 21:41:47807 *bytes_read = HANDLE_EINTR(recvmsg(pipe_, &msg, MSG_DONTWAIT));
[email protected]334f3022012-02-29 22:48:14808 }
[email protected]3d5a60b2012-03-01 21:41:47809 if (*bytes_read < 0) {
[email protected]334f3022012-02-29 22:48:14810 if (errno == EAGAIN) {
[email protected]3d5a60b2012-03-01 21:41:47811 return READ_PENDING;
[email protected]334f3022012-02-29 22:48:14812#if defined(OS_MACOSX)
813 } else if (errno == EPERM) {
814 // On OSX, reading from a pipe with no listener returns EPERM
815 // treat this as a special case to prevent spurious error messages
816 // to the console.
[email protected]3d5a60b2012-03-01 21:41:47817 return READ_FAILED;
[email protected]334f3022012-02-29 22:48:14818#endif // OS_MACOSX
819 } else if (errno == ECONNRESET || errno == EPIPE) {
[email protected]3d5a60b2012-03-01 21:41:47820 return READ_FAILED;
[email protected]334f3022012-02-29 22:48:14821 } else {
822 PLOG(ERROR) << "pipe error (" << pipe_ << ")";
[email protected]3d5a60b2012-03-01 21:41:47823 return READ_FAILED;
[email protected]334f3022012-02-29 22:48:14824 }
[email protected]3d5a60b2012-03-01 21:41:47825 } else if (*bytes_read == 0) {
[email protected]334f3022012-02-29 22:48:14826 // The pipe has closed...
[email protected]3d5a60b2012-03-01 21:41:47827 return READ_FAILED;
[email protected]334f3022012-02-29 22:48:14828 }
[email protected]3d5a60b2012-03-01 21:41:47829 DCHECK(*bytes_read);
[email protected]334f3022012-02-29 22:48:14830
831 CloseClientFileDescriptor();
832
833 // Read any file descriptors from the message.
834 if (!ExtractFileDescriptorsFromMsghdr(&msg))
[email protected]3d5a60b2012-03-01 21:41:47835 return READ_FAILED;
836 return READ_SUCCEEDED;
[email protected]334f3022012-02-29 22:48:14837}
838
839#if defined(IPC_USES_READWRITE)
[email protected]2f60c9b2014-06-06 20:13:51840bool ChannelPosix::ReadFileDescriptorsFromFDPipe() {
[email protected]334f3022012-02-29 22:48:14841 char dummy;
842 struct iovec fd_pipe_iov = { &dummy, 1 };
843
844 struct msghdr msg = { 0 };
845 msg.msg_iov = &fd_pipe_iov;
846 msg.msg_iovlen = 1;
847 msg.msg_control = input_cmsg_buf_;
848 msg.msg_controllen = sizeof(input_cmsg_buf_);
849 ssize_t bytes_received = HANDLE_EINTR(recvmsg(fd_pipe_, &msg, MSG_DONTWAIT));
850
851 if (bytes_received != 1)
852 return true; // No message waiting.
853
854 if (!ExtractFileDescriptorsFromMsghdr(&msg))
855 return false;
856 return true;
857}
858#endif
859
[email protected]d805c6a2012-03-08 12:30:28860// On Posix, we need to fix up the file descriptors before the input message
861// is dispatched.
862//
863// This will read from the input_fds_ (READWRITE mode only) and read more
864// handles from the FD pipe if necessary.
[email protected]2f60c9b2014-06-06 20:13:51865bool ChannelPosix::WillDispatchInputMessage(Message* msg) {
[email protected]334f3022012-02-29 22:48:14866 uint16 header_fds = msg->header()->num_fds;
867 if (!header_fds)
868 return true; // Nothing to do.
869
870 // The message has file descriptors.
871 const char* error = NULL;
872 if (header_fds > input_fds_.size()) {
873 // The message has been completely received, but we didn't get
874 // enough file descriptors.
875#if defined(IPC_USES_READWRITE)
876 if (!ReadFileDescriptorsFromFDPipe())
877 return false;
878 if (header_fds > input_fds_.size())
879#endif // IPC_USES_READWRITE
880 error = "Message needs unreceived descriptors";
881 }
882
883 if (header_fds > FileDescriptorSet::kMaxDescriptorsPerMessage)
884 error = "Message requires an excessive number of descriptors";
885
886 if (error) {
887 LOG(WARNING) << error
888 << " channel:" << this
889 << " message-type:" << msg->type()
890 << " header()->num_fds:" << header_fds;
[email protected]334f3022012-02-29 22:48:14891 // Abort the connection.
892 ClearInputFDs();
893 return false;
894 }
895
[email protected]7e9eecb62012-04-09 21:40:44896 // The shenaniganery below with &foo.front() requires input_fds_ to have
897 // contiguous underlying storage (such as a simple array or a std::vector).
898 // This is why the header warns not to make input_fds_ a deque<>.
[email protected]334f3022012-02-29 22:48:14899 msg->file_descriptor_set()->SetDescriptors(&input_fds_.front(),
900 header_fds);
901 input_fds_.erase(input_fds_.begin(), input_fds_.begin() + header_fds);
902 return true;
903}
904
[email protected]2f60c9b2014-06-06 20:13:51905bool ChannelPosix::DidEmptyInputBuffers() {
[email protected]3d5a60b2012-03-01 21:41:47906 // When the input data buffer is empty, the fds should be too. If this is
907 // not the case, we probably have a rogue renderer which is trying to fill
908 // our descriptor table.
909 return input_fds_.empty();
910}
911
[email protected]2f60c9b2014-06-06 20:13:51912bool ChannelPosix::ExtractFileDescriptorsFromMsghdr(msghdr* msg) {
[email protected]334f3022012-02-29 22:48:14913 // Check that there are any control messages. On OSX, CMSG_FIRSTHDR will
914 // return an invalid non-NULL pointer in the case that controllen == 0.
915 if (msg->msg_controllen == 0)
916 return true;
917
918 for (cmsghdr* cmsg = CMSG_FIRSTHDR(msg);
919 cmsg;
920 cmsg = CMSG_NXTHDR(msg, cmsg)) {
921 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
922 unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0);
923 DCHECK_EQ(0U, payload_len % sizeof(int));
924 const int* file_descriptors = reinterpret_cast<int*>(CMSG_DATA(cmsg));
925 unsigned num_file_descriptors = payload_len / 4;
926 input_fds_.insert(input_fds_.end(),
927 file_descriptors,
928 file_descriptors + num_file_descriptors);
929
930 // Check this after adding the FDs so we don't leak them.
931 if (msg->msg_flags & MSG_CTRUNC) {
932 ClearInputFDs();
933 return false;
934 }
935
936 return true;
937 }
938 }
939
940 // No file descriptors found, but that's OK.
941 return true;
942}
943
[email protected]2f60c9b2014-06-06 20:13:51944void ChannelPosix::ClearInputFDs() {
[email protected]7e9eecb62012-04-09 21:40:44945 for (size_t i = 0; i < input_fds_.size(); ++i) {
[email protected]d89eec82013-12-03 14:10:59946 if (IGNORE_EINTR(close(input_fds_[i])) < 0)
[email protected]334f3022012-02-29 22:48:14947 PLOG(ERROR) << "close ";
[email protected]334f3022012-02-29 22:48:14948 }
[email protected]7e9eecb62012-04-09 21:40:44949 input_fds_.clear();
[email protected]334f3022012-02-29 22:48:14950}
951
[email protected]2f60c9b2014-06-06 20:13:51952void ChannelPosix::QueueCloseFDMessage(int fd, int hops) {
[email protected]dc875dc2013-10-15 00:07:00953 switch (hops) {
954 case 1:
955 case 2: {
956 // Create the message
957 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
[email protected]753bb252013-11-04 22:28:12958 CLOSE_FD_MESSAGE_TYPE,
959 IPC::Message::PRIORITY_NORMAL));
[email protected]dc875dc2013-10-15 00:07:00960 if (!msg->WriteInt(hops - 1) || !msg->WriteInt(fd)) {
961 NOTREACHED() << "Unable to pickle close fd.";
962 }
963 // Send(msg.release());
964 output_queue_.push(msg.release());
965 break;
966 }
967
968 default:
969 NOTREACHED();
970 break;
971 }
972}
973
[email protected]2f60c9b2014-06-06 20:13:51974void ChannelPosix::HandleInternalMessage(const Message& msg) {
[email protected]334f3022012-02-29 22:48:14975 // The Hello message contains only the process id.
[email protected]ce208f872012-03-07 20:42:56976 PickleIterator iter(msg);
[email protected]dc875dc2013-10-15 00:07:00977
978 switch (msg.type()) {
979 default:
980 NOTREACHED();
981 break;
982
983 case Channel::HELLO_MESSAGE_TYPE:
984 int pid;
985 if (!msg.ReadInt(&iter, &pid))
986 NOTREACHED();
[email protected]334f3022012-02-29 22:48:14987
988#if defined(IPC_USES_READWRITE)
[email protected]dc875dc2013-10-15 00:07:00989 if (mode_ & MODE_SERVER_FLAG) {
990 // With IPC_USES_READWRITE, the Hello message from the client to the
991 // server also contains the fd_pipe_, which will be used for all
992 // subsequent file descriptor passing.
993 DCHECK_EQ(msg.file_descriptor_set()->size(), 1U);
994 base::FileDescriptor descriptor;
995 if (!msg.ReadFileDescriptor(&iter, &descriptor)) {
996 NOTREACHED();
997 }
998 fd_pipe_ = descriptor.fd;
999 CHECK(descriptor.auto_close);
1000 }
[email protected]787f5e462013-10-11 04:22:341001#endif // IPC_USES_READWRITE
[email protected]dc875dc2013-10-15 00:07:001002 peer_pid_ = pid;
1003 listener()->OnChannelConnected(pid);
1004 break;
1005
1006#if defined(OS_MACOSX)
1007 case Channel::CLOSE_FD_MESSAGE_TYPE:
1008 int fd, hops;
1009 if (!msg.ReadInt(&iter, &hops))
1010 NOTREACHED();
1011 if (!msg.ReadInt(&iter, &fd))
1012 NOTREACHED();
1013 if (hops == 0) {
1014 if (fds_to_close_.erase(fd) > 0) {
[email protected]d89eec82013-12-03 14:10:591015 if (IGNORE_EINTR(close(fd)) < 0)
[email protected]dc875dc2013-10-15 00:07:001016 PLOG(ERROR) << "close";
1017 } else {
1018 NOTREACHED();
1019 }
1020 } else {
1021 QueueCloseFDMessage(fd, hops);
1022 }
1023 break;
1024#endif
1025 }
[email protected]334f3022012-02-29 22:48:141026}
1027
[email protected]2f60c9b2014-06-06 20:13:511028void ChannelPosix::Close() {
[email protected]fa95fc92008-12-08 18:10:141029 // Close can be called multiple time, so we need to make sure we're
1030 // idempotent.
1031
[email protected]22b42c52010-12-20 06:59:231032 ResetToAcceptingConnectionState();
[email protected]fa95fc92008-12-08 18:10:141033
[email protected]22b42c52010-12-20 06:59:231034 if (must_unlink_) {
1035 unlink(pipe_name_.c_str());
1036 must_unlink_ = false;
1037 }
[email protected]fa95fc92008-12-08 18:10:141038 if (server_listen_pipe_ != -1) {
[email protected]d89eec82013-12-03 14:10:591039 if (IGNORE_EINTR(close(server_listen_pipe_)) < 0)
[email protected]334f3022012-02-29 22:48:141040 DPLOG(ERROR) << "close " << server_listen_pipe_;
[email protected]fa95fc92008-12-08 18:10:141041 server_listen_pipe_ = -1;
[email protected]22b42c52010-12-20 06:59:231042 // Unregister libevent for the listening socket and close it.
1043 server_listen_connection_watcher_.StopWatchingFileDescriptor();
[email protected]fa95fc92008-12-08 18:10:141044 }
1045
[email protected]2ce26c432011-09-19 17:08:121046 CloseClientFileDescriptor();
[email protected]fa95fc92008-12-08 18:10:141047}
1048
[email protected]2f60c9b2014-06-06 20:13:511049base::ProcessId ChannelPosix::GetPeerPID() const {
1050 return peer_pid_;
1051}
1052
[email protected]514411fc2008-12-10 22:28:111053//------------------------------------------------------------------------------
[email protected]2f60c9b2014-06-06 20:13:511054// Channel's methods
[email protected]22b42c52010-12-20 06:59:231055
[email protected]313c00e52011-08-09 06:46:061056// static
[email protected]2f60c9b2014-06-06 20:13:511057scoped_ptr<Channel> Channel::Create(
1058 const IPC::ChannelHandle &channel_handle, Mode mode, Listener* listener) {
1059 return scoped_ptr<Channel>(
1060 new ChannelPosix(channel_handle, mode, listener));
[email protected]313c00e52011-08-09 06:46:061061}
1062
[email protected]5c41e6e12012-03-17 02:20:461063// static
1064std::string Channel::GenerateVerifiedChannelID(const std::string& prefix) {
1065 // A random name is sufficient validation on posix systems, so we don't need
1066 // an additional shared secret.
1067
1068 std::string id = prefix;
1069 if (!id.empty())
1070 id.append(".");
1071
1072 return id.append(GenerateUniqueRandomChannelID());
1073}
1074
1075
[email protected]2f60c9b2014-06-06 20:13:511076bool Channel::IsNamedServerInitialized(
1077 const std::string& channel_id) {
1078 return ChannelPosix::IsNamedServerInitialized(channel_id);
1079}
1080
[email protected]e1d67a882011-08-31 21:11:041081#if defined(OS_LINUX)
1082// static
1083void Channel::SetGlobalPid(int pid) {
[email protected]2f60c9b2014-06-06 20:13:511084 ChannelPosix::SetGlobalPid(pid);
[email protected]e1d67a882011-08-31 21:11:041085}
1086#endif // OS_LINUX
1087
[email protected]d4651ff2008-12-02 16:51:581088} // namespace IPC