blob: a88506c344ecb6e2f4159927b673e2227aff93b1 [file] [log] [blame]
[email protected]3b63f8f42011-03-28 01:54:151// Copyright (c) 2011 The Chromium Authors. All rights reserved.
[email protected]d4651ff2008-12-02 16:51:582// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]946d1b22009-07-22 23:57:215#include "ipc/ipc_channel_posix.h"
[email protected]d4651ff2008-12-02 16:51:586
[email protected]c3110742008-12-11 00:36:477#include <errno.h>
[email protected]fa95fc92008-12-08 18:10:148#include <fcntl.h>
[email protected]e45e6c02008-12-15 22:02:179#include <stddef.h>
[email protected]fa95fc92008-12-08 18:10:1410#include <sys/types.h>
11#include <sys/socket.h>
12#include <sys/stat.h>
[email protected]e45e6c02008-12-15 22:02:1713#include <sys/un.h>
[email protected]e45e6c02008-12-15 22:02:1714
[email protected]e8fce882009-01-20 22:02:5815#include <string>
16#include <map>
17
[email protected]df3c1ca12008-12-19 21:37:0118#include "base/command_line.h"
[email protected]157c61b2009-05-01 21:37:3119#include "base/eintr_wrapper.h"
[email protected]22b42c52010-12-20 06:59:2320#include "base/file_path.h"
21#include "base/file_util.h"
[email protected]cc8f1462009-06-12 17:36:5522#include "base/global_descriptors_posix.h"
[email protected]fa95fc92008-12-08 18:10:1423#include "base/logging.h"
[email protected]3b63f8f42011-03-28 01:54:1524#include "base/memory/scoped_ptr.h"
25#include "base/memory/singleton.h"
[email protected]fa95fc92008-12-08 18:10:1426#include "base/process_util.h"
[email protected]7286e3fc2011-07-19 22:13:2427#include "base/stl_util.h"
[email protected]946d1b22009-07-22 23:57:2128#include "base/string_util.h"
[email protected]20305ec2011-01-21 04:55:5229#include "base/synchronization/lock.h"
[email protected]946d1b22009-07-22 23:57:2130#include "ipc/ipc_descriptors.h"
31#include "ipc/ipc_switches.h"
32#include "ipc/file_descriptor_set_posix.h"
33#include "ipc/ipc_logging.h"
34#include "ipc/ipc_message_utils.h"
[email protected]d4651ff2008-12-02 16:51:5835
36namespace IPC {
37
[email protected]5f594c02009-05-01 22:37:5938// IPC channels on Windows use named pipes (CreateNamedPipe()) with
[email protected]22b42c52010-12-20 06:59:2339// channel ids as the pipe names. Channels on POSIX use sockets as
40// pipes These don't quite line up.
[email protected]5f594c02009-05-01 22:37:5941//
[email protected]22b42c52010-12-20 06:59:2342// When creating a child subprocess we use a socket pair and the parent side of
43// the fork arranges it such that the initial control channel ends up on the
[email protected]cc8f1462009-06-12 17:36:5544// magic file descriptor kPrimaryIPCChannel in the child. Future
[email protected]5f594c02009-05-01 22:37:5945// connections (file descriptors) can then be passed via that
46// connection via sendmsg().
[email protected]22b42c52010-12-20 06:59:2347//
48// A POSIX IPC channel can also be set up as a server for a bound UNIX domain
49// socket, and will handle multiple connect and disconnect sequences. Currently
50// it is limited to one connection at a time.
[email protected]5f594c02009-05-01 22:37:5951
[email protected]fa95fc92008-12-08 18:10:1452//------------------------------------------------------------------------------
[email protected]fa95fc92008-12-08 18:10:1453namespace {
54
[email protected]5f594c02009-05-01 22:37:5955// The PipeMap class works around this quirk related to unit tests:
[email protected]e8fce882009-01-20 22:02:5856//
[email protected]5f594c02009-05-01 22:37:5957// When running as a server, we install the client socket in a
[email protected]cc8f1462009-06-12 17:36:5558// specific file descriptor number (@kPrimaryIPCChannel). However, we
[email protected]5f594c02009-05-01 22:37:5959// also have to support the case where we are running unittests in the
60// same process. (We do not support forking without execing.)
[email protected]e8fce882009-01-20 22:02:5861//
62// Case 1: normal running
63// The IPC server object will install a mapping in PipeMap from the
64// name which it was given to the client pipe. When forking the client, the
65// GetClientFileDescriptorMapping will ensure that the socket is installed in
[email protected]cc8f1462009-06-12 17:36:5566// the magic slot (@kPrimaryIPCChannel). The client will search for the
[email protected]e8fce882009-01-20 22:02:5867// mapping, but it won't find any since we are in a new process. Thus the
68// magic fd number is returned. Once the client connects, the server will
[email protected]5f594c02009-05-01 22:37:5969// close its copy of the client socket and remove the mapping.
[email protected]e8fce882009-01-20 22:02:5870//
71// Case 2: unittests - client and server in the same process
72// The IPC server will install a mapping as before. The client will search
73// for a mapping and find out. It duplicates the file descriptor and
74// connects. Once the client connects, the server will close the original
75// copy of the client socket and remove the mapping. Thus, when the client
76// object closes, it will close the only remaining copy of the client socket
77// in the fd table and the server will see EOF on its side.
78//
79// TODO(port): a client process cannot connect to multiple IPC channels with
80// this scheme.
81
82class PipeMap {
83 public:
[email protected]864b5582010-12-04 23:00:1084 static PipeMap* GetInstance() {
85 return Singleton<PipeMap>::get();
86 }
87
[email protected]42ce94e2010-12-08 19:28:0988 ~PipeMap() {
89 // Shouldn't have left over pipes.
[email protected]f6b8ce32011-03-02 00:03:1890 DCHECK(map_.empty());
[email protected]42ce94e2010-12-08 19:28:0991 }
92
[email protected]e8fce882009-01-20 22:02:5893 // Lookup a given channel id. Return -1 if not found.
94 int Lookup(const std::string& channel_id) {
[email protected]20305ec2011-01-21 04:55:5295 base::AutoLock locked(lock_);
[email protected]e8fce882009-01-20 22:02:5896
97 ChannelToFDMap::const_iterator i = map_.find(channel_id);
98 if (i == map_.end())
99 return -1;
100 return i->second;
101 }
102
103 // Remove the mapping for the given channel id. No error is signaled if the
104 // channel_id doesn't exist
[email protected]f0ef2da2009-07-08 01:26:34105 void RemoveAndClose(const std::string& channel_id) {
[email protected]20305ec2011-01-21 04:55:52106 base::AutoLock locked(lock_);
[email protected]e8fce882009-01-20 22:02:58107
108 ChannelToFDMap::iterator i = map_.find(channel_id);
[email protected]f0ef2da2009-07-08 01:26:34109 if (i != map_.end()) {
[email protected]70eb6572010-06-23 00:37:46110 if (HANDLE_EINTR(close(i->second)) < 0)
[email protected]5484722e2010-12-09 01:13:12111 PLOG(ERROR) << "close " << channel_id;
[email protected]e8fce882009-01-20 22:02:58112 map_.erase(i);
[email protected]f0ef2da2009-07-08 01:26:34113 }
[email protected]e8fce882009-01-20 22:02:58114 }
115
116 // Insert a mapping from @channel_id to @fd. It's a fatal error to insert a
117 // mapping if one already exists for the given channel_id
118 void Insert(const std::string& channel_id, int fd) {
[email protected]20305ec2011-01-21 04:55:52119 base::AutoLock locked(lock_);
[email protected]60ea6052011-04-18 20:07:08120 DCHECK_NE(-1, fd);
[email protected]e8fce882009-01-20 22:02:58121
122 ChannelToFDMap::const_iterator i = map_.find(channel_id);
[email protected]d2e884d2009-06-22 20:37:52123 CHECK(i == map_.end()) << "Creating second IPC server (fd " << fd << ") "
124 << "for '" << channel_id << "' while first "
125 << "(fd " << i->second << ") still exists";
[email protected]e8fce882009-01-20 22:02:58126 map_[channel_id] = fd;
127 }
128
129 private:
[email protected]20305ec2011-01-21 04:55:52130 base::Lock lock_;
[email protected]e8fce882009-01-20 22:02:58131 typedef std::map<std::string, int> ChannelToFDMap;
132 ChannelToFDMap map_;
[email protected]864b5582010-12-04 23:00:10133
134 friend struct DefaultSingletonTraits<PipeMap>;
[email protected]e8fce882009-01-20 22:02:58135};
136
[email protected]df3c1ca12008-12-19 21:37:01137//------------------------------------------------------------------------------
[email protected]22b42c52010-12-20 06:59:23138// Verify that kMaxPipeNameLength is a decent size.
[email protected]cffa687f2010-12-08 20:33:46139COMPILE_ASSERT(sizeof(((sockaddr_un*)0)->sun_path) >= kMaxPipeNameLength,
140 BAD_SUN_PATH_LENGTH);
[email protected]fa95fc92008-12-08 18:10:14141
[email protected]22b42c52010-12-20 06:59:23142// Creates a unix domain socket bound to the specified name that is listening
143// for connections.
144bool CreateServerUnixDomainSocket(const std::string& pipe_name,
145 int* server_listen_fd) {
[email protected]fa95fc92008-12-08 18:10:14146 DCHECK(server_listen_fd);
[email protected]fa95fc92008-12-08 18:10:14147
[email protected]02d66512009-03-17 01:48:35148 if (pipe_name.length() == 0 || pipe_name.length() >= kMaxPipeNameLength) {
[email protected]3c524252011-08-25 14:14:05149 DLOG(ERROR) << "pipe_name.length() == " << pipe_name.length();
[email protected]fa95fc92008-12-08 18:10:14150 return false;
151 }
152
153 // Create socket.
154 int fd = socket(AF_UNIX, SOCK_STREAM, 0);
155 if (fd < 0) {
156 return false;
157 }
158
159 // Make socket non-blocking
160 if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
[email protected]22b42c52010-12-20 06:59:23161 PLOG(ERROR) << "fcntl(O_NONBLOCK) " << pipe_name;
[email protected]70eb6572010-06-23 00:37:46162 if (HANDLE_EINTR(close(fd)) < 0)
[email protected]5484722e2010-12-09 01:13:12163 PLOG(ERROR) << "close " << pipe_name;
[email protected]fa95fc92008-12-08 18:10:14164 return false;
165 }
166
167 // Delete any old FS instances.
168 unlink(pipe_name.c_str());
169
[email protected]6bef6c82011-01-20 21:42:08170 // Make sure the path we need exists.
[email protected]22b42c52010-12-20 06:59:23171 FilePath path(pipe_name);
172 FilePath dir_path = path.DirName();
173 if (!file_util::CreateDirectory(dir_path)) {
174 return false;
175 }
176
[email protected]6bef6c82011-01-20 21:42:08177 // Create unix_addr structure.
[email protected]fa95fc92008-12-08 18:10:14178 struct sockaddr_un unix_addr;
179 memset(&unix_addr, 0, sizeof(unix_addr));
180 unix_addr.sun_family = AF_UNIX;
[email protected]22b42c52010-12-20 06:59:23181 int path_len = snprintf(unix_addr.sun_path, IPC::kMaxPipeNameLength,
182 "%s", pipe_name.c_str());
183 DCHECK_EQ(static_cast<int>(pipe_name.length()), path_len);
184 size_t unix_addr_len = offsetof(struct sockaddr_un,
185 sun_path) + path_len + 1;
[email protected]fa95fc92008-12-08 18:10:14186
187 // Bind the socket.
188 if (bind(fd, reinterpret_cast<const sockaddr*>(&unix_addr),
189 unix_addr_len) != 0) {
[email protected]5484722e2010-12-09 01:13:12190 PLOG(ERROR) << "bind " << pipe_name;
[email protected]70eb6572010-06-23 00:37:46191 if (HANDLE_EINTR(close(fd)) < 0)
[email protected]5484722e2010-12-09 01:13:12192 PLOG(ERROR) << "close " << pipe_name;
[email protected]fa95fc92008-12-08 18:10:14193 return false;
194 }
195
196 // Start listening on the socket.
197 const int listen_queue_length = 1;
198 if (listen(fd, listen_queue_length) != 0) {
[email protected]5484722e2010-12-09 01:13:12199 PLOG(ERROR) << "listen " << pipe_name;
[email protected]70eb6572010-06-23 00:37:46200 if (HANDLE_EINTR(close(fd)) < 0)
[email protected]5484722e2010-12-09 01:13:12201 PLOG(ERROR) << "close " << pipe_name;
[email protected]fa95fc92008-12-08 18:10:14202 return false;
203 }
204
205 *server_listen_fd = fd;
206 return true;
207}
208
[email protected]22b42c52010-12-20 06:59:23209// Accept a connection on a socket we are listening to.
210bool ServerAcceptConnection(int server_listen_fd, int* server_socket) {
[email protected]fa95fc92008-12-08 18:10:14211 DCHECK(server_socket);
212
[email protected]157c61b2009-05-01 21:37:31213 int accept_fd = HANDLE_EINTR(accept(server_listen_fd, NULL, 0));
[email protected]fa95fc92008-12-08 18:10:14214 if (accept_fd < 0)
215 return false;
[email protected]3af21262008-12-16 21:49:34216 if (fcntl(accept_fd, F_SETFL, O_NONBLOCK) == -1) {
[email protected]22b42c52010-12-20 06:59:23217 PLOG(ERROR) << "fcntl(O_NONBLOCK) " << accept_fd;
[email protected]70eb6572010-06-23 00:37:46218 if (HANDLE_EINTR(close(accept_fd)) < 0)
[email protected]5484722e2010-12-09 01:13:12219 PLOG(ERROR) << "close " << accept_fd;
[email protected]3af21262008-12-16 21:49:34220 return false;
221 }
[email protected]fa95fc92008-12-08 18:10:14222
223 *server_socket = accept_fd;
224 return true;
225}
226
[email protected]22b42c52010-12-20 06:59:23227bool CreateClientUnixDomainSocket(const std::string& pipe_name,
228 int* client_socket) {
[email protected]fa95fc92008-12-08 18:10:14229 DCHECK(client_socket);
[email protected]5484722e2010-12-09 01:13:12230 DCHECK_GT(pipe_name.length(), 0u);
[email protected]02d66512009-03-17 01:48:35231 DCHECK_LT(pipe_name.length(), kMaxPipeNameLength);
[email protected]fa95fc92008-12-08 18:10:14232
[email protected]5484722e2010-12-09 01:13:12233 if (pipe_name.length() == 0 || pipe_name.length() >= kMaxPipeNameLength) {
234 return false;
235 }
236
[email protected]fa95fc92008-12-08 18:10:14237 // Create socket.
238 int fd = socket(AF_UNIX, SOCK_STREAM, 0);
239 if (fd < 0) {
[email protected]5484722e2010-12-09 01:13:12240 PLOG(ERROR) << "socket " << pipe_name;
[email protected]fa95fc92008-12-08 18:10:14241 return false;
242 }
243
244 // Make socket non-blocking
245 if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
[email protected]22b42c52010-12-20 06:59:23246 PLOG(ERROR) << "fcntl(O_NONBLOCK) " << pipe_name;
[email protected]70eb6572010-06-23 00:37:46247 if (HANDLE_EINTR(close(fd)) < 0)
[email protected]5484722e2010-12-09 01:13:12248 PLOG(ERROR) << "close " << pipe_name;
[email protected]fa95fc92008-12-08 18:10:14249 return false;
250 }
251
252 // Create server side of socket.
[email protected]5484722e2010-12-09 01:13:12253 struct sockaddr_un server_unix_addr;
[email protected]fa95fc92008-12-08 18:10:14254 memset(&server_unix_addr, 0, sizeof(server_unix_addr));
255 server_unix_addr.sun_family = AF_UNIX;
[email protected]22b42c52010-12-20 06:59:23256 int path_len = snprintf(server_unix_addr.sun_path, IPC::kMaxPipeNameLength,
257 "%s", pipe_name.c_str());
258 DCHECK_EQ(static_cast<int>(pipe_name.length()), path_len);
259 size_t server_unix_addr_len = offsetof(struct sockaddr_un,
260 sun_path) + path_len + 1;
[email protected]fa95fc92008-12-08 18:10:14261
[email protected]157c61b2009-05-01 21:37:31262 if (HANDLE_EINTR(connect(fd, reinterpret_cast<sockaddr*>(&server_unix_addr),
263 server_unix_addr_len)) != 0) {
[email protected]5484722e2010-12-09 01:13:12264 PLOG(ERROR) << "connect " << pipe_name;
[email protected]70eb6572010-06-23 00:37:46265 if (HANDLE_EINTR(close(fd)) < 0)
[email protected]5484722e2010-12-09 01:13:12266 PLOG(ERROR) << "close " << pipe_name;
[email protected]fa95fc92008-12-08 18:10:14267 return false;
268 }
269
270 *client_socket = fd;
271 return true;
272}
273
[email protected]86c3d9e2009-12-08 14:48:08274bool SocketWriteErrorIsRecoverable() {
275#if defined(OS_MACOSX)
276 // On OS X if sendmsg() is trying to send fds between processes and there
277 // isn't enough room in the output buffer to send the fd structure over
278 // atomically then EMSGSIZE is returned.
279 //
280 // EMSGSIZE presents a problem since the system APIs can only call us when
281 // there's room in the socket buffer and not when there is "enough" room.
282 //
283 // The current behavior is to return to the event loop when EMSGSIZE is
284 // received and hopefull service another FD. This is however still
285 // technically a busy wait since the event loop will call us right back until
286 // the receiver has read enough data to allow passing the FD over atomically.
287 return errno == EAGAIN || errno == EMSGSIZE;
288#else
289 return errno == EAGAIN;
[email protected]22b42c52010-12-20 06:59:23290#endif // OS_MACOSX
[email protected]86c3d9e2009-12-08 14:48:08291}
292
[email protected]fa95fc92008-12-08 18:10:14293} // namespace
[email protected]d4651ff2008-12-02 16:51:58294//------------------------------------------------------------------------------
295
[email protected]e1d67a882011-08-31 21:11:04296#if defined(OS_LINUX)
297int Channel::ChannelImpl::global_pid_ = 0;
298#endif // OS_LINUX
299
[email protected]42ce94e2010-12-08 19:28:09300Channel::ChannelImpl::ChannelImpl(const IPC::ChannelHandle& channel_handle,
301 Mode mode, Listener* listener)
[email protected]fa95fc92008-12-08 18:10:14302 : mode_(mode),
[email protected]e45e6c02008-12-15 22:02:17303 is_blocked_on_write_(false),
[email protected]22b42c52010-12-20 06:59:23304 waiting_connect_(true),
[email protected]e45e6c02008-12-15 22:02:17305 message_send_bytes_written_(0),
306 server_listen_pipe_(-1),
307 pipe_(-1),
[email protected]df3c1ca12008-12-19 21:37:01308 client_pipe_(-1),
[email protected]e40f5a0b2010-12-08 21:22:24309#if defined(IPC_USES_READWRITE)
[email protected]baf556a2009-09-04 21:34:05310 fd_pipe_(-1),
311 remote_fd_pipe_(-1),
[email protected]22b42c52010-12-20 06:59:23312#endif // IPC_USES_READWRITE
313 pipe_name_(channel_handle.name),
[email protected]e45e6c02008-12-15 22:02:17314 listener_(listener),
[email protected]bf84c582011-08-23 03:17:02315 must_unlink_(false) {
[email protected]df60edb2011-06-21 22:48:29316 memset(input_buf_, 0, sizeof(input_buf_));
317 memset(input_cmsg_buf_, 0, sizeof(input_cmsg_buf_));
[email protected]1707726c2011-02-03 20:35:09318 if (!CreatePipe(channel_handle)) {
[email protected]22b42c52010-12-20 06:59:23319 // The pipe may have been closed already.
[email protected]1707726c2011-02-03 20:35:09320 const char *modestr = (mode_ & MODE_SERVER_FLAG) ? "server" : "client";
[email protected]42ce94e2010-12-08 19:28:09321 LOG(WARNING) << "Unable to create pipe named \"" << channel_handle.name
[email protected]22b42c52010-12-20 06:59:23322 << "\" in " << modestr << " mode";
[email protected]fa95fc92008-12-08 18:10:14323 }
[email protected]d4651ff2008-12-02 16:51:58324}
325
[email protected]601858c02010-09-01 17:08:20326Channel::ChannelImpl::~ChannelImpl() {
327 Close();
328}
329
[email protected]d2e884d2009-06-22 20:37:52330bool SocketPair(int* fd1, int* fd2) {
331 int pipe_fds[2];
332 if (socketpair(AF_UNIX, SOCK_STREAM, 0, pipe_fds) != 0) {
[email protected]57b765672009-10-13 18:27:40333 PLOG(ERROR) << "socketpair()";
[email protected]d2e884d2009-06-22 20:37:52334 return false;
335 }
336
337 // Set both ends to be non-blocking.
338 if (fcntl(pipe_fds[0], F_SETFL, O_NONBLOCK) == -1 ||
339 fcntl(pipe_fds[1], F_SETFL, O_NONBLOCK) == -1) {
[email protected]57b765672009-10-13 18:27:40340 PLOG(ERROR) << "fcntl(O_NONBLOCK)";
[email protected]70eb6572010-06-23 00:37:46341 if (HANDLE_EINTR(close(pipe_fds[0])) < 0)
342 PLOG(ERROR) << "close";
343 if (HANDLE_EINTR(close(pipe_fds[1])) < 0)
344 PLOG(ERROR) << "close";
[email protected]d2e884d2009-06-22 20:37:52345 return false;
346 }
347
348 *fd1 = pipe_fds[0];
349 *fd2 = pipe_fds[1];
350
351 return true;
352}
353
[email protected]1707726c2011-02-03 20:35:09354bool Channel::ChannelImpl::CreatePipe(
355 const IPC::ChannelHandle& channel_handle) {
[email protected]fa95fc92008-12-08 18:10:14356 DCHECK(server_listen_pipe_ == -1 && pipe_ == -1);
[email protected]22b42c52010-12-20 06:59:23357
358 // Four possible cases:
359 // 1) It's a channel wrapping a pipe that is given to us.
360 // 2) It's for a named channel, so we create it.
361 // 3) It's for a client that we implement ourself. This is used
362 // in unittesting.
363 // 4) It's the initial IPC channel:
364 // 4a) Client side: Pull the pipe out of the GlobalDescriptors set.
365 // 4b) Server side: create the pipe.
366
[email protected]6aad23f92011-03-02 22:27:14367 int local_pipe = -1;
[email protected]22b42c52010-12-20 06:59:23368 if (channel_handle.socket.fd != -1) {
369 // Case 1 from comment above.
[email protected]6aad23f92011-03-02 22:27:14370 local_pipe = channel_handle.socket.fd;
[email protected]22b42c52010-12-20 06:59:23371#if defined(IPC_USES_READWRITE)
372 // Test the socket passed into us to make sure it is nonblocking.
373 // We don't want to call read/write on a blocking socket.
[email protected]6aad23f92011-03-02 22:27:14374 int value = fcntl(local_pipe, F_GETFL);
[email protected]22b42c52010-12-20 06:59:23375 if (value == -1) {
376 PLOG(ERROR) << "fcntl(F_GETFL) " << pipe_name_;
377 return false;
378 }
379 if (!(value & O_NONBLOCK)) {
380 LOG(ERROR) << "Socket " << pipe_name_ << " must be O_NONBLOCK";
381 return false;
382 }
383#endif // IPC_USES_READWRITE
[email protected]1707726c2011-02-03 20:35:09384 } else if (mode_ & MODE_NAMED_FLAG) {
[email protected]22b42c52010-12-20 06:59:23385 // Case 2 from comment above.
[email protected]1707726c2011-02-03 20:35:09386 if (mode_ & MODE_SERVER_FLAG) {
[email protected]6aad23f92011-03-02 22:27:14387 if (!CreateServerUnixDomainSocket(pipe_name_, &local_pipe)) {
[email protected]df3c1ca12008-12-19 21:37:01388 return false;
389 }
[email protected]56f0f262011-02-24 17:14:36390 must_unlink_ = true;
[email protected]1707726c2011-02-03 20:35:09391 } else if (mode_ & MODE_CLIENT_FLAG) {
[email protected]6aad23f92011-03-02 22:27:14392 if (!CreateClientUnixDomainSocket(pipe_name_, &local_pipe)) {
[email protected]df3c1ca12008-12-19 21:37:01393 return false;
394 }
[email protected]1707726c2011-02-03 20:35:09395 } else {
[email protected]6aad23f92011-03-02 22:27:14396 LOG(ERROR) << "Bad mode: " << mode_;
[email protected]1707726c2011-02-03 20:35:09397 return false;
[email protected]fa95fc92008-12-08 18:10:14398 }
399 } else {
[email protected]6aad23f92011-03-02 22:27:14400 local_pipe = PipeMap::GetInstance()->Lookup(pipe_name_);
[email protected]1707726c2011-02-03 20:35:09401 if (mode_ & MODE_CLIENT_FLAG) {
[email protected]6aad23f92011-03-02 22:27:14402 if (local_pipe != -1) {
[email protected]22b42c52010-12-20 06:59:23403 // Case 3 from comment above.
404 // We only allow one connection.
[email protected]6aad23f92011-03-02 22:27:14405 local_pipe = HANDLE_EINTR(dup(local_pipe));
[email protected]22b42c52010-12-20 06:59:23406 PipeMap::GetInstance()->RemoveAndClose(pipe_name_);
[email protected]d2e884d2009-06-22 20:37:52407 } else {
[email protected]22b42c52010-12-20 06:59:23408 // Case 4a from comment above.
[email protected]554a8852009-11-30 22:14:37409 // Guard against inappropriate reuse of the initial IPC channel. If
410 // an IPC channel closes and someone attempts to reuse it by name, the
411 // initial channel must not be recycled here. http://crbug.com/26754.
412 static bool used_initial_channel = false;
413 if (used_initial_channel) {
[email protected]9f816f72010-03-16 20:31:10414 LOG(FATAL) << "Denying attempt to reuse initial IPC channel for "
415 << pipe_name_;
[email protected]554a8852009-11-30 22:14:37416 return false;
417 }
418 used_initial_channel = true;
419
[email protected]6aad23f92011-03-02 22:27:14420 local_pipe =
421 base::GlobalDescriptors::GetInstance()->Get(kPrimaryIPCChannel);
[email protected]df3c1ca12008-12-19 21:37:01422 }
[email protected]1707726c2011-02-03 20:35:09423 } else if (mode_ & MODE_SERVER_FLAG) {
[email protected]22b42c52010-12-20 06:59:23424 // Case 4b from comment above.
[email protected]6aad23f92011-03-02 22:27:14425 if (local_pipe != -1) {
[email protected]22b42c52010-12-20 06:59:23426 LOG(ERROR) << "Server already exists for " << pipe_name_;
[email protected]baf556a2009-09-04 21:34:05427 return false;
428 }
[email protected]6aad23f92011-03-02 22:27:14429 if (!SocketPair(&local_pipe, &client_pipe_))
[email protected]22b42c52010-12-20 06:59:23430 return false;
431 PipeMap::GetInstance()->Insert(pipe_name_, client_pipe_);
432 } else {
[email protected]6aad23f92011-03-02 22:27:14433 LOG(ERROR) << "Bad mode: " << mode_;
[email protected]22b42c52010-12-20 06:59:23434 return false;
[email protected]baf556a2009-09-04 21:34:05435 }
436 }
[email protected]22b42c52010-12-20 06:59:23437
[email protected]22b42c52010-12-20 06:59:23438#if defined(IPC_USES_READWRITE)
439 // Create a dedicated socketpair() for exchanging file descriptors.
440 // See comments for IPC_USES_READWRITE for details.
[email protected]1707726c2011-02-03 20:35:09441 if (mode_ & MODE_CLIENT_FLAG) {
[email protected]22b42c52010-12-20 06:59:23442 if (!SocketPair(&fd_pipe_, &remote_fd_pipe_)) {
443 return false;
444 }
445 }
446#endif // IPC_USES_READWRITE
447
[email protected]6aad23f92011-03-02 22:27:14448 if ((mode_ & MODE_SERVER_FLAG) && (mode_ & MODE_NAMED_FLAG)) {
449 server_listen_pipe_ = local_pipe;
450 local_pipe = -1;
451 }
452
453 pipe_ = local_pipe;
[email protected]fa95fc92008-12-08 18:10:14454 return true;
[email protected]d4651ff2008-12-02 16:51:58455}
456
[email protected]514411fc2008-12-10 22:28:11457bool Channel::ChannelImpl::Connect() {
[email protected]22b42c52010-12-20 06:59:23458 if (server_listen_pipe_ == -1 && pipe_ == -1) {
[email protected]6aad23f92011-03-02 22:27:14459 DLOG(INFO) << "Channel creation failed: " << pipe_name_;
[email protected]22b42c52010-12-20 06:59:23460 return false;
461 }
462
463 bool did_connect = true;
464 if (server_listen_pipe_ != -1) {
465 // Watch the pipe for connections, and turn any connections into
466 // active sockets.
[email protected]e45e6c02008-12-15 22:02:17467 MessageLoopForIO::current()->WatchFileDescriptor(
468 server_listen_pipe_,
469 true,
470 MessageLoopForIO::WATCH_READ,
471 &server_listen_connection_watcher_,
472 this);
[email protected]fa95fc92008-12-08 18:10:14473 } else {
[email protected]22b42c52010-12-20 06:59:23474 did_connect = AcceptConnection();
[email protected]fa95fc92008-12-08 18:10:14475 }
[email protected]22b42c52010-12-20 06:59:23476 return did_connect;
[email protected]d4651ff2008-12-02 16:51:58477}
[email protected]fa95fc92008-12-08 18:10:14478
[email protected]514411fc2008-12-10 22:28:11479bool Channel::ChannelImpl::ProcessIncomingMessages() {
[email protected]fa95fc92008-12-08 18:10:14480 ssize_t bytes_read = 0;
481
[email protected]526776c2009-02-07 00:39:26482 struct msghdr msg = {0};
483 struct iovec iov = {input_buf_, Channel::kReadBufferSize};
484
[email protected]526776c2009-02-07 00:39:26485 msg.msg_iovlen = 1;
486 msg.msg_control = input_cmsg_buf_;
[email protected]526776c2009-02-07 00:39:26487
[email protected]fa95fc92008-12-08 18:10:14488 for (;;) {
[email protected]baf556a2009-09-04 21:34:05489 msg.msg_iov = &iov;
[email protected]cef7c522009-02-10 08:15:02490
[email protected]fa95fc92008-12-08 18:10:14491 if (bytes_read == 0) {
492 if (pipe_ == -1)
493 return false;
494
495 // Read from pipe.
[email protected]526776c2009-02-07 00:39:26496 // recvmsg() returns 0 if the connection has closed or EAGAIN if no data
497 // is waiting on the pipe.
[email protected]e40f5a0b2010-12-08 21:22:24498#if defined(IPC_USES_READWRITE)
[email protected]baf556a2009-09-04 21:34:05499 if (fd_pipe_ >= 0) {
500 bytes_read = HANDLE_EINTR(read(pipe_, input_buf_,
501 Channel::kReadBufferSize));
502 msg.msg_controllen = 0;
503 } else
[email protected]22b42c52010-12-20 06:59:23504#endif // IPC_USES_READWRITE
[email protected]baf556a2009-09-04 21:34:05505 {
506 msg.msg_controllen = sizeof(input_cmsg_buf_);
507 bytes_read = HANDLE_EINTR(recvmsg(pipe_, &msg, MSG_DONTWAIT));
508 }
[email protected]fa95fc92008-12-08 18:10:14509 if (bytes_read < 0) {
510 if (errno == EAGAIN) {
511 return true;
[email protected]7f6f06232009-05-22 21:15:39512#if defined(OS_MACOSX)
513 } else if (errno == EPERM) {
514 // On OSX, reading from a pipe with no listener returns EPERM
515 // treat this as a special case to prevent spurious error messages
516 // to the console.
517 return false;
[email protected]22b42c52010-12-20 06:59:23518#endif // OS_MACOSX
[email protected]7bf54f5e2009-10-23 01:48:21519 } else if (errno == ECONNRESET || errno == EPIPE) {
[email protected]d8365fc2009-10-16 19:44:31520 return false;
[email protected]fa95fc92008-12-08 18:10:14521 } else {
[email protected]57b765672009-10-13 18:27:40522 PLOG(ERROR) << "pipe error (" << pipe_ << ")";
[email protected]fa95fc92008-12-08 18:10:14523 return false;
524 }
525 } else if (bytes_read == 0) {
526 // The pipe has closed...
[email protected]e8fce882009-01-20 22:02:58527 return false;
[email protected]fa95fc92008-12-08 18:10:14528 }
529 }
530 DCHECK(bytes_read);
531
[email protected]e8fce882009-01-20 22:02:58532 if (client_pipe_ != -1) {
[email protected]864b5582010-12-04 23:00:10533 PipeMap::GetInstance()->RemoveAndClose(pipe_name_);
[email protected]e8fce882009-01-20 22:02:58534 client_pipe_ = -1;
535 }
536
[email protected]526776c2009-02-07 00:39:26537 // a pointer to an array of |num_wire_fds| file descriptors from the read
[email protected]337c6bf2009-02-07 00:51:58538 const int* wire_fds = NULL;
[email protected]526776c2009-02-07 00:39:26539 unsigned num_wire_fds = 0;
540
541 // walk the list of control messages and, if we find an array of file
542 // descriptors, save a pointer to the array
[email protected]526776c2009-02-07 00:39:26543
[email protected]afb4bad2009-02-12 02:39:31544 // This next if statement is to work around an OSX issue where
545 // CMSG_FIRSTHDR will return non-NULL in the case that controllen == 0.
546 // Here's a test case:
547 //
548 // int main() {
549 // struct msghdr msg;
550 // msg.msg_control = &msg;
551 // msg.msg_controllen = 0;
552 // if (CMSG_FIRSTHDR(&msg))
553 // printf("Bug found!\n");
554 // }
555 if (msg.msg_controllen > 0) {
556 // On OSX, CMSG_FIRSTHDR doesn't handle the case where controllen is 0
557 // and will return a pointer into nowhere.
558 for (struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg); cmsg;
559 cmsg = CMSG_NXTHDR(&msg, cmsg)) {
560 if (cmsg->cmsg_level == SOL_SOCKET &&
561 cmsg->cmsg_type == SCM_RIGHTS) {
562 const unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0);
[email protected]60ea6052011-04-18 20:07:08563 DCHECK_EQ(0U, payload_len % sizeof(int));
[email protected]afb4bad2009-02-12 02:39:31564 wire_fds = reinterpret_cast<int*>(CMSG_DATA(cmsg));
565 num_wire_fds = payload_len / 4;
566
567 if (msg.msg_flags & MSG_CTRUNC) {
568 LOG(ERROR) << "SCM_RIGHTS message was truncated"
569 << " cmsg_len:" << cmsg->cmsg_len
570 << " fd:" << pipe_;
571 for (unsigned i = 0; i < num_wire_fds; ++i)
[email protected]70eb6572010-06-23 00:37:46572 if (HANDLE_EINTR(close(wire_fds[i])) < 0)
[email protected]22b42c52010-12-20 06:59:23573 PLOG(ERROR) << "close " << i;
[email protected]afb4bad2009-02-12 02:39:31574 return false;
575 }
576 break;
[email protected]526776c2009-02-07 00:39:26577 }
[email protected]526776c2009-02-07 00:39:26578 }
579 }
580
[email protected]fa95fc92008-12-08 18:10:14581 // Process messages from input buffer.
582 const char *p;
583 const char *end;
584 if (input_overflow_buf_.empty()) {
585 p = input_buf_;
586 end = p + bytes_read;
587 } else {
[email protected]05094a32011-09-01 00:50:13588 if (input_overflow_buf_.size() > (kMaximumMessageSize - bytes_read)) {
[email protected]fa95fc92008-12-08 18:10:14589 input_overflow_buf_.clear();
590 LOG(ERROR) << "IPC message is too big";
591 return false;
592 }
593 input_overflow_buf_.append(input_buf_, bytes_read);
594 p = input_overflow_buf_.data();
595 end = p + input_overflow_buf_.size();
596 }
597
[email protected]526776c2009-02-07 00:39:26598 // A pointer to an array of |num_fds| file descriptors which includes any
599 // fds that have spilled over from a previous read.
[email protected]baf556a2009-09-04 21:34:05600 const int* fds = NULL;
601 unsigned num_fds = 0;
[email protected]526776c2009-02-07 00:39:26602 unsigned fds_i = 0; // the index of the first unused descriptor
603
604 if (input_overflow_fds_.empty()) {
605 fds = wire_fds;
606 num_fds = num_wire_fds;
607 } else {
[email protected]baf556a2009-09-04 21:34:05608 if (num_wire_fds > 0) {
609 const size_t prev_size = input_overflow_fds_.size();
610 input_overflow_fds_.resize(prev_size + num_wire_fds);
611 memcpy(&input_overflow_fds_[prev_size], wire_fds,
612 num_wire_fds * sizeof(int));
613 }
[email protected]526776c2009-02-07 00:39:26614 fds = &input_overflow_fds_[0];
615 num_fds = input_overflow_fds_.size();
616 }
617
[email protected]fa95fc92008-12-08 18:10:14618 while (p < end) {
619 const char* message_tail = Message::FindNext(p, end);
620 if (message_tail) {
621 int len = static_cast<int>(message_tail - p);
[email protected]7135bb042009-02-12 04:05:28622 Message m(p, len);
[email protected]5484722e2010-12-09 01:13:12623 const uint16 header_fds = m.header()->num_fds;
624 if (header_fds) {
[email protected]526776c2009-02-07 00:39:26625 // the message has file descriptors
[email protected]7135bb042009-02-12 04:05:28626 const char* error = NULL;
[email protected]5484722e2010-12-09 01:13:12627 if (header_fds > num_fds - fds_i) {
[email protected]526776c2009-02-07 00:39:26628 // the message has been completely received, but we didn't get
629 // enough file descriptors.
[email protected]e40f5a0b2010-12-08 21:22:24630#if defined(IPC_USES_READWRITE)
[email protected]22b42c52010-12-20 06:59:23631 char dummy;
632 struct iovec fd_pipe_iov = { &dummy, 1 };
633 msg.msg_iov = &fd_pipe_iov;
634 msg.msg_controllen = sizeof(input_cmsg_buf_);
635 ssize_t n = HANDLE_EINTR(recvmsg(fd_pipe_, &msg, MSG_DONTWAIT));
636 if (n == 1 && msg.msg_controllen > 0) {
637 for (struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg); cmsg;
638 cmsg = CMSG_NXTHDR(&msg, cmsg)) {
639 if (cmsg->cmsg_level == SOL_SOCKET &&
640 cmsg->cmsg_type == SCM_RIGHTS) {
641 const unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0);
[email protected]60ea6052011-04-18 20:07:08642 DCHECK_EQ(0U, payload_len % sizeof(int));
[email protected]22b42c52010-12-20 06:59:23643 wire_fds = reinterpret_cast<int*>(CMSG_DATA(cmsg));
644 num_wire_fds = payload_len / 4;
[email protected]baf556a2009-09-04 21:34:05645
[email protected]22b42c52010-12-20 06:59:23646 if (msg.msg_flags & MSG_CTRUNC) {
647 LOG(ERROR) << "SCM_RIGHTS message was truncated"
648 << " cmsg_len:" << cmsg->cmsg_len
649 << " fd:" << pipe_;
650 for (unsigned i = 0; i < num_wire_fds; ++i)
651 if (HANDLE_EINTR(close(wire_fds[i])) < 0)
652 PLOG(ERROR) << "close " << i;
653 return false;
[email protected]baf556a2009-09-04 21:34:05654 }
[email protected]22b42c52010-12-20 06:59:23655 break;
[email protected]baf556a2009-09-04 21:34:05656 }
[email protected]22b42c52010-12-20 06:59:23657 }
658 if (input_overflow_fds_.empty()) {
659 fds = wire_fds;
660 num_fds = num_wire_fds;
661 } else {
662 if (num_wire_fds > 0) {
663 const size_t prev_size = input_overflow_fds_.size();
664 input_overflow_fds_.resize(prev_size + num_wire_fds);
665 memcpy(&input_overflow_fds_[prev_size], wire_fds,
666 num_wire_fds * sizeof(int));
[email protected]baf556a2009-09-04 21:34:05667 }
[email protected]22b42c52010-12-20 06:59:23668 fds = &input_overflow_fds_[0];
669 num_fds = input_overflow_fds_.size();
[email protected]baf556a2009-09-04 21:34:05670 }
671 }
[email protected]5484722e2010-12-09 01:13:12672 if (header_fds > num_fds - fds_i)
[email protected]22b42c52010-12-20 06:59:23673#endif // IPC_USES_READWRITE
[email protected]baf556a2009-09-04 21:34:05674 error = "Message needs unreceived descriptors";
[email protected]7135bb042009-02-12 04:05:28675 }
676
[email protected]5484722e2010-12-09 01:13:12677 if (header_fds >
[email protected]05094a32011-09-01 00:50:13678 FileDescriptorSet::kMaxDescriptorsPerMessage) {
[email protected]7135bb042009-02-12 04:05:28679 // There are too many descriptors in this message
680 error = "Message requires an excessive number of descriptors";
681 }
682
683 if (error) {
684 LOG(WARNING) << error
[email protected]526776c2009-02-07 00:39:26685 << " channel:" << this
686 << " message-type:" << m.type()
[email protected]5484722e2010-12-09 01:13:12687 << " header()->num_fds:" << header_fds
[email protected]526776c2009-02-07 00:39:26688 << " num_fds:" << num_fds
689 << " fds_i:" << fds_i;
[email protected]a89a55dd2010-04-19 14:51:13690#if defined(CHROMIUM_SELINUX)
691 LOG(WARNING) << "In the case of SELinux this can be caused when "
692 "using a --user-data-dir to which the default "
693 "policy doesn't give the renderer access to. ";
[email protected]22b42c52010-12-20 06:59:23694#endif // CHROMIUM_SELINUX
[email protected]526776c2009-02-07 00:39:26695 // close the existing file descriptors so that we don't leak them
696 for (unsigned i = fds_i; i < num_fds; ++i)
[email protected]70eb6572010-06-23 00:37:46697 if (HANDLE_EINTR(close(fds[i])) < 0)
[email protected]22b42c52010-12-20 06:59:23698 PLOG(ERROR) << "close " << i;
[email protected]526776c2009-02-07 00:39:26699 input_overflow_fds_.clear();
[email protected]7135bb042009-02-12 04:05:28700 // abort the connection
[email protected]526776c2009-02-07 00:39:26701 return false;
702 }
703
[email protected]d0c0b1d2009-02-12 18:32:45704 m.file_descriptor_set()->SetDescriptors(
[email protected]5484722e2010-12-09 01:13:12705 &fds[fds_i], header_fds);
706 fds_i += header_fds;
[email protected]526776c2009-02-07 00:39:26707 }
[email protected]2a9d601b2010-10-19 23:50:00708 DVLOG(2) << "received message on channel @" << this
[email protected]5484722e2010-12-09 01:13:12709 << " with type " << m.type() << " on fd " << pipe_;
[email protected]22b42c52010-12-20 06:59:23710 if (IsHelloMessage(&m)) {
[email protected]fa95fc92008-12-08 18:10:14711 // The Hello message contains only the process id.
[email protected]baf556a2009-09-04 21:34:05712 void *iter = NULL;
713 int pid;
714 if (!m.ReadInt(&iter, &pid)) {
715 NOTREACHED();
716 }
[email protected]e40f5a0b2010-12-08 21:22:24717#if defined(IPC_USES_READWRITE)
[email protected]1707726c2011-02-03 20:35:09718 if (mode_ & MODE_SERVER_FLAG) {
[email protected]22b42c52010-12-20 06:59:23719 // With IPC_USES_READWRITE, the Hello message from the client to the
720 // server also contains the fd_pipe_, which will be used for all
[email protected]baf556a2009-09-04 21:34:05721 // subsequent file descriptor passing.
[email protected]7ee1a44c2010-07-23 14:18:59722 DCHECK_EQ(m.file_descriptor_set()->size(), 1U);
[email protected]baf556a2009-09-04 21:34:05723 base::FileDescriptor descriptor;
724 if (!m.ReadFileDescriptor(&iter, &descriptor)) {
725 NOTREACHED();
726 }
727 fd_pipe_ = descriptor.fd;
728 CHECK(descriptor.auto_close);
729 }
[email protected]22b42c52010-12-20 06:59:23730#endif // IPC_USES_READWRITE
[email protected]bf84c582011-08-23 03:17:02731 listener_->OnChannelConnected(pid);
[email protected]fa95fc92008-12-08 18:10:14732 } else {
733 listener_->OnMessageReceived(m);
734 }
735 p = message_tail;
736 } else {
737 // Last message is partial.
738 break;
739 }
[email protected]baf556a2009-09-04 21:34:05740 input_overflow_fds_ = std::vector<int>(&fds[fds_i], &fds[num_fds]);
741 fds_i = 0;
[email protected]e0b93ff2011-06-22 05:19:17742 fds = vector_as_array(&input_overflow_fds_);
[email protected]baf556a2009-09-04 21:34:05743 num_fds = input_overflow_fds_.size();
[email protected]fa95fc92008-12-08 18:10:14744 }
745 input_overflow_buf_.assign(p, end - p);
[email protected]526776c2009-02-07 00:39:26746 input_overflow_fds_ = std::vector<int>(&fds[fds_i], &fds[num_fds]);
[email protected]fa95fc92008-12-08 18:10:14747
[email protected]afb4bad2009-02-12 02:39:31748 // When the input data buffer is empty, the overflow fds should be too. If
749 // this is not the case, we probably have a rogue renderer which is trying
750 // to fill our descriptor table.
751 if (input_overflow_buf_.empty() && !input_overflow_fds_.empty()) {
752 // We close these descriptors in Close()
753 return false;
754 }
755
[email protected]fa95fc92008-12-08 18:10:14756 bytes_read = 0; // Get more data.
757 }
[email protected]fa95fc92008-12-08 18:10:14758}
759
[email protected]514411fc2008-12-10 22:28:11760bool Channel::ChannelImpl::ProcessOutgoingMessages() {
[email protected]fa95fc92008-12-08 18:10:14761 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
762 // no connection?
[email protected]22b42c52010-12-20 06:59:23763 if (output_queue_.empty())
[email protected]c7f91e82010-12-20 06:39:44764 return true;
[email protected]c7f91e82010-12-20 06:39:44765
[email protected]22b42c52010-12-20 06:59:23766 if (pipe_ == -1)
[email protected]fa95fc92008-12-08 18:10:14767 return false;
768
[email protected]fa95fc92008-12-08 18:10:14769 // Write out all the messages we can till the write blocks or there are no
770 // more outgoing messages.
771 while (!output_queue_.empty()) {
772 Message* msg = output_queue_.front();
773
774 size_t amt_to_write = msg->size() - message_send_bytes_written_;
[email protected]60ea6052011-04-18 20:07:08775 DCHECK_NE(0U, amt_to_write);
[email protected]baf556a2009-09-04 21:34:05776 const char* out_bytes = reinterpret_cast<const char*>(msg->data()) +
[email protected]fa95fc92008-12-08 18:10:14777 message_send_bytes_written_;
[email protected]526776c2009-02-07 00:39:26778
[email protected]157c61b2009-05-01 21:37:31779 struct msghdr msgh = {0};
780 struct iovec iov = {const_cast<char*>(out_bytes), amt_to_write};
781 msgh.msg_iov = &iov;
782 msgh.msg_iovlen = 1;
783 char buf[CMSG_SPACE(
[email protected]05094a32011-09-01 00:50:13784 sizeof(int) * FileDescriptorSet::kMaxDescriptorsPerMessage)];
[email protected]526776c2009-02-07 00:39:26785
[email protected]baf556a2009-09-04 21:34:05786 ssize_t bytes_written = 1;
787 int fd_written = -1;
788
[email protected]157c61b2009-05-01 21:37:31789 if (message_send_bytes_written_ == 0 &&
790 !msg->file_descriptor_set()->empty()) {
791 // This is the first chunk of a message which has descriptors to send
792 struct cmsghdr *cmsg;
793 const unsigned num_fds = msg->file_descriptor_set()->size();
[email protected]526776c2009-02-07 00:39:26794
[email protected]05094a32011-09-01 00:50:13795 DCHECK(num_fds <= FileDescriptorSet::kMaxDescriptorsPerMessage);
[email protected]aac449e2010-06-10 21:39:04796 if (msg->file_descriptor_set()->ContainsDirectoryDescriptor()) {
797 LOG(FATAL) << "Panic: attempting to transport directory descriptor over"
798 " IPC. Aborting to maintain sandbox isolation.";
799 // If you have hit this then something tried to send a file descriptor
800 // to a directory over an IPC channel. Since IPC channels span
801 // sandboxes this is very bad: the receiving process can use openat
802 // with ".." elements in the path in order to reach the real
803 // filesystem.
804 }
[email protected]526776c2009-02-07 00:39:26805
[email protected]157c61b2009-05-01 21:37:31806 msgh.msg_control = buf;
807 msgh.msg_controllen = CMSG_SPACE(sizeof(int) * num_fds);
808 cmsg = CMSG_FIRSTHDR(&msgh);
809 cmsg->cmsg_level = SOL_SOCKET;
810 cmsg->cmsg_type = SCM_RIGHTS;
811 cmsg->cmsg_len = CMSG_LEN(sizeof(int) * num_fds);
812 msg->file_descriptor_set()->GetDescriptors(
813 reinterpret_cast<int*>(CMSG_DATA(cmsg)));
814 msgh.msg_controllen = cmsg->cmsg_len;
[email protected]526776c2009-02-07 00:39:26815
[email protected]168ae922009-12-04 18:08:45816 // DCHECK_LE above already checks that
[email protected]05094a32011-09-01 00:50:13817 // num_fds < kMaxDescriptorsPerMessage so no danger of overflow.
[email protected]168ae922009-12-04 18:08:45818 msg->header()->num_fds = static_cast<uint16>(num_fds);
[email protected]baf556a2009-09-04 21:34:05819
[email protected]e40f5a0b2010-12-08 21:22:24820#if defined(IPC_USES_READWRITE)
[email protected]22b42c52010-12-20 06:59:23821 if (!IsHelloMessage(msg)) {
[email protected]baf556a2009-09-04 21:34:05822 // Only the Hello message sends the file descriptor with the message.
823 // Subsequently, we can send file descriptors on the dedicated
824 // fd_pipe_ which makes Seccomp sandbox operation more efficient.
825 struct iovec fd_pipe_iov = { const_cast<char *>(""), 1 };
826 msgh.msg_iov = &fd_pipe_iov;
827 fd_written = fd_pipe_;
828 bytes_written = HANDLE_EINTR(sendmsg(fd_pipe_, &msgh, MSG_DONTWAIT));
829 msgh.msg_iov = &iov;
830 msgh.msg_controllen = 0;
831 if (bytes_written > 0) {
832 msg->file_descriptor_set()->CommitAll();
833 }
834 }
[email protected]22b42c52010-12-20 06:59:23835#endif // IPC_USES_READWRITE
[email protected]157c61b2009-05-01 21:37:31836 }
837
[email protected]baf556a2009-09-04 21:34:05838 if (bytes_written == 1) {
839 fd_written = pipe_;
[email protected]e40f5a0b2010-12-08 21:22:24840#if defined(IPC_USES_READWRITE)
[email protected]1707726c2011-02-03 20:35:09841 if ((mode_ & MODE_CLIENT_FLAG) && IsHelloMessage(msg)) {
[email protected]7ee1a44c2010-07-23 14:18:59842 DCHECK_EQ(msg->file_descriptor_set()->size(), 1U);
[email protected]baf556a2009-09-04 21:34:05843 }
[email protected]22b42c52010-12-20 06:59:23844 if (!msgh.msg_controllen) {
[email protected]baf556a2009-09-04 21:34:05845 bytes_written = HANDLE_EINTR(write(pipe_, out_bytes, amt_to_write));
846 } else
[email protected]22b42c52010-12-20 06:59:23847#endif // IPC_USES_READWRITE
[email protected]baf556a2009-09-04 21:34:05848 {
849 bytes_written = HANDLE_EINTR(sendmsg(pipe_, &msgh, MSG_DONTWAIT));
850 }
851 }
[email protected]157c61b2009-05-01 21:37:31852 if (bytes_written > 0)
853 msg->file_descriptor_set()->CommitAll();
[email protected]fa95fc92008-12-08 18:10:14854
[email protected]86c3d9e2009-12-08 14:48:08855 if (bytes_written < 0 && !SocketWriteErrorIsRecoverable()) {
[email protected]cb38c0b22009-05-27 18:29:48856#if defined(OS_MACOSX)
857 // On OSX writing to a pipe with no listener returns EPERM.
858 if (errno == EPERM) {
859 Close();
860 return false;
861 }
862#endif // OS_MACOSX
[email protected]7bf54f5e2009-10-23 01:48:21863 if (errno == EPIPE) {
864 Close();
865 return false;
866 }
[email protected]780ae942009-12-03 13:35:46867 PLOG(ERROR) << "pipe error on "
868 << fd_written
[email protected]9fbc2f2f2011-02-11 08:43:52869 << " Currently writing message of size: "
[email protected]86c3d9e2009-12-08 14:48:08870 << msg->size();
[email protected]fa95fc92008-12-08 18:10:14871 return false;
872 }
873
874 if (static_cast<size_t>(bytes_written) != amt_to_write) {
[email protected]3d1b6662009-01-29 17:03:11875 if (bytes_written > 0) {
876 // If write() fails with EAGAIN then bytes_written will be -1.
877 message_send_bytes_written_ += bytes_written;
878 }
[email protected]fa95fc92008-12-08 18:10:14879
880 // Tell libevent to call us back once things are unblocked.
[email protected]e45e6c02008-12-15 22:02:17881 is_blocked_on_write_ = true;
882 MessageLoopForIO::current()->WatchFileDescriptor(
883 pipe_,
884 false, // One shot
885 MessageLoopForIO::WATCH_WRITE,
886 &write_watcher_,
887 this);
[email protected]3d1b6662009-01-29 17:03:11888 return true;
[email protected]fa95fc92008-12-08 18:10:14889 } else {
890 message_send_bytes_written_ = 0;
891
892 // Message sent OK!
[email protected]2a9d601b2010-10-19 23:50:00893 DVLOG(2) << "sent message @" << msg << " on channel @" << this
[email protected]5484722e2010-12-09 01:13:12894 << " with type " << msg->type() << " on fd " << pipe_;
[email protected]baf556a2009-09-04 21:34:05895 delete output_queue_.front();
[email protected]fa95fc92008-12-08 18:10:14896 output_queue_.pop();
[email protected]fa95fc92008-12-08 18:10:14897 }
898 }
899 return true;
900}
901
[email protected]514411fc2008-12-10 22:28:11902bool Channel::ChannelImpl::Send(Message* message) {
[email protected]2a9d601b2010-10-19 23:50:00903 DVLOG(2) << "sending message @" << message << " on channel @" << this
904 << " with type " << message->type()
905 << " (" << output_queue_.size() << " in queue)";
[email protected]fa95fc92008-12-08 18:10:14906
[email protected]4c2c1db2009-03-20 20:56:55907#ifdef IPC_MESSAGE_LOG_ENABLED
[email protected]8e8bb6d2010-12-13 08:18:55908 Logging::GetInstance()->OnSendMessage(message, "");
[email protected]22b42c52010-12-20 06:59:23909#endif // IPC_MESSAGE_LOG_ENABLED
[email protected]fa95fc92008-12-08 18:10:14910
911 output_queue_.push(message);
[email protected]22b42c52010-12-20 06:59:23912 if (!is_blocked_on_write_ && !waiting_connect_) {
913 return ProcessOutgoingMessages();
[email protected]fa95fc92008-12-08 18:10:14914 }
915
916 return true;
917}
918
[email protected]cc8f1462009-06-12 17:36:55919int Channel::ChannelImpl::GetClientFileDescriptor() const {
920 return client_pipe_;
[email protected]df3c1ca12008-12-19 21:37:01921}
922
[email protected]22b42c52010-12-20 06:59:23923bool Channel::ChannelImpl::AcceptsConnections() const {
924 return server_listen_pipe_ != -1;
925}
[email protected]9a44a4db62010-12-20 06:19:07926
[email protected]22b42c52010-12-20 06:59:23927bool Channel::ChannelImpl::HasAcceptedConnection() const {
928 return AcceptsConnections() && pipe_ != -1;
929}
[email protected]9a44a4db62010-12-20 06:19:07930
[email protected]8ec3fbe2011-04-06 12:01:44931bool Channel::ChannelImpl::GetClientEuid(uid_t* client_euid) const {
932 DCHECK(HasAcceptedConnection());
933#if defined(OS_MACOSX)
934 uid_t peer_euid;
935 gid_t peer_gid;
936 if (getpeereid(pipe_, &peer_euid, &peer_gid) != 0) {
937 PLOG(ERROR) << "getpeereid " << pipe_;
938 return false;
939 }
940 *client_euid = peer_euid;
941 return true;
[email protected]94f8c952011-06-25 04:54:41942#elif defined(OS_SOLARIS)
943 return false;
[email protected]8ec3fbe2011-04-06 12:01:44944#else
945 struct ucred cred;
946 socklen_t cred_len = sizeof(cred);
947 if (getsockopt(pipe_, SOL_SOCKET, SO_PEERCRED, &cred, &cred_len) != 0) {
948 PLOG(ERROR) << "getsockopt " << pipe_;
949 return false;
950 }
951 if (cred_len < sizeof(cred)) {
952 NOTREACHED() << "Truncated ucred from SO_PEERCRED?";
953 return false;
954 }
955 *client_euid = cred.uid;
956 return true;
957#endif
958}
959
[email protected]22b42c52010-12-20 06:59:23960void Channel::ChannelImpl::ResetToAcceptingConnectionState() {
961 // Unregister libevent for the unix domain socket and close it.
962 read_watcher_.StopWatchingFileDescriptor();
963 write_watcher_.StopWatchingFileDescriptor();
964 if (pipe_ != -1) {
965 if (HANDLE_EINTR(close(pipe_)) < 0)
966 PLOG(ERROR) << "close pipe_ " << pipe_name_;
967 pipe_ = -1;
968 }
969#if defined(IPC_USES_READWRITE)
970 if (fd_pipe_ != -1) {
971 if (HANDLE_EINTR(close(fd_pipe_)) < 0)
972 PLOG(ERROR) << "close fd_pipe_ " << pipe_name_;
973 fd_pipe_ = -1;
974 }
975 if (remote_fd_pipe_ != -1) {
976 if (HANDLE_EINTR(close(remote_fd_pipe_)) < 0)
977 PLOG(ERROR) << "close remote_fd_pipe_ " << pipe_name_;
978 remote_fd_pipe_ = -1;
979 }
980#endif // IPC_USES_READWRITE
[email protected]c7f91e82010-12-20 06:39:44981
[email protected]22b42c52010-12-20 06:59:23982 while (!output_queue_.empty()) {
983 Message* m = output_queue_.front();
984 output_queue_.pop();
985 delete m;
[email protected]c7f91e82010-12-20 06:39:44986 }
987
[email protected]22b42c52010-12-20 06:59:23988 // Close any outstanding, received file descriptors.
989 for (std::vector<int>::iterator
990 i = input_overflow_fds_.begin(); i != input_overflow_fds_.end(); ++i) {
991 if (HANDLE_EINTR(close(*i)) < 0)
992 PLOG(ERROR) << "close";
993 }
994 input_overflow_fds_.clear();
995}
996
[email protected]313c00e52011-08-09 06:46:06997// static
998bool Channel::ChannelImpl::IsNamedServerInitialized(
999 const std::string& channel_id) {
1000 return file_util::PathExists(FilePath(channel_id));
1001}
1002
[email protected]e1d67a882011-08-31 21:11:041003#if defined(OS_LINUX)
1004// static
1005void Channel::ChannelImpl::SetGlobalPid(int pid) {
1006 global_pid_ = pid;
1007}
1008#endif // OS_LINUX
1009
[email protected]22b42c52010-12-20 06:59:231010// Called by libevent when we can read from the pipe without blocking.
1011void Channel::ChannelImpl::OnFileCanReadWithoutBlocking(int fd) {
1012 bool send_server_hello_msg = false;
1013 if (fd == server_listen_pipe_) {
1014 int new_pipe = 0;
1015 if (!ServerAcceptConnection(server_listen_pipe_, &new_pipe)) {
[email protected]c7f91e82010-12-20 06:39:441016 Close();
[email protected]22b42c52010-12-20 06:59:231017 listener_->OnChannelListenError();
1018 }
1019
1020 if (pipe_ != -1) {
1021 // We already have a connection. We only handle one at a time.
1022 // close our new descriptor.
1023 if (HANDLE_EINTR(shutdown(new_pipe, SHUT_RDWR)) < 0)
1024 PLOG(ERROR) << "shutdown " << pipe_name_;
1025 if (HANDLE_EINTR(close(new_pipe)) < 0)
1026 PLOG(ERROR) << "close " << pipe_name_;
1027 listener_->OnChannelDenied();
[email protected]c7f91e82010-12-20 06:39:441028 return;
[email protected]9a44a4db62010-12-20 06:19:071029 }
[email protected]22b42c52010-12-20 06:59:231030 pipe_ = new_pipe;
1031
[email protected]8ec3fbe2011-04-06 12:01:441032 if ((mode_ & MODE_OPEN_ACCESS_FLAG) == 0) {
1033 // Verify that the IPC channel peer is running as the same user.
1034 uid_t client_euid;
1035 if (!GetClientEuid(&client_euid)) {
1036 LOG(ERROR) << "Unable to query client euid";
1037 ResetToAcceptingConnectionState();
1038 return;
1039 }
1040 if (client_euid != geteuid()) {
1041 LOG(WARNING) << "Client euid is not authorised";
1042 ResetToAcceptingConnectionState();
1043 return;
1044 }
1045 }
1046
[email protected]22b42c52010-12-20 06:59:231047 if (!AcceptConnection()) {
1048 NOTREACHED() << "AcceptConnection should not fail on server";
1049 }
1050 send_server_hello_msg = true;
1051 waiting_connect_ = false;
1052 } else if (fd == pipe_) {
[email protected]1707726c2011-02-03 20:35:091053 if (waiting_connect_ && (mode_ & MODE_SERVER_FLAG)) {
[email protected]22b42c52010-12-20 06:59:231054 send_server_hello_msg = true;
1055 waiting_connect_ = false;
1056 }
1057 if (!ProcessIncomingMessages()) {
[email protected]887250a2011-02-28 20:30:471058 // ClosePipeOnError may delete this object, so we mustn't call
1059 // ProcessOutgoingMessages.
1060 send_server_hello_msg = false;
[email protected]22b42c52010-12-20 06:59:231061 ClosePipeOnError();
1062 }
1063 } else {
1064 NOTREACHED() << "Unknown pipe " << fd;
[email protected]fa95fc92008-12-08 18:10:141065 }
1066
1067 // If we're a server and handshaking, then we want to make sure that we
1068 // only send our handshake message after we've processed the client's.
1069 // This gives us a chance to kill the client if the incoming handshake
1070 // is invalid.
1071 if (send_server_hello_msg) {
1072 ProcessOutgoingMessages();
1073 }
1074}
1075
1076// Called by libevent when we can write to the pipe without blocking.
[email protected]e45e6c02008-12-15 22:02:171077void Channel::ChannelImpl::OnFileCanWriteWithoutBlocking(int fd) {
[email protected]60ea6052011-04-18 20:07:081078 DCHECK_EQ(pipe_, fd);
[email protected]22b42c52010-12-20 06:59:231079 is_blocked_on_write_ = false;
[email protected]fa95fc92008-12-08 18:10:141080 if (!ProcessOutgoingMessages()) {
[email protected]22b42c52010-12-20 06:59:231081 ClosePipeOnError();
[email protected]9a44a4db62010-12-20 06:19:071082 }
1083}
1084
[email protected]22b42c52010-12-20 06:59:231085bool Channel::ChannelImpl::AcceptConnection() {
1086 MessageLoopForIO::current()->WatchFileDescriptor(pipe_,
1087 true,
1088 MessageLoopForIO::WATCH_READ,
1089 &read_watcher_,
1090 this);
1091 QueueHelloMessage();
1092
[email protected]1707726c2011-02-03 20:35:091093 if (mode_ & MODE_CLIENT_FLAG) {
[email protected]22b42c52010-12-20 06:59:231094 // If we are a client we want to send a hello message out immediately.
1095 // In server mode we will send a hello message when we receive one from a
1096 // client.
1097 waiting_connect_ = false;
1098 return ProcessOutgoingMessages();
[email protected]1707726c2011-02-03 20:35:091099 } else if (mode_ & MODE_SERVER_FLAG) {
[email protected]22b42c52010-12-20 06:59:231100 waiting_connect_ = true;
1101 return true;
[email protected]1707726c2011-02-03 20:35:091102 } else {
1103 NOTREACHED();
1104 return false;
[email protected]22b42c52010-12-20 06:59:231105 }
1106}
1107
1108void Channel::ChannelImpl::ClosePipeOnError() {
1109 if (HasAcceptedConnection()) {
1110 ResetToAcceptingConnectionState();
1111 listener_->OnChannelError();
1112 } else {
1113 Close();
1114 if (AcceptsConnections()) {
1115 listener_->OnChannelListenError();
1116 } else {
1117 listener_->OnChannelError();
1118 }
1119 }
1120}
1121
[email protected]e1d67a882011-08-31 21:11:041122int Channel::ChannelImpl::GetHelloMessageProcId() {
1123 int pid = base::GetCurrentProcId();
1124#if defined(OS_LINUX)
1125 // Our process may be in a sandbox with a separate PID namespace.
1126 if (global_pid_) {
1127 pid = global_pid_;
1128 }
1129#endif
1130 return pid;
1131}
1132
[email protected]22b42c52010-12-20 06:59:231133void Channel::ChannelImpl::QueueHelloMessage() {
1134 // Create the Hello message
1135 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
1136 HELLO_MESSAGE_TYPE,
1137 IPC::Message::PRIORITY_NORMAL));
[email protected]e1d67a882011-08-31 21:11:041138 if (!msg->WriteInt(GetHelloMessageProcId())) {
[email protected]22b42c52010-12-20 06:59:231139 NOTREACHED() << "Unable to pickle hello message proc id";
1140 }
1141#if defined(IPC_USES_READWRITE)
1142 scoped_ptr<Message> hello;
1143 if (remote_fd_pipe_ != -1) {
1144 if (!msg->WriteFileDescriptor(base::FileDescriptor(remote_fd_pipe_,
1145 false))) {
1146 NOTREACHED() << "Unable to pickle hello message file descriptors";
1147 }
1148 DCHECK_EQ(msg->file_descriptor_set()->size(), 1U);
1149 }
1150#endif // IPC_USES_READWRITE
1151 output_queue_.push(msg.release());
1152}
1153
1154bool Channel::ChannelImpl::IsHelloMessage(const Message* m) const {
1155 return m->routing_id() == MSG_ROUTING_NONE && m->type() == HELLO_MESSAGE_TYPE;
1156}
1157
[email protected]514411fc2008-12-10 22:28:111158void Channel::ChannelImpl::Close() {
[email protected]fa95fc92008-12-08 18:10:141159 // Close can be called multiple time, so we need to make sure we're
1160 // idempotent.
1161
[email protected]22b42c52010-12-20 06:59:231162 ResetToAcceptingConnectionState();
[email protected]fa95fc92008-12-08 18:10:141163
[email protected]22b42c52010-12-20 06:59:231164 if (must_unlink_) {
1165 unlink(pipe_name_.c_str());
1166 must_unlink_ = false;
1167 }
[email protected]fa95fc92008-12-08 18:10:141168 if (server_listen_pipe_ != -1) {
[email protected]70eb6572010-06-23 00:37:461169 if (HANDLE_EINTR(close(server_listen_pipe_)) < 0)
[email protected]5484722e2010-12-09 01:13:121170 PLOG(ERROR) << "close " << server_listen_pipe_;
[email protected]fa95fc92008-12-08 18:10:141171 server_listen_pipe_ = -1;
[email protected]22b42c52010-12-20 06:59:231172 // Unregister libevent for the listening socket and close it.
1173 server_listen_connection_watcher_.StopWatchingFileDescriptor();
[email protected]fa95fc92008-12-08 18:10:141174 }
1175
[email protected]df3c1ca12008-12-19 21:37:011176 if (client_pipe_ != -1) {
[email protected]864b5582010-12-04 23:00:101177 PipeMap::GetInstance()->RemoveAndClose(pipe_name_);
[email protected]df3c1ca12008-12-19 21:37:011178 client_pipe_ = -1;
1179 }
[email protected]fa95fc92008-12-08 18:10:141180}
1181
[email protected]514411fc2008-12-10 22:28:111182//------------------------------------------------------------------------------
1183// Channel's methods simply call through to ChannelImpl.
[email protected]42ce94e2010-12-08 19:28:091184Channel::Channel(const IPC::ChannelHandle& channel_handle, Mode mode,
[email protected]514411fc2008-12-10 22:28:111185 Listener* listener)
[email protected]42ce94e2010-12-08 19:28:091186 : channel_impl_(new ChannelImpl(channel_handle, mode, listener)) {
[email protected]514411fc2008-12-10 22:28:111187}
1188
1189Channel::~Channel() {
1190 delete channel_impl_;
1191}
1192
1193bool Channel::Connect() {
1194 return channel_impl_->Connect();
1195}
1196
1197void Channel::Close() {
1198 channel_impl_->Close();
1199}
1200
1201void Channel::set_listener(Listener* listener) {
1202 channel_impl_->set_listener(listener);
1203}
1204
1205bool Channel::Send(Message* message) {
1206 return channel_impl_->Send(message);
1207}
1208
[email protected]cc8f1462009-06-12 17:36:551209int Channel::GetClientFileDescriptor() const {
1210 return channel_impl_->GetClientFileDescriptor();
[email protected]df3c1ca12008-12-19 21:37:011211}
1212
[email protected]22b42c52010-12-20 06:59:231213bool Channel::AcceptsConnections() const {
1214 return channel_impl_->AcceptsConnections();
1215}
1216
1217bool Channel::HasAcceptedConnection() const {
1218 return channel_impl_->HasAcceptedConnection();
1219}
1220
[email protected]8ec3fbe2011-04-06 12:01:441221bool Channel::GetClientEuid(uid_t* client_euid) const {
1222 return channel_impl_->GetClientEuid(client_euid);
1223}
1224
[email protected]22b42c52010-12-20 06:59:231225void Channel::ResetToAcceptingConnectionState() {
1226 channel_impl_->ResetToAcceptingConnectionState();
1227}
1228
[email protected]313c00e52011-08-09 06:46:061229// static
1230bool Channel::IsNamedServerInitialized(const std::string& channel_id) {
1231 return ChannelImpl::IsNamedServerInitialized(channel_id);
1232}
1233
[email protected]e1d67a882011-08-31 21:11:041234#if defined(OS_LINUX)
1235// static
1236void Channel::SetGlobalPid(int pid) {
1237 ChannelImpl::SetGlobalPid(pid);
1238}
1239#endif // OS_LINUX
1240
[email protected]d4651ff2008-12-02 16:51:581241} // namespace IPC