blob: ac9de554657771704fe9d7a58bbad53c5587522d [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"
rsesek@chromium.org19319712013-07-24 14:15:24 +090032#include "base/process/process_handle.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>;
epenner@chromium.org913c9482014-03-19 15:34:52 +0900138#if defined(OS_ANDROID)
139 friend void ::IPC::Channel::NotifyProcessForkedForTesting();
140#endif
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900141};
142
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900143//------------------------------------------------------------------------------
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900144
jeremy@chromium.org2a85b112009-12-08 23:48:08 +0900145bool 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;
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900161#endif // OS_MACOSX
jeremy@chromium.org2a85b112009-12-08 23:48:08 +0900162}
163
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900164} // namespace
epenner@chromium.org913c9482014-03-19 15:34:52 +0900165
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
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900174//------------------------------------------------------------------------------
175
jamescook@chromium.org2d471f02011-09-01 06:11:04 +0900176#if defined(OS_LINUX)
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +0900177int ChannelPosix::global_pid_ = 0;
jamescook@chromium.org2d471f02011-09-01 06:11:04 +0900178#endif // OS_LINUX
179
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +0900180ChannelPosix::ChannelPosix(const IPC::ChannelHandle& channel_handle,
181 Mode mode, Listener* listener)
brettw@chromium.org0e9d0a12012-03-08 21:30:28 +0900182 : ChannelReader(listener),
183 mode_(mode),
jschuh@chromium.orga5cd0762012-04-05 11:38:34 +0900184 peer_pid_(base::kNullProcessId),
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900185 is_blocked_on_write_(false),
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900186 waiting_connect_(true),
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900187 message_send_bytes_written_(0),
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900188 server_listen_pipe_(-1),
189 pipe_(-1),
190 client_pipe_(-1),
dmaclach@chromium.org2680d3a2010-12-09 06:22:24 +0900191#if defined(IPC_USES_READWRITE)
agl@chromium.orga81f84a2009-09-05 06:34:05 +0900192 fd_pipe_(-1),
193 remote_fd_pipe_(-1),
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900194#endif // IPC_USES_READWRITE
195 pipe_name_(channel_handle.name),
satorux@chromium.orgad12d3d2011-08-23 12:17:02 +0900196 must_unlink_(false) {
jhawkins@chromium.org8fa070a2011-06-22 07:48:29 +0900197 memset(input_cmsg_buf_, 0, sizeof(input_cmsg_buf_));
dmaclach@chromium.orgf146c292011-02-04 05:35:09 +0900198 if (!CreatePipe(channel_handle)) {
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900199 // The pipe may have been closed already.
dmaclach@chromium.orgf146c292011-02-04 05:35:09 +0900200 const char *modestr = (mode_ & MODE_SERVER_FLAG) ? "server" : "client";
dmaclach@chromium.org058c4a72010-12-09 04:28:09 +0900201 LOG(WARNING) << "Unable to create pipe named \"" << channel_handle.name
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900202 << "\" in " << modestr << " mode";
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900203 }
204}
205
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +0900206ChannelPosix::~ChannelPosix() {
erg@google.coma7331b62010-09-02 02:08:20 +0900207 Close();
208}
209
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900210bool SocketPair(int* fd1, int* fd2) {
211 int pipe_fds[2];
212 if (socketpair(AF_UNIX, SOCK_STREAM, 0, pipe_fds) != 0) {
tschmelcher@chromium.org90a3f8a2009-10-14 03:27:40 +0900213 PLOG(ERROR) << "socketpair()";
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900214 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) {
tschmelcher@chromium.org90a3f8a2009-10-14 03:27:40 +0900220 PLOG(ERROR) << "fcntl(O_NONBLOCK)";
mark@chromium.orgfa5a0f92013-12-03 23:10:59 +0900221 if (IGNORE_EINTR(close(pipe_fds[0])) < 0)
thakis@chromium.org965db9a2010-06-23 09:37:46 +0900222 PLOG(ERROR) << "close";
mark@chromium.orgfa5a0f92013-12-03 23:10:59 +0900223 if (IGNORE_EINTR(close(pipe_fds[1])) < 0)
thakis@chromium.org965db9a2010-06-23 09:37:46 +0900224 PLOG(ERROR) << "close";
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900225 return false;
226 }
227
228 *fd1 = pipe_fds[0];
229 *fd2 = pipe_fds[1];
230
231 return true;
232}
233
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +0900234bool ChannelPosix::CreatePipe(
dmaclach@chromium.orgf146c292011-02-04 05:35:09 +0900235 const IPC::ChannelHandle& channel_handle) {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900236 DCHECK(server_listen_pipe_ == -1 && pipe_ == -1);
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900237
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
epenner@chromium.org913c9482014-03-19 15:34:52 +0900242 // in single-process unittesting.
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900243 // 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
dmaclach@chromium.org2812db62011-03-03 07:27:14 +0900247 int local_pipe = -1;
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900248 if (channel_handle.socket.fd != -1) {
249 // Case 1 from comment above.
dmaclach@chromium.org2812db62011-03-03 07:27:14 +0900250 local_pipe = channel_handle.socket.fd;
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900251#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.
dmaclach@chromium.org2812db62011-03-03 07:27:14 +0900254 int value = fcntl(local_pipe, F_GETFL);
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900255 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
dmaclach@chromium.orgf146c292011-02-04 05:35:09 +0900264 } else if (mode_ & MODE_NAMED_FLAG) {
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900265 // Case 2 from comment above.
dmaclach@chromium.orgf146c292011-02-04 05:35:09 +0900266 if (mode_ & MODE_SERVER_FLAG) {
jeremya@chromium.orgf14bfab2013-03-13 13:23:10 +0900267 if (!CreateServerUnixDomainSocket(base::FilePath(pipe_name_),
268 &local_pipe)) {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900269 return false;
270 }
dmaclach@chromium.org0c55c562011-02-25 02:14:36 +0900271 must_unlink_ = true;
dmaclach@chromium.orgf146c292011-02-04 05:35:09 +0900272 } else if (mode_ & MODE_CLIENT_FLAG) {
jeremya@chromium.orgf14bfab2013-03-13 13:23:10 +0900273 if (!CreateClientUnixDomainSocket(base::FilePath(pipe_name_),
274 &local_pipe)) {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900275 return false;
276 }
dmaclach@chromium.orgf146c292011-02-04 05:35:09 +0900277 } else {
dmaclach@chromium.org2812db62011-03-03 07:27:14 +0900278 LOG(ERROR) << "Bad mode: " << mode_;
dmaclach@chromium.orgf146c292011-02-04 05:35:09 +0900279 return false;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900280 }
281 } else {
dmaclach@chromium.org2812db62011-03-03 07:27:14 +0900282 local_pipe = PipeMap::GetInstance()->Lookup(pipe_name_);
dmaclach@chromium.orgf146c292011-02-04 05:35:09 +0900283 if (mode_ & MODE_CLIENT_FLAG) {
dmaclach@chromium.org2812db62011-03-03 07:27:14 +0900284 if (local_pipe != -1) {
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900285 // Case 3 from comment above.
286 // We only allow one connection.
dmaclach@chromium.org2812db62011-03-03 07:27:14 +0900287 local_pipe = HANDLE_EINTR(dup(local_pipe));
phajdan.jr@chromium.orgaf9455b2011-09-20 02:08:12 +0900288 PipeMap::GetInstance()->Remove(pipe_name_);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900289 } else {
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900290 // Case 4a from comment above.
mark@chromium.orgae34f8c2009-12-01 07:14:37 +0900291 // 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) {
mark@chromium.orgc973c0f2010-03-17 05:31:10 +0900296 LOG(FATAL) << "Denying attempt to reuse initial IPC channel for "
297 << pipe_name_;
mark@chromium.orgae34f8c2009-12-01 07:14:37 +0900298 return false;
299 }
300 used_initial_channel = true;
301
dmaclach@chromium.org2812db62011-03-03 07:27:14 +0900302 local_pipe =
303 base::GlobalDescriptors::GetInstance()->Get(kPrimaryIPCChannel);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900304 }
dmaclach@chromium.orgf146c292011-02-04 05:35:09 +0900305 } else if (mode_ & MODE_SERVER_FLAG) {
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900306 // Case 4b from comment above.
dmaclach@chromium.org2812db62011-03-03 07:27:14 +0900307 if (local_pipe != -1) {
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900308 LOG(ERROR) << "Server already exists for " << pipe_name_;
agl@chromium.orga81f84a2009-09-05 06:34:05 +0900309 return false;
310 }
phajdan.jr@chromium.orgaf9455b2011-09-20 02:08:12 +0900311 base::AutoLock lock(client_pipe_lock_);
dmaclach@chromium.org2812db62011-03-03 07:27:14 +0900312 if (!SocketPair(&local_pipe, &client_pipe_))
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900313 return false;
314 PipeMap::GetInstance()->Insert(pipe_name_, client_pipe_);
315 } else {
dmaclach@chromium.org2812db62011-03-03 07:27:14 +0900316 LOG(ERROR) << "Bad mode: " << mode_;
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900317 return false;
agl@chromium.orga81f84a2009-09-05 06:34:05 +0900318 }
319 }
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900320
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900321#if defined(IPC_USES_READWRITE)
322 // Create a dedicated socketpair() for exchanging file descriptors.
323 // See comments for IPC_USES_READWRITE for details.
dmaclach@chromium.orgf146c292011-02-04 05:35:09 +0900324 if (mode_ & MODE_CLIENT_FLAG) {
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900325 if (!SocketPair(&fd_pipe_, &remote_fd_pipe_)) {
326 return false;
327 }
328 }
329#endif // IPC_USES_READWRITE
330
dmaclach@chromium.org2812db62011-03-03 07:27:14 +0900331 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;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900337 return true;
338}
339
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +0900340bool ChannelPosix::Connect() {
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900341 if (server_listen_pipe_ == -1 && pipe_ == -1) {
hubbe@chromium.orga53c97c2014-02-21 09:18:29 +0900342 DLOG(WARNING) << "Channel creation failed: " << pipe_name_;
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900343 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.
xhwang@chromium.org0b2c2a52013-05-01 05:55:03 +0900350 base::MessageLoopForIO::current()->WatchFileDescriptor(
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900351 server_listen_pipe_,
352 true,
xhwang@chromium.org0b2c2a52013-05-01 05:55:03 +0900353 base::MessageLoopForIO::WATCH_READ,
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900354 &server_listen_connection_watcher_,
355 this);
356 } else {
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900357 did_connect = AcceptConnection();
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900358 }
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900359 return did_connect;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900360}
361
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +0900362void ChannelPosix::CloseFileDescriptors(Message* msg) {
hubbe@chromium.org683920d2013-10-15 09:07:00 +0900363#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
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +0900383bool ChannelPosix::ProcessOutgoingMessages() {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900384 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
385 // no connection?
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900386 if (output_queue_.empty())
dmaclach@chromium.orgf22df392010-12-20 15:39:44 +0900387 return true;
dmaclach@chromium.orgf22df392010-12-20 15:39:44 +0900388
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900389 if (pipe_ == -1)
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900390 return false;
391
392 // 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_;
david.mike.futcher@gmail.com9eb2aa52011-04-19 05:07:08 +0900398 DCHECK_NE(0U, amt_to_write);
agl@chromium.orga81f84a2009-09-05 06:34:05 +0900399 const char* out_bytes = reinterpret_cast<const char*>(msg->data()) +
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900400 message_send_bytes_written_;
401
402 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(
pkasting@chromium.org9687a8f2011-09-01 09:50:13 +0900407 sizeof(int) * FileDescriptorSet::kMaxDescriptorsPerMessage)];
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900408
agl@chromium.orga81f84a2009-09-05 06:34:05 +0900409 ssize_t bytes_written = 1;
410 int fd_written = -1;
411
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900412 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();
417
pkasting@chromium.org9687a8f2011-09-01 09:50:13 +0900418 DCHECK(num_fds <= FileDescriptorSet::kMaxDescriptorsPerMessage);
agl@chromium.orgc1e93ea2010-06-11 06:39:04 +0900419 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 }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900428
429 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;
438
apatrick@google.coma2406772009-12-05 03:08:45 +0900439 // DCHECK_LE above already checks that
pkasting@chromium.org9687a8f2011-09-01 09:50:13 +0900440 // num_fds < kMaxDescriptorsPerMessage so no danger of overflow.
apatrick@google.coma2406772009-12-05 03:08:45 +0900441 msg->header()->num_fds = static_cast<uint16>(num_fds);
agl@chromium.orga81f84a2009-09-05 06:34:05 +0900442
dmaclach@chromium.org2680d3a2010-12-09 06:22:24 +0900443#if defined(IPC_USES_READWRITE)
brettw@chromium.org0e9d0a12012-03-08 21:30:28 +0900444 if (!IsHelloMessage(*msg)) {
agl@chromium.orga81f84a2009-09-05 06:34:05 +0900445 // 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) {
hubbe@chromium.org683920d2013-10-15 09:07:00 +0900455 CloseFileDescriptors(msg);
agl@chromium.orga81f84a2009-09-05 06:34:05 +0900456 }
457 }
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900458#endif // IPC_USES_READWRITE
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900459 }
460
agl@chromium.orga81f84a2009-09-05 06:34:05 +0900461 if (bytes_written == 1) {
462 fd_written = pipe_;
dmaclach@chromium.org2680d3a2010-12-09 06:22:24 +0900463#if defined(IPC_USES_READWRITE)
brettw@chromium.org0e9d0a12012-03-08 21:30:28 +0900464 if ((mode_ & MODE_CLIENT_FLAG) && IsHelloMessage(*msg)) {
thomasvl@google.com9a242072010-07-23 23:18:59 +0900465 DCHECK_EQ(msg->file_descriptor_set()->size(), 1U);
agl@chromium.orga81f84a2009-09-05 06:34:05 +0900466 }
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900467 if (!msgh.msg_controllen) {
agl@chromium.orga81f84a2009-09-05 06:34:05 +0900468 bytes_written = HANDLE_EINTR(write(pipe_, out_bytes, amt_to_write));
469 } else
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900470#endif // IPC_USES_READWRITE
agl@chromium.orga81f84a2009-09-05 06:34:05 +0900471 {
472 bytes_written = HANDLE_EINTR(sendmsg(pipe_, &msgh, MSG_DONTWAIT));
473 }
474 }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900475 if (bytes_written > 0)
hubbe@chromium.org683920d2013-10-15 09:07:00 +0900476 CloseFileDescriptors(msg);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900477
jeremy@chromium.org2a85b112009-12-08 23:48:08 +0900478 if (bytes_written < 0 && !SocketWriteErrorIsRecoverable()) {
hubbe@chromium.orga53c97c2014-02-21 09:18:29 +0900479 // 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.
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900485#if defined(OS_MACOSX)
486 // On OSX writing to a pipe with no listener returns EPERM.
487 if (errno == EPERM) {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900488 return false;
489 }
490#endif // OS_MACOSX
evan@chromium.org7d3eaa72009-10-23 10:48:21 +0900491 if (errno == EPIPE) {
evan@chromium.org7d3eaa72009-10-23 10:48:21 +0900492 return false;
493 }
jeremy@chromium.org53a4fac2009-12-03 22:35:46 +0900494 PLOG(ERROR) << "pipe error on "
495 << fd_written
thestig@chromium.org8b563352011-02-11 17:43:52 +0900496 << " Currently writing message of size: "
jeremy@chromium.org2a85b112009-12-08 23:48:08 +0900497 << msg->size();
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900498 return false;
499 }
500
501 if (static_cast<size_t>(bytes_written) != amt_to_write) {
502 if (bytes_written > 0) {
503 // If write() fails with EAGAIN then bytes_written will be -1.
504 message_send_bytes_written_ += bytes_written;
505 }
506
507 // Tell libevent to call us back once things are unblocked.
508 is_blocked_on_write_ = true;
xhwang@chromium.org0b2c2a52013-05-01 05:55:03 +0900509 base::MessageLoopForIO::current()->WatchFileDescriptor(
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900510 pipe_,
511 false, // One shot
xhwang@chromium.org0b2c2a52013-05-01 05:55:03 +0900512 base::MessageLoopForIO::WATCH_WRITE,
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900513 &write_watcher_,
514 this);
515 return true;
516 } else {
517 message_send_bytes_written_ = 0;
518
519 // Message sent OK!
pkasting@chromium.orgfcdd54b2010-10-20 08:50:00 +0900520 DVLOG(2) << "sent message @" << msg << " on channel @" << this
dmaclach@chromium.orgdec0e2b2010-12-09 10:13:12 +0900521 << " with type " << msg->type() << " on fd " << pipe_;
agl@chromium.orga81f84a2009-09-05 06:34:05 +0900522 delete output_queue_.front();
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900523 output_queue_.pop();
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900524 }
525 }
526 return true;
527}
528
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +0900529bool ChannelPosix::Send(Message* message) {
pkasting@chromium.orgfcdd54b2010-10-20 08:50:00 +0900530 DVLOG(2) << "sending message @" << message << " on channel @" << this
531 << " with type " << message->type()
532 << " (" << output_queue_.size() << " in queue)";
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900533
534#ifdef IPC_MESSAGE_LOG_ENABLED
satish@chromium.orgaa870602010-12-13 17:18:55 +0900535 Logging::GetInstance()->OnSendMessage(message, "");
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900536#endif // IPC_MESSAGE_LOG_ENABLED
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900537
jbates@chromium.org7cc80332012-09-18 12:41:29 +0900538 message->TraceMessageBegin();
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900539 output_queue_.push(message);
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900540 if (!is_blocked_on_write_ && !waiting_connect_) {
hubbe@chromium.org105da532014-02-19 02:42:20 +0900541 return ProcessOutgoingMessages();
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900542 }
543
544 return true;
545}
546
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +0900547int ChannelPosix::GetClientFileDescriptor() const {
phajdan.jr@chromium.orgaf9455b2011-09-20 02:08:12 +0900548 base::AutoLock lock(client_pipe_lock_);
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900549 return client_pipe_;
550}
551
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +0900552int ChannelPosix::TakeClientFileDescriptor() {
phajdan.jr@chromium.orgaf9455b2011-09-20 02:08:12 +0900553 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
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +0900562void ChannelPosix::CloseClientFileDescriptor() {
phajdan.jr@chromium.orgaf9455b2011-09-20 02:08:12 +0900563 base::AutoLock lock(client_pipe_lock_);
564 if (client_pipe_ != -1) {
565 PipeMap::GetInstance()->Remove(pipe_name_);
mark@chromium.orgfa5a0f92013-12-03 23:10:59 +0900566 if (IGNORE_EINTR(close(client_pipe_)) < 0)
phajdan.jr@chromium.orgaf9455b2011-09-20 02:08:12 +0900567 PLOG(ERROR) << "close " << pipe_name_;
568 client_pipe_ = -1;
569 }
570}
571
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +0900572bool ChannelPosix::AcceptsConnections() const {
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900573 return server_listen_pipe_ != -1;
574}
dmaclach@chromium.org6a9b0c72010-12-20 15:19:07 +0900575
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +0900576bool ChannelPosix::HasAcceptedConnection() const {
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900577 return AcceptsConnections() && pipe_ != -1;
578}
dmaclach@chromium.org6a9b0c72010-12-20 15:19:07 +0900579
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +0900580bool ChannelPosix::GetPeerEuid(uid_t* peer_euid) const {
jeremya@chromium.orgf14bfab2013-03-13 13:23:10 +0900581 DCHECK(!(mode_ & MODE_SERVER) || HasAcceptedConnection());
582 return IPC::GetPeerEuid(pipe_, peer_euid);
wez@chromium.org7cce0912011-04-06 21:01:44 +0900583}
584
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +0900585void ChannelPosix::ResetToAcceptingConnectionState() {
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900586 // Unregister libevent for the unix domain socket and close it.
587 read_watcher_.StopWatchingFileDescriptor();
588 write_watcher_.StopWatchingFileDescriptor();
589 if (pipe_ != -1) {
mark@chromium.orgfa5a0f92013-12-03 23:10:59 +0900590 if (IGNORE_EINTR(close(pipe_)) < 0)
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900591 PLOG(ERROR) << "close pipe_ " << pipe_name_;
592 pipe_ = -1;
593 }
594#if defined(IPC_USES_READWRITE)
595 if (fd_pipe_ != -1) {
mark@chromium.orgfa5a0f92013-12-03 23:10:59 +0900596 if (IGNORE_EINTR(close(fd_pipe_)) < 0)
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900597 PLOG(ERROR) << "close fd_pipe_ " << pipe_name_;
598 fd_pipe_ = -1;
599 }
600 if (remote_fd_pipe_ != -1) {
mark@chromium.orgfa5a0f92013-12-03 23:10:59 +0900601 if (IGNORE_EINTR(close(remote_fd_pipe_)) < 0)
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900602 PLOG(ERROR) << "close remote_fd_pipe_ " << pipe_name_;
603 remote_fd_pipe_ = -1;
604 }
605#endif // IPC_USES_READWRITE
dmaclach@chromium.orgf22df392010-12-20 15:39:44 +0900606
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900607 while (!output_queue_.empty()) {
608 Message* m = output_queue_.front();
609 output_queue_.pop();
610 delete m;
dmaclach@chromium.orgf22df392010-12-20 15:39:44 +0900611 }
612
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900613 // Close any outstanding, received file descriptors.
brettw@chromium.org293988a2012-03-01 07:48:14 +0900614 ClearInputFDs();
hubbe@chromium.org683920d2013-10-15 09:07:00 +0900615
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) {
mark@chromium.orgfa5a0f92013-12-03 23:10:59 +0900621 if (IGNORE_EINTR(close(*i)) < 0)
hubbe@chromium.org683920d2013-10-15 09:07:00 +0900622 PLOG(ERROR) << "close";
623 }
624 fds_to_close_.clear();
625#endif
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900626}
627
kkania@chromium.orgf37b4e52011-08-09 15:46:06 +0900628// static
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +0900629bool ChannelPosix::IsNamedServerInitialized(
kkania@chromium.orgf37b4e52011-08-09 15:46:06 +0900630 const std::string& channel_id) {
brettw@chromium.org10b64122013-07-12 02:36:07 +0900631 return base::PathExists(base::FilePath(channel_id));
kkania@chromium.orgf37b4e52011-08-09 15:46:06 +0900632}
633
jamescook@chromium.org2d471f02011-09-01 06:11:04 +0900634#if defined(OS_LINUX)
635// static
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +0900636void ChannelPosix::SetGlobalPid(int pid) {
jamescook@chromium.org2d471f02011-09-01 06:11:04 +0900637 global_pid_ = pid;
638}
639#endif // OS_LINUX
640
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900641// Called by libevent when we can read from the pipe without blocking.
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +0900642void ChannelPosix::OnFileCanReadWithoutBlocking(int fd) {
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900643 if (fd == server_listen_pipe_) {
644 int new_pipe = 0;
jeremya@chromium.orgf14bfab2013-03-13 13:23:10 +0900645 if (!ServerAcceptConnection(server_listen_pipe_, &new_pipe) ||
646 new_pipe < 0) {
dmaclach@chromium.orgf22df392010-12-20 15:39:44 +0900647 Close();
brettw@chromium.org0e9d0a12012-03-08 21:30:28 +0900648 listener()->OnChannelListenError();
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900649 }
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)
brettw@chromium.org293988a2012-03-01 07:48:14 +0900655 DPLOG(ERROR) << "shutdown " << pipe_name_;
mark@chromium.orgfa5a0f92013-12-03 23:10:59 +0900656 if (IGNORE_EINTR(close(new_pipe)) < 0)
brettw@chromium.org293988a2012-03-01 07:48:14 +0900657 DPLOG(ERROR) << "close " << pipe_name_;
brettw@chromium.org0e9d0a12012-03-08 21:30:28 +0900658 listener()->OnChannelDenied();
dmaclach@chromium.orgf22df392010-12-20 15:39:44 +0900659 return;
dmaclach@chromium.org6a9b0c72010-12-20 15:19:07 +0900660 }
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900661 pipe_ = new_pipe;
662
wez@chromium.org7cce0912011-04-06 21:01:44 +0900663 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;
jeremya@chromium.orgf14bfab2013-03-13 13:23:10 +0900666 if (!GetPeerEuid(&client_euid)) {
brettw@chromium.org293988a2012-03-01 07:48:14 +0900667 DLOG(ERROR) << "Unable to query client euid";
wez@chromium.org7cce0912011-04-06 21:01:44 +0900668 ResetToAcceptingConnectionState();
669 return;
670 }
671 if (client_euid != geteuid()) {
brettw@chromium.org293988a2012-03-01 07:48:14 +0900672 DLOG(WARNING) << "Client euid is not authorised";
wez@chromium.org7cce0912011-04-06 21:01:44 +0900673 ResetToAcceptingConnectionState();
674 return;
675 }
676 }
677
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900678 if (!AcceptConnection()) {
679 NOTREACHED() << "AcceptConnection should not fail on server";
680 }
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900681 waiting_connect_ = false;
682 } else if (fd == pipe_) {
dmaclach@chromium.orgf146c292011-02-04 05:35:09 +0900683 if (waiting_connect_ && (mode_ & MODE_SERVER_FLAG)) {
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900684 waiting_connect_ = false;
685 }
686 if (!ProcessIncomingMessages()) {
agl@chromium.org0d5ac662011-03-01 05:30:47 +0900687 // ClosePipeOnError may delete this object, so we mustn't call
688 // ProcessOutgoingMessages.
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900689 ClosePipeOnError();
hubbe@chromium.org683920d2013-10-15 09:07:00 +0900690 return;
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900691 }
692 } else {
693 NOTREACHED() << "Unknown pipe " << fd;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900694 }
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
hubbe@chromium.orga53c97c2014-02-21 09:18:29 +0900699 // is invalid. This also flushes any closefd messages.
hubbe@chromium.org683920d2013-10-15 09:07:00 +0900700 if (!is_blocked_on_write_) {
701 if (!ProcessOutgoingMessages()) {
702 ClosePipeOnError();
703 }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900704 }
705}
706
707// Called by libevent when we can write to the pipe without blocking.
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +0900708void ChannelPosix::OnFileCanWriteWithoutBlocking(int fd) {
david.mike.futcher@gmail.com9eb2aa52011-04-19 05:07:08 +0900709 DCHECK_EQ(pipe_, fd);
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900710 is_blocked_on_write_ = false;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +0900711 if (!ProcessOutgoingMessages()) {
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900712 ClosePipeOnError();
dmaclach@chromium.org6a9b0c72010-12-20 15:19:07 +0900713 }
714}
715
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +0900716bool ChannelPosix::AcceptConnection() {
xhwang@chromium.org0b2c2a52013-05-01 05:55:03 +0900717 base::MessageLoopForIO::current()->WatchFileDescriptor(
718 pipe_, true, base::MessageLoopForIO::WATCH_READ, &read_watcher_, this);
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900719 QueueHelloMessage();
720
dmaclach@chromium.orgf146c292011-02-04 05:35:09 +0900721 if (mode_ & MODE_CLIENT_FLAG) {
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900722 // 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;
hubbe@chromium.org105da532014-02-19 02:42:20 +0900726 return ProcessOutgoingMessages();
dmaclach@chromium.orgf146c292011-02-04 05:35:09 +0900727 } else if (mode_ & MODE_SERVER_FLAG) {
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900728 waiting_connect_ = true;
729 return true;
dmaclach@chromium.orgf146c292011-02-04 05:35:09 +0900730 } else {
731 NOTREACHED();
732 return false;
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900733 }
734}
735
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +0900736void ChannelPosix::ClosePipeOnError() {
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900737 if (HasAcceptedConnection()) {
738 ResetToAcceptingConnectionState();
brettw@chromium.org0e9d0a12012-03-08 21:30:28 +0900739 listener()->OnChannelError();
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900740 } else {
741 Close();
742 if (AcceptsConnections()) {
brettw@chromium.org0e9d0a12012-03-08 21:30:28 +0900743 listener()->OnChannelListenError();
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900744 } else {
brettw@chromium.org0e9d0a12012-03-08 21:30:28 +0900745 listener()->OnChannelError();
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900746 }
747 }
748}
749
morrita@chromium.org15996aa2014-08-05 08:44:17 +0900750int ChannelPosix::GetHelloMessageProcId() const {
jamescook@chromium.org2d471f02011-09-01 06:11:04 +0900751 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
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +0900761void ChannelPosix::QueueHelloMessage() {
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900762 // Create the Hello message
763 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
bbudge@chromium.orgab4c6bc2013-11-05 07:28:12 +0900764 HELLO_MESSAGE_TYPE,
765 IPC::Message::PRIORITY_NORMAL));
jamescook@chromium.org2d471f02011-09-01 06:11:04 +0900766 if (!msg->WriteInt(GetHelloMessageProcId())) {
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +0900767 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
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +0900782ChannelPosix::ReadState ChannelPosix::ReadData(
brettw@chromium.org828e8592012-03-02 06:41:47 +0900783 char* buffer,
784 int buffer_len,
785 int* bytes_read) {
786 if (pipe_ == -1)
787 return READ_FAILED;
788
brettw@chromium.org293988a2012-03-01 07:48:14 +0900789 struct msghdr msg = {0};
790
shenhan@google.com8a6e4992012-06-05 10:54:46 +0900791 struct iovec iov = {buffer, static_cast<size_t>(buffer_len)};
brettw@chromium.org293988a2012-03-01 07:48:14 +0900792 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.
brettw@chromium.org293988a2012-03-01 07:48:14 +0900799#if defined(IPC_USES_READWRITE)
800 if (fd_pipe_ >= 0) {
brettw@chromium.org828e8592012-03-02 06:41:47 +0900801 *bytes_read = HANDLE_EINTR(read(pipe_, buffer, buffer_len));
brettw@chromium.org293988a2012-03-01 07:48:14 +0900802 msg.msg_controllen = 0;
803 } else
804#endif // IPC_USES_READWRITE
805 {
806 msg.msg_controllen = sizeof(input_cmsg_buf_);
brettw@chromium.org828e8592012-03-02 06:41:47 +0900807 *bytes_read = HANDLE_EINTR(recvmsg(pipe_, &msg, MSG_DONTWAIT));
brettw@chromium.org293988a2012-03-01 07:48:14 +0900808 }
brettw@chromium.org828e8592012-03-02 06:41:47 +0900809 if (*bytes_read < 0) {
brettw@chromium.org293988a2012-03-01 07:48:14 +0900810 if (errno == EAGAIN) {
brettw@chromium.org828e8592012-03-02 06:41:47 +0900811 return READ_PENDING;
brettw@chromium.org293988a2012-03-01 07:48:14 +0900812#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.
brettw@chromium.org828e8592012-03-02 06:41:47 +0900817 return READ_FAILED;
brettw@chromium.org293988a2012-03-01 07:48:14 +0900818#endif // OS_MACOSX
819 } else if (errno == ECONNRESET || errno == EPIPE) {
brettw@chromium.org828e8592012-03-02 06:41:47 +0900820 return READ_FAILED;
brettw@chromium.org293988a2012-03-01 07:48:14 +0900821 } else {
822 PLOG(ERROR) << "pipe error (" << pipe_ << ")";
brettw@chromium.org828e8592012-03-02 06:41:47 +0900823 return READ_FAILED;
brettw@chromium.org293988a2012-03-01 07:48:14 +0900824 }
brettw@chromium.org828e8592012-03-02 06:41:47 +0900825 } else if (*bytes_read == 0) {
brettw@chromium.org293988a2012-03-01 07:48:14 +0900826 // The pipe has closed...
brettw@chromium.org828e8592012-03-02 06:41:47 +0900827 return READ_FAILED;
brettw@chromium.org293988a2012-03-01 07:48:14 +0900828 }
brettw@chromium.org828e8592012-03-02 06:41:47 +0900829 DCHECK(*bytes_read);
brettw@chromium.org293988a2012-03-01 07:48:14 +0900830
831 CloseClientFileDescriptor();
832
833 // Read any file descriptors from the message.
834 if (!ExtractFileDescriptorsFromMsghdr(&msg))
brettw@chromium.org828e8592012-03-02 06:41:47 +0900835 return READ_FAILED;
836 return READ_SUCCEEDED;
brettw@chromium.org293988a2012-03-01 07:48:14 +0900837}
838
839#if defined(IPC_USES_READWRITE)
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +0900840bool ChannelPosix::ReadFileDescriptorsFromFDPipe() {
brettw@chromium.org293988a2012-03-01 07:48:14 +0900841 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
brettw@chromium.org0e9d0a12012-03-08 21:30:28 +0900860// 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.
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +0900865bool ChannelPosix::WillDispatchInputMessage(Message* msg) {
brettw@chromium.org293988a2012-03-01 07:48:14 +0900866 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;
brettw@chromium.org293988a2012-03-01 07:48:14 +0900891 // Abort the connection.
892 ClearInputFDs();
893 return false;
894 }
895
fischman@chromium.org8b60dfa2012-04-10 06:40:44 +0900896 // 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<>.
brettw@chromium.org293988a2012-03-01 07:48:14 +0900899 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
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +0900905bool ChannelPosix::DidEmptyInputBuffers() {
brettw@chromium.org828e8592012-03-02 06:41:47 +0900906 // 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
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +0900912bool ChannelPosix::ExtractFileDescriptorsFromMsghdr(msghdr* msg) {
brettw@chromium.org293988a2012-03-01 07:48:14 +0900913 // 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
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +0900944void ChannelPosix::ClearInputFDs() {
fischman@chromium.org8b60dfa2012-04-10 06:40:44 +0900945 for (size_t i = 0; i < input_fds_.size(); ++i) {
mark@chromium.orgfa5a0f92013-12-03 23:10:59 +0900946 if (IGNORE_EINTR(close(input_fds_[i])) < 0)
brettw@chromium.org293988a2012-03-01 07:48:14 +0900947 PLOG(ERROR) << "close ";
brettw@chromium.org293988a2012-03-01 07:48:14 +0900948 }
fischman@chromium.org8b60dfa2012-04-10 06:40:44 +0900949 input_fds_.clear();
brettw@chromium.org293988a2012-03-01 07:48:14 +0900950}
951
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +0900952void ChannelPosix::QueueCloseFDMessage(int fd, int hops) {
hubbe@chromium.org683920d2013-10-15 09:07:00 +0900953 switch (hops) {
954 case 1:
955 case 2: {
956 // Create the message
957 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
bbudge@chromium.orgab4c6bc2013-11-05 07:28:12 +0900958 CLOSE_FD_MESSAGE_TYPE,
959 IPC::Message::PRIORITY_NORMAL));
hubbe@chromium.org683920d2013-10-15 09:07:00 +0900960 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
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +0900974void ChannelPosix::HandleInternalMessage(const Message& msg) {
brettw@chromium.org293988a2012-03-01 07:48:14 +0900975 // The Hello message contains only the process id.
jbates@chromium.org0fc87362012-03-08 05:42:56 +0900976 PickleIterator iter(msg);
hubbe@chromium.org683920d2013-10-15 09:07:00 +0900977
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();
brettw@chromium.org293988a2012-03-01 07:48:14 +0900987
988#if defined(IPC_USES_READWRITE)
hubbe@chromium.org683920d2013-10-15 09:07:00 +0900989 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 }
benwells@chromium.org6ecd7122013-10-11 13:22:34 +09001001#endif // IPC_USES_READWRITE
hubbe@chromium.org683920d2013-10-15 09:07:00 +09001002 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) {
mark@chromium.orgfa5a0f92013-12-03 23:10:59 +09001015 if (IGNORE_EINTR(close(fd)) < 0)
hubbe@chromium.org683920d2013-10-15 09:07:00 +09001016 PLOG(ERROR) << "close";
1017 } else {
1018 NOTREACHED();
1019 }
1020 } else {
1021 QueueCloseFDMessage(fd, hops);
1022 }
1023 break;
1024#endif
1025 }
brettw@chromium.org293988a2012-03-01 07:48:14 +09001026}
1027
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +09001028void ChannelPosix::Close() {
agl@chromium.org1c6dcf22009-07-23 08:57:21 +09001029 // Close can be called multiple time, so we need to make sure we're
1030 // idempotent.
1031
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +09001032 ResetToAcceptingConnectionState();
agl@chromium.org1c6dcf22009-07-23 08:57:21 +09001033
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +09001034 if (must_unlink_) {
1035 unlink(pipe_name_.c_str());
1036 must_unlink_ = false;
1037 }
agl@chromium.org1c6dcf22009-07-23 08:57:21 +09001038 if (server_listen_pipe_ != -1) {
mark@chromium.orgfa5a0f92013-12-03 23:10:59 +09001039 if (IGNORE_EINTR(close(server_listen_pipe_)) < 0)
brettw@chromium.org293988a2012-03-01 07:48:14 +09001040 DPLOG(ERROR) << "close " << server_listen_pipe_;
agl@chromium.org1c6dcf22009-07-23 08:57:21 +09001041 server_listen_pipe_ = -1;
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +09001042 // Unregister libevent for the listening socket and close it.
1043 server_listen_connection_watcher_.StopWatchingFileDescriptor();
agl@chromium.org1c6dcf22009-07-23 08:57:21 +09001044 }
1045
phajdan.jr@chromium.orgaf9455b2011-09-20 02:08:12 +09001046 CloseClientFileDescriptor();
agl@chromium.org1c6dcf22009-07-23 08:57:21 +09001047}
1048
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +09001049base::ProcessId ChannelPosix::GetPeerPID() const {
1050 return peer_pid_;
1051}
1052
morrita@chromium.org15996aa2014-08-05 08:44:17 +09001053base::ProcessId ChannelPosix::GetSelfPID() const {
1054 return GetHelloMessageProcId();
1055}
1056
1057ChannelHandle ChannelPosix::TakePipeHandle() {
1058 ChannelHandle handle = ChannelHandle(pipe_name_,
1059 base::FileDescriptor(pipe_, false));
1060 pipe_ = -1;
1061 return handle;
1062}
1063
agl@chromium.org1c6dcf22009-07-23 08:57:21 +09001064//------------------------------------------------------------------------------
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +09001065// Channel's methods
dmaclach@chromium.orgc1d3d422010-12-20 15:59:23 +09001066
kkania@chromium.orgf37b4e52011-08-09 15:46:06 +09001067// static
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +09001068scoped_ptr<Channel> Channel::Create(
1069 const IPC::ChannelHandle &channel_handle, Mode mode, Listener* listener) {
morrita@chromium.org844f1c32014-06-07 15:15:53 +09001070 return make_scoped_ptr(new ChannelPosix(
1071 channel_handle, mode, listener)).PassAs<Channel>();
kkania@chromium.orgf37b4e52011-08-09 15:46:06 +09001072}
1073
jschuh@chromium.orgf75a4d12012-03-17 11:20:46 +09001074// static
1075std::string Channel::GenerateVerifiedChannelID(const std::string& prefix) {
1076 // A random name is sufficient validation on posix systems, so we don't need
1077 // an additional shared secret.
1078
1079 std::string id = prefix;
1080 if (!id.empty())
1081 id.append(".");
1082
1083 return id.append(GenerateUniqueRandomChannelID());
1084}
1085
1086
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +09001087bool Channel::IsNamedServerInitialized(
1088 const std::string& channel_id) {
1089 return ChannelPosix::IsNamedServerInitialized(channel_id);
1090}
1091
jamescook@chromium.org2d471f02011-09-01 06:11:04 +09001092#if defined(OS_LINUX)
1093// static
1094void Channel::SetGlobalPid(int pid) {
morrita@chromium.orgfde2b6b2014-06-07 05:13:51 +09001095 ChannelPosix::SetGlobalPid(pid);
jamescook@chromium.org2d471f02011-09-01 06:11:04 +09001096}
1097#endif // OS_LINUX
1098
agl@chromium.org1c6dcf22009-07-23 08:57:21 +09001099} // namespace IPC