blob: 5ff25aa73a55476a8624c68edbbd7e29b46fa4f6 [file] [log] [blame]
[email protected]2a9d601b2010-10-19 23:50:001// Copyright (c) 2010 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]e8fce882009-01-20 22:02:5823#include "base/lock.h"
[email protected]fa95fc92008-12-08 18:10:1424#include "base/logging.h"
25#include "base/process_util.h"
26#include "base/scoped_ptr.h"
[email protected]e8fce882009-01-20 22:02:5827#include "base/singleton.h"
[email protected]946d1b22009-07-22 23:57:2128#include "base/string_util.h"
29#include "ipc/ipc_descriptors.h"
30#include "ipc/ipc_switches.h"
31#include "ipc/file_descriptor_set_posix.h"
32#include "ipc/ipc_logging.h"
33#include "ipc/ipc_message_utils.h"
[email protected]d4651ff2008-12-02 16:51:5834
35namespace IPC {
36
[email protected]5f594c02009-05-01 22:37:5937// IPC channels on Windows use named pipes (CreateNamedPipe()) with
[email protected]22b42c52010-12-20 06:59:2338// channel ids as the pipe names. Channels on POSIX use sockets as
39// pipes These don't quite line up.
[email protected]5f594c02009-05-01 22:37:5940//
[email protected]22b42c52010-12-20 06:59:2341// When creating a child subprocess we use a socket pair and the parent side of
42// the fork arranges it such that the initial control channel ends up on the
[email protected]cc8f1462009-06-12 17:36:5543// magic file descriptor kPrimaryIPCChannel in the child. Future
[email protected]5f594c02009-05-01 22:37:5944// connections (file descriptors) can then be passed via that
45// connection via sendmsg().
[email protected]22b42c52010-12-20 06:59:2346//
47// A POSIX IPC channel can also be set up as a server for a bound UNIX domain
48// socket, and will handle multiple connect and disconnect sequences. Currently
49// it is limited to one connection at a time.
[email protected]5f594c02009-05-01 22:37:5950
[email protected]fa95fc92008-12-08 18:10:1451//------------------------------------------------------------------------------
[email protected]fa95fc92008-12-08 18:10:1452namespace {
53
[email protected]5f594c02009-05-01 22:37:5954// The PipeMap class works around this quirk related to unit tests:
[email protected]e8fce882009-01-20 22:02:5855//
[email protected]5f594c02009-05-01 22:37:5956// When running as a server, we install the client socket in a
[email protected]cc8f1462009-06-12 17:36:5557// specific file descriptor number (@kPrimaryIPCChannel). However, we
[email protected]5f594c02009-05-01 22:37:5958// also have to support the case where we are running unittests in the
59// same process. (We do not support forking without execing.)
[email protected]e8fce882009-01-20 22:02:5860//
61// Case 1: normal running
62// The IPC server object will install a mapping in PipeMap from the
63// name which it was given to the client pipe. When forking the client, the
64// GetClientFileDescriptorMapping will ensure that the socket is installed in
[email protected]cc8f1462009-06-12 17:36:5565// the magic slot (@kPrimaryIPCChannel). The client will search for the
[email protected]e8fce882009-01-20 22:02:5866// mapping, but it won't find any since we are in a new process. Thus the
67// magic fd number is returned. Once the client connects, the server will
[email protected]5f594c02009-05-01 22:37:5968// close its copy of the client socket and remove the mapping.
[email protected]e8fce882009-01-20 22:02:5869//
70// Case 2: unittests - client and server in the same process
71// The IPC server will install a mapping as before. The client will search
72// for a mapping and find out. It duplicates the file descriptor and
73// connects. Once the client connects, the server will close the original
74// copy of the client socket and remove the mapping. Thus, when the client
75// object closes, it will close the only remaining copy of the client socket
76// in the fd table and the server will see EOF on its side.
77//
78// TODO(port): a client process cannot connect to multiple IPC channels with
79// this scheme.
80
81class PipeMap {
82 public:
[email protected]864b5582010-12-04 23:00:1083 static PipeMap* GetInstance() {
84 return Singleton<PipeMap>::get();
85 }
86
[email protected]42ce94e2010-12-08 19:28:0987 ~PipeMap() {
88 // Shouldn't have left over pipes.
89 DCHECK(map_.size() == 0);
90 }
91
[email protected]e8fce882009-01-20 22:02:5892 // Lookup a given channel id. Return -1 if not found.
93 int Lookup(const std::string& channel_id) {
94 AutoLock locked(lock_);
95
96 ChannelToFDMap::const_iterator i = map_.find(channel_id);
97 if (i == map_.end())
98 return -1;
99 return i->second;
100 }
101
102 // Remove the mapping for the given channel id. No error is signaled if the
103 // channel_id doesn't exist
[email protected]f0ef2da2009-07-08 01:26:34104 void RemoveAndClose(const std::string& channel_id) {
[email protected]e8fce882009-01-20 22:02:58105 AutoLock locked(lock_);
106
107 ChannelToFDMap::iterator i = map_.find(channel_id);
[email protected]f0ef2da2009-07-08 01:26:34108 if (i != map_.end()) {
[email protected]70eb6572010-06-23 00:37:46109 if (HANDLE_EINTR(close(i->second)) < 0)
[email protected]5484722e2010-12-09 01:13:12110 PLOG(ERROR) << "close " << channel_id;
[email protected]e8fce882009-01-20 22:02:58111 map_.erase(i);
[email protected]f0ef2da2009-07-08 01:26:34112 }
[email protected]e8fce882009-01-20 22:02:58113 }
114
115 // Insert a mapping from @channel_id to @fd. It's a fatal error to insert a
116 // mapping if one already exists for the given channel_id
117 void Insert(const std::string& channel_id, int fd) {
118 AutoLock locked(lock_);
119 DCHECK(fd != -1);
120
121 ChannelToFDMap::const_iterator i = map_.find(channel_id);
[email protected]d2e884d2009-06-22 20:37:52122 CHECK(i == map_.end()) << "Creating second IPC server (fd " << fd << ") "
123 << "for '" << channel_id << "' while first "
124 << "(fd " << i->second << ") still exists";
[email protected]e8fce882009-01-20 22:02:58125 map_[channel_id] = fd;
126 }
127
128 private:
129 Lock lock_;
130 typedef std::map<std::string, int> ChannelToFDMap;
131 ChannelToFDMap map_;
[email protected]864b5582010-12-04 23:00:10132
133 friend struct DefaultSingletonTraits<PipeMap>;
[email protected]e8fce882009-01-20 22:02:58134};
135
[email protected]df3c1ca12008-12-19 21:37:01136//------------------------------------------------------------------------------
[email protected]22b42c52010-12-20 06:59:23137// Verify that kMaxPipeNameLength is a decent size.
[email protected]cffa687f2010-12-08 20:33:46138COMPILE_ASSERT(sizeof(((sockaddr_un*)0)->sun_path) >= kMaxPipeNameLength,
139 BAD_SUN_PATH_LENGTH);
[email protected]fa95fc92008-12-08 18:10:14140
[email protected]22b42c52010-12-20 06:59:23141// Creates a unix domain socket bound to the specified name that is listening
142// for connections.
143bool CreateServerUnixDomainSocket(const std::string& pipe_name,
144 int* server_listen_fd) {
[email protected]fa95fc92008-12-08 18:10:14145 DCHECK(server_listen_fd);
[email protected]02d66512009-03-17 01:48:35146 DCHECK_GT(pipe_name.length(), 0u);
147 DCHECK_LT(pipe_name.length(), kMaxPipeNameLength);
[email protected]fa95fc92008-12-08 18:10:14148
[email protected]02d66512009-03-17 01:48:35149 if (pipe_name.length() == 0 || pipe_name.length() >= kMaxPipeNameLength) {
[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]22b42c52010-12-20 06:59:23170 // Make sure the path we need exists.
171 FilePath path(pipe_name);
172 FilePath dir_path = path.DirName();
173 if (!file_util::CreateDirectory(dir_path)) {
174 return false;
175 }
176
[email protected]fa95fc92008-12-08 18:10:14177 // Create unix_addr structure
178 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]42ce94e2010-12-08 19:28:09296Channel::ChannelImpl::ChannelImpl(const IPC::ChannelHandle& channel_handle,
297 Mode mode, Listener* listener)
[email protected]fa95fc92008-12-08 18:10:14298 : mode_(mode),
[email protected]e45e6c02008-12-15 22:02:17299 is_blocked_on_write_(false),
[email protected]22b42c52010-12-20 06:59:23300 waiting_connect_(true),
[email protected]e45e6c02008-12-15 22:02:17301 message_send_bytes_written_(0),
302 server_listen_pipe_(-1),
303 pipe_(-1),
[email protected]df3c1ca12008-12-19 21:37:01304 client_pipe_(-1),
[email protected]e40f5a0b2010-12-08 21:22:24305#if defined(IPC_USES_READWRITE)
[email protected]baf556a2009-09-04 21:34:05306 fd_pipe_(-1),
307 remote_fd_pipe_(-1),
[email protected]22b42c52010-12-20 06:59:23308#endif // IPC_USES_READWRITE
309 pipe_name_(channel_handle.name),
[email protected]e45e6c02008-12-15 22:02:17310 listener_(listener),
[email protected]22b42c52010-12-20 06:59:23311 must_unlink_(false),
[email protected]e45e6c02008-12-15 22:02:17312 factory_(this) {
[email protected]22b42c52010-12-20 06:59:23313 // Check to see if we want to implement using domain sockets.
314 bool uses_domain_socket = false;
315 bool listening_socket = false;
316 if (mode_ == MODE_NAMED_SERVER) {
317 uses_domain_socket = true;
318 listening_socket = true;
319 mode_ = MODE_SERVER;
320 } else if (mode_ == MODE_NAMED_CLIENT) {
321 uses_domain_socket = true;
322 mode_ = MODE_CLIENT;
323 }
324 if (!CreatePipe(channel_handle, uses_domain_socket, listening_socket)) {
325 // The pipe may have been closed already.
326 const char *modestr = (mode_ == MODE_SERVER
327 || mode_ == MODE_NAMED_SERVER) ? "server" : "client";
[email protected]fa95fc92008-12-08 18:10:14328 // The pipe may have been closed already.
[email protected]42ce94e2010-12-08 19:28:09329 LOG(WARNING) << "Unable to create pipe named \"" << channel_handle.name
[email protected]22b42c52010-12-20 06:59:23330 << "\" in " << modestr << " mode";
[email protected]fa95fc92008-12-08 18:10:14331 }
[email protected]d4651ff2008-12-02 16:51:58332}
333
[email protected]601858c02010-09-01 17:08:20334Channel::ChannelImpl::~ChannelImpl() {
335 Close();
336}
337
[email protected]d2e884d2009-06-22 20:37:52338bool SocketPair(int* fd1, int* fd2) {
339 int pipe_fds[2];
340 if (socketpair(AF_UNIX, SOCK_STREAM, 0, pipe_fds) != 0) {
[email protected]57b765672009-10-13 18:27:40341 PLOG(ERROR) << "socketpair()";
[email protected]d2e884d2009-06-22 20:37:52342 return false;
343 }
344
345 // Set both ends to be non-blocking.
346 if (fcntl(pipe_fds[0], F_SETFL, O_NONBLOCK) == -1 ||
347 fcntl(pipe_fds[1], F_SETFL, O_NONBLOCK) == -1) {
[email protected]57b765672009-10-13 18:27:40348 PLOG(ERROR) << "fcntl(O_NONBLOCK)";
[email protected]70eb6572010-06-23 00:37:46349 if (HANDLE_EINTR(close(pipe_fds[0])) < 0)
350 PLOG(ERROR) << "close";
351 if (HANDLE_EINTR(close(pipe_fds[1])) < 0)
352 PLOG(ERROR) << "close";
[email protected]d2e884d2009-06-22 20:37:52353 return false;
354 }
355
356 *fd1 = pipe_fds[0];
357 *fd2 = pipe_fds[1];
358
359 return true;
360}
361
[email protected]22b42c52010-12-20 06:59:23362bool Channel::ChannelImpl::CreatePipe(const IPC::ChannelHandle& channel_handle,
363 bool uses_domain_sockets,
364 bool listening_socket) {
[email protected]fa95fc92008-12-08 18:10:14365 DCHECK(server_listen_pipe_ == -1 && pipe_ == -1);
[email protected]22b42c52010-12-20 06:59:23366
367 // Four possible cases:
368 // 1) It's a channel wrapping a pipe that is given to us.
369 // 2) It's for a named channel, so we create it.
370 // 3) It's for a client that we implement ourself. This is used
371 // in unittesting.
372 // 4) It's the initial IPC channel:
373 // 4a) Client side: Pull the pipe out of the GlobalDescriptors set.
374 // 4b) Server side: create the pipe.
375
376 if (channel_handle.socket.fd != -1) {
377 // Case 1 from comment above.
378 pipe_ = channel_handle.socket.fd;
379#if defined(IPC_USES_READWRITE)
380 // Test the socket passed into us to make sure it is nonblocking.
381 // We don't want to call read/write on a blocking socket.
382 int value = fcntl(pipe_, F_GETFL);
383 if (value == -1) {
384 PLOG(ERROR) << "fcntl(F_GETFL) " << pipe_name_;
385 return false;
386 }
387 if (!(value & O_NONBLOCK)) {
388 LOG(ERROR) << "Socket " << pipe_name_ << " must be O_NONBLOCK";
389 return false;
390 }
391#endif // IPC_USES_READWRITE
392 } else if (uses_domain_sockets) {
393 // Case 2 from comment above.
394 must_unlink_ = true;
395 if (mode_ == MODE_SERVER) {
396 if (!CreateServerUnixDomainSocket(pipe_name_, &pipe_)) {
[email protected]df3c1ca12008-12-19 21:37:01397 return false;
398 }
[email protected]22b42c52010-12-20 06:59:23399 } else if (mode_ == MODE_CLIENT) {
400 if (!CreateClientUnixDomainSocket(pipe_name_, &pipe_)) {
[email protected]df3c1ca12008-12-19 21:37:01401 return false;
402 }
[email protected]fa95fc92008-12-08 18:10:14403 }
404 } else {
[email protected]22b42c52010-12-20 06:59:23405 pipe_ = PipeMap::GetInstance()->Lookup(pipe_name_);
406 if (mode_ == MODE_CLIENT) {
407 if (pipe_ != -1) {
408 // Case 3 from comment above.
409 // We only allow one connection.
410 pipe_ = HANDLE_EINTR(dup(pipe_));
411 PipeMap::GetInstance()->RemoveAndClose(pipe_name_);
[email protected]d2e884d2009-06-22 20:37:52412 } else {
[email protected]22b42c52010-12-20 06:59:23413 // Case 4a from comment above.
[email protected]554a8852009-11-30 22:14:37414 // Guard against inappropriate reuse of the initial IPC channel. If
415 // an IPC channel closes and someone attempts to reuse it by name, the
416 // initial channel must not be recycled here. http://crbug.com/26754.
417 static bool used_initial_channel = false;
418 if (used_initial_channel) {
[email protected]9f816f72010-03-16 20:31:10419 LOG(FATAL) << "Denying attempt to reuse initial IPC channel for "
420 << pipe_name_;
[email protected]554a8852009-11-30 22:14:37421 return false;
422 }
423 used_initial_channel = true;
424
[email protected]9b85081af2010-12-07 21:26:47425 pipe_ = base::GlobalDescriptors::GetInstance()->Get(kPrimaryIPCChannel);
[email protected]df3c1ca12008-12-19 21:37:01426 }
[email protected]22b42c52010-12-20 06:59:23427 } else if (mode_ == MODE_SERVER) {
428 // Case 4b from comment above.
429 if (pipe_ != -1) {
430 LOG(ERROR) << "Server already exists for " << pipe_name_;
[email protected]baf556a2009-09-04 21:34:05431 return false;
432 }
[email protected]22b42c52010-12-20 06:59:23433 if (!SocketPair(&pipe_, &client_pipe_))
434 return false;
435 PipeMap::GetInstance()->Insert(pipe_name_, client_pipe_);
436 } else {
437 LOG(FATAL) << "Unknown mode " << mode_;
438 return false;
[email protected]baf556a2009-09-04 21:34:05439 }
440 }
[email protected]22b42c52010-12-20 06:59:23441
442 if (mode_ == MODE_SERVER) {
443 if (listening_socket) {
444 server_listen_pipe_ = pipe_;
445 pipe_ = -1;
446 }
[email protected]fa95fc92008-12-08 18:10:14447 }
448
[email protected]22b42c52010-12-20 06:59:23449#if defined(IPC_USES_READWRITE)
450 // Create a dedicated socketpair() for exchanging file descriptors.
451 // See comments for IPC_USES_READWRITE for details.
452 if (mode_ == MODE_CLIENT) {
453 if (!SocketPair(&fd_pipe_, &remote_fd_pipe_)) {
454 return false;
455 }
456 }
457#endif // IPC_USES_READWRITE
458
[email protected]fa95fc92008-12-08 18:10:14459 return true;
[email protected]d4651ff2008-12-02 16:51:58460}
461
[email protected]514411fc2008-12-10 22:28:11462bool Channel::ChannelImpl::Connect() {
[email protected]22b42c52010-12-20 06:59:23463 if (server_listen_pipe_ == -1 && pipe_ == -1) {
464 NOTREACHED() << "Must call create on a channel before calling connect";
465 return false;
466 }
467
468 bool did_connect = true;
469 if (server_listen_pipe_ != -1) {
470 // Watch the pipe for connections, and turn any connections into
471 // active sockets.
[email protected]e45e6c02008-12-15 22:02:17472 MessageLoopForIO::current()->WatchFileDescriptor(
473 server_listen_pipe_,
474 true,
475 MessageLoopForIO::WATCH_READ,
476 &server_listen_connection_watcher_,
477 this);
[email protected]fa95fc92008-12-08 18:10:14478 } else {
[email protected]22b42c52010-12-20 06:59:23479 did_connect = AcceptConnection();
[email protected]fa95fc92008-12-08 18:10:14480 }
[email protected]22b42c52010-12-20 06:59:23481 return did_connect;
[email protected]d4651ff2008-12-02 16:51:58482}
[email protected]fa95fc92008-12-08 18:10:14483
[email protected]514411fc2008-12-10 22:28:11484bool Channel::ChannelImpl::ProcessIncomingMessages() {
[email protected]fa95fc92008-12-08 18:10:14485 ssize_t bytes_read = 0;
486
[email protected]526776c2009-02-07 00:39:26487 struct msghdr msg = {0};
488 struct iovec iov = {input_buf_, Channel::kReadBufferSize};
489
[email protected]526776c2009-02-07 00:39:26490 msg.msg_iovlen = 1;
491 msg.msg_control = input_cmsg_buf_;
[email protected]526776c2009-02-07 00:39:26492
[email protected]fa95fc92008-12-08 18:10:14493 for (;;) {
[email protected]baf556a2009-09-04 21:34:05494 msg.msg_iov = &iov;
[email protected]cef7c522009-02-10 08:15:02495
[email protected]fa95fc92008-12-08 18:10:14496 if (bytes_read == 0) {
497 if (pipe_ == -1)
498 return false;
499
500 // Read from pipe.
[email protected]526776c2009-02-07 00:39:26501 // recvmsg() returns 0 if the connection has closed or EAGAIN if no data
502 // is waiting on the pipe.
[email protected]e40f5a0b2010-12-08 21:22:24503#if defined(IPC_USES_READWRITE)
[email protected]baf556a2009-09-04 21:34:05504 if (fd_pipe_ >= 0) {
505 bytes_read = HANDLE_EINTR(read(pipe_, input_buf_,
506 Channel::kReadBufferSize));
507 msg.msg_controllen = 0;
508 } else
[email protected]22b42c52010-12-20 06:59:23509#endif // IPC_USES_READWRITE
[email protected]baf556a2009-09-04 21:34:05510 {
511 msg.msg_controllen = sizeof(input_cmsg_buf_);
512 bytes_read = HANDLE_EINTR(recvmsg(pipe_, &msg, MSG_DONTWAIT));
513 }
[email protected]fa95fc92008-12-08 18:10:14514 if (bytes_read < 0) {
515 if (errno == EAGAIN) {
516 return true;
[email protected]7f6f06232009-05-22 21:15:39517#if defined(OS_MACOSX)
518 } else if (errno == EPERM) {
519 // On OSX, reading from a pipe with no listener returns EPERM
520 // treat this as a special case to prevent spurious error messages
521 // to the console.
522 return false;
[email protected]22b42c52010-12-20 06:59:23523#endif // OS_MACOSX
[email protected]7bf54f5e2009-10-23 01:48:21524 } else if (errno == ECONNRESET || errno == EPIPE) {
[email protected]d8365fc2009-10-16 19:44:31525 return false;
[email protected]fa95fc92008-12-08 18:10:14526 } else {
[email protected]57b765672009-10-13 18:27:40527 PLOG(ERROR) << "pipe error (" << pipe_ << ")";
[email protected]fa95fc92008-12-08 18:10:14528 return false;
529 }
530 } else if (bytes_read == 0) {
531 // The pipe has closed...
[email protected]e8fce882009-01-20 22:02:58532 return false;
[email protected]fa95fc92008-12-08 18:10:14533 }
534 }
535 DCHECK(bytes_read);
536
[email protected]e8fce882009-01-20 22:02:58537 if (client_pipe_ != -1) {
[email protected]864b5582010-12-04 23:00:10538 PipeMap::GetInstance()->RemoveAndClose(pipe_name_);
[email protected]e8fce882009-01-20 22:02:58539 client_pipe_ = -1;
540 }
541
[email protected]526776c2009-02-07 00:39:26542 // a pointer to an array of |num_wire_fds| file descriptors from the read
[email protected]337c6bf2009-02-07 00:51:58543 const int* wire_fds = NULL;
[email protected]526776c2009-02-07 00:39:26544 unsigned num_wire_fds = 0;
545
546 // walk the list of control messages and, if we find an array of file
547 // descriptors, save a pointer to the array
[email protected]526776c2009-02-07 00:39:26548
[email protected]afb4bad2009-02-12 02:39:31549 // This next if statement is to work around an OSX issue where
550 // CMSG_FIRSTHDR will return non-NULL in the case that controllen == 0.
551 // Here's a test case:
552 //
553 // int main() {
554 // struct msghdr msg;
555 // msg.msg_control = &msg;
556 // msg.msg_controllen = 0;
557 // if (CMSG_FIRSTHDR(&msg))
558 // printf("Bug found!\n");
559 // }
560 if (msg.msg_controllen > 0) {
561 // On OSX, CMSG_FIRSTHDR doesn't handle the case where controllen is 0
562 // and will return a pointer into nowhere.
563 for (struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg); cmsg;
564 cmsg = CMSG_NXTHDR(&msg, cmsg)) {
565 if (cmsg->cmsg_level == SOL_SOCKET &&
566 cmsg->cmsg_type == SCM_RIGHTS) {
567 const unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0);
568 DCHECK(payload_len % sizeof(int) == 0);
569 wire_fds = reinterpret_cast<int*>(CMSG_DATA(cmsg));
570 num_wire_fds = payload_len / 4;
571
572 if (msg.msg_flags & MSG_CTRUNC) {
573 LOG(ERROR) << "SCM_RIGHTS message was truncated"
574 << " cmsg_len:" << cmsg->cmsg_len
575 << " fd:" << pipe_;
576 for (unsigned i = 0; i < num_wire_fds; ++i)
[email protected]70eb6572010-06-23 00:37:46577 if (HANDLE_EINTR(close(wire_fds[i])) < 0)
[email protected]22b42c52010-12-20 06:59:23578 PLOG(ERROR) << "close " << i;
[email protected]afb4bad2009-02-12 02:39:31579 return false;
580 }
581 break;
[email protected]526776c2009-02-07 00:39:26582 }
[email protected]526776c2009-02-07 00:39:26583 }
584 }
585
[email protected]fa95fc92008-12-08 18:10:14586 // Process messages from input buffer.
587 const char *p;
588 const char *end;
589 if (input_overflow_buf_.empty()) {
590 p = input_buf_;
591 end = p + bytes_read;
592 } else {
593 if (input_overflow_buf_.size() >
594 static_cast<size_t>(kMaximumMessageSize - bytes_read)) {
595 input_overflow_buf_.clear();
596 LOG(ERROR) << "IPC message is too big";
597 return false;
598 }
599 input_overflow_buf_.append(input_buf_, bytes_read);
600 p = input_overflow_buf_.data();
601 end = p + input_overflow_buf_.size();
602 }
603
[email protected]526776c2009-02-07 00:39:26604 // A pointer to an array of |num_fds| file descriptors which includes any
605 // fds that have spilled over from a previous read.
[email protected]baf556a2009-09-04 21:34:05606 const int* fds = NULL;
607 unsigned num_fds = 0;
[email protected]526776c2009-02-07 00:39:26608 unsigned fds_i = 0; // the index of the first unused descriptor
609
610 if (input_overflow_fds_.empty()) {
611 fds = wire_fds;
612 num_fds = num_wire_fds;
613 } else {
[email protected]baf556a2009-09-04 21:34:05614 if (num_wire_fds > 0) {
615 const size_t prev_size = input_overflow_fds_.size();
616 input_overflow_fds_.resize(prev_size + num_wire_fds);
617 memcpy(&input_overflow_fds_[prev_size], wire_fds,
618 num_wire_fds * sizeof(int));
619 }
[email protected]526776c2009-02-07 00:39:26620 fds = &input_overflow_fds_[0];
621 num_fds = input_overflow_fds_.size();
622 }
623
[email protected]fa95fc92008-12-08 18:10:14624 while (p < end) {
625 const char* message_tail = Message::FindNext(p, end);
626 if (message_tail) {
627 int len = static_cast<int>(message_tail - p);
[email protected]7135bb042009-02-12 04:05:28628 Message m(p, len);
[email protected]5484722e2010-12-09 01:13:12629 const uint16 header_fds = m.header()->num_fds;
630 if (header_fds) {
[email protected]526776c2009-02-07 00:39:26631 // the message has file descriptors
[email protected]7135bb042009-02-12 04:05:28632 const char* error = NULL;
[email protected]5484722e2010-12-09 01:13:12633 if (header_fds > num_fds - fds_i) {
[email protected]526776c2009-02-07 00:39:26634 // the message has been completely received, but we didn't get
635 // enough file descriptors.
[email protected]e40f5a0b2010-12-08 21:22:24636#if defined(IPC_USES_READWRITE)
[email protected]22b42c52010-12-20 06:59:23637 char dummy;
638 struct iovec fd_pipe_iov = { &dummy, 1 };
639 msg.msg_iov = &fd_pipe_iov;
640 msg.msg_controllen = sizeof(input_cmsg_buf_);
641 ssize_t n = HANDLE_EINTR(recvmsg(fd_pipe_, &msg, MSG_DONTWAIT));
642 if (n == 1 && msg.msg_controllen > 0) {
643 for (struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg); cmsg;
644 cmsg = CMSG_NXTHDR(&msg, cmsg)) {
645 if (cmsg->cmsg_level == SOL_SOCKET &&
646 cmsg->cmsg_type == SCM_RIGHTS) {
647 const unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0);
648 DCHECK(payload_len % sizeof(int) == 0);
649 wire_fds = reinterpret_cast<int*>(CMSG_DATA(cmsg));
650 num_wire_fds = payload_len / 4;
[email protected]baf556a2009-09-04 21:34:05651
[email protected]22b42c52010-12-20 06:59:23652 if (msg.msg_flags & MSG_CTRUNC) {
653 LOG(ERROR) << "SCM_RIGHTS message was truncated"
654 << " cmsg_len:" << cmsg->cmsg_len
655 << " fd:" << pipe_;
656 for (unsigned i = 0; i < num_wire_fds; ++i)
657 if (HANDLE_EINTR(close(wire_fds[i])) < 0)
658 PLOG(ERROR) << "close " << i;
659 return false;
[email protected]baf556a2009-09-04 21:34:05660 }
[email protected]22b42c52010-12-20 06:59:23661 break;
[email protected]baf556a2009-09-04 21:34:05662 }
[email protected]22b42c52010-12-20 06:59:23663 }
664 if (input_overflow_fds_.empty()) {
665 fds = wire_fds;
666 num_fds = num_wire_fds;
667 } else {
668 if (num_wire_fds > 0) {
669 const size_t prev_size = input_overflow_fds_.size();
670 input_overflow_fds_.resize(prev_size + num_wire_fds);
671 memcpy(&input_overflow_fds_[prev_size], wire_fds,
672 num_wire_fds * sizeof(int));
[email protected]baf556a2009-09-04 21:34:05673 }
[email protected]22b42c52010-12-20 06:59:23674 fds = &input_overflow_fds_[0];
675 num_fds = input_overflow_fds_.size();
[email protected]baf556a2009-09-04 21:34:05676 }
677 }
[email protected]5484722e2010-12-09 01:13:12678 if (header_fds > num_fds - fds_i)
[email protected]22b42c52010-12-20 06:59:23679#endif // IPC_USES_READWRITE
[email protected]baf556a2009-09-04 21:34:05680 error = "Message needs unreceived descriptors";
[email protected]7135bb042009-02-12 04:05:28681 }
682
[email protected]5484722e2010-12-09 01:13:12683 if (header_fds >
[email protected]d0c0b1d2009-02-12 18:32:45684 FileDescriptorSet::MAX_DESCRIPTORS_PER_MESSAGE) {
[email protected]7135bb042009-02-12 04:05:28685 // There are too many descriptors in this message
686 error = "Message requires an excessive number of descriptors";
687 }
688
689 if (error) {
690 LOG(WARNING) << error
[email protected]526776c2009-02-07 00:39:26691 << " channel:" << this
692 << " message-type:" << m.type()
[email protected]5484722e2010-12-09 01:13:12693 << " header()->num_fds:" << header_fds
[email protected]526776c2009-02-07 00:39:26694 << " num_fds:" << num_fds
695 << " fds_i:" << fds_i;
[email protected]a89a55dd2010-04-19 14:51:13696#if defined(CHROMIUM_SELINUX)
697 LOG(WARNING) << "In the case of SELinux this can be caused when "
698 "using a --user-data-dir to which the default "
699 "policy doesn't give the renderer access to. ";
[email protected]22b42c52010-12-20 06:59:23700#endif // CHROMIUM_SELINUX
[email protected]526776c2009-02-07 00:39:26701 // close the existing file descriptors so that we don't leak them
702 for (unsigned i = fds_i; i < num_fds; ++i)
[email protected]70eb6572010-06-23 00:37:46703 if (HANDLE_EINTR(close(fds[i])) < 0)
[email protected]22b42c52010-12-20 06:59:23704 PLOG(ERROR) << "close " << i;
[email protected]526776c2009-02-07 00:39:26705 input_overflow_fds_.clear();
[email protected]7135bb042009-02-12 04:05:28706 // abort the connection
[email protected]526776c2009-02-07 00:39:26707 return false;
708 }
709
[email protected]d0c0b1d2009-02-12 18:32:45710 m.file_descriptor_set()->SetDescriptors(
[email protected]5484722e2010-12-09 01:13:12711 &fds[fds_i], header_fds);
712 fds_i += header_fds;
[email protected]526776c2009-02-07 00:39:26713 }
[email protected]2a9d601b2010-10-19 23:50:00714 DVLOG(2) << "received message on channel @" << this
[email protected]5484722e2010-12-09 01:13:12715 << " with type " << m.type() << " on fd " << pipe_;
[email protected]22b42c52010-12-20 06:59:23716 if (IsHelloMessage(&m)) {
[email protected]fa95fc92008-12-08 18:10:14717 // The Hello message contains only the process id.
[email protected]baf556a2009-09-04 21:34:05718 void *iter = NULL;
719 int pid;
720 if (!m.ReadInt(&iter, &pid)) {
721 NOTREACHED();
722 }
[email protected]e40f5a0b2010-12-08 21:22:24723#if defined(IPC_USES_READWRITE)
[email protected]22b42c52010-12-20 06:59:23724 if (mode_ == MODE_SERVER) {
725 // With IPC_USES_READWRITE, the Hello message from the client to the
726 // server also contains the fd_pipe_, which will be used for all
[email protected]baf556a2009-09-04 21:34:05727 // subsequent file descriptor passing.
[email protected]7ee1a44c2010-07-23 14:18:59728 DCHECK_EQ(m.file_descriptor_set()->size(), 1U);
[email protected]baf556a2009-09-04 21:34:05729 base::FileDescriptor descriptor;
730 if (!m.ReadFileDescriptor(&iter, &descriptor)) {
731 NOTREACHED();
732 }
733 fd_pipe_ = descriptor.fd;
734 CHECK(descriptor.auto_close);
735 }
[email protected]22b42c52010-12-20 06:59:23736#endif // IPC_USES_READWRITE
[email protected]baf556a2009-09-04 21:34:05737 listener_->OnChannelConnected(pid);
[email protected]fa95fc92008-12-08 18:10:14738 } else {
739 listener_->OnMessageReceived(m);
740 }
741 p = message_tail;
742 } else {
743 // Last message is partial.
744 break;
745 }
[email protected]baf556a2009-09-04 21:34:05746 input_overflow_fds_ = std::vector<int>(&fds[fds_i], &fds[num_fds]);
747 fds_i = 0;
748 fds = &input_overflow_fds_[0];
749 num_fds = input_overflow_fds_.size();
[email protected]fa95fc92008-12-08 18:10:14750 }
751 input_overflow_buf_.assign(p, end - p);
[email protected]526776c2009-02-07 00:39:26752 input_overflow_fds_ = std::vector<int>(&fds[fds_i], &fds[num_fds]);
[email protected]fa95fc92008-12-08 18:10:14753
[email protected]afb4bad2009-02-12 02:39:31754 // When the input data buffer is empty, the overflow fds should be too. If
755 // this is not the case, we probably have a rogue renderer which is trying
756 // to fill our descriptor table.
757 if (input_overflow_buf_.empty() && !input_overflow_fds_.empty()) {
758 // We close these descriptors in Close()
759 return false;
760 }
761
[email protected]fa95fc92008-12-08 18:10:14762 bytes_read = 0; // Get more data.
763 }
[email protected]fa95fc92008-12-08 18:10:14764}
765
[email protected]514411fc2008-12-10 22:28:11766bool Channel::ChannelImpl::ProcessOutgoingMessages() {
[email protected]fa95fc92008-12-08 18:10:14767 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
768 // no connection?
[email protected]22b42c52010-12-20 06:59:23769 if (output_queue_.empty())
[email protected]c7f91e82010-12-20 06:39:44770 return true;
[email protected]c7f91e82010-12-20 06:39:44771
[email protected]22b42c52010-12-20 06:59:23772 if (pipe_ == -1)
[email protected]fa95fc92008-12-08 18:10:14773 return false;
774
[email protected]fa95fc92008-12-08 18:10:14775 // Write out all the messages we can till the write blocks or there are no
776 // more outgoing messages.
777 while (!output_queue_.empty()) {
778 Message* msg = output_queue_.front();
779
780 size_t amt_to_write = msg->size() - message_send_bytes_written_;
[email protected]3d1b6662009-01-29 17:03:11781 DCHECK(amt_to_write != 0);
[email protected]baf556a2009-09-04 21:34:05782 const char* out_bytes = reinterpret_cast<const char*>(msg->data()) +
[email protected]fa95fc92008-12-08 18:10:14783 message_send_bytes_written_;
[email protected]526776c2009-02-07 00:39:26784
[email protected]157c61b2009-05-01 21:37:31785 struct msghdr msgh = {0};
786 struct iovec iov = {const_cast<char*>(out_bytes), amt_to_write};
787 msgh.msg_iov = &iov;
788 msgh.msg_iovlen = 1;
789 char buf[CMSG_SPACE(
790 sizeof(int[FileDescriptorSet::MAX_DESCRIPTORS_PER_MESSAGE]))];
[email protected]526776c2009-02-07 00:39:26791
[email protected]baf556a2009-09-04 21:34:05792 ssize_t bytes_written = 1;
793 int fd_written = -1;
794
[email protected]157c61b2009-05-01 21:37:31795 if (message_send_bytes_written_ == 0 &&
796 !msg->file_descriptor_set()->empty()) {
797 // This is the first chunk of a message which has descriptors to send
798 struct cmsghdr *cmsg;
799 const unsigned num_fds = msg->file_descriptor_set()->size();
[email protected]526776c2009-02-07 00:39:26800
[email protected]157c61b2009-05-01 21:37:31801 DCHECK_LE(num_fds, FileDescriptorSet::MAX_DESCRIPTORS_PER_MESSAGE);
[email protected]aac449e2010-06-10 21:39:04802 if (msg->file_descriptor_set()->ContainsDirectoryDescriptor()) {
803 LOG(FATAL) << "Panic: attempting to transport directory descriptor over"
804 " IPC. Aborting to maintain sandbox isolation.";
805 // If you have hit this then something tried to send a file descriptor
806 // to a directory over an IPC channel. Since IPC channels span
807 // sandboxes this is very bad: the receiving process can use openat
808 // with ".." elements in the path in order to reach the real
809 // filesystem.
810 }
[email protected]526776c2009-02-07 00:39:26811
[email protected]157c61b2009-05-01 21:37:31812 msgh.msg_control = buf;
813 msgh.msg_controllen = CMSG_SPACE(sizeof(int) * num_fds);
814 cmsg = CMSG_FIRSTHDR(&msgh);
815 cmsg->cmsg_level = SOL_SOCKET;
816 cmsg->cmsg_type = SCM_RIGHTS;
817 cmsg->cmsg_len = CMSG_LEN(sizeof(int) * num_fds);
818 msg->file_descriptor_set()->GetDescriptors(
819 reinterpret_cast<int*>(CMSG_DATA(cmsg)));
820 msgh.msg_controllen = cmsg->cmsg_len;
[email protected]526776c2009-02-07 00:39:26821
[email protected]168ae922009-12-04 18:08:45822 // DCHECK_LE above already checks that
823 // num_fds < MAX_DESCRIPTORS_PER_MESSAGE so no danger of overflow.
824 msg->header()->num_fds = static_cast<uint16>(num_fds);
[email protected]baf556a2009-09-04 21:34:05825
[email protected]e40f5a0b2010-12-08 21:22:24826#if defined(IPC_USES_READWRITE)
[email protected]22b42c52010-12-20 06:59:23827 if (!IsHelloMessage(msg)) {
[email protected]baf556a2009-09-04 21:34:05828 // Only the Hello message sends the file descriptor with the message.
829 // Subsequently, we can send file descriptors on the dedicated
830 // fd_pipe_ which makes Seccomp sandbox operation more efficient.
831 struct iovec fd_pipe_iov = { const_cast<char *>(""), 1 };
832 msgh.msg_iov = &fd_pipe_iov;
833 fd_written = fd_pipe_;
834 bytes_written = HANDLE_EINTR(sendmsg(fd_pipe_, &msgh, MSG_DONTWAIT));
835 msgh.msg_iov = &iov;
836 msgh.msg_controllen = 0;
837 if (bytes_written > 0) {
838 msg->file_descriptor_set()->CommitAll();
839 }
840 }
[email protected]22b42c52010-12-20 06:59:23841#endif // IPC_USES_READWRITE
[email protected]157c61b2009-05-01 21:37:31842 }
843
[email protected]baf556a2009-09-04 21:34:05844 if (bytes_written == 1) {
845 fd_written = pipe_;
[email protected]e40f5a0b2010-12-08 21:22:24846#if defined(IPC_USES_READWRITE)
[email protected]22b42c52010-12-20 06:59:23847 if (mode_ != MODE_SERVER && IsHelloMessage(msg)) {
[email protected]7ee1a44c2010-07-23 14:18:59848 DCHECK_EQ(msg->file_descriptor_set()->size(), 1U);
[email protected]baf556a2009-09-04 21:34:05849 }
[email protected]22b42c52010-12-20 06:59:23850 if (!msgh.msg_controllen) {
[email protected]baf556a2009-09-04 21:34:05851 bytes_written = HANDLE_EINTR(write(pipe_, out_bytes, amt_to_write));
852 } else
[email protected]22b42c52010-12-20 06:59:23853#endif // IPC_USES_READWRITE
[email protected]baf556a2009-09-04 21:34:05854 {
855 bytes_written = HANDLE_EINTR(sendmsg(pipe_, &msgh, MSG_DONTWAIT));
856 }
857 }
[email protected]157c61b2009-05-01 21:37:31858 if (bytes_written > 0)
859 msg->file_descriptor_set()->CommitAll();
[email protected]fa95fc92008-12-08 18:10:14860
[email protected]86c3d9e2009-12-08 14:48:08861 if (bytes_written < 0 && !SocketWriteErrorIsRecoverable()) {
[email protected]cb38c0b22009-05-27 18:29:48862#if defined(OS_MACOSX)
863 // On OSX writing to a pipe with no listener returns EPERM.
864 if (errno == EPERM) {
865 Close();
866 return false;
867 }
868#endif // OS_MACOSX
[email protected]7bf54f5e2009-10-23 01:48:21869 if (errno == EPIPE) {
870 Close();
871 return false;
872 }
[email protected]780ae942009-12-03 13:35:46873 PLOG(ERROR) << "pipe error on "
874 << fd_written
875 << " Currently writing message of size:"
[email protected]86c3d9e2009-12-08 14:48:08876 << msg->size();
[email protected]fa95fc92008-12-08 18:10:14877 return false;
878 }
879
880 if (static_cast<size_t>(bytes_written) != amt_to_write) {
[email protected]3d1b6662009-01-29 17:03:11881 if (bytes_written > 0) {
882 // If write() fails with EAGAIN then bytes_written will be -1.
883 message_send_bytes_written_ += bytes_written;
884 }
[email protected]fa95fc92008-12-08 18:10:14885
886 // Tell libevent to call us back once things are unblocked.
[email protected]e45e6c02008-12-15 22:02:17887 is_blocked_on_write_ = true;
888 MessageLoopForIO::current()->WatchFileDescriptor(
889 pipe_,
890 false, // One shot
891 MessageLoopForIO::WATCH_WRITE,
892 &write_watcher_,
893 this);
[email protected]3d1b6662009-01-29 17:03:11894 return true;
[email protected]fa95fc92008-12-08 18:10:14895 } else {
896 message_send_bytes_written_ = 0;
897
898 // Message sent OK!
[email protected]2a9d601b2010-10-19 23:50:00899 DVLOG(2) << "sent message @" << msg << " on channel @" << this
[email protected]5484722e2010-12-09 01:13:12900 << " with type " << msg->type() << " on fd " << pipe_;
[email protected]baf556a2009-09-04 21:34:05901 delete output_queue_.front();
[email protected]fa95fc92008-12-08 18:10:14902 output_queue_.pop();
[email protected]fa95fc92008-12-08 18:10:14903 }
904 }
905 return true;
906}
907
[email protected]514411fc2008-12-10 22:28:11908bool Channel::ChannelImpl::Send(Message* message) {
[email protected]2a9d601b2010-10-19 23:50:00909 DVLOG(2) << "sending message @" << message << " on channel @" << this
910 << " with type " << message->type()
911 << " (" << output_queue_.size() << " in queue)";
[email protected]fa95fc92008-12-08 18:10:14912
[email protected]4c2c1db2009-03-20 20:56:55913#ifdef IPC_MESSAGE_LOG_ENABLED
[email protected]8e8bb6d2010-12-13 08:18:55914 Logging::GetInstance()->OnSendMessage(message, "");
[email protected]22b42c52010-12-20 06:59:23915#endif // IPC_MESSAGE_LOG_ENABLED
[email protected]fa95fc92008-12-08 18:10:14916
917 output_queue_.push(message);
[email protected]22b42c52010-12-20 06:59:23918 if (!is_blocked_on_write_ && !waiting_connect_) {
919 return ProcessOutgoingMessages();
[email protected]fa95fc92008-12-08 18:10:14920 }
921
922 return true;
923}
924
[email protected]cc8f1462009-06-12 17:36:55925int Channel::ChannelImpl::GetClientFileDescriptor() const {
926 return client_pipe_;
[email protected]df3c1ca12008-12-19 21:37:01927}
928
[email protected]22b42c52010-12-20 06:59:23929bool Channel::ChannelImpl::AcceptsConnections() const {
930 return server_listen_pipe_ != -1;
931}
[email protected]9a44a4db62010-12-20 06:19:07932
[email protected]22b42c52010-12-20 06:59:23933bool Channel::ChannelImpl::HasAcceptedConnection() const {
934 return AcceptsConnections() && pipe_ != -1;
935}
[email protected]9a44a4db62010-12-20 06:19:07936
[email protected]22b42c52010-12-20 06:59:23937void Channel::ChannelImpl::ResetToAcceptingConnectionState() {
938 // Unregister libevent for the unix domain socket and close it.
939 read_watcher_.StopWatchingFileDescriptor();
940 write_watcher_.StopWatchingFileDescriptor();
941 if (pipe_ != -1) {
942 if (HANDLE_EINTR(close(pipe_)) < 0)
943 PLOG(ERROR) << "close pipe_ " << pipe_name_;
944 pipe_ = -1;
945 }
946#if defined(IPC_USES_READWRITE)
947 if (fd_pipe_ != -1) {
948 if (HANDLE_EINTR(close(fd_pipe_)) < 0)
949 PLOG(ERROR) << "close fd_pipe_ " << pipe_name_;
950 fd_pipe_ = -1;
951 }
952 if (remote_fd_pipe_ != -1) {
953 if (HANDLE_EINTR(close(remote_fd_pipe_)) < 0)
954 PLOG(ERROR) << "close remote_fd_pipe_ " << pipe_name_;
955 remote_fd_pipe_ = -1;
956 }
957#endif // IPC_USES_READWRITE
[email protected]c7f91e82010-12-20 06:39:44958
[email protected]22b42c52010-12-20 06:59:23959 while (!output_queue_.empty()) {
960 Message* m = output_queue_.front();
961 output_queue_.pop();
962 delete m;
[email protected]c7f91e82010-12-20 06:39:44963 }
964
[email protected]22b42c52010-12-20 06:59:23965 // Close any outstanding, received file descriptors.
966 for (std::vector<int>::iterator
967 i = input_overflow_fds_.begin(); i != input_overflow_fds_.end(); ++i) {
968 if (HANDLE_EINTR(close(*i)) < 0)
969 PLOG(ERROR) << "close";
970 }
971 input_overflow_fds_.clear();
972}
973
974// Called by libevent when we can read from the pipe without blocking.
975void Channel::ChannelImpl::OnFileCanReadWithoutBlocking(int fd) {
976 bool send_server_hello_msg = false;
977 if (fd == server_listen_pipe_) {
978 int new_pipe = 0;
979 if (!ServerAcceptConnection(server_listen_pipe_, &new_pipe)) {
[email protected]c7f91e82010-12-20 06:39:44980 Close();
[email protected]22b42c52010-12-20 06:59:23981 listener_->OnChannelListenError();
982 }
983
984 if (pipe_ != -1) {
985 // We already have a connection. We only handle one at a time.
986 // close our new descriptor.
987 if (HANDLE_EINTR(shutdown(new_pipe, SHUT_RDWR)) < 0)
988 PLOG(ERROR) << "shutdown " << pipe_name_;
989 if (HANDLE_EINTR(close(new_pipe)) < 0)
990 PLOG(ERROR) << "close " << pipe_name_;
991 listener_->OnChannelDenied();
[email protected]c7f91e82010-12-20 06:39:44992 return;
[email protected]9a44a4db62010-12-20 06:19:07993 }
[email protected]22b42c52010-12-20 06:59:23994 pipe_ = new_pipe;
995
996 if (!AcceptConnection()) {
997 NOTREACHED() << "AcceptConnection should not fail on server";
998 }
999 send_server_hello_msg = true;
1000 waiting_connect_ = false;
1001 } else if (fd == pipe_) {
1002 if (waiting_connect_ && mode_ == MODE_SERVER) {
1003 send_server_hello_msg = true;
1004 waiting_connect_ = false;
1005 }
1006 if (!ProcessIncomingMessages()) {
1007 ClosePipeOnError();
1008 }
1009 } else {
1010 NOTREACHED() << "Unknown pipe " << fd;
[email protected]fa95fc92008-12-08 18:10:141011 }
1012
1013 // If we're a server and handshaking, then we want to make sure that we
1014 // only send our handshake message after we've processed the client's.
1015 // This gives us a chance to kill the client if the incoming handshake
1016 // is invalid.
1017 if (send_server_hello_msg) {
1018 ProcessOutgoingMessages();
1019 }
1020}
1021
1022// Called by libevent when we can write to the pipe without blocking.
[email protected]e45e6c02008-12-15 22:02:171023void Channel::ChannelImpl::OnFileCanWriteWithoutBlocking(int fd) {
[email protected]22b42c52010-12-20 06:59:231024 DCHECK(fd == pipe_);
1025 is_blocked_on_write_ = false;
[email protected]fa95fc92008-12-08 18:10:141026 if (!ProcessOutgoingMessages()) {
[email protected]22b42c52010-12-20 06:59:231027 ClosePipeOnError();
[email protected]9a44a4db62010-12-20 06:19:071028 }
1029}
1030
[email protected]22b42c52010-12-20 06:59:231031bool Channel::ChannelImpl::AcceptConnection() {
1032 MessageLoopForIO::current()->WatchFileDescriptor(pipe_,
1033 true,
1034 MessageLoopForIO::WATCH_READ,
1035 &read_watcher_,
1036 this);
1037 QueueHelloMessage();
1038
1039 if (mode_ == MODE_CLIENT) {
1040 // If we are a client we want to send a hello message out immediately.
1041 // In server mode we will send a hello message when we receive one from a
1042 // client.
1043 waiting_connect_ = false;
1044 return ProcessOutgoingMessages();
1045 } else {
1046 waiting_connect_ = true;
1047 return true;
1048 }
1049}
1050
1051void Channel::ChannelImpl::ClosePipeOnError() {
1052 if (HasAcceptedConnection()) {
1053 ResetToAcceptingConnectionState();
1054 listener_->OnChannelError();
1055 } else {
1056 Close();
1057 if (AcceptsConnections()) {
1058 listener_->OnChannelListenError();
1059 } else {
1060 listener_->OnChannelError();
1061 }
1062 }
1063}
1064
1065void Channel::ChannelImpl::QueueHelloMessage() {
1066 // Create the Hello message
1067 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
1068 HELLO_MESSAGE_TYPE,
1069 IPC::Message::PRIORITY_NORMAL));
1070
1071 if (!msg->WriteInt(base::GetCurrentProcId())) {
1072 NOTREACHED() << "Unable to pickle hello message proc id";
1073 }
1074#if defined(IPC_USES_READWRITE)
1075 scoped_ptr<Message> hello;
1076 if (remote_fd_pipe_ != -1) {
1077 if (!msg->WriteFileDescriptor(base::FileDescriptor(remote_fd_pipe_,
1078 false))) {
1079 NOTREACHED() << "Unable to pickle hello message file descriptors";
1080 }
1081 DCHECK_EQ(msg->file_descriptor_set()->size(), 1U);
1082 }
1083#endif // IPC_USES_READWRITE
1084 output_queue_.push(msg.release());
1085}
1086
1087bool Channel::ChannelImpl::IsHelloMessage(const Message* m) const {
1088 return m->routing_id() == MSG_ROUTING_NONE && m->type() == HELLO_MESSAGE_TYPE;
1089}
1090
[email protected]514411fc2008-12-10 22:28:111091void Channel::ChannelImpl::Close() {
[email protected]fa95fc92008-12-08 18:10:141092 // Close can be called multiple time, so we need to make sure we're
1093 // idempotent.
1094
[email protected]22b42c52010-12-20 06:59:231095 ResetToAcceptingConnectionState();
[email protected]fa95fc92008-12-08 18:10:141096
[email protected]22b42c52010-12-20 06:59:231097 if (must_unlink_) {
1098 unlink(pipe_name_.c_str());
1099 must_unlink_ = false;
1100 }
[email protected]fa95fc92008-12-08 18:10:141101 if (server_listen_pipe_ != -1) {
[email protected]70eb6572010-06-23 00:37:461102 if (HANDLE_EINTR(close(server_listen_pipe_)) < 0)
[email protected]5484722e2010-12-09 01:13:121103 PLOG(ERROR) << "close " << server_listen_pipe_;
[email protected]fa95fc92008-12-08 18:10:141104 server_listen_pipe_ = -1;
[email protected]22b42c52010-12-20 06:59:231105 // Unregister libevent for the listening socket and close it.
1106 server_listen_connection_watcher_.StopWatchingFileDescriptor();
[email protected]fa95fc92008-12-08 18:10:141107 }
1108
[email protected]df3c1ca12008-12-19 21:37:011109 if (client_pipe_ != -1) {
[email protected]864b5582010-12-04 23:00:101110 PipeMap::GetInstance()->RemoveAndClose(pipe_name_);
[email protected]df3c1ca12008-12-19 21:37:011111 client_pipe_ = -1;
1112 }
[email protected]fa95fc92008-12-08 18:10:141113}
1114
[email protected]514411fc2008-12-10 22:28:111115//------------------------------------------------------------------------------
1116// Channel's methods simply call through to ChannelImpl.
[email protected]42ce94e2010-12-08 19:28:091117Channel::Channel(const IPC::ChannelHandle& channel_handle, Mode mode,
[email protected]514411fc2008-12-10 22:28:111118 Listener* listener)
[email protected]42ce94e2010-12-08 19:28:091119 : channel_impl_(new ChannelImpl(channel_handle, mode, listener)) {
[email protected]514411fc2008-12-10 22:28:111120}
1121
1122Channel::~Channel() {
1123 delete channel_impl_;
1124}
1125
1126bool Channel::Connect() {
1127 return channel_impl_->Connect();
1128}
1129
1130void Channel::Close() {
1131 channel_impl_->Close();
1132}
1133
1134void Channel::set_listener(Listener* listener) {
1135 channel_impl_->set_listener(listener);
1136}
1137
1138bool Channel::Send(Message* message) {
1139 return channel_impl_->Send(message);
1140}
1141
[email protected]cc8f1462009-06-12 17:36:551142int Channel::GetClientFileDescriptor() const {
1143 return channel_impl_->GetClientFileDescriptor();
[email protected]df3c1ca12008-12-19 21:37:011144}
1145
[email protected]22b42c52010-12-20 06:59:231146bool Channel::AcceptsConnections() const {
1147 return channel_impl_->AcceptsConnections();
1148}
1149
1150bool Channel::HasAcceptedConnection() const {
1151 return channel_impl_->HasAcceptedConnection();
1152}
1153
1154void Channel::ResetToAcceptingConnectionState() {
1155 channel_impl_->ResetToAcceptingConnectionState();
1156}
1157
[email protected]d4651ff2008-12-02 16:51:581158} // namespace IPC