blob: e4852b4de321a0d7536e993fab5162b93dfd24ce [file] [log] [blame]
[email protected]d4651ff2008-12-02 16:51:581// Copyright (c) 2008 The Chromium Authors. All rights reserved.
2// 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]cc8f1462009-06-12 17:36:5520#include "base/global_descriptors_posix.h"
[email protected]e8fce882009-01-20 22:02:5821#include "base/lock.h"
[email protected]fa95fc92008-12-08 18:10:1422#include "base/logging.h"
23#include "base/process_util.h"
24#include "base/scoped_ptr.h"
[email protected]e8fce882009-01-20 22:02:5825#include "base/singleton.h"
[email protected]e6f02ab2009-04-10 22:29:2926#include "base/stats_counters.h"
[email protected]946d1b22009-07-22 23:57:2127#include "base/string_util.h"
28#include "ipc/ipc_descriptors.h"
29#include "ipc/ipc_switches.h"
30#include "ipc/file_descriptor_set_posix.h"
31#include "ipc/ipc_logging.h"
32#include "ipc/ipc_message_utils.h"
[email protected]d4651ff2008-12-02 16:51:5833
34namespace IPC {
35
[email protected]5f594c02009-05-01 22:37:5936// IPC channels on Windows use named pipes (CreateNamedPipe()) with
37// channel ids as the pipe names. Channels on POSIX use anonymous
38// Unix domain sockets created via socketpair() as pipes. These don't
39// quite line up.
40//
41// When creating a child subprocess, the parent side of the fork
42// 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().
46
[email protected]fa95fc92008-12-08 18:10:1447//------------------------------------------------------------------------------
[email protected]fa95fc92008-12-08 18:10:1448namespace {
49
[email protected]5f594c02009-05-01 22:37:5950// The PipeMap class works around this quirk related to unit tests:
[email protected]e8fce882009-01-20 22:02:5851//
[email protected]5f594c02009-05-01 22:37:5952// When running as a server, we install the client socket in a
[email protected]cc8f1462009-06-12 17:36:5553// specific file descriptor number (@kPrimaryIPCChannel). However, we
[email protected]5f594c02009-05-01 22:37:5954// also have to support the case where we are running unittests in the
55// same process. (We do not support forking without execing.)
[email protected]e8fce882009-01-20 22:02:5856//
57// Case 1: normal running
58// The IPC server object will install a mapping in PipeMap from the
59// name which it was given to the client pipe. When forking the client, the
60// GetClientFileDescriptorMapping will ensure that the socket is installed in
[email protected]cc8f1462009-06-12 17:36:5561// the magic slot (@kPrimaryIPCChannel). The client will search for the
[email protected]e8fce882009-01-20 22:02:5862// mapping, but it won't find any since we are in a new process. Thus the
63// magic fd number is returned. Once the client connects, the server will
[email protected]5f594c02009-05-01 22:37:5964// close its copy of the client socket and remove the mapping.
[email protected]e8fce882009-01-20 22:02:5865//
66// Case 2: unittests - client and server in the same process
67// The IPC server will install a mapping as before. The client will search
68// for a mapping and find out. It duplicates the file descriptor and
69// connects. Once the client connects, the server will close the original
70// copy of the client socket and remove the mapping. Thus, when the client
71// object closes, it will close the only remaining copy of the client socket
72// in the fd table and the server will see EOF on its side.
73//
74// TODO(port): a client process cannot connect to multiple IPC channels with
75// this scheme.
76
77class PipeMap {
78 public:
79 // Lookup a given channel id. Return -1 if not found.
80 int Lookup(const std::string& channel_id) {
81 AutoLock locked(lock_);
82
83 ChannelToFDMap::const_iterator i = map_.find(channel_id);
84 if (i == map_.end())
85 return -1;
86 return i->second;
87 }
88
89 // Remove the mapping for the given channel id. No error is signaled if the
90 // channel_id doesn't exist
[email protected]f0ef2da2009-07-08 01:26:3491 void RemoveAndClose(const std::string& channel_id) {
[email protected]e8fce882009-01-20 22:02:5892 AutoLock locked(lock_);
93
94 ChannelToFDMap::iterator i = map_.find(channel_id);
[email protected]f0ef2da2009-07-08 01:26:3495 if (i != map_.end()) {
[email protected]70eb6572010-06-23 00:37:4696 if (HANDLE_EINTR(close(i->second)) < 0)
97 PLOG(ERROR) << "close";
[email protected]e8fce882009-01-20 22:02:5898 map_.erase(i);
[email protected]f0ef2da2009-07-08 01:26:3499 }
[email protected]e8fce882009-01-20 22:02:58100 }
101
102 // Insert a mapping from @channel_id to @fd. It's a fatal error to insert a
103 // mapping if one already exists for the given channel_id
104 void Insert(const std::string& channel_id, int fd) {
105 AutoLock locked(lock_);
106 DCHECK(fd != -1);
107
108 ChannelToFDMap::const_iterator i = map_.find(channel_id);
[email protected]d2e884d2009-06-22 20:37:52109 CHECK(i == map_.end()) << "Creating second IPC server (fd " << fd << ") "
110 << "for '" << channel_id << "' while first "
111 << "(fd " << i->second << ") still exists";
[email protected]e8fce882009-01-20 22:02:58112 map_[channel_id] = fd;
113 }
114
115 private:
116 Lock lock_;
117 typedef std::map<std::string, int> ChannelToFDMap;
118 ChannelToFDMap map_;
119};
120
[email protected]d2e884d2009-06-22 20:37:52121// Used to map a channel name to the equivalent FD # in the current process.
122// Returns -1 if the channel is unknown.
123int ChannelNameToFD(const std::string& channel_id) {
[email protected]e8fce882009-01-20 22:02:58124 // See the large block comment above PipeMap for the reasoning here.
125 const int fd = Singleton<PipeMap>()->Lookup(channel_id);
[email protected]e8fce882009-01-20 22:02:58126
[email protected]d2e884d2009-06-22 20:37:52127 if (fd != -1) {
128 int dup_fd = dup(fd);
129 if (dup_fd < 0)
[email protected]57b765672009-10-13 18:27:40130 PLOG(FATAL) << "dup(" << fd << ")";
[email protected]d2e884d2009-06-22 20:37:52131 return dup_fd;
132 }
133
134 return fd;
[email protected]df3c1ca12008-12-19 21:37:01135}
136
137//------------------------------------------------------------------------------
[email protected]02d66512009-03-17 01:48:35138sockaddr_un sizecheck;
139const size_t kMaxPipeNameLength = sizeof(sizecheck.sun_path);
[email protected]fa95fc92008-12-08 18:10:14140
141// Creates a Fifo with the specified name ready to listen on.
[email protected]5f594c02009-05-01 22:37:59142bool CreateServerFifo(const std::string& pipe_name, int* server_listen_fd) {
[email protected]fa95fc92008-12-08 18:10:14143 DCHECK(server_listen_fd);
[email protected]02d66512009-03-17 01:48:35144 DCHECK_GT(pipe_name.length(), 0u);
145 DCHECK_LT(pipe_name.length(), kMaxPipeNameLength);
[email protected]fa95fc92008-12-08 18:10:14146
[email protected]02d66512009-03-17 01:48:35147 if (pipe_name.length() == 0 || pipe_name.length() >= kMaxPipeNameLength) {
[email protected]fa95fc92008-12-08 18:10:14148 return false;
149 }
150
151 // Create socket.
152 int fd = socket(AF_UNIX, SOCK_STREAM, 0);
153 if (fd < 0) {
154 return false;
155 }
156
157 // Make socket non-blocking
158 if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
[email protected]70eb6572010-06-23 00:37:46159 if (HANDLE_EINTR(close(fd)) < 0)
160 PLOG(ERROR) << "close";
[email protected]fa95fc92008-12-08 18:10:14161 return false;
162 }
163
164 // Delete any old FS instances.
165 unlink(pipe_name.c_str());
166
167 // Create unix_addr structure
168 struct sockaddr_un unix_addr;
169 memset(&unix_addr, 0, sizeof(unix_addr));
170 unix_addr.sun_family = AF_UNIX;
[email protected]02d66512009-03-17 01:48:35171 snprintf(unix_addr.sun_path, kMaxPipeNameLength, "%s", pipe_name.c_str());
[email protected]fa95fc92008-12-08 18:10:14172 size_t unix_addr_len = offsetof(struct sockaddr_un, sun_path) +
173 strlen(unix_addr.sun_path) + 1;
174
175 // Bind the socket.
176 if (bind(fd, reinterpret_cast<const sockaddr*>(&unix_addr),
177 unix_addr_len) != 0) {
[email protected]70eb6572010-06-23 00:37:46178 if (HANDLE_EINTR(close(fd)) < 0)
179 PLOG(ERROR) << "close";
[email protected]fa95fc92008-12-08 18:10:14180 return false;
181 }
182
183 // Start listening on the socket.
184 const int listen_queue_length = 1;
185 if (listen(fd, listen_queue_length) != 0) {
[email protected]70eb6572010-06-23 00:37:46186 if (HANDLE_EINTR(close(fd)) < 0)
187 PLOG(ERROR) << "close";
[email protected]fa95fc92008-12-08 18:10:14188 return false;
189 }
190
191 *server_listen_fd = fd;
192 return true;
193}
194
195// Accept a connection on a fifo.
196bool ServerAcceptFifoConnection(int server_listen_fd, int* server_socket) {
197 DCHECK(server_socket);
198
[email protected]157c61b2009-05-01 21:37:31199 int accept_fd = HANDLE_EINTR(accept(server_listen_fd, NULL, 0));
[email protected]fa95fc92008-12-08 18:10:14200 if (accept_fd < 0)
201 return false;
[email protected]3af21262008-12-16 21:49:34202 if (fcntl(accept_fd, F_SETFL, O_NONBLOCK) == -1) {
[email protected]70eb6572010-06-23 00:37:46203 if (HANDLE_EINTR(close(accept_fd)) < 0)
204 PLOG(ERROR) << "close";
[email protected]3af21262008-12-16 21:49:34205 return false;
206 }
[email protected]fa95fc92008-12-08 18:10:14207
208 *server_socket = accept_fd;
209 return true;
210}
211
212bool ClientConnectToFifo(const std::string &pipe_name, int* client_socket) {
213 DCHECK(client_socket);
[email protected]02d66512009-03-17 01:48:35214 DCHECK_LT(pipe_name.length(), kMaxPipeNameLength);
[email protected]fa95fc92008-12-08 18:10:14215
216 // Create socket.
217 int fd = socket(AF_UNIX, SOCK_STREAM, 0);
218 if (fd < 0) {
219 LOG(ERROR) << "fd is invalid";
220 return false;
221 }
222
223 // Make socket non-blocking
224 if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
[email protected]02d66512009-03-17 01:48:35225 LOG(ERROR) << "fcntl failed";
[email protected]70eb6572010-06-23 00:37:46226 if (HANDLE_EINTR(close(fd)) < 0)
227 PLOG(ERROR) << "close";
[email protected]fa95fc92008-12-08 18:10:14228 return false;
229 }
230
231 // Create server side of socket.
232 struct sockaddr_un server_unix_addr;
233 memset(&server_unix_addr, 0, sizeof(server_unix_addr));
234 server_unix_addr.sun_family = AF_UNIX;
[email protected]02d66512009-03-17 01:48:35235 snprintf(server_unix_addr.sun_path, kMaxPipeNameLength, "%s",
[email protected]fa95fc92008-12-08 18:10:14236 pipe_name.c_str());
237 size_t server_unix_addr_len = offsetof(struct sockaddr_un, sun_path) +
238 strlen(server_unix_addr.sun_path) + 1;
239
[email protected]157c61b2009-05-01 21:37:31240 if (HANDLE_EINTR(connect(fd, reinterpret_cast<sockaddr*>(&server_unix_addr),
241 server_unix_addr_len)) != 0) {
[email protected]70eb6572010-06-23 00:37:46242 if (HANDLE_EINTR(close(fd)) < 0)
243 PLOG(ERROR) << "close";
[email protected]fa95fc92008-12-08 18:10:14244 return false;
245 }
246
247 *client_socket = fd;
248 return true;
249}
250
[email protected]86c3d9e2009-12-08 14:48:08251bool SocketWriteErrorIsRecoverable() {
252#if defined(OS_MACOSX)
253 // On OS X if sendmsg() is trying to send fds between processes and there
254 // isn't enough room in the output buffer to send the fd structure over
255 // atomically then EMSGSIZE is returned.
256 //
257 // EMSGSIZE presents a problem since the system APIs can only call us when
258 // there's room in the socket buffer and not when there is "enough" room.
259 //
260 // The current behavior is to return to the event loop when EMSGSIZE is
261 // received and hopefull service another FD. This is however still
262 // technically a busy wait since the event loop will call us right back until
263 // the receiver has read enough data to allow passing the FD over atomically.
264 return errno == EAGAIN || errno == EMSGSIZE;
265#else
266 return errno == EAGAIN;
267#endif
268}
269
[email protected]fa95fc92008-12-08 18:10:14270} // namespace
[email protected]d4651ff2008-12-02 16:51:58271//------------------------------------------------------------------------------
272
[email protected]9a3a293b2009-06-04 22:28:16273Channel::ChannelImpl::ChannelImpl(const std::string& channel_id, Mode mode,
[email protected]514411fc2008-12-10 22:28:11274 Listener* listener)
[email protected]fa95fc92008-12-08 18:10:14275 : mode_(mode),
[email protected]e45e6c02008-12-15 22:02:17276 is_blocked_on_write_(false),
277 message_send_bytes_written_(0),
[email protected]bb975362009-01-21 01:00:22278 uses_fifo_(CommandLine::ForCurrentProcess()->HasSwitch(
[email protected]97c42bcf2009-02-27 07:21:58279 switches::kIPCUseFIFO)),
[email protected]e45e6c02008-12-15 22:02:17280 server_listen_pipe_(-1),
281 pipe_(-1),
[email protected]df3c1ca12008-12-19 21:37:01282 client_pipe_(-1),
[email protected]e39333ec2010-05-19 18:17:53283#if !defined(OS_MACOSX)
[email protected]baf556a2009-09-04 21:34:05284 fd_pipe_(-1),
285 remote_fd_pipe_(-1),
286#endif
[email protected]e45e6c02008-12-15 22:02:17287 listener_(listener),
288 waiting_connect_(true),
[email protected]e45e6c02008-12-15 22:02:17289 factory_(this) {
[email protected]fa95fc92008-12-08 18:10:14290 if (!CreatePipe(channel_id, mode)) {
291 // The pipe may have been closed already.
[email protected]57b765672009-10-13 18:27:40292 PLOG(WARNING) << "Unable to create pipe named \"" << channel_id
293 << "\" in " << (mode == MODE_SERVER ? "server" : "client")
294 << " mode";
[email protected]fa95fc92008-12-08 18:10:14295 }
[email protected]d4651ff2008-12-02 16:51:58296}
297
[email protected]601858c02010-09-01 17:08:20298Channel::ChannelImpl::~ChannelImpl() {
299 Close();
300}
301
[email protected]d2e884d2009-06-22 20:37:52302// static
303void AddChannelSocket(const std::string& name, int socket) {
304 Singleton<PipeMap>()->Insert(name, socket);
305}
306
307// static
[email protected]f0ef2da2009-07-08 01:26:34308void RemoveAndCloseChannelSocket(const std::string& name) {
309 Singleton<PipeMap>()->RemoveAndClose(name);
310}
311
312// static
[email protected]9f816f72010-03-16 20:31:10313bool ChannelSocketExists(const std::string& name) {
314 return Singleton<PipeMap>()->Lookup(name) != -1;
315}
316
317// static
[email protected]d2e884d2009-06-22 20:37:52318bool SocketPair(int* fd1, int* fd2) {
319 int pipe_fds[2];
320 if (socketpair(AF_UNIX, SOCK_STREAM, 0, pipe_fds) != 0) {
[email protected]57b765672009-10-13 18:27:40321 PLOG(ERROR) << "socketpair()";
[email protected]d2e884d2009-06-22 20:37:52322 return false;
323 }
324
325 // Set both ends to be non-blocking.
326 if (fcntl(pipe_fds[0], F_SETFL, O_NONBLOCK) == -1 ||
327 fcntl(pipe_fds[1], F_SETFL, O_NONBLOCK) == -1) {
[email protected]57b765672009-10-13 18:27:40328 PLOG(ERROR) << "fcntl(O_NONBLOCK)";
[email protected]70eb6572010-06-23 00:37:46329 if (HANDLE_EINTR(close(pipe_fds[0])) < 0)
330 PLOG(ERROR) << "close";
331 if (HANDLE_EINTR(close(pipe_fds[1])) < 0)
332 PLOG(ERROR) << "close";
[email protected]d2e884d2009-06-22 20:37:52333 return false;
334 }
335
336 *fd1 = pipe_fds[0];
337 *fd2 = pipe_fds[1];
338
339 return true;
340}
341
[email protected]9a3a293b2009-06-04 22:28:16342bool Channel::ChannelImpl::CreatePipe(const std::string& channel_id,
[email protected]514411fc2008-12-10 22:28:11343 Mode mode) {
[email protected]fa95fc92008-12-08 18:10:14344 DCHECK(server_listen_pipe_ == -1 && pipe_ == -1);
345
[email protected]df3c1ca12008-12-19 21:37:01346 if (uses_fifo_) {
[email protected]5f594c02009-05-01 22:37:59347 // This only happens in unit tests; see the comment above PipeMap.
348 // TODO(playmobil): We shouldn't need to create fifos on disk.
349 // TODO(playmobil): If we do, they should be in the user data directory.
350 // TODO(playmobil): Cleanup any stale fifos.
[email protected]9a3a293b2009-06-04 22:28:16351 pipe_name_ = "/var/tmp/chrome_" + channel_id;
[email protected]df3c1ca12008-12-19 21:37:01352 if (mode == MODE_SERVER) {
353 if (!CreateServerFifo(pipe_name_, &server_listen_pipe_)) {
354 return false;
355 }
356 } else {
357 if (!ClientConnectToFifo(pipe_name_, &pipe_)) {
358 return false;
359 }
360 waiting_connect_ = false;
[email protected]fa95fc92008-12-08 18:10:14361 }
362 } else {
[email protected]d2e884d2009-06-22 20:37:52363 // This is the normal (non-unit-test) case, where we're using sockets.
364 // Three possible cases:
365 // 1) It's for a channel we already have a pipe for; reuse it.
366 // 2) It's the initial IPC channel:
367 // 2a) Server side: create the pipe.
368 // 2b) Client side: Pull the pipe out of the GlobalDescriptors set.
[email protected]9a3a293b2009-06-04 22:28:16369 pipe_name_ = channel_id;
[email protected]d2e884d2009-06-22 20:37:52370 pipe_ = ChannelNameToFD(pipe_name_);
371 if (pipe_ < 0) {
372 // Initial IPC channel.
373 if (mode == MODE_SERVER) {
374 if (!SocketPair(&pipe_, &client_pipe_))
375 return false;
376 AddChannelSocket(pipe_name_, client_pipe_);
377 } else {
[email protected]554a8852009-11-30 22:14:37378 // Guard against inappropriate reuse of the initial IPC channel. If
379 // an IPC channel closes and someone attempts to reuse it by name, the
380 // initial channel must not be recycled here. http://crbug.com/26754.
381 static bool used_initial_channel = false;
382 if (used_initial_channel) {
[email protected]9f816f72010-03-16 20:31:10383 LOG(FATAL) << "Denying attempt to reuse initial IPC channel for "
384 << pipe_name_;
[email protected]554a8852009-11-30 22:14:37385 return false;
386 }
387 used_initial_channel = true;
388
[email protected]d2e884d2009-06-22 20:37:52389 pipe_ = Singleton<base::GlobalDescriptors>()->Get(kPrimaryIPCChannel);
[email protected]df3c1ca12008-12-19 21:37:01390 }
[email protected]df3c1ca12008-12-19 21:37:01391 } else {
[email protected]baf556a2009-09-04 21:34:05392 waiting_connect_ = mode == MODE_SERVER;
[email protected]fa95fc92008-12-08 18:10:14393 }
[email protected]fa95fc92008-12-08 18:10:14394 }
395
396 // Create the Hello message to be sent when Connect is called
397 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
398 HELLO_MESSAGE_TYPE,
399 IPC::Message::PRIORITY_NORMAL));
[email protected]e39333ec2010-05-19 18:17:53400 #if !defined(OS_MACOSX)
[email protected]baf556a2009-09-04 21:34:05401 if (!uses_fifo_) {
402 // On Linux, the seccomp sandbox makes it very expensive to call
403 // recvmsg() and sendmsg(). Often, we are perfectly OK with resorting to
404 // read() and write(), which are cheap.
405 //
406 // As we cannot anticipate, when the sender will provide us with file
407 // handles, we have to make the decision about whether we call read() or
408 // recvmsg() before we actually make the call. The easiest option is to
409 // create a dedicated socketpair() for exchanging file handles.
410 if (mode == MODE_SERVER) {
411 fd_pipe_ = -1;
412 } else if (remote_fd_pipe_ == -1) {
413 if (!SocketPair(&fd_pipe_, &remote_fd_pipe_)) {
414 return false;
415 }
416 }
417 }
418 #endif
[email protected]fa95fc92008-12-08 18:10:14419 if (!msg->WriteInt(base::GetCurrentProcId())) {
420 Close();
421 return false;
422 }
423
424 output_queue_.push(msg.release());
425 return true;
[email protected]d4651ff2008-12-02 16:51:58426}
427
[email protected]514411fc2008-12-10 22:28:11428bool Channel::ChannelImpl::Connect() {
[email protected]df3c1ca12008-12-19 21:37:01429 if (mode_ == MODE_SERVER && uses_fifo_) {
[email protected]fa95fc92008-12-08 18:10:14430 if (server_listen_pipe_ == -1) {
431 return false;
432 }
[email protected]e45e6c02008-12-15 22:02:17433 MessageLoopForIO::current()->WatchFileDescriptor(
434 server_listen_pipe_,
435 true,
436 MessageLoopForIO::WATCH_READ,
437 &server_listen_connection_watcher_,
438 this);
[email protected]fa95fc92008-12-08 18:10:14439 } else {
440 if (pipe_ == -1) {
441 return false;
442 }
[email protected]e45e6c02008-12-15 22:02:17443 MessageLoopForIO::current()->WatchFileDescriptor(
444 pipe_,
445 true,
446 MessageLoopForIO::WATCH_READ,
447 &read_watcher_,
448 this);
[email protected]baf556a2009-09-04 21:34:05449 waiting_connect_ = mode_ == MODE_SERVER;
[email protected]fa95fc92008-12-08 18:10:14450 }
451
452 if (!waiting_connect_)
453 return ProcessOutgoingMessages();
454 return true;
[email protected]d4651ff2008-12-02 16:51:58455}
[email protected]fa95fc92008-12-08 18:10:14456
[email protected]514411fc2008-12-10 22:28:11457bool Channel::ChannelImpl::ProcessIncomingMessages() {
[email protected]fa95fc92008-12-08 18:10:14458 ssize_t bytes_read = 0;
459
[email protected]526776c2009-02-07 00:39:26460 struct msghdr msg = {0};
461 struct iovec iov = {input_buf_, Channel::kReadBufferSize};
462
[email protected]526776c2009-02-07 00:39:26463 msg.msg_iovlen = 1;
464 msg.msg_control = input_cmsg_buf_;
[email protected]526776c2009-02-07 00:39:26465
[email protected]fa95fc92008-12-08 18:10:14466 for (;;) {
[email protected]baf556a2009-09-04 21:34:05467 msg.msg_iov = &iov;
[email protected]cef7c522009-02-10 08:15:02468
[email protected]fa95fc92008-12-08 18:10:14469 if (bytes_read == 0) {
470 if (pipe_ == -1)
471 return false;
472
473 // Read from pipe.
[email protected]526776c2009-02-07 00:39:26474 // recvmsg() returns 0 if the connection has closed or EAGAIN if no data
475 // is waiting on the pipe.
[email protected]e39333ec2010-05-19 18:17:53476#if !defined(OS_MACOSX)
[email protected]baf556a2009-09-04 21:34:05477 if (fd_pipe_ >= 0) {
478 bytes_read = HANDLE_EINTR(read(pipe_, input_buf_,
479 Channel::kReadBufferSize));
480 msg.msg_controllen = 0;
481 } else
482#endif
483 {
484 msg.msg_controllen = sizeof(input_cmsg_buf_);
485 bytes_read = HANDLE_EINTR(recvmsg(pipe_, &msg, MSG_DONTWAIT));
486 }
[email protected]fa95fc92008-12-08 18:10:14487 if (bytes_read < 0) {
488 if (errno == EAGAIN) {
489 return true;
[email protected]7f6f06232009-05-22 21:15:39490#if defined(OS_MACOSX)
491 } else if (errno == EPERM) {
492 // On OSX, reading from a pipe with no listener returns EPERM
493 // treat this as a special case to prevent spurious error messages
494 // to the console.
495 return false;
496#endif // defined(OS_MACOSX)
[email protected]7bf54f5e2009-10-23 01:48:21497 } else if (errno == ECONNRESET || errno == EPIPE) {
[email protected]d8365fc2009-10-16 19:44:31498 return false;
[email protected]fa95fc92008-12-08 18:10:14499 } else {
[email protected]57b765672009-10-13 18:27:40500 PLOG(ERROR) << "pipe error (" << pipe_ << ")";
[email protected]fa95fc92008-12-08 18:10:14501 return false;
502 }
503 } else if (bytes_read == 0) {
504 // The pipe has closed...
[email protected]e8fce882009-01-20 22:02:58505 return false;
[email protected]fa95fc92008-12-08 18:10:14506 }
507 }
508 DCHECK(bytes_read);
509
[email protected]e8fce882009-01-20 22:02:58510 if (client_pipe_ != -1) {
[email protected]f0ef2da2009-07-08 01:26:34511 Singleton<PipeMap>()->RemoveAndClose(pipe_name_);
[email protected]e8fce882009-01-20 22:02:58512 client_pipe_ = -1;
513 }
514
[email protected]526776c2009-02-07 00:39:26515 // a pointer to an array of |num_wire_fds| file descriptors from the read
[email protected]337c6bf2009-02-07 00:51:58516 const int* wire_fds = NULL;
[email protected]526776c2009-02-07 00:39:26517 unsigned num_wire_fds = 0;
518
519 // walk the list of control messages and, if we find an array of file
520 // descriptors, save a pointer to the array
[email protected]526776c2009-02-07 00:39:26521
[email protected]afb4bad2009-02-12 02:39:31522 // This next if statement is to work around an OSX issue where
523 // CMSG_FIRSTHDR will return non-NULL in the case that controllen == 0.
524 // Here's a test case:
525 //
526 // int main() {
527 // struct msghdr msg;
528 // msg.msg_control = &msg;
529 // msg.msg_controllen = 0;
530 // if (CMSG_FIRSTHDR(&msg))
531 // printf("Bug found!\n");
532 // }
533 if (msg.msg_controllen > 0) {
534 // On OSX, CMSG_FIRSTHDR doesn't handle the case where controllen is 0
535 // and will return a pointer into nowhere.
536 for (struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg); cmsg;
537 cmsg = CMSG_NXTHDR(&msg, cmsg)) {
538 if (cmsg->cmsg_level == SOL_SOCKET &&
539 cmsg->cmsg_type == SCM_RIGHTS) {
540 const unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0);
541 DCHECK(payload_len % sizeof(int) == 0);
542 wire_fds = reinterpret_cast<int*>(CMSG_DATA(cmsg));
543 num_wire_fds = payload_len / 4;
544
545 if (msg.msg_flags & MSG_CTRUNC) {
546 LOG(ERROR) << "SCM_RIGHTS message was truncated"
547 << " cmsg_len:" << cmsg->cmsg_len
548 << " fd:" << pipe_;
549 for (unsigned i = 0; i < num_wire_fds; ++i)
[email protected]70eb6572010-06-23 00:37:46550 if (HANDLE_EINTR(close(wire_fds[i])) < 0)
551 PLOG(ERROR) << "close" << i;
[email protected]afb4bad2009-02-12 02:39:31552 return false;
553 }
554 break;
[email protected]526776c2009-02-07 00:39:26555 }
[email protected]526776c2009-02-07 00:39:26556 }
557 }
558
[email protected]fa95fc92008-12-08 18:10:14559 // Process messages from input buffer.
560 const char *p;
561 const char *end;
562 if (input_overflow_buf_.empty()) {
563 p = input_buf_;
564 end = p + bytes_read;
565 } else {
566 if (input_overflow_buf_.size() >
567 static_cast<size_t>(kMaximumMessageSize - bytes_read)) {
568 input_overflow_buf_.clear();
569 LOG(ERROR) << "IPC message is too big";
570 return false;
571 }
572 input_overflow_buf_.append(input_buf_, bytes_read);
573 p = input_overflow_buf_.data();
574 end = p + input_overflow_buf_.size();
575 }
576
[email protected]526776c2009-02-07 00:39:26577 // A pointer to an array of |num_fds| file descriptors which includes any
578 // fds that have spilled over from a previous read.
[email protected]baf556a2009-09-04 21:34:05579 const int* fds = NULL;
580 unsigned num_fds = 0;
[email protected]526776c2009-02-07 00:39:26581 unsigned fds_i = 0; // the index of the first unused descriptor
582
583 if (input_overflow_fds_.empty()) {
584 fds = wire_fds;
585 num_fds = num_wire_fds;
586 } else {
[email protected]baf556a2009-09-04 21:34:05587 if (num_wire_fds > 0) {
588 const size_t prev_size = input_overflow_fds_.size();
589 input_overflow_fds_.resize(prev_size + num_wire_fds);
590 memcpy(&input_overflow_fds_[prev_size], wire_fds,
591 num_wire_fds * sizeof(int));
592 }
[email protected]526776c2009-02-07 00:39:26593 fds = &input_overflow_fds_[0];
594 num_fds = input_overflow_fds_.size();
595 }
596
[email protected]fa95fc92008-12-08 18:10:14597 while (p < end) {
598 const char* message_tail = Message::FindNext(p, end);
599 if (message_tail) {
600 int len = static_cast<int>(message_tail - p);
[email protected]7135bb042009-02-12 04:05:28601 Message m(p, len);
[email protected]baf556a2009-09-04 21:34:05602
[email protected]526776c2009-02-07 00:39:26603 if (m.header()->num_fds) {
604 // the message has file descriptors
[email protected]7135bb042009-02-12 04:05:28605 const char* error = NULL;
[email protected]526776c2009-02-07 00:39:26606 if (m.header()->num_fds > num_fds - fds_i) {
607 // the message has been completely received, but we didn't get
608 // enough file descriptors.
[email protected]e39333ec2010-05-19 18:17:53609#if !defined(OS_MACOSX)
[email protected]baf556a2009-09-04 21:34:05610 if (!uses_fifo_) {
611 char dummy;
612 struct iovec fd_pipe_iov = { &dummy, 1 };
613 msg.msg_iov = &fd_pipe_iov;
614 msg.msg_controllen = sizeof(input_cmsg_buf_);
615 ssize_t n = HANDLE_EINTR(recvmsg(fd_pipe_, &msg, MSG_DONTWAIT));
616 if (n == 1 && msg.msg_controllen > 0) {
617 for (struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg); cmsg;
618 cmsg = CMSG_NXTHDR(&msg, cmsg)) {
619 if (cmsg->cmsg_level == SOL_SOCKET &&
620 cmsg->cmsg_type == SCM_RIGHTS) {
621 const unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0);
622 DCHECK(payload_len % sizeof(int) == 0);
623 wire_fds = reinterpret_cast<int*>(CMSG_DATA(cmsg));
624 num_wire_fds = payload_len / 4;
625
626 if (msg.msg_flags & MSG_CTRUNC) {
627 LOG(ERROR) << "SCM_RIGHTS message was truncated"
628 << " cmsg_len:" << cmsg->cmsg_len
629 << " fd:" << pipe_;
630 for (unsigned i = 0; i < num_wire_fds; ++i)
[email protected]70eb6572010-06-23 00:37:46631 if (HANDLE_EINTR(close(wire_fds[i])) < 0)
632 PLOG(ERROR) << "close" << i;
[email protected]baf556a2009-09-04 21:34:05633 return false;
634 }
635 break;
636 }
637 }
638 if (input_overflow_fds_.empty()) {
639 fds = wire_fds;
640 num_fds = num_wire_fds;
641 } else {
642 if (num_wire_fds > 0) {
643 const size_t prev_size = input_overflow_fds_.size();
644 input_overflow_fds_.resize(prev_size + num_wire_fds);
645 memcpy(&input_overflow_fds_[prev_size], wire_fds,
646 num_wire_fds * sizeof(int));
647 }
648 fds = &input_overflow_fds_[0];
649 num_fds = input_overflow_fds_.size();
650 }
651 }
652 }
653 if (m.header()->num_fds > num_fds - fds_i)
654#endif
655 error = "Message needs unreceived descriptors";
[email protected]7135bb042009-02-12 04:05:28656 }
657
658 if (m.header()->num_fds >
[email protected]d0c0b1d2009-02-12 18:32:45659 FileDescriptorSet::MAX_DESCRIPTORS_PER_MESSAGE) {
[email protected]7135bb042009-02-12 04:05:28660 // There are too many descriptors in this message
661 error = "Message requires an excessive number of descriptors";
662 }
663
664 if (error) {
665 LOG(WARNING) << error
[email protected]526776c2009-02-07 00:39:26666 << " channel:" << this
667 << " message-type:" << m.type()
668 << " header()->num_fds:" << m.header()->num_fds
669 << " num_fds:" << num_fds
670 << " fds_i:" << fds_i;
[email protected]a89a55dd2010-04-19 14:51:13671#if defined(CHROMIUM_SELINUX)
672 LOG(WARNING) << "In the case of SELinux this can be caused when "
673 "using a --user-data-dir to which the default "
674 "policy doesn't give the renderer access to. ";
675#endif
[email protected]526776c2009-02-07 00:39:26676 // close the existing file descriptors so that we don't leak them
677 for (unsigned i = fds_i; i < num_fds; ++i)
[email protected]70eb6572010-06-23 00:37:46678 if (HANDLE_EINTR(close(fds[i])) < 0)
679 PLOG(ERROR) << "close" << i;
[email protected]526776c2009-02-07 00:39:26680 input_overflow_fds_.clear();
[email protected]7135bb042009-02-12 04:05:28681 // abort the connection
[email protected]526776c2009-02-07 00:39:26682 return false;
683 }
684
[email protected]d0c0b1d2009-02-12 18:32:45685 m.file_descriptor_set()->SetDescriptors(
686 &fds[fds_i], m.header()->num_fds);
[email protected]526776c2009-02-07 00:39:26687 fds_i += m.header()->num_fds;
688 }
[email protected]fa95fc92008-12-08 18:10:14689#ifdef IPC_MESSAGE_DEBUG_EXTRA
690 DLOG(INFO) << "received message on channel @" << this <<
691 " with type " << m.type();
692#endif
693 if (m.routing_id() == MSG_ROUTING_NONE &&
694 m.type() == HELLO_MESSAGE_TYPE) {
695 // The Hello message contains only the process id.
[email protected]baf556a2009-09-04 21:34:05696 void *iter = NULL;
697 int pid;
698 if (!m.ReadInt(&iter, &pid)) {
699 NOTREACHED();
700 }
[email protected]e39333ec2010-05-19 18:17:53701#if !defined(OS_MACOSX)
[email protected]baf556a2009-09-04 21:34:05702 if (mode_ == MODE_SERVER && !uses_fifo_) {
[email protected]e39333ec2010-05-19 18:17:53703 // On non-Mac, the Hello message from the client to the server
[email protected]baf556a2009-09-04 21:34:05704 // also contains the fd_pipe_, which will be used for all
705 // subsequent file descriptor passing.
[email protected]7ee1a44c2010-07-23 14:18:59706 DCHECK_EQ(m.file_descriptor_set()->size(), 1U);
[email protected]baf556a2009-09-04 21:34:05707 base::FileDescriptor descriptor;
708 if (!m.ReadFileDescriptor(&iter, &descriptor)) {
709 NOTREACHED();
710 }
711 fd_pipe_ = descriptor.fd;
712 CHECK(descriptor.auto_close);
713 }
714#endif
715 listener_->OnChannelConnected(pid);
[email protected]fa95fc92008-12-08 18:10:14716 } else {
717 listener_->OnMessageReceived(m);
718 }
719 p = message_tail;
720 } else {
721 // Last message is partial.
722 break;
723 }
[email protected]baf556a2009-09-04 21:34:05724 input_overflow_fds_ = std::vector<int>(&fds[fds_i], &fds[num_fds]);
725 fds_i = 0;
726 fds = &input_overflow_fds_[0];
727 num_fds = input_overflow_fds_.size();
[email protected]fa95fc92008-12-08 18:10:14728 }
729 input_overflow_buf_.assign(p, end - p);
[email protected]526776c2009-02-07 00:39:26730 input_overflow_fds_ = std::vector<int>(&fds[fds_i], &fds[num_fds]);
[email protected]fa95fc92008-12-08 18:10:14731
[email protected]afb4bad2009-02-12 02:39:31732 // When the input data buffer is empty, the overflow fds should be too. If
733 // this is not the case, we probably have a rogue renderer which is trying
734 // to fill our descriptor table.
735 if (input_overflow_buf_.empty() && !input_overflow_fds_.empty()) {
736 // We close these descriptors in Close()
737 return false;
738 }
739
[email protected]fa95fc92008-12-08 18:10:14740 bytes_read = 0; // Get more data.
741 }
742
743 return true;
744}
745
[email protected]514411fc2008-12-10 22:28:11746bool Channel::ChannelImpl::ProcessOutgoingMessages() {
[email protected]fa95fc92008-12-08 18:10:14747 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
748 // no connection?
[email protected]e45e6c02008-12-15 22:02:17749 is_blocked_on_write_ = false;
[email protected]fa95fc92008-12-08 18:10:14750
[email protected]baf556a2009-09-04 21:34:05751 if (output_queue_.empty()) {
[email protected]fa95fc92008-12-08 18:10:14752 return true;
[email protected]baf556a2009-09-04 21:34:05753 }
[email protected]fa95fc92008-12-08 18:10:14754
[email protected]baf556a2009-09-04 21:34:05755 if (pipe_ == -1) {
[email protected]fa95fc92008-12-08 18:10:14756 return false;
[email protected]baf556a2009-09-04 21:34:05757 }
[email protected]fa95fc92008-12-08 18:10:14758
[email protected]fa95fc92008-12-08 18:10:14759 // Write out all the messages we can till the write blocks or there are no
760 // more outgoing messages.
761 while (!output_queue_.empty()) {
762 Message* msg = output_queue_.front();
763
[email protected]e39333ec2010-05-19 18:17:53764#if !defined(OS_MACOSX)
[email protected]baf556a2009-09-04 21:34:05765 scoped_ptr<Message> hello;
766 if (remote_fd_pipe_ != -1 &&
767 msg->routing_id() == MSG_ROUTING_NONE &&
768 msg->type() == HELLO_MESSAGE_TYPE) {
769 hello.reset(new Message(MSG_ROUTING_NONE,
770 HELLO_MESSAGE_TYPE,
771 IPC::Message::PRIORITY_NORMAL));
772 void* iter = NULL;
773 int pid;
774 if (!msg->ReadInt(&iter, &pid) ||
775 !hello->WriteInt(pid)) {
776 NOTREACHED();
777 }
778 DCHECK_EQ(hello->size(), msg->size());
779 if (!hello->WriteFileDescriptor(base::FileDescriptor(remote_fd_pipe_,
780 false))) {
781 NOTREACHED();
782 }
783 msg = hello.get();
[email protected]7ee1a44c2010-07-23 14:18:59784 DCHECK_EQ(msg->file_descriptor_set()->size(), 1U);
[email protected]baf556a2009-09-04 21:34:05785 }
786#endif
787
[email protected]fa95fc92008-12-08 18:10:14788 size_t amt_to_write = msg->size() - message_send_bytes_written_;
[email protected]3d1b6662009-01-29 17:03:11789 DCHECK(amt_to_write != 0);
[email protected]baf556a2009-09-04 21:34:05790 const char* out_bytes = reinterpret_cast<const char*>(msg->data()) +
[email protected]fa95fc92008-12-08 18:10:14791 message_send_bytes_written_;
[email protected]526776c2009-02-07 00:39:26792
[email protected]157c61b2009-05-01 21:37:31793 struct msghdr msgh = {0};
794 struct iovec iov = {const_cast<char*>(out_bytes), amt_to_write};
795 msgh.msg_iov = &iov;
796 msgh.msg_iovlen = 1;
797 char buf[CMSG_SPACE(
798 sizeof(int[FileDescriptorSet::MAX_DESCRIPTORS_PER_MESSAGE]))];
[email protected]526776c2009-02-07 00:39:26799
[email protected]baf556a2009-09-04 21:34:05800 ssize_t bytes_written = 1;
801 int fd_written = -1;
802
[email protected]157c61b2009-05-01 21:37:31803 if (message_send_bytes_written_ == 0 &&
804 !msg->file_descriptor_set()->empty()) {
805 // This is the first chunk of a message which has descriptors to send
806 struct cmsghdr *cmsg;
807 const unsigned num_fds = msg->file_descriptor_set()->size();
[email protected]526776c2009-02-07 00:39:26808
[email protected]157c61b2009-05-01 21:37:31809 DCHECK_LE(num_fds, FileDescriptorSet::MAX_DESCRIPTORS_PER_MESSAGE);
[email protected]aac449e2010-06-10 21:39:04810 if (msg->file_descriptor_set()->ContainsDirectoryDescriptor()) {
811 LOG(FATAL) << "Panic: attempting to transport directory descriptor over"
812 " IPC. Aborting to maintain sandbox isolation.";
813 // If you have hit this then something tried to send a file descriptor
814 // to a directory over an IPC channel. Since IPC channels span
815 // sandboxes this is very bad: the receiving process can use openat
816 // with ".." elements in the path in order to reach the real
817 // filesystem.
818 }
[email protected]526776c2009-02-07 00:39:26819
[email protected]157c61b2009-05-01 21:37:31820 msgh.msg_control = buf;
821 msgh.msg_controllen = CMSG_SPACE(sizeof(int) * num_fds);
822 cmsg = CMSG_FIRSTHDR(&msgh);
823 cmsg->cmsg_level = SOL_SOCKET;
824 cmsg->cmsg_type = SCM_RIGHTS;
825 cmsg->cmsg_len = CMSG_LEN(sizeof(int) * num_fds);
826 msg->file_descriptor_set()->GetDescriptors(
827 reinterpret_cast<int*>(CMSG_DATA(cmsg)));
828 msgh.msg_controllen = cmsg->cmsg_len;
[email protected]526776c2009-02-07 00:39:26829
[email protected]168ae922009-12-04 18:08:45830 // DCHECK_LE above already checks that
831 // num_fds < MAX_DESCRIPTORS_PER_MESSAGE so no danger of overflow.
832 msg->header()->num_fds = static_cast<uint16>(num_fds);
[email protected]baf556a2009-09-04 21:34:05833
[email protected]e39333ec2010-05-19 18:17:53834#if !defined(OS_MACOSX)
[email protected]baf556a2009-09-04 21:34:05835 if (!uses_fifo_ &&
836 (msg->routing_id() != MSG_ROUTING_NONE ||
837 msg->type() != HELLO_MESSAGE_TYPE)) {
838 // Only the Hello message sends the file descriptor with the message.
839 // Subsequently, we can send file descriptors on the dedicated
840 // fd_pipe_ which makes Seccomp sandbox operation more efficient.
841 struct iovec fd_pipe_iov = { const_cast<char *>(""), 1 };
842 msgh.msg_iov = &fd_pipe_iov;
843 fd_written = fd_pipe_;
844 bytes_written = HANDLE_EINTR(sendmsg(fd_pipe_, &msgh, MSG_DONTWAIT));
845 msgh.msg_iov = &iov;
846 msgh.msg_controllen = 0;
847 if (bytes_written > 0) {
848 msg->file_descriptor_set()->CommitAll();
849 }
850 }
851#endif
[email protected]157c61b2009-05-01 21:37:31852 }
853
[email protected]baf556a2009-09-04 21:34:05854 if (bytes_written == 1) {
855 fd_written = pipe_;
[email protected]e39333ec2010-05-19 18:17:53856#if !defined(OS_MACOSX)
[email protected]baf556a2009-09-04 21:34:05857 if (mode_ != MODE_SERVER && !uses_fifo_ &&
858 msg->routing_id() == MSG_ROUTING_NONE &&
859 msg->type() == HELLO_MESSAGE_TYPE) {
[email protected]7ee1a44c2010-07-23 14:18:59860 DCHECK_EQ(msg->file_descriptor_set()->size(), 1U);
[email protected]baf556a2009-09-04 21:34:05861 }
862 if (!uses_fifo_ && !msgh.msg_controllen) {
863 bytes_written = HANDLE_EINTR(write(pipe_, out_bytes, amt_to_write));
864 } else
865#endif
866 {
867 bytes_written = HANDLE_EINTR(sendmsg(pipe_, &msgh, MSG_DONTWAIT));
868 }
869 }
[email protected]157c61b2009-05-01 21:37:31870 if (bytes_written > 0)
871 msg->file_descriptor_set()->CommitAll();
[email protected]fa95fc92008-12-08 18:10:14872
[email protected]86c3d9e2009-12-08 14:48:08873 if (bytes_written < 0 && !SocketWriteErrorIsRecoverable()) {
[email protected]cb38c0b22009-05-27 18:29:48874#if defined(OS_MACOSX)
875 // On OSX writing to a pipe with no listener returns EPERM.
876 if (errno == EPERM) {
877 Close();
878 return false;
879 }
880#endif // OS_MACOSX
[email protected]7bf54f5e2009-10-23 01:48:21881 if (errno == EPIPE) {
882 Close();
883 return false;
884 }
[email protected]780ae942009-12-03 13:35:46885 PLOG(ERROR) << "pipe error on "
886 << fd_written
887 << " Currently writing message of size:"
[email protected]86c3d9e2009-12-08 14:48:08888 << msg->size();
[email protected]fa95fc92008-12-08 18:10:14889 return false;
890 }
891
892 if (static_cast<size_t>(bytes_written) != amt_to_write) {
[email protected]3d1b6662009-01-29 17:03:11893 if (bytes_written > 0) {
894 // If write() fails with EAGAIN then bytes_written will be -1.
895 message_send_bytes_written_ += bytes_written;
896 }
[email protected]fa95fc92008-12-08 18:10:14897
898 // Tell libevent to call us back once things are unblocked.
[email protected]e45e6c02008-12-15 22:02:17899 is_blocked_on_write_ = true;
900 MessageLoopForIO::current()->WatchFileDescriptor(
901 pipe_,
902 false, // One shot
903 MessageLoopForIO::WATCH_WRITE,
904 &write_watcher_,
905 this);
[email protected]3d1b6662009-01-29 17:03:11906 return true;
[email protected]fa95fc92008-12-08 18:10:14907 } else {
908 message_send_bytes_written_ = 0;
909
910 // Message sent OK!
911#ifdef IPC_MESSAGE_DEBUG_EXTRA
912 DLOG(INFO) << "sent message @" << msg << " on channel @" << this <<
913 " with type " << msg->type();
914#endif
[email protected]baf556a2009-09-04 21:34:05915 delete output_queue_.front();
[email protected]fa95fc92008-12-08 18:10:14916 output_queue_.pop();
[email protected]fa95fc92008-12-08 18:10:14917 }
918 }
919 return true;
920}
921
[email protected]514411fc2008-12-10 22:28:11922bool Channel::ChannelImpl::Send(Message* message) {
[email protected]fa95fc92008-12-08 18:10:14923#ifdef IPC_MESSAGE_DEBUG_EXTRA
924 DLOG(INFO) << "sending message @" << message << " on channel @" << this
925 << " with type " << message->type()
926 << " (" << output_queue_.size() << " in queue)";
927#endif
928
[email protected]4c2c1db2009-03-20 20:56:55929#ifdef IPC_MESSAGE_LOG_ENABLED
[email protected]9a3a293b2009-06-04 22:28:16930 Logging::current()->OnSendMessage(message, "");
[email protected]4c2c1db2009-03-20 20:56:55931#endif
[email protected]fa95fc92008-12-08 18:10:14932
933 output_queue_.push(message);
934 if (!waiting_connect_) {
[email protected]e45e6c02008-12-15 22:02:17935 if (!is_blocked_on_write_) {
[email protected]fa95fc92008-12-08 18:10:14936 if (!ProcessOutgoingMessages())
937 return false;
938 }
939 }
940
941 return true;
942}
943
[email protected]cc8f1462009-06-12 17:36:55944int Channel::ChannelImpl::GetClientFileDescriptor() const {
945 return client_pipe_;
[email protected]df3c1ca12008-12-19 21:37:01946}
947
[email protected]fa95fc92008-12-08 18:10:14948// Called by libevent when we can read from th pipe without blocking.
[email protected]e45e6c02008-12-15 22:02:17949void Channel::ChannelImpl::OnFileCanReadWithoutBlocking(int fd) {
[email protected]fa95fc92008-12-08 18:10:14950 bool send_server_hello_msg = false;
951 if (waiting_connect_ && mode_ == MODE_SERVER) {
[email protected]baf556a2009-09-04 21:34:05952 if (uses_fifo_) {
953 if (!ServerAcceptFifoConnection(server_listen_pipe_, &pipe_)) {
954 Close();
955 }
[email protected]df3c1ca12008-12-19 21:37:01956
[email protected]baf556a2009-09-04 21:34:05957 // No need to watch the listening socket any longer since only one client
958 // can connect. So unregister with libevent.
959 server_listen_connection_watcher_.StopWatchingFileDescriptor();
960
961 // Start watching our end of the socket.
962 MessageLoopForIO::current()->WatchFileDescriptor(
963 pipe_,
964 true,
965 MessageLoopForIO::WATCH_READ,
966 &read_watcher_,
967 this);
968
969 waiting_connect_ = false;
970 } else {
971 // In the case of a socketpair() the server starts listening on its end
972 // of the pipe in Connect().
973 waiting_connect_ = false;
[email protected]fa95fc92008-12-08 18:10:14974 }
[email protected]fa95fc92008-12-08 18:10:14975 send_server_hello_msg = true;
976 }
977
978 if (!waiting_connect_ && fd == pipe_) {
979 if (!ProcessIncomingMessages()) {
980 Close();
981 listener_->OnChannelError();
[email protected]9808ca42009-09-25 23:35:39982 // The OnChannelError() call may delete this, so we need to exit now.
983 return;
[email protected]fa95fc92008-12-08 18:10:14984 }
985 }
986
987 // If we're a server and handshaking, then we want to make sure that we
988 // only send our handshake message after we've processed the client's.
989 // This gives us a chance to kill the client if the incoming handshake
990 // is invalid.
991 if (send_server_hello_msg) {
992 ProcessOutgoingMessages();
993 }
994}
995
996// Called by libevent when we can write to the pipe without blocking.
[email protected]e45e6c02008-12-15 22:02:17997void Channel::ChannelImpl::OnFileCanWriteWithoutBlocking(int fd) {
[email protected]fa95fc92008-12-08 18:10:14998 if (!ProcessOutgoingMessages()) {
999 Close();
1000 listener_->OnChannelError();
1001 }
1002}
1003
[email protected]514411fc2008-12-10 22:28:111004void Channel::ChannelImpl::Close() {
[email protected]fa95fc92008-12-08 18:10:141005 // Close can be called multiple time, so we need to make sure we're
1006 // idempotent.
1007
1008 // Unregister libevent for the listening socket and close it.
[email protected]e45e6c02008-12-15 22:02:171009 server_listen_connection_watcher_.StopWatchingFileDescriptor();
[email protected]fa95fc92008-12-08 18:10:141010
1011 if (server_listen_pipe_ != -1) {
[email protected]70eb6572010-06-23 00:37:461012 if (HANDLE_EINTR(close(server_listen_pipe_)) < 0)
1013 PLOG(ERROR) << "close";
[email protected]fa95fc92008-12-08 18:10:141014 server_listen_pipe_ = -1;
1015 }
1016
1017 // Unregister libevent for the FIFO and close it.
[email protected]e45e6c02008-12-15 22:02:171018 read_watcher_.StopWatchingFileDescriptor();
1019 write_watcher_.StopWatchingFileDescriptor();
[email protected]fa95fc92008-12-08 18:10:141020 if (pipe_ != -1) {
[email protected]70eb6572010-06-23 00:37:461021 if (HANDLE_EINTR(close(pipe_)) < 0)
1022 PLOG(ERROR) << "close";
[email protected]fa95fc92008-12-08 18:10:141023 pipe_ = -1;
1024 }
[email protected]df3c1ca12008-12-19 21:37:011025 if (client_pipe_ != -1) {
[email protected]f0ef2da2009-07-08 01:26:341026 Singleton<PipeMap>()->RemoveAndClose(pipe_name_);
[email protected]df3c1ca12008-12-19 21:37:011027 client_pipe_ = -1;
1028 }
[email protected]e39333ec2010-05-19 18:17:531029#if !defined(OS_MACOSX)
[email protected]baf556a2009-09-04 21:34:051030 if (fd_pipe_ != -1) {
[email protected]70eb6572010-06-23 00:37:461031 if (HANDLE_EINTR(close(fd_pipe_)) < 0)
1032 PLOG(ERROR) << "close";
[email protected]baf556a2009-09-04 21:34:051033 fd_pipe_ = -1;
1034 }
1035 if (remote_fd_pipe_ != -1) {
[email protected]70eb6572010-06-23 00:37:461036 if (HANDLE_EINTR(close(remote_fd_pipe_)) < 0)
1037 PLOG(ERROR) << "close";
[email protected]baf556a2009-09-04 21:34:051038 remote_fd_pipe_ = -1;
1039 }
1040#endif
[email protected]fa95fc92008-12-08 18:10:141041
[email protected]5f594c02009-05-01 22:37:591042 if (uses_fifo_) {
1043 // Unlink the FIFO
1044 unlink(pipe_name_.c_str());
1045 }
[email protected]fa95fc92008-12-08 18:10:141046
1047 while (!output_queue_.empty()) {
1048 Message* m = output_queue_.front();
1049 output_queue_.pop();
1050 delete m;
1051 }
[email protected]526776c2009-02-07 00:39:261052
1053 // Close any outstanding, received file descriptors
1054 for (std::vector<int>::iterator
1055 i = input_overflow_fds_.begin(); i != input_overflow_fds_.end(); ++i) {
[email protected]70eb6572010-06-23 00:37:461056 if (HANDLE_EINTR(close(*i)) < 0)
1057 PLOG(ERROR) << "close";
[email protected]526776c2009-02-07 00:39:261058 }
1059 input_overflow_fds_.clear();
[email protected]fa95fc92008-12-08 18:10:141060}
1061
[email protected]514411fc2008-12-10 22:28:111062//------------------------------------------------------------------------------
1063// Channel's methods simply call through to ChannelImpl.
[email protected]9a3a293b2009-06-04 22:28:161064Channel::Channel(const std::string& channel_id, Mode mode,
[email protected]514411fc2008-12-10 22:28:111065 Listener* listener)
1066 : channel_impl_(new ChannelImpl(channel_id, mode, listener)) {
1067}
1068
1069Channel::~Channel() {
1070 delete channel_impl_;
1071}
1072
1073bool Channel::Connect() {
1074 return channel_impl_->Connect();
1075}
1076
1077void Channel::Close() {
1078 channel_impl_->Close();
1079}
1080
1081void Channel::set_listener(Listener* listener) {
1082 channel_impl_->set_listener(listener);
1083}
1084
1085bool Channel::Send(Message* message) {
1086 return channel_impl_->Send(message);
1087}
1088
[email protected]cc8f1462009-06-12 17:36:551089int Channel::GetClientFileDescriptor() const {
1090 return channel_impl_->GetClientFileDescriptor();
[email protected]df3c1ca12008-12-19 21:37:011091}
1092
[email protected]d4651ff2008-12-02 16:51:581093} // namespace IPC