blob: f685dc09216b76cd2c8526be0c1ee1ff04407fba [file] [log] [blame]
jrg@chromium.org8b302f32012-01-26 08:53:06 +09001// Copyright (c) 2012 The Chromium Authors. All rights reserved.
agl@chromium.org1c6dcf22009-07-23 08:57:21 +09002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "ipc/ipc_channel_posix.h"
6
7#include <errno.h>
8#include <fcntl.h>
9#include <stddef.h>
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090010#include <sys/socket.h>
11#include <sys/stat.h>
brettw@chromium.org59eef1f2013-02-24 14:40:52 +090012#include <sys/types.h>
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090013#include <sys/un.h>
shenhan@google.com8a6e4992012-06-05 10:54:46 +090014#include <unistd.h>
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090015
mark@chromium.org61edb8b2011-10-19 02:46:22 +090016#if defined(OS_OPENBSD)
17#include <sys/uio.h>
18#endif
19
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090020#include <map>
brettw@chromium.org59eef1f2013-02-24 14:40:52 +090021#include <string>
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090022
23#include "base/command_line.h"
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +090024#include "base/file_util.h"
brettw@chromium.org59eef1f2013-02-24 14:40:52 +090025#include "base/files/file_path.h"
ajwong@chromium.org8e2e3002011-09-22 03:05:41 +090026#include "base/location.h"
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090027#include "base/logging.h"
levin@chromium.org5c528682011-03-28 10:54:15 +090028#include "base/memory/scoped_ptr.h"
29#include "base/memory/singleton.h"
brettw@chromium.orgb1788fb2012-11-15 05:54:35 +090030#include "base/posix/eintr_wrapper.h"
brettw@chromium.orgea3b3f22012-11-10 08:46:54 +090031#include "base/posix/global_descriptors.h"
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090032#include "base/process_util.h"
jschuh@chromium.orgf75a4d12012-03-17 11:20:46 +090033#include "base/rand_util.h"
dilmah@chromium.orgdc4b9702011-07-20 07:13:24 +090034#include "base/stl_util.h"
avi@chromium.orge7eaf392013-06-11 15:32:18 +090035#include "base/strings/string_util.h"
brettw@chromium.orgabe477a2011-01-21 13:55:52 +090036#include "base/synchronization/lock.h"
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090037#include "ipc/file_descriptor_set_posix.h"
tfarina@chromium.orgb6d81202012-11-16 07:22:17 +090038#include "ipc/ipc_descriptors.h"
39#include "ipc/ipc_listener.h"
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090040#include "ipc/ipc_logging.h"
41#include "ipc/ipc_message_utils.h"
tfarina@chromium.orgb6d81202012-11-16 07:22:17 +090042#include "ipc/ipc_switches.h"
jeremya@chromium.orgf14bfab2013-03-13 13:23:10 +090043#include "ipc/unix_domain_socket_util.h"
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090044
45namespace IPC {
46
47// IPC channels on Windows use named pipes (CreateNamedPipe()) with
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +090048// channel ids as the pipe names. Channels on POSIX use sockets as
49// pipes These don't quite line up.
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090050//
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +090051// 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
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090053// magic file descriptor kPrimaryIPCChannel in the child. Future
54// connections (file descriptors) can then be passed via that
55// connection via sendmsg().
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +090056//
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.
agl@chromium.org1c6dcf22009-07-23 08:57:21 +090060
61//------------------------------------------------------------------------------
62namespace {
63
64// The PipeMap class works around this quirk related to unit tests:
65//
66// When running as a server, we install the client socket in a
67// specific file descriptor number (@kPrimaryIPCChannel). However, we
68// also have to support the case where we are running unittests in the
69// same process. (We do not support forking without execing.)
70//
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
75// the magic slot (@kPrimaryIPCChannel). The client will search for the
76// 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
78// close its copy of the client socket and remove the mapping.
79//
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:
satish@chromium.org77222832010-12-05 08:00:10 +090093 static PipeMap* GetInstance() {
94 return Singleton<PipeMap>::get();
95 }
96
dmaclach@chromium.org058c4a72010-12-09 04:28:09 +090097 ~PipeMap() {
98 // Shouldn't have left over pipes.
erg@google.comaed4b382011-03-02 09:03:18 +090099 DCHECK(map_.empty());
dmaclach@chromium.org058c4a72010-12-09 04:28:09 +0900100 }
101
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900102 // Lookup a given channel id. Return -1 if not found.
103 int Lookup(const std::string& channel_id) {
brettw@chromium.orgabe477a2011-01-21 13:55:52 +0900104 base::AutoLock locked(lock_);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900105
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
phajdan.jr@chromium.orgaf9455b2011-09-20 02:08:12 +0900114 void Remove(const std::string& channel_id) {
brettw@chromium.orgabe477a2011-01-21 13:55:52 +0900115 base::AutoLock locked(lock_);
phajdan.jr@chromium.orgaf9455b2011-09-20 02:08:12 +0900116 map_.erase(channel_id);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900117 }
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) {
brettw@chromium.orgabe477a2011-01-21 13:55:52 +0900122 base::AutoLock locked(lock_);
david.mike.futcher@gmail.com9eb2aa52011-04-19 05:07:08 +0900123 DCHECK_NE(-1, fd);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900124
125 ChannelToFDMap::const_iterator i = map_.find(channel_id);
126 CHECK(i == map_.end()) << "Creating second IPC server (fd " << fd << ") "
127 << "for '" << channel_id << "' while first "
128 << "(fd " << i->second << ") still exists";
129 map_[channel_id] = fd;
130 }
131
132 private:
brettw@chromium.orgabe477a2011-01-21 13:55:52 +0900133 base::Lock lock_;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900134 typedef std::map<std::string, int> ChannelToFDMap;
135 ChannelToFDMap map_;
satish@chromium.org77222832010-12-05 08:00:10 +0900136
137 friend struct DefaultSingletonTraits<PipeMap>;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900138};
139
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900140//------------------------------------------------------------------------------
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900141
jeremy@chromium.org2a85b112009-12-08 23:48:08 +0900142bool SocketWriteErrorIsRecoverable() {
143#if defined(OS_MACOSX)
144 // On OS X if sendmsg() is trying to send fds between processes and there
145 // isn't enough room in the output buffer to send the fd structure over
146 // atomically then EMSGSIZE is returned.
147 //
148 // EMSGSIZE presents a problem since the system APIs can only call us when
149 // there's room in the socket buffer and not when there is "enough" room.
150 //
151 // The current behavior is to return to the event loop when EMSGSIZE is
152 // received and hopefull service another FD. This is however still
153 // technically a busy wait since the event loop will call us right back until
154 // the receiver has read enough data to allow passing the FD over atomically.
155 return errno == EAGAIN || errno == EMSGSIZE;
156#else
157 return errno == EAGAIN;
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900158#endif // OS_MACOSX
jeremy@chromium.org2a85b112009-12-08 23:48:08 +0900159}
160
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900161} // namespace
162//------------------------------------------------------------------------------
163
jamescook@chromium.org2d471f02011-09-01 06:11:04 +0900164#if defined(OS_LINUX)
165int Channel::ChannelImpl::global_pid_ = 0;
166#endif // OS_LINUX
167
dmaclach@chromium.org058c4a72010-12-09 04:28:09 +0900168Channel::ChannelImpl::ChannelImpl(const IPC::ChannelHandle& channel_handle,
169 Mode mode, Listener* listener)
brettw@chromium.org0e9d0a12012-03-08 21:30:28 +0900170 : ChannelReader(listener),
171 mode_(mode),
jschuh@chromium.orga5cd0762012-04-05 11:38:34 +0900172 peer_pid_(base::kNullProcessId),
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900173 is_blocked_on_write_(false),
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900174 waiting_connect_(true),
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900175 message_send_bytes_written_(0),
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900176 server_listen_pipe_(-1),
177 pipe_(-1),
178 client_pipe_(-1),
dmaclach@chromium.org2680d3a2010-12-09 06:22:24 +0900179#if defined(IPC_USES_READWRITE)
agl@chromium.orga81f84a2009-09-05 06:34:05 +0900180 fd_pipe_(-1),
181 remote_fd_pipe_(-1),
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900182#endif // IPC_USES_READWRITE
183 pipe_name_(channel_handle.name),
satorux@chromium.orgad12d3d2011-08-23 12:17:02 +0900184 must_unlink_(false) {
jhawkins@chromium.org8fa070a2011-06-22 07:48:29 +0900185 memset(input_cmsg_buf_, 0, sizeof(input_cmsg_buf_));
dmaclach@chromium.orgf146c292011-02-04 05:35:09 +0900186 if (!CreatePipe(channel_handle)) {
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900187 // The pipe may have been closed already.
dmaclach@chromium.orgf146c292011-02-04 05:35:09 +0900188 const char *modestr = (mode_ & MODE_SERVER_FLAG) ? "server" : "client";
dmaclach@chromium.org058c4a72010-12-09 04:28:09 +0900189 LOG(WARNING) << "Unable to create pipe named \"" << channel_handle.name
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900190 << "\" in " << modestr << " mode";
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900191 }
192}
193
erg@google.coma7331b62010-09-02 02:08:20 +0900194Channel::ChannelImpl::~ChannelImpl() {
195 Close();
196}
197
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900198bool SocketPair(int* fd1, int* fd2) {
199 int pipe_fds[2];
200 if (socketpair(AF_UNIX, SOCK_STREAM, 0, pipe_fds) != 0) {
tschmelcher@chromium.org90a3f8a2009-10-14 03:27:40 +0900201 PLOG(ERROR) << "socketpair()";
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900202 return false;
203 }
204
205 // Set both ends to be non-blocking.
206 if (fcntl(pipe_fds[0], F_SETFL, O_NONBLOCK) == -1 ||
207 fcntl(pipe_fds[1], F_SETFL, O_NONBLOCK) == -1) {
tschmelcher@chromium.org90a3f8a2009-10-14 03:27:40 +0900208 PLOG(ERROR) << "fcntl(O_NONBLOCK)";
thakis@chromium.org965db9a2010-06-23 09:37:46 +0900209 if (HANDLE_EINTR(close(pipe_fds[0])) < 0)
210 PLOG(ERROR) << "close";
211 if (HANDLE_EINTR(close(pipe_fds[1])) < 0)
212 PLOG(ERROR) << "close";
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900213 return false;
214 }
215
216 *fd1 = pipe_fds[0];
217 *fd2 = pipe_fds[1];
218
219 return true;
220}
221
dmaclach@chromium.orgf146c292011-02-04 05:35:09 +0900222bool Channel::ChannelImpl::CreatePipe(
223 const IPC::ChannelHandle& channel_handle) {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900224 DCHECK(server_listen_pipe_ == -1 && pipe_ == -1);
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900225
226 // Four possible cases:
227 // 1) It's a channel wrapping a pipe that is given to us.
228 // 2) It's for a named channel, so we create it.
229 // 3) It's for a client that we implement ourself. This is used
230 // in unittesting.
231 // 4) It's the initial IPC channel:
232 // 4a) Client side: Pull the pipe out of the GlobalDescriptors set.
233 // 4b) Server side: create the pipe.
234
dmaclach@chromium.org2812db62011-03-03 07:27:14 +0900235 int local_pipe = -1;
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900236 if (channel_handle.socket.fd != -1) {
237 // Case 1 from comment above.
dmaclach@chromium.org2812db62011-03-03 07:27:14 +0900238 local_pipe = channel_handle.socket.fd;
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900239#if defined(IPC_USES_READWRITE)
240 // Test the socket passed into us to make sure it is nonblocking.
241 // We don't want to call read/write on a blocking socket.
dmaclach@chromium.org2812db62011-03-03 07:27:14 +0900242 int value = fcntl(local_pipe, F_GETFL);
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900243 if (value == -1) {
244 PLOG(ERROR) << "fcntl(F_GETFL) " << pipe_name_;
245 return false;
246 }
247 if (!(value & O_NONBLOCK)) {
248 LOG(ERROR) << "Socket " << pipe_name_ << " must be O_NONBLOCK";
249 return false;
250 }
251#endif // IPC_USES_READWRITE
dmaclach@chromium.orgf146c292011-02-04 05:35:09 +0900252 } else if (mode_ & MODE_NAMED_FLAG) {
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900253 // Case 2 from comment above.
dmaclach@chromium.orgf146c292011-02-04 05:35:09 +0900254 if (mode_ & MODE_SERVER_FLAG) {
jeremya@chromium.orgf14bfab2013-03-13 13:23:10 +0900255 if (!CreateServerUnixDomainSocket(base::FilePath(pipe_name_),
256 &local_pipe)) {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900257 return false;
258 }
dmaclach@chromium.org0c55c562011-02-25 02:14:36 +0900259 must_unlink_ = true;
dmaclach@chromium.orgf146c292011-02-04 05:35:09 +0900260 } else if (mode_ & MODE_CLIENT_FLAG) {
jeremya@chromium.orgf14bfab2013-03-13 13:23:10 +0900261 if (!CreateClientUnixDomainSocket(base::FilePath(pipe_name_),
262 &local_pipe)) {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900263 return false;
264 }
dmaclach@chromium.orgf146c292011-02-04 05:35:09 +0900265 } else {
dmaclach@chromium.org2812db62011-03-03 07:27:14 +0900266 LOG(ERROR) << "Bad mode: " << mode_;
dmaclach@chromium.orgf146c292011-02-04 05:35:09 +0900267 return false;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900268 }
269 } else {
dmaclach@chromium.org2812db62011-03-03 07:27:14 +0900270 local_pipe = PipeMap::GetInstance()->Lookup(pipe_name_);
dmaclach@chromium.orgf146c292011-02-04 05:35:09 +0900271 if (mode_ & MODE_CLIENT_FLAG) {
dmaclach@chromium.org2812db62011-03-03 07:27:14 +0900272 if (local_pipe != -1) {
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900273 // Case 3 from comment above.
274 // We only allow one connection.
dmaclach@chromium.org2812db62011-03-03 07:27:14 +0900275 local_pipe = HANDLE_EINTR(dup(local_pipe));
phajdan.jr@chromium.orgaf9455b2011-09-20 02:08:12 +0900276 PipeMap::GetInstance()->Remove(pipe_name_);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900277 } else {
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900278 // Case 4a from comment above.
mark@chromium.orgae34f8c2009-12-01 07:14:37 +0900279 // Guard against inappropriate reuse of the initial IPC channel. If
280 // an IPC channel closes and someone attempts to reuse it by name, the
281 // initial channel must not be recycled here. http://crbug.com/26754.
282 static bool used_initial_channel = false;
283 if (used_initial_channel) {
mark@chromium.orgc973c0f2010-03-17 05:31:10 +0900284 LOG(FATAL) << "Denying attempt to reuse initial IPC channel for "
285 << pipe_name_;
mark@chromium.orgae34f8c2009-12-01 07:14:37 +0900286 return false;
287 }
288 used_initial_channel = true;
289
dmaclach@chromium.org2812db62011-03-03 07:27:14 +0900290 local_pipe =
291 base::GlobalDescriptors::GetInstance()->Get(kPrimaryIPCChannel);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900292 }
dmaclach@chromium.orgf146c292011-02-04 05:35:09 +0900293 } else if (mode_ & MODE_SERVER_FLAG) {
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900294 // Case 4b from comment above.
dmaclach@chromium.org2812db62011-03-03 07:27:14 +0900295 if (local_pipe != -1) {
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900296 LOG(ERROR) << "Server already exists for " << pipe_name_;
agl@chromium.orga81f84a2009-09-05 06:34:05 +0900297 return false;
298 }
phajdan.jr@chromium.orgaf9455b2011-09-20 02:08:12 +0900299 base::AutoLock lock(client_pipe_lock_);
dmaclach@chromium.org2812db62011-03-03 07:27:14 +0900300 if (!SocketPair(&local_pipe, &client_pipe_))
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900301 return false;
302 PipeMap::GetInstance()->Insert(pipe_name_, client_pipe_);
303 } else {
dmaclach@chromium.org2812db62011-03-03 07:27:14 +0900304 LOG(ERROR) << "Bad mode: " << mode_;
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900305 return false;
agl@chromium.orga81f84a2009-09-05 06:34:05 +0900306 }
307 }
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900308
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900309#if defined(IPC_USES_READWRITE)
310 // Create a dedicated socketpair() for exchanging file descriptors.
311 // See comments for IPC_USES_READWRITE for details.
dmaclach@chromium.orgf146c292011-02-04 05:35:09 +0900312 if (mode_ & MODE_CLIENT_FLAG) {
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900313 if (!SocketPair(&fd_pipe_, &remote_fd_pipe_)) {
314 return false;
315 }
316 }
317#endif // IPC_USES_READWRITE
318
dmaclach@chromium.org2812db62011-03-03 07:27:14 +0900319 if ((mode_ & MODE_SERVER_FLAG) && (mode_ & MODE_NAMED_FLAG)) {
320 server_listen_pipe_ = local_pipe;
321 local_pipe = -1;
322 }
323
324 pipe_ = local_pipe;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900325 return true;
326}
327
328bool Channel::ChannelImpl::Connect() {
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900329 if (server_listen_pipe_ == -1 && pipe_ == -1) {
dmaclach@chromium.org2812db62011-03-03 07:27:14 +0900330 DLOG(INFO) << "Channel creation failed: " << pipe_name_;
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900331 return false;
332 }
333
334 bool did_connect = true;
335 if (server_listen_pipe_ != -1) {
336 // Watch the pipe for connections, and turn any connections into
337 // active sockets.
xhwang@chromium.org0b2c2a52013-05-01 05:55:03 +0900338 base::MessageLoopForIO::current()->WatchFileDescriptor(
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900339 server_listen_pipe_,
340 true,
xhwang@chromium.org0b2c2a52013-05-01 05:55:03 +0900341 base::MessageLoopForIO::WATCH_READ,
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900342 &server_listen_connection_watcher_,
343 this);
344 } else {
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900345 did_connect = AcceptConnection();
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900346 }
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900347 return did_connect;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900348}
349
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900350bool Channel::ChannelImpl::ProcessOutgoingMessages() {
351 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
352 // no connection?
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900353 if (output_queue_.empty())
dmaclach@chromium.orgf22df392010-12-20 15:39:44 +0900354 return true;
dmaclach@chromium.orgf22df392010-12-20 15:39:44 +0900355
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900356 if (pipe_ == -1)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900357 return false;
358
359 // Write out all the messages we can till the write blocks or there are no
360 // more outgoing messages.
361 while (!output_queue_.empty()) {
362 Message* msg = output_queue_.front();
363
364 size_t amt_to_write = msg->size() - message_send_bytes_written_;
david.mike.futcher@gmail.com9eb2aa52011-04-19 05:07:08 +0900365 DCHECK_NE(0U, amt_to_write);
agl@chromium.orga81f84a2009-09-05 06:34:05 +0900366 const char* out_bytes = reinterpret_cast<const char*>(msg->data()) +
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900367 message_send_bytes_written_;
368
369 struct msghdr msgh = {0};
370 struct iovec iov = {const_cast<char*>(out_bytes), amt_to_write};
371 msgh.msg_iov = &iov;
372 msgh.msg_iovlen = 1;
373 char buf[CMSG_SPACE(
pkasting@chromium.org9687a8f2011-09-01 09:50:13 +0900374 sizeof(int) * FileDescriptorSet::kMaxDescriptorsPerMessage)];
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900375
agl@chromium.orga81f84a2009-09-05 06:34:05 +0900376 ssize_t bytes_written = 1;
377 int fd_written = -1;
378
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900379 if (message_send_bytes_written_ == 0 &&
380 !msg->file_descriptor_set()->empty()) {
381 // This is the first chunk of a message which has descriptors to send
382 struct cmsghdr *cmsg;
383 const unsigned num_fds = msg->file_descriptor_set()->size();
384
pkasting@chromium.org9687a8f2011-09-01 09:50:13 +0900385 DCHECK(num_fds <= FileDescriptorSet::kMaxDescriptorsPerMessage);
agl@chromium.orgc1e93ea2010-06-11 06:39:04 +0900386 if (msg->file_descriptor_set()->ContainsDirectoryDescriptor()) {
387 LOG(FATAL) << "Panic: attempting to transport directory descriptor over"
388 " IPC. Aborting to maintain sandbox isolation.";
389 // If you have hit this then something tried to send a file descriptor
390 // to a directory over an IPC channel. Since IPC channels span
391 // sandboxes this is very bad: the receiving process can use openat
392 // with ".." elements in the path in order to reach the real
393 // filesystem.
394 }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900395
396 msgh.msg_control = buf;
397 msgh.msg_controllen = CMSG_SPACE(sizeof(int) * num_fds);
398 cmsg = CMSG_FIRSTHDR(&msgh);
399 cmsg->cmsg_level = SOL_SOCKET;
400 cmsg->cmsg_type = SCM_RIGHTS;
401 cmsg->cmsg_len = CMSG_LEN(sizeof(int) * num_fds);
402 msg->file_descriptor_set()->GetDescriptors(
403 reinterpret_cast<int*>(CMSG_DATA(cmsg)));
404 msgh.msg_controllen = cmsg->cmsg_len;
405
apatrick@google.coma2406772009-12-05 03:08:45 +0900406 // DCHECK_LE above already checks that
pkasting@chromium.org9687a8f2011-09-01 09:50:13 +0900407 // num_fds < kMaxDescriptorsPerMessage so no danger of overflow.
apatrick@google.coma2406772009-12-05 03:08:45 +0900408 msg->header()->num_fds = static_cast<uint16>(num_fds);
agl@chromium.orga81f84a2009-09-05 06:34:05 +0900409
dmaclach@chromium.org2680d3a2010-12-09 06:22:24 +0900410#if defined(IPC_USES_READWRITE)
brettw@chromium.org0e9d0a12012-03-08 21:30:28 +0900411 if (!IsHelloMessage(*msg)) {
agl@chromium.orga81f84a2009-09-05 06:34:05 +0900412 // Only the Hello message sends the file descriptor with the message.
413 // Subsequently, we can send file descriptors on the dedicated
414 // fd_pipe_ which makes Seccomp sandbox operation more efficient.
415 struct iovec fd_pipe_iov = { const_cast<char *>(""), 1 };
416 msgh.msg_iov = &fd_pipe_iov;
417 fd_written = fd_pipe_;
418 bytes_written = HANDLE_EINTR(sendmsg(fd_pipe_, &msgh, MSG_DONTWAIT));
419 msgh.msg_iov = &iov;
420 msgh.msg_controllen = 0;
421 if (bytes_written > 0) {
422 msg->file_descriptor_set()->CommitAll();
423 }
424 }
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900425#endif // IPC_USES_READWRITE
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900426 }
427
agl@chromium.orga81f84a2009-09-05 06:34:05 +0900428 if (bytes_written == 1) {
429 fd_written = pipe_;
dmaclach@chromium.org2680d3a2010-12-09 06:22:24 +0900430#if defined(IPC_USES_READWRITE)
brettw@chromium.org0e9d0a12012-03-08 21:30:28 +0900431 if ((mode_ & MODE_CLIENT_FLAG) && IsHelloMessage(*msg)) {
thomasvl@google.com9a242072010-07-23 23:18:59 +0900432 DCHECK_EQ(msg->file_descriptor_set()->size(), 1U);
agl@chromium.orga81f84a2009-09-05 06:34:05 +0900433 }
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900434 if (!msgh.msg_controllen) {
agl@chromium.orga81f84a2009-09-05 06:34:05 +0900435 bytes_written = HANDLE_EINTR(write(pipe_, out_bytes, amt_to_write));
436 } else
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900437#endif // IPC_USES_READWRITE
agl@chromium.orga81f84a2009-09-05 06:34:05 +0900438 {
439 bytes_written = HANDLE_EINTR(sendmsg(pipe_, &msgh, MSG_DONTWAIT));
440 }
441 }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900442 if (bytes_written > 0)
443 msg->file_descriptor_set()->CommitAll();
444
jeremy@chromium.org2a85b112009-12-08 23:48:08 +0900445 if (bytes_written < 0 && !SocketWriteErrorIsRecoverable()) {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900446#if defined(OS_MACOSX)
447 // On OSX writing to a pipe with no listener returns EPERM.
448 if (errno == EPERM) {
449 Close();
450 return false;
451 }
452#endif // OS_MACOSX
evan@chromium.org7d3eaa72009-10-23 10:48:21 +0900453 if (errno == EPIPE) {
454 Close();
455 return false;
456 }
jeremy@chromium.org53a4fac2009-12-03 22:35:46 +0900457 PLOG(ERROR) << "pipe error on "
458 << fd_written
thestig@chromium.org8b563352011-02-11 17:43:52 +0900459 << " Currently writing message of size: "
jeremy@chromium.org2a85b112009-12-08 23:48:08 +0900460 << msg->size();
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900461 return false;
462 }
463
464 if (static_cast<size_t>(bytes_written) != amt_to_write) {
465 if (bytes_written > 0) {
466 // If write() fails with EAGAIN then bytes_written will be -1.
467 message_send_bytes_written_ += bytes_written;
468 }
469
470 // Tell libevent to call us back once things are unblocked.
471 is_blocked_on_write_ = true;
xhwang@chromium.org0b2c2a52013-05-01 05:55:03 +0900472 base::MessageLoopForIO::current()->WatchFileDescriptor(
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900473 pipe_,
474 false, // One shot
xhwang@chromium.org0b2c2a52013-05-01 05:55:03 +0900475 base::MessageLoopForIO::WATCH_WRITE,
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900476 &write_watcher_,
477 this);
478 return true;
479 } else {
480 message_send_bytes_written_ = 0;
481
482 // Message sent OK!
pkasting@chromium.orgfcdd54b2010-10-20 08:50:00 +0900483 DVLOG(2) << "sent message @" << msg << " on channel @" << this
dmaclach@chromium.orgdec0e2b2010-12-09 10:13:12 +0900484 << " with type " << msg->type() << " on fd " << pipe_;
agl@chromium.orga81f84a2009-09-05 06:34:05 +0900485 delete output_queue_.front();
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900486 output_queue_.pop();
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900487 }
488 }
489 return true;
490}
491
492bool Channel::ChannelImpl::Send(Message* message) {
pkasting@chromium.orgfcdd54b2010-10-20 08:50:00 +0900493 DVLOG(2) << "sending message @" << message << " on channel @" << this
494 << " with type " << message->type()
495 << " (" << output_queue_.size() << " in queue)";
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900496
497#ifdef IPC_MESSAGE_LOG_ENABLED
satish@chromium.orgaa870602010-12-13 17:18:55 +0900498 Logging::GetInstance()->OnSendMessage(message, "");
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900499#endif // IPC_MESSAGE_LOG_ENABLED
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900500
jbates@chromium.org7cc80332012-09-18 12:41:29 +0900501 message->TraceMessageBegin();
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900502 output_queue_.push(message);
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900503 if (!is_blocked_on_write_ && !waiting_connect_) {
504 return ProcessOutgoingMessages();
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900505 }
506
507 return true;
508}
509
phajdan.jr@chromium.orgaf9455b2011-09-20 02:08:12 +0900510int Channel::ChannelImpl::GetClientFileDescriptor() {
511 base::AutoLock lock(client_pipe_lock_);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900512 return client_pipe_;
513}
514
phajdan.jr@chromium.orgaf9455b2011-09-20 02:08:12 +0900515int Channel::ChannelImpl::TakeClientFileDescriptor() {
516 base::AutoLock lock(client_pipe_lock_);
517 int fd = client_pipe_;
518 if (client_pipe_ != -1) {
519 PipeMap::GetInstance()->Remove(pipe_name_);
520 client_pipe_ = -1;
521 }
522 return fd;
523}
524
525void Channel::ChannelImpl::CloseClientFileDescriptor() {
526 base::AutoLock lock(client_pipe_lock_);
527 if (client_pipe_ != -1) {
528 PipeMap::GetInstance()->Remove(pipe_name_);
529 if (HANDLE_EINTR(close(client_pipe_)) < 0)
530 PLOG(ERROR) << "close " << pipe_name_;
531 client_pipe_ = -1;
532 }
533}
534
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900535bool Channel::ChannelImpl::AcceptsConnections() const {
536 return server_listen_pipe_ != -1;
537}
dmaclach@chromium.org6a9b0c72010-12-20 15:19:07 +0900538
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900539bool Channel::ChannelImpl::HasAcceptedConnection() const {
540 return AcceptsConnections() && pipe_ != -1;
541}
dmaclach@chromium.org6a9b0c72010-12-20 15:19:07 +0900542
jeremya@chromium.orgf14bfab2013-03-13 13:23:10 +0900543bool Channel::ChannelImpl::GetPeerEuid(uid_t* peer_euid) const {
544 DCHECK(!(mode_ & MODE_SERVER) || HasAcceptedConnection());
545 return IPC::GetPeerEuid(pipe_, peer_euid);
wez@chromium.org7cce0912011-04-06 21:01:44 +0900546}
547
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900548void Channel::ChannelImpl::ResetToAcceptingConnectionState() {
549 // Unregister libevent for the unix domain socket and close it.
550 read_watcher_.StopWatchingFileDescriptor();
551 write_watcher_.StopWatchingFileDescriptor();
552 if (pipe_ != -1) {
553 if (HANDLE_EINTR(close(pipe_)) < 0)
554 PLOG(ERROR) << "close pipe_ " << pipe_name_;
555 pipe_ = -1;
556 }
557#if defined(IPC_USES_READWRITE)
558 if (fd_pipe_ != -1) {
559 if (HANDLE_EINTR(close(fd_pipe_)) < 0)
560 PLOG(ERROR) << "close fd_pipe_ " << pipe_name_;
561 fd_pipe_ = -1;
562 }
563 if (remote_fd_pipe_ != -1) {
564 if (HANDLE_EINTR(close(remote_fd_pipe_)) < 0)
565 PLOG(ERROR) << "close remote_fd_pipe_ " << pipe_name_;
566 remote_fd_pipe_ = -1;
567 }
568#endif // IPC_USES_READWRITE
dmaclach@chromium.orgf22df392010-12-20 15:39:44 +0900569
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900570 while (!output_queue_.empty()) {
571 Message* m = output_queue_.front();
572 output_queue_.pop();
573 delete m;
dmaclach@chromium.orgf22df392010-12-20 15:39:44 +0900574 }
575
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900576 // Close any outstanding, received file descriptors.
brettw@chromium.org293988a2012-03-01 07:48:14 +0900577 ClearInputFDs();
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900578}
579
kkania@chromium.orgf37b4e52011-08-09 15:46:06 +0900580// static
581bool Channel::ChannelImpl::IsNamedServerInitialized(
582 const std::string& channel_id) {
brettw@chromium.org10b64122013-07-12 02:36:07 +0900583 return base::PathExists(base::FilePath(channel_id));
kkania@chromium.orgf37b4e52011-08-09 15:46:06 +0900584}
585
jamescook@chromium.org2d471f02011-09-01 06:11:04 +0900586#if defined(OS_LINUX)
587// static
588void Channel::ChannelImpl::SetGlobalPid(int pid) {
589 global_pid_ = pid;
590}
591#endif // OS_LINUX
592
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900593// Called by libevent when we can read from the pipe without blocking.
594void Channel::ChannelImpl::OnFileCanReadWithoutBlocking(int fd) {
595 bool send_server_hello_msg = false;
596 if (fd == server_listen_pipe_) {
597 int new_pipe = 0;
jeremya@chromium.orgf14bfab2013-03-13 13:23:10 +0900598 if (!ServerAcceptConnection(server_listen_pipe_, &new_pipe) ||
599 new_pipe < 0) {
dmaclach@chromium.orgf22df392010-12-20 15:39:44 +0900600 Close();
brettw@chromium.org0e9d0a12012-03-08 21:30:28 +0900601 listener()->OnChannelListenError();
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900602 }
603
604 if (pipe_ != -1) {
605 // We already have a connection. We only handle one at a time.
606 // close our new descriptor.
607 if (HANDLE_EINTR(shutdown(new_pipe, SHUT_RDWR)) < 0)
brettw@chromium.org293988a2012-03-01 07:48:14 +0900608 DPLOG(ERROR) << "shutdown " << pipe_name_;
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900609 if (HANDLE_EINTR(close(new_pipe)) < 0)
brettw@chromium.org293988a2012-03-01 07:48:14 +0900610 DPLOG(ERROR) << "close " << pipe_name_;
brettw@chromium.org0e9d0a12012-03-08 21:30:28 +0900611 listener()->OnChannelDenied();
dmaclach@chromium.orgf22df392010-12-20 15:39:44 +0900612 return;
dmaclach@chromium.org6a9b0c72010-12-20 15:19:07 +0900613 }
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900614 pipe_ = new_pipe;
615
wez@chromium.org7cce0912011-04-06 21:01:44 +0900616 if ((mode_ & MODE_OPEN_ACCESS_FLAG) == 0) {
617 // Verify that the IPC channel peer is running as the same user.
618 uid_t client_euid;
jeremya@chromium.orgf14bfab2013-03-13 13:23:10 +0900619 if (!GetPeerEuid(&client_euid)) {
brettw@chromium.org293988a2012-03-01 07:48:14 +0900620 DLOG(ERROR) << "Unable to query client euid";
wez@chromium.org7cce0912011-04-06 21:01:44 +0900621 ResetToAcceptingConnectionState();
622 return;
623 }
624 if (client_euid != geteuid()) {
brettw@chromium.org293988a2012-03-01 07:48:14 +0900625 DLOG(WARNING) << "Client euid is not authorised";
wez@chromium.org7cce0912011-04-06 21:01:44 +0900626 ResetToAcceptingConnectionState();
627 return;
628 }
629 }
630
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900631 if (!AcceptConnection()) {
632 NOTREACHED() << "AcceptConnection should not fail on server";
633 }
634 send_server_hello_msg = true;
635 waiting_connect_ = false;
636 } else if (fd == pipe_) {
dmaclach@chromium.orgf146c292011-02-04 05:35:09 +0900637 if (waiting_connect_ && (mode_ & MODE_SERVER_FLAG)) {
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900638 send_server_hello_msg = true;
639 waiting_connect_ = false;
640 }
641 if (!ProcessIncomingMessages()) {
agl@chromium.org0d5ac662011-03-01 05:30:47 +0900642 // ClosePipeOnError may delete this object, so we mustn't call
643 // ProcessOutgoingMessages.
644 send_server_hello_msg = false;
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900645 ClosePipeOnError();
646 }
647 } else {
648 NOTREACHED() << "Unknown pipe " << fd;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900649 }
650
651 // If we're a server and handshaking, then we want to make sure that we
652 // only send our handshake message after we've processed the client's.
653 // This gives us a chance to kill the client if the incoming handshake
654 // is invalid.
655 if (send_server_hello_msg) {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900656 ProcessOutgoingMessages();
657 }
658}
659
660// Called by libevent when we can write to the pipe without blocking.
661void Channel::ChannelImpl::OnFileCanWriteWithoutBlocking(int fd) {
david.mike.futcher@gmail.com9eb2aa52011-04-19 05:07:08 +0900662 DCHECK_EQ(pipe_, fd);
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900663 is_blocked_on_write_ = false;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900664 if (!ProcessOutgoingMessages()) {
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900665 ClosePipeOnError();
dmaclach@chromium.org6a9b0c72010-12-20 15:19:07 +0900666 }
667}
668
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900669bool Channel::ChannelImpl::AcceptConnection() {
xhwang@chromium.org0b2c2a52013-05-01 05:55:03 +0900670 base::MessageLoopForIO::current()->WatchFileDescriptor(
671 pipe_, true, base::MessageLoopForIO::WATCH_READ, &read_watcher_, this);
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900672 QueueHelloMessage();
673
dmaclach@chromium.orgf146c292011-02-04 05:35:09 +0900674 if (mode_ & MODE_CLIENT_FLAG) {
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900675 // If we are a client we want to send a hello message out immediately.
676 // In server mode we will send a hello message when we receive one from a
677 // client.
678 waiting_connect_ = false;
679 return ProcessOutgoingMessages();
dmaclach@chromium.orgf146c292011-02-04 05:35:09 +0900680 } else if (mode_ & MODE_SERVER_FLAG) {
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900681 waiting_connect_ = true;
682 return true;
dmaclach@chromium.orgf146c292011-02-04 05:35:09 +0900683 } else {
684 NOTREACHED();
685 return false;
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900686 }
687}
688
689void Channel::ChannelImpl::ClosePipeOnError() {
690 if (HasAcceptedConnection()) {
691 ResetToAcceptingConnectionState();
brettw@chromium.org0e9d0a12012-03-08 21:30:28 +0900692 listener()->OnChannelError();
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900693 } else {
694 Close();
695 if (AcceptsConnections()) {
brettw@chromium.org0e9d0a12012-03-08 21:30:28 +0900696 listener()->OnChannelListenError();
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900697 } else {
brettw@chromium.org0e9d0a12012-03-08 21:30:28 +0900698 listener()->OnChannelError();
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900699 }
700 }
701}
702
jamescook@chromium.org2d471f02011-09-01 06:11:04 +0900703int Channel::ChannelImpl::GetHelloMessageProcId() {
704 int pid = base::GetCurrentProcId();
705#if defined(OS_LINUX)
706 // Our process may be in a sandbox with a separate PID namespace.
707 if (global_pid_) {
708 pid = global_pid_;
709 }
710#endif
711 return pid;
712}
713
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900714void Channel::ChannelImpl::QueueHelloMessage() {
715 // Create the Hello message
716 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
717 HELLO_MESSAGE_TYPE,
718 IPC::Message::PRIORITY_NORMAL));
jamescook@chromium.org2d471f02011-09-01 06:11:04 +0900719 if (!msg->WriteInt(GetHelloMessageProcId())) {
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900720 NOTREACHED() << "Unable to pickle hello message proc id";
721 }
722#if defined(IPC_USES_READWRITE)
723 scoped_ptr<Message> hello;
724 if (remote_fd_pipe_ != -1) {
725 if (!msg->WriteFileDescriptor(base::FileDescriptor(remote_fd_pipe_,
726 false))) {
727 NOTREACHED() << "Unable to pickle hello message file descriptors";
728 }
729 DCHECK_EQ(msg->file_descriptor_set()->size(), 1U);
730 }
731#endif // IPC_USES_READWRITE
732 output_queue_.push(msg.release());
733}
734
brettw@chromium.org828e8592012-03-02 06:41:47 +0900735Channel::ChannelImpl::ReadState Channel::ChannelImpl::ReadData(
736 char* buffer,
737 int buffer_len,
738 int* bytes_read) {
739 if (pipe_ == -1)
740 return READ_FAILED;
741
brettw@chromium.org293988a2012-03-01 07:48:14 +0900742 struct msghdr msg = {0};
743
shenhan@google.com8a6e4992012-06-05 10:54:46 +0900744 struct iovec iov = {buffer, static_cast<size_t>(buffer_len)};
brettw@chromium.org293988a2012-03-01 07:48:14 +0900745 msg.msg_iov = &iov;
746 msg.msg_iovlen = 1;
747
748 msg.msg_control = input_cmsg_buf_;
749
750 // recvmsg() returns 0 if the connection has closed or EAGAIN if no data
751 // is waiting on the pipe.
brettw@chromium.org293988a2012-03-01 07:48:14 +0900752#if defined(IPC_USES_READWRITE)
753 if (fd_pipe_ >= 0) {
brettw@chromium.org828e8592012-03-02 06:41:47 +0900754 *bytes_read = HANDLE_EINTR(read(pipe_, buffer, buffer_len));
brettw@chromium.org293988a2012-03-01 07:48:14 +0900755 msg.msg_controllen = 0;
756 } else
757#endif // IPC_USES_READWRITE
758 {
759 msg.msg_controllen = sizeof(input_cmsg_buf_);
brettw@chromium.org828e8592012-03-02 06:41:47 +0900760 *bytes_read = HANDLE_EINTR(recvmsg(pipe_, &msg, MSG_DONTWAIT));
brettw@chromium.org293988a2012-03-01 07:48:14 +0900761 }
brettw@chromium.org828e8592012-03-02 06:41:47 +0900762 if (*bytes_read < 0) {
brettw@chromium.org293988a2012-03-01 07:48:14 +0900763 if (errno == EAGAIN) {
brettw@chromium.org828e8592012-03-02 06:41:47 +0900764 return READ_PENDING;
brettw@chromium.org293988a2012-03-01 07:48:14 +0900765#if defined(OS_MACOSX)
766 } else if (errno == EPERM) {
767 // On OSX, reading from a pipe with no listener returns EPERM
768 // treat this as a special case to prevent spurious error messages
769 // to the console.
brettw@chromium.org828e8592012-03-02 06:41:47 +0900770 return READ_FAILED;
brettw@chromium.org293988a2012-03-01 07:48:14 +0900771#endif // OS_MACOSX
772 } else if (errno == ECONNRESET || errno == EPIPE) {
brettw@chromium.org828e8592012-03-02 06:41:47 +0900773 return READ_FAILED;
brettw@chromium.org293988a2012-03-01 07:48:14 +0900774 } else {
775 PLOG(ERROR) << "pipe error (" << pipe_ << ")";
brettw@chromium.org828e8592012-03-02 06:41:47 +0900776 return READ_FAILED;
brettw@chromium.org293988a2012-03-01 07:48:14 +0900777 }
brettw@chromium.org828e8592012-03-02 06:41:47 +0900778 } else if (*bytes_read == 0) {
brettw@chromium.org293988a2012-03-01 07:48:14 +0900779 // The pipe has closed...
brettw@chromium.org828e8592012-03-02 06:41:47 +0900780 return READ_FAILED;
brettw@chromium.org293988a2012-03-01 07:48:14 +0900781 }
brettw@chromium.org828e8592012-03-02 06:41:47 +0900782 DCHECK(*bytes_read);
brettw@chromium.org293988a2012-03-01 07:48:14 +0900783
784 CloseClientFileDescriptor();
785
786 // Read any file descriptors from the message.
787 if (!ExtractFileDescriptorsFromMsghdr(&msg))
brettw@chromium.org828e8592012-03-02 06:41:47 +0900788 return READ_FAILED;
789 return READ_SUCCEEDED;
brettw@chromium.org293988a2012-03-01 07:48:14 +0900790}
791
792#if defined(IPC_USES_READWRITE)
793bool Channel::ChannelImpl::ReadFileDescriptorsFromFDPipe() {
794 char dummy;
795 struct iovec fd_pipe_iov = { &dummy, 1 };
796
797 struct msghdr msg = { 0 };
798 msg.msg_iov = &fd_pipe_iov;
799 msg.msg_iovlen = 1;
800 msg.msg_control = input_cmsg_buf_;
801 msg.msg_controllen = sizeof(input_cmsg_buf_);
802 ssize_t bytes_received = HANDLE_EINTR(recvmsg(fd_pipe_, &msg, MSG_DONTWAIT));
803
804 if (bytes_received != 1)
805 return true; // No message waiting.
806
807 if (!ExtractFileDescriptorsFromMsghdr(&msg))
808 return false;
809 return true;
810}
811#endif
812
brettw@chromium.org0e9d0a12012-03-08 21:30:28 +0900813// On Posix, we need to fix up the file descriptors before the input message
814// is dispatched.
815//
816// This will read from the input_fds_ (READWRITE mode only) and read more
817// handles from the FD pipe if necessary.
brettw@chromium.org828e8592012-03-02 06:41:47 +0900818bool Channel::ChannelImpl::WillDispatchInputMessage(Message* msg) {
brettw@chromium.org293988a2012-03-01 07:48:14 +0900819 uint16 header_fds = msg->header()->num_fds;
820 if (!header_fds)
821 return true; // Nothing to do.
822
823 // The message has file descriptors.
824 const char* error = NULL;
825 if (header_fds > input_fds_.size()) {
826 // The message has been completely received, but we didn't get
827 // enough file descriptors.
828#if defined(IPC_USES_READWRITE)
829 if (!ReadFileDescriptorsFromFDPipe())
830 return false;
831 if (header_fds > input_fds_.size())
832#endif // IPC_USES_READWRITE
833 error = "Message needs unreceived descriptors";
834 }
835
836 if (header_fds > FileDescriptorSet::kMaxDescriptorsPerMessage)
837 error = "Message requires an excessive number of descriptors";
838
839 if (error) {
840 LOG(WARNING) << error
841 << " channel:" << this
842 << " message-type:" << msg->type()
843 << " header()->num_fds:" << header_fds;
brettw@chromium.org293988a2012-03-01 07:48:14 +0900844 // Abort the connection.
845 ClearInputFDs();
846 return false;
847 }
848
fischman@chromium.org8b60dfa2012-04-10 06:40:44 +0900849 // The shenaniganery below with &foo.front() requires input_fds_ to have
850 // contiguous underlying storage (such as a simple array or a std::vector).
851 // This is why the header warns not to make input_fds_ a deque<>.
brettw@chromium.org293988a2012-03-01 07:48:14 +0900852 msg->file_descriptor_set()->SetDescriptors(&input_fds_.front(),
853 header_fds);
854 input_fds_.erase(input_fds_.begin(), input_fds_.begin() + header_fds);
855 return true;
856}
857
brettw@chromium.org828e8592012-03-02 06:41:47 +0900858bool Channel::ChannelImpl::DidEmptyInputBuffers() {
859 // When the input data buffer is empty, the fds should be too. If this is
860 // not the case, we probably have a rogue renderer which is trying to fill
861 // our descriptor table.
862 return input_fds_.empty();
863}
864
brettw@chromium.org293988a2012-03-01 07:48:14 +0900865bool Channel::ChannelImpl::ExtractFileDescriptorsFromMsghdr(msghdr* msg) {
866 // Check that there are any control messages. On OSX, CMSG_FIRSTHDR will
867 // return an invalid non-NULL pointer in the case that controllen == 0.
868 if (msg->msg_controllen == 0)
869 return true;
870
871 for (cmsghdr* cmsg = CMSG_FIRSTHDR(msg);
872 cmsg;
873 cmsg = CMSG_NXTHDR(msg, cmsg)) {
874 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
875 unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0);
876 DCHECK_EQ(0U, payload_len % sizeof(int));
877 const int* file_descriptors = reinterpret_cast<int*>(CMSG_DATA(cmsg));
878 unsigned num_file_descriptors = payload_len / 4;
879 input_fds_.insert(input_fds_.end(),
880 file_descriptors,
881 file_descriptors + num_file_descriptors);
882
883 // Check this after adding the FDs so we don't leak them.
884 if (msg->msg_flags & MSG_CTRUNC) {
885 ClearInputFDs();
886 return false;
887 }
888
889 return true;
890 }
891 }
892
893 // No file descriptors found, but that's OK.
894 return true;
895}
896
897void Channel::ChannelImpl::ClearInputFDs() {
fischman@chromium.org8b60dfa2012-04-10 06:40:44 +0900898 for (size_t i = 0; i < input_fds_.size(); ++i) {
899 if (HANDLE_EINTR(close(input_fds_[i])) < 0)
brettw@chromium.org293988a2012-03-01 07:48:14 +0900900 PLOG(ERROR) << "close ";
brettw@chromium.org293988a2012-03-01 07:48:14 +0900901 }
fischman@chromium.org8b60dfa2012-04-10 06:40:44 +0900902 input_fds_.clear();
brettw@chromium.org293988a2012-03-01 07:48:14 +0900903}
904
905void Channel::ChannelImpl::HandleHelloMessage(const Message& msg) {
906 // The Hello message contains only the process id.
jbates@chromium.org0fc87362012-03-08 05:42:56 +0900907 PickleIterator iter(msg);
brettw@chromium.org293988a2012-03-01 07:48:14 +0900908 int pid;
909 if (!msg.ReadInt(&iter, &pid))
910 NOTREACHED();
911
912#if defined(IPC_USES_READWRITE)
913 if (mode_ & MODE_SERVER_FLAG) {
914 // With IPC_USES_READWRITE, the Hello message from the client to the
915 // server also contains the fd_pipe_, which will be used for all
916 // subsequent file descriptor passing.
917 DCHECK_EQ(msg.file_descriptor_set()->size(), 1U);
918 base::FileDescriptor descriptor;
919 if (!msg.ReadFileDescriptor(&iter, &descriptor)) {
920 NOTREACHED();
921 }
922 fd_pipe_ = descriptor.fd;
923 CHECK(descriptor.auto_close);
924 }
925#endif // IPC_USES_READWRITE
jschuh@chromium.orga5cd0762012-04-05 11:38:34 +0900926 peer_pid_ = pid;
brettw@chromium.org0e9d0a12012-03-08 21:30:28 +0900927 listener()->OnChannelConnected(pid);
brettw@chromium.org293988a2012-03-01 07:48:14 +0900928}
929
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900930void Channel::ChannelImpl::Close() {
931 // Close can be called multiple time, so we need to make sure we're
932 // idempotent.
933
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900934 ResetToAcceptingConnectionState();
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900935
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900936 if (must_unlink_) {
937 unlink(pipe_name_.c_str());
938 must_unlink_ = false;
939 }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900940 if (server_listen_pipe_ != -1) {
thakis@chromium.org965db9a2010-06-23 09:37:46 +0900941 if (HANDLE_EINTR(close(server_listen_pipe_)) < 0)
brettw@chromium.org293988a2012-03-01 07:48:14 +0900942 DPLOG(ERROR) << "close " << server_listen_pipe_;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900943 server_listen_pipe_ = -1;
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900944 // Unregister libevent for the listening socket and close it.
945 server_listen_connection_watcher_.StopWatchingFileDescriptor();
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900946 }
947
phajdan.jr@chromium.orgaf9455b2011-09-20 02:08:12 +0900948 CloseClientFileDescriptor();
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900949}
950
951//------------------------------------------------------------------------------
952// Channel's methods simply call through to ChannelImpl.
dmaclach@chromium.org058c4a72010-12-09 04:28:09 +0900953Channel::Channel(const IPC::ChannelHandle& channel_handle, Mode mode,
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900954 Listener* listener)
dmaclach@chromium.org058c4a72010-12-09 04:28:09 +0900955 : channel_impl_(new ChannelImpl(channel_handle, mode, listener)) {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900956}
957
958Channel::~Channel() {
959 delete channel_impl_;
960}
961
962bool Channel::Connect() {
963 return channel_impl_->Connect();
964}
965
966void Channel::Close() {
dmichael@chromium.orgb9a99ce2012-05-17 03:58:32 +0900967 if (channel_impl_)
968 channel_impl_->Close();
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900969}
970
jschuh@chromium.orga5cd0762012-04-05 11:38:34 +0900971base::ProcessId Channel::peer_pid() const {
972 return channel_impl_->peer_pid();
973}
974
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900975bool Channel::Send(Message* message) {
976 return channel_impl_->Send(message);
977}
978
979int Channel::GetClientFileDescriptor() const {
980 return channel_impl_->GetClientFileDescriptor();
981}
982
phajdan.jr@chromium.orgaf9455b2011-09-20 02:08:12 +0900983int Channel::TakeClientFileDescriptor() {
984 return channel_impl_->TakeClientFileDescriptor();
985}
986
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900987bool Channel::AcceptsConnections() const {
988 return channel_impl_->AcceptsConnections();
989}
990
991bool Channel::HasAcceptedConnection() const {
992 return channel_impl_->HasAcceptedConnection();
993}
994
jeremya@chromium.orgf14bfab2013-03-13 13:23:10 +0900995bool Channel::GetPeerEuid(uid_t* peer_euid) const {
996 return channel_impl_->GetPeerEuid(peer_euid);
wez@chromium.org7cce0912011-04-06 21:01:44 +0900997}
998
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900999void Channel::ResetToAcceptingConnectionState() {
1000 channel_impl_->ResetToAcceptingConnectionState();
1001}
1002
kkania@chromium.orgf37b4e52011-08-09 15:46:06 +09001003// static
1004bool Channel::IsNamedServerInitialized(const std::string& channel_id) {
1005 return ChannelImpl::IsNamedServerInitialized(channel_id);
1006}
1007
jschuh@chromium.orgf75a4d12012-03-17 11:20:46 +09001008// static
1009std::string Channel::GenerateVerifiedChannelID(const std::string& prefix) {
1010 // A random name is sufficient validation on posix systems, so we don't need
1011 // an additional shared secret.
1012
1013 std::string id = prefix;
1014 if (!id.empty())
1015 id.append(".");
1016
1017 return id.append(GenerateUniqueRandomChannelID());
1018}
1019
1020
jamescook@chromium.org2d471f02011-09-01 06:11:04 +09001021#if defined(OS_LINUX)
1022// static
1023void Channel::SetGlobalPid(int pid) {
1024 ChannelImpl::SetGlobalPid(pid);
1025}
1026#endif // OS_LINUX
1027
agl@chromium.org1c6dcf22009-07-23 08:57:21 +09001028} // namespace IPC