Roll src/third_party/WebKit d9c6159:8139f33 (svn 201974:201975)
[chromium-blink-merge.git] / ipc / ipc_channel_posix.cc
bloba3b5ae1e52c3f5d0d3e9d0b01f15d3abed0aed79
1 // Copyright (c) 2012 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.
5 #include "ipc/ipc_channel_posix.h"
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <stddef.h>
10 #include <stdint.h>
11 #include <sys/socket.h>
12 #include <sys/stat.h>
13 #include <sys/types.h>
14 #include <unistd.h>
16 #if defined(OS_OPENBSD)
17 #include <sys/uio.h>
18 #endif
20 #if !defined(OS_NACL_NONSFI)
21 #include <sys/un.h>
22 #endif
24 #include <map>
25 #include <string>
27 #include "base/command_line.h"
28 #include "base/files/file_path.h"
29 #include "base/files/file_util.h"
30 #include "base/location.h"
31 #include "base/logging.h"
32 #include "base/memory/scoped_ptr.h"
33 #include "base/memory/singleton.h"
34 #include "base/posix/eintr_wrapper.h"
35 #include "base/posix/global_descriptors.h"
36 #include "base/process/process_handle.h"
37 #include "base/rand_util.h"
38 #include "base/stl_util.h"
39 #include "base/strings/string_util.h"
40 #include "base/synchronization/lock.h"
41 #include "ipc/ipc_descriptors.h"
42 #include "ipc/ipc_listener.h"
43 #include "ipc/ipc_logging.h"
44 #include "ipc/ipc_message_attachment_set.h"
45 #include "ipc/ipc_message_utils.h"
46 #include "ipc/ipc_platform_file_attachment_posix.h"
47 #include "ipc/ipc_switches.h"
48 #include "ipc/unix_domain_socket_util.h"
50 namespace IPC {
52 // IPC channels on Windows use named pipes (CreateNamedPipe()) with
53 // channel ids as the pipe names. Channels on POSIX use sockets as
54 // pipes These don't quite line up.
56 // When creating a child subprocess we use a socket pair and the parent side of
57 // the fork arranges it such that the initial control channel ends up on the
58 // magic file descriptor kPrimaryIPCChannel in the child. Future
59 // connections (file descriptors) can then be passed via that
60 // connection via sendmsg().
62 // A POSIX IPC channel can also be set up as a server for a bound UNIX domain
63 // socket, and will handle multiple connect and disconnect sequences. Currently
64 // it is limited to one connection at a time.
66 //------------------------------------------------------------------------------
67 namespace {
69 // The PipeMap class works around this quirk related to unit tests:
71 // When running as a server, we install the client socket in a
72 // specific file descriptor number (@kPrimaryIPCChannel). However, we
73 // also have to support the case where we are running unittests in the
74 // same process. (We do not support forking without execing.)
76 // Case 1: normal running
77 // The IPC server object will install a mapping in PipeMap from the
78 // name which it was given to the client pipe. When forking the client, the
79 // GetClientFileDescriptorMapping will ensure that the socket is installed in
80 // the magic slot (@kPrimaryIPCChannel). The client will search for the
81 // mapping, but it won't find any since we are in a new process. Thus the
82 // magic fd number is returned. Once the client connects, the server will
83 // close its copy of the client socket and remove the mapping.
85 // Case 2: unittests - client and server in the same process
86 // The IPC server will install a mapping as before. The client will search
87 // for a mapping and find out. It duplicates the file descriptor and
88 // connects. Once the client connects, the server will close the original
89 // copy of the client socket and remove the mapping. Thus, when the client
90 // object closes, it will close the only remaining copy of the client socket
91 // in the fd table and the server will see EOF on its side.
93 // TODO(port): a client process cannot connect to multiple IPC channels with
94 // this scheme.
96 class PipeMap {
97 public:
98 static PipeMap* GetInstance() {
99 return Singleton<PipeMap>::get();
102 ~PipeMap() {
103 // Shouldn't have left over pipes.
104 DCHECK(map_.empty());
107 // Lookup a given channel id. Return -1 if not found.
108 int Lookup(const std::string& channel_id) {
109 base::AutoLock locked(lock_);
111 ChannelToFDMap::const_iterator i = map_.find(channel_id);
112 if (i == map_.end())
113 return -1;
114 return i->second;
117 // Remove the mapping for the given channel id. No error is signaled if the
118 // channel_id doesn't exist
119 void Remove(const std::string& channel_id) {
120 base::AutoLock locked(lock_);
121 map_.erase(channel_id);
124 // Insert a mapping from @channel_id to @fd. It's a fatal error to insert a
125 // mapping if one already exists for the given channel_id
126 void Insert(const std::string& channel_id, int fd) {
127 base::AutoLock locked(lock_);
128 DCHECK_NE(-1, fd);
130 ChannelToFDMap::const_iterator i = map_.find(channel_id);
131 CHECK(i == map_.end()) << "Creating second IPC server (fd " << fd << ") "
132 << "for '" << channel_id << "' while first "
133 << "(fd " << i->second << ") still exists";
134 map_[channel_id] = fd;
137 private:
138 base::Lock lock_;
139 typedef std::map<std::string, int> ChannelToFDMap;
140 ChannelToFDMap map_;
142 friend struct DefaultSingletonTraits<PipeMap>;
143 #if defined(OS_ANDROID)
144 friend void ::IPC::Channel::NotifyProcessForkedForTesting();
145 #endif
148 //------------------------------------------------------------------------------
150 bool SocketWriteErrorIsRecoverable() {
151 #if defined(OS_MACOSX)
152 // On OS X if sendmsg() is trying to send fds between processes and there
153 // isn't enough room in the output buffer to send the fd structure over
154 // atomically then EMSGSIZE is returned.
156 // EMSGSIZE presents a problem since the system APIs can only call us when
157 // there's room in the socket buffer and not when there is "enough" room.
159 // The current behavior is to return to the event loop when EMSGSIZE is
160 // received and hopefull service another FD. This is however still
161 // technically a busy wait since the event loop will call us right back until
162 // the receiver has read enough data to allow passing the FD over atomically.
163 return errno == EAGAIN || errno == EMSGSIZE;
164 #else
165 return errno == EAGAIN;
166 #endif // OS_MACOSX
169 } // namespace
171 #if defined(OS_ANDROID)
172 // When we fork for simple tests on Android, we can't 'exec', so we need to
173 // reset these entries manually to get the expected testing behavior.
174 void Channel::NotifyProcessForkedForTesting() {
175 PipeMap::GetInstance()->map_.clear();
177 #endif
179 //------------------------------------------------------------------------------
181 #if defined(OS_LINUX)
182 int ChannelPosix::global_pid_ = 0;
183 #endif // OS_LINUX
185 ChannelPosix::ChannelPosix(const IPC::ChannelHandle& channel_handle,
186 Mode mode,
187 Listener* listener,
188 AttachmentBroker* broker)
189 : ChannelReader(listener),
190 mode_(mode),
191 peer_pid_(base::kNullProcessId),
192 is_blocked_on_write_(false),
193 waiting_connect_(true),
194 message_send_bytes_written_(0),
195 pipe_name_(channel_handle.name),
196 in_dtor_(false),
197 must_unlink_(false),
198 broker_(broker) {
199 if (!CreatePipe(channel_handle)) {
200 // The pipe may have been closed already.
201 const char *modestr = (mode_ & MODE_SERVER_FLAG) ? "server" : "client";
202 LOG(WARNING) << "Unable to create pipe named \"" << channel_handle.name
203 << "\" in " << modestr << " mode";
207 ChannelPosix::~ChannelPosix() {
208 in_dtor_ = true;
209 Close();
212 bool SocketPair(int* fd1, int* fd2) {
213 int pipe_fds[2];
214 if (socketpair(AF_UNIX, SOCK_STREAM, 0, pipe_fds) != 0) {
215 PLOG(ERROR) << "socketpair()";
216 return false;
219 // Set both ends to be non-blocking.
220 if (fcntl(pipe_fds[0], F_SETFL, O_NONBLOCK) == -1 ||
221 fcntl(pipe_fds[1], F_SETFL, O_NONBLOCK) == -1) {
222 PLOG(ERROR) << "fcntl(O_NONBLOCK)";
223 if (IGNORE_EINTR(close(pipe_fds[0])) < 0)
224 PLOG(ERROR) << "close";
225 if (IGNORE_EINTR(close(pipe_fds[1])) < 0)
226 PLOG(ERROR) << "close";
227 return false;
230 *fd1 = pipe_fds[0];
231 *fd2 = pipe_fds[1];
233 return true;
236 bool ChannelPosix::CreatePipe(
237 const IPC::ChannelHandle& channel_handle) {
238 DCHECK(!server_listen_pipe_.is_valid() && !pipe_.is_valid());
240 // Four possible cases:
241 // 1) It's a channel wrapping a pipe that is given to us.
242 // 2) It's for a named channel, so we create it.
243 // 3) It's for a client that we implement ourself. This is used
244 // in single-process unittesting.
245 // 4) It's the initial IPC channel:
246 // 4a) Client side: Pull the pipe out of the GlobalDescriptors set.
247 // 4b) Server side: create the pipe.
249 base::ScopedFD local_pipe;
250 if (channel_handle.socket.fd != -1) {
251 // Case 1 from comment above.
252 local_pipe.reset(channel_handle.socket.fd);
253 } else if (mode_ & MODE_NAMED_FLAG) {
254 #if defined(OS_NACL_NONSFI)
255 LOG(FATAL)
256 << "IPC channels in nacl_helper_nonsfi should not be in NAMED mode.";
257 #else
258 // Case 2 from comment above.
259 int local_pipe_fd = -1;
261 if (mode_ & MODE_SERVER_FLAG) {
262 if (!CreateServerUnixDomainSocket(base::FilePath(pipe_name_),
263 &local_pipe_fd)) {
264 return false;
267 must_unlink_ = true;
268 } else if (mode_ & MODE_CLIENT_FLAG) {
269 if (!CreateClientUnixDomainSocket(base::FilePath(pipe_name_),
270 &local_pipe_fd)) {
271 return false;
273 } else {
274 LOG(ERROR) << "Bad mode: " << mode_;
275 return false;
278 local_pipe.reset(local_pipe_fd);
279 #endif // !defined(OS_NACL_NONSFI)
280 } else {
281 local_pipe.reset(PipeMap::GetInstance()->Lookup(pipe_name_));
282 if (mode_ & MODE_CLIENT_FLAG) {
283 if (local_pipe.is_valid()) {
284 // Case 3 from comment above.
285 // We only allow one connection.
286 local_pipe.reset(HANDLE_EINTR(dup(local_pipe.release())));
287 PipeMap::GetInstance()->Remove(pipe_name_);
288 } else {
289 // Case 4a from comment above.
290 // Guard against inappropriate reuse of the initial IPC channel. If
291 // an IPC channel closes and someone attempts to reuse it by name, the
292 // initial channel must not be recycled here. http://crbug.com/26754.
293 static bool used_initial_channel = false;
294 if (used_initial_channel) {
295 LOG(FATAL) << "Denying attempt to reuse initial IPC channel for "
296 << pipe_name_;
297 return false;
299 used_initial_channel = true;
301 local_pipe.reset(
302 base::GlobalDescriptors::GetInstance()->Get(kPrimaryIPCChannel));
304 } else if (mode_ & MODE_SERVER_FLAG) {
305 // Case 4b from comment above.
306 if (local_pipe.is_valid()) {
307 LOG(ERROR) << "Server already exists for " << pipe_name_;
308 // This is a client side pipe registered by other server and
309 // shouldn't be closed.
310 ignore_result(local_pipe.release());
311 return false;
313 base::AutoLock lock(client_pipe_lock_);
314 int local_pipe_fd = -1, client_pipe_fd = -1;
315 if (!SocketPair(&local_pipe_fd, &client_pipe_fd))
316 return false;
317 local_pipe.reset(local_pipe_fd);
318 client_pipe_.reset(client_pipe_fd);
319 PipeMap::GetInstance()->Insert(pipe_name_, client_pipe_fd);
320 } else {
321 LOG(ERROR) << "Bad mode: " << mode_;
322 return false;
326 if ((mode_ & MODE_SERVER_FLAG) && (mode_ & MODE_NAMED_FLAG)) {
327 #if defined(OS_NACL_NONSFI)
328 LOG(FATAL) << "IPC channels in nacl_helper_nonsfi "
329 << "should not be in NAMED or SERVER mode.";
330 #else
331 server_listen_pipe_.reset(local_pipe.release());
332 #endif
333 } else {
334 pipe_.reset(local_pipe.release());
336 return true;
339 bool ChannelPosix::Connect() {
340 if (!server_listen_pipe_.is_valid() && !pipe_.is_valid()) {
341 DLOG(WARNING) << "Channel creation failed: " << pipe_name_;
342 return false;
345 bool did_connect = true;
346 if (server_listen_pipe_.is_valid()) {
347 #if defined(OS_NACL_NONSFI)
348 LOG(FATAL) << "IPC channels in nacl_helper_nonsfi "
349 << "should always be in client mode.";
350 #else
351 // Watch the pipe for connections, and turn any connections into
352 // active sockets.
353 base::MessageLoopForIO::current()->WatchFileDescriptor(
354 server_listen_pipe_.get(),
355 true,
356 base::MessageLoopForIO::WATCH_READ,
357 &server_listen_connection_watcher_,
358 this);
359 #endif
360 } else {
361 did_connect = AcceptConnection();
363 return did_connect;
366 void ChannelPosix::CloseFileDescriptors(Message* msg) {
367 #if defined(OS_MACOSX)
368 // There is a bug on OSX which makes it dangerous to close
369 // a file descriptor while it is in transit. So instead we
370 // store the file descriptor in a set and send a message to
371 // the recipient, which is queued AFTER the message that
372 // sent the FD. The recipient will reply to the message,
373 // letting us know that it is now safe to close the file
374 // descriptor. For more information, see:
375 // http://crbug.com/298276
376 std::vector<int> to_close;
377 msg->attachment_set()->ReleaseFDsToClose(&to_close);
378 for (size_t i = 0; i < to_close.size(); i++) {
379 fds_to_close_.insert(to_close[i]);
380 QueueCloseFDMessage(to_close[i], 2);
382 #else
383 msg->attachment_set()->CommitAll();
384 #endif
387 bool ChannelPosix::ProcessOutgoingMessages() {
388 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
389 // no connection?
390 if (output_queue_.empty())
391 return true;
393 if (!pipe_.is_valid())
394 return false;
396 // Write out all the messages we can till the write blocks or there are no
397 // more outgoing messages.
398 while (!output_queue_.empty()) {
399 Message* msg = output_queue_.front();
401 size_t amt_to_write = msg->size() - message_send_bytes_written_;
402 DCHECK_NE(0U, amt_to_write);
403 const char* out_bytes = reinterpret_cast<const char*>(msg->data()) +
404 message_send_bytes_written_;
406 struct msghdr msgh = {0};
407 struct iovec iov = {const_cast<char*>(out_bytes), amt_to_write};
408 msgh.msg_iov = &iov;
409 msgh.msg_iovlen = 1;
410 char buf[CMSG_SPACE(sizeof(int) *
411 MessageAttachmentSet::kMaxDescriptorsPerMessage)];
413 ssize_t bytes_written = 1;
414 int fd_written = -1;
416 if (message_send_bytes_written_ == 0 && !msg->attachment_set()->empty()) {
417 // This is the first chunk of a message which has descriptors to send
418 struct cmsghdr *cmsg;
419 const unsigned num_fds = msg->attachment_set()->size();
421 DCHECK(num_fds <= MessageAttachmentSet::kMaxDescriptorsPerMessage);
422 if (msg->attachment_set()->ContainsDirectoryDescriptor()) {
423 LOG(FATAL) << "Panic: attempting to transport directory descriptor over"
424 " IPC. Aborting to maintain sandbox isolation.";
425 // If you have hit this then something tried to send a file descriptor
426 // to a directory over an IPC channel. Since IPC channels span
427 // sandboxes this is very bad: the receiving process can use openat
428 // with ".." elements in the path in order to reach the real
429 // filesystem.
432 msgh.msg_control = buf;
433 msgh.msg_controllen = CMSG_SPACE(sizeof(int) * num_fds);
434 cmsg = CMSG_FIRSTHDR(&msgh);
435 cmsg->cmsg_level = SOL_SOCKET;
436 cmsg->cmsg_type = SCM_RIGHTS;
437 cmsg->cmsg_len = CMSG_LEN(sizeof(int) * num_fds);
438 msg->attachment_set()->PeekDescriptors(
439 reinterpret_cast<int*>(CMSG_DATA(cmsg)));
440 msgh.msg_controllen = cmsg->cmsg_len;
442 // DCHECK_LE above already checks that
443 // num_fds < kMaxDescriptorsPerMessage so no danger of overflow.
444 msg->header()->num_fds = static_cast<uint16_t>(num_fds);
447 if (bytes_written == 1) {
448 fd_written = pipe_.get();
449 bytes_written = HANDLE_EINTR(sendmsg(pipe_.get(), &msgh, MSG_DONTWAIT));
451 if (bytes_written > 0)
452 CloseFileDescriptors(msg);
454 if (bytes_written < 0 && !SocketWriteErrorIsRecoverable()) {
455 // We can't close the pipe here, because calling OnChannelError
456 // may destroy this object, and that would be bad if we are
457 // called from Send(). Instead, we return false and hope the
458 // caller will close the pipe. If they do not, the pipe will
459 // still be closed next time OnFileCanReadWithoutBlocking is
460 // called.
461 #if defined(OS_MACOSX)
462 // On OSX writing to a pipe with no listener returns EPERM.
463 if (errno == EPERM) {
464 return false;
466 #endif // OS_MACOSX
467 if (errno == EPIPE) {
468 return false;
470 PLOG(ERROR) << "pipe error on "
471 << fd_written
472 << " Currently writing message of size: "
473 << msg->size();
474 return false;
477 if (static_cast<size_t>(bytes_written) != amt_to_write) {
478 if (bytes_written > 0) {
479 // If write() fails with EAGAIN then bytes_written will be -1.
480 message_send_bytes_written_ += bytes_written;
483 // Tell libevent to call us back once things are unblocked.
484 is_blocked_on_write_ = true;
485 base::MessageLoopForIO::current()->WatchFileDescriptor(
486 pipe_.get(),
487 false, // One shot
488 base::MessageLoopForIO::WATCH_WRITE,
489 &write_watcher_,
490 this);
491 return true;
492 } else {
493 message_send_bytes_written_ = 0;
495 // Message sent OK!
496 DVLOG(2) << "sent message @" << msg << " on channel @" << this
497 << " with type " << msg->type() << " on fd " << pipe_.get();
498 delete output_queue_.front();
499 output_queue_.pop();
502 return true;
505 bool ChannelPosix::Send(Message* message) {
506 DCHECK(!message->HasMojoHandles());
507 DVLOG(2) << "sending message @" << message << " on channel @" << this
508 << " with type " << message->type()
509 << " (" << output_queue_.size() << " in queue)";
511 #ifdef IPC_MESSAGE_LOG_ENABLED
512 Logging::GetInstance()->OnSendMessage(message, "");
513 #endif // IPC_MESSAGE_LOG_ENABLED
515 TRACE_EVENT_WITH_FLOW0(TRACE_DISABLED_BY_DEFAULT("ipc.flow"),
516 "ChannelPosix::Send",
517 message->flags(),
518 TRACE_EVENT_FLAG_FLOW_OUT);
519 output_queue_.push(message);
520 if (!is_blocked_on_write_ && !waiting_connect_) {
521 return ProcessOutgoingMessages();
524 return true;
527 AttachmentBroker* ChannelPosix::GetAttachmentBroker() {
528 return broker_;
531 int ChannelPosix::GetClientFileDescriptor() const {
532 base::AutoLock lock(client_pipe_lock_);
533 return client_pipe_.get();
536 base::ScopedFD ChannelPosix::TakeClientFileDescriptor() {
537 base::AutoLock lock(client_pipe_lock_);
538 if (!client_pipe_.is_valid())
539 return base::ScopedFD();
540 PipeMap::GetInstance()->Remove(pipe_name_);
541 return client_pipe_.Pass();
544 void ChannelPosix::CloseClientFileDescriptor() {
545 base::AutoLock lock(client_pipe_lock_);
546 if (!client_pipe_.is_valid())
547 return;
548 PipeMap::GetInstance()->Remove(pipe_name_);
549 client_pipe_.reset();
552 bool ChannelPosix::AcceptsConnections() const {
553 return server_listen_pipe_.is_valid();
556 bool ChannelPosix::HasAcceptedConnection() const {
557 return AcceptsConnections() && pipe_.is_valid();
560 #if !defined(OS_NACL_NONSFI)
561 // GetPeerEuid is not supported in nacl_helper_nonsfi.
562 bool ChannelPosix::GetPeerEuid(uid_t* peer_euid) const {
563 DCHECK(!(mode_ & MODE_SERVER) || HasAcceptedConnection());
564 return IPC::GetPeerEuid(pipe_.get(), peer_euid);
566 #endif
568 void ChannelPosix::ResetToAcceptingConnectionState() {
569 // Unregister libevent for the unix domain socket and close it.
570 read_watcher_.StopWatchingFileDescriptor();
571 write_watcher_.StopWatchingFileDescriptor();
572 ResetSafely(&pipe_);
574 while (!output_queue_.empty()) {
575 Message* m = output_queue_.front();
576 output_queue_.pop();
577 CloseFileDescriptors(m);
578 delete m;
581 // Close any outstanding, received file descriptors.
582 ClearInputFDs();
584 #if defined(OS_MACOSX)
585 // Clear any outstanding, sent file descriptors.
586 for (std::set<int>::iterator i = fds_to_close_.begin();
587 i != fds_to_close_.end();
588 ++i) {
589 if (IGNORE_EINTR(close(*i)) < 0)
590 PLOG(ERROR) << "close";
592 fds_to_close_.clear();
593 #endif
596 // static
597 bool ChannelPosix::IsNamedServerInitialized(
598 const std::string& channel_id) {
599 return base::PathExists(base::FilePath(channel_id));
602 #if defined(OS_LINUX)
603 // static
604 void ChannelPosix::SetGlobalPid(int pid) {
605 global_pid_ = pid;
607 #endif // OS_LINUX
609 // Called by libevent when we can read from the pipe without blocking.
610 void ChannelPosix::OnFileCanReadWithoutBlocking(int fd) {
611 if (fd == server_listen_pipe_.get()) {
612 #if defined(OS_NACL_NONSFI)
613 LOG(FATAL)
614 << "IPC channels in nacl_helper_nonsfi should not be SERVER mode.";
615 #else
616 int new_pipe = 0;
617 if (!ServerAcceptConnection(server_listen_pipe_.get(), &new_pipe) ||
618 new_pipe < 0) {
619 Close();
620 listener()->OnChannelListenError();
623 if (pipe_.is_valid()) {
624 // We already have a connection. We only handle one at a time.
625 // close our new descriptor.
626 if (HANDLE_EINTR(shutdown(new_pipe, SHUT_RDWR)) < 0)
627 DPLOG(ERROR) << "shutdown " << pipe_name_;
628 if (IGNORE_EINTR(close(new_pipe)) < 0)
629 DPLOG(ERROR) << "close " << pipe_name_;
630 listener()->OnChannelDenied();
631 return;
633 pipe_.reset(new_pipe);
635 if ((mode_ & MODE_OPEN_ACCESS_FLAG) == 0) {
636 // Verify that the IPC channel peer is running as the same user.
637 uid_t client_euid;
638 if (!GetPeerEuid(&client_euid)) {
639 DLOG(ERROR) << "Unable to query client euid";
640 ResetToAcceptingConnectionState();
641 return;
643 if (client_euid != geteuid()) {
644 DLOG(WARNING) << "Client euid is not authorised";
645 ResetToAcceptingConnectionState();
646 return;
650 if (!AcceptConnection()) {
651 NOTREACHED() << "AcceptConnection should not fail on server";
653 waiting_connect_ = false;
654 #endif
655 } else if (fd == pipe_) {
656 if (waiting_connect_ && (mode_ & MODE_SERVER_FLAG)) {
657 waiting_connect_ = false;
659 if (ProcessIncomingMessages() == DISPATCH_ERROR) {
660 // ClosePipeOnError may delete this object, so we mustn't call
661 // ProcessOutgoingMessages.
662 ClosePipeOnError();
663 return;
665 } else {
666 NOTREACHED() << "Unknown pipe " << fd;
669 // If we're a server and handshaking, then we want to make sure that we
670 // only send our handshake message after we've processed the client's.
671 // This gives us a chance to kill the client if the incoming handshake
672 // is invalid. This also flushes any closefd messages.
673 if (!is_blocked_on_write_) {
674 if (!ProcessOutgoingMessages()) {
675 ClosePipeOnError();
680 // Called by libevent when we can write to the pipe without blocking.
681 void ChannelPosix::OnFileCanWriteWithoutBlocking(int fd) {
682 DCHECK_EQ(pipe_.get(), fd);
683 is_blocked_on_write_ = false;
684 if (!ProcessOutgoingMessages()) {
685 ClosePipeOnError();
689 bool ChannelPosix::AcceptConnection() {
690 base::MessageLoopForIO::current()->WatchFileDescriptor(
691 pipe_.get(),
692 true,
693 base::MessageLoopForIO::WATCH_READ,
694 &read_watcher_,
695 this);
696 QueueHelloMessage();
698 if (mode_ & MODE_CLIENT_FLAG) {
699 // If we are a client we want to send a hello message out immediately.
700 // In server mode we will send a hello message when we receive one from a
701 // client.
702 waiting_connect_ = false;
703 return ProcessOutgoingMessages();
704 } else if (mode_ & MODE_SERVER_FLAG) {
705 waiting_connect_ = true;
706 return true;
707 } else {
708 NOTREACHED();
709 return false;
713 void ChannelPosix::ClosePipeOnError() {
714 if (HasAcceptedConnection()) {
715 ResetToAcceptingConnectionState();
716 listener()->OnChannelError();
717 } else {
718 Close();
719 if (AcceptsConnections()) {
720 listener()->OnChannelListenError();
721 } else {
722 listener()->OnChannelError();
727 int ChannelPosix::GetHelloMessageProcId() const {
728 #if defined(OS_NACL_NONSFI)
729 // In nacl_helper_nonsfi, getpid() invoked by GetCurrentProcId() is not
730 // allowed and would cause a SIGSYS crash because of the seccomp sandbox.
731 return -1;
732 #else
733 int pid = base::GetCurrentProcId();
734 #if defined(OS_LINUX)
735 // Our process may be in a sandbox with a separate PID namespace.
736 if (global_pid_) {
737 pid = global_pid_;
739 #endif // defined(OS_LINUX)
740 return pid;
741 #endif // defined(OS_NACL_NONSFI)
744 void ChannelPosix::QueueHelloMessage() {
745 // Create the Hello message
746 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
747 HELLO_MESSAGE_TYPE,
748 IPC::Message::PRIORITY_NORMAL));
749 if (!msg->WriteInt(GetHelloMessageProcId())) {
750 NOTREACHED() << "Unable to pickle hello message proc id";
752 output_queue_.push(msg.release());
755 ChannelPosix::ReadState ChannelPosix::ReadData(
756 char* buffer,
757 int buffer_len,
758 int* bytes_read) {
759 if (!pipe_.is_valid())
760 return READ_FAILED;
762 struct msghdr msg = {0};
764 struct iovec iov = {buffer, static_cast<size_t>(buffer_len)};
765 msg.msg_iov = &iov;
766 msg.msg_iovlen = 1;
768 char input_cmsg_buf[kMaxReadFDBuffer];
769 msg.msg_control = input_cmsg_buf;
771 // recvmsg() returns 0 if the connection has closed or EAGAIN if no data
772 // is waiting on the pipe.
773 msg.msg_controllen = sizeof(input_cmsg_buf);
774 *bytes_read = HANDLE_EINTR(recvmsg(pipe_.get(), &msg, MSG_DONTWAIT));
776 if (*bytes_read < 0) {
777 if (errno == EAGAIN) {
778 return READ_PENDING;
779 #if defined(OS_MACOSX)
780 } else if (errno == EPERM) {
781 // On OSX, reading from a pipe with no listener returns EPERM
782 // treat this as a special case to prevent spurious error messages
783 // to the console.
784 return READ_FAILED;
785 #endif // OS_MACOSX
786 } else if (errno == ECONNRESET || errno == EPIPE) {
787 return READ_FAILED;
788 } else {
789 PLOG(ERROR) << "pipe error (" << pipe_.get() << ")";
790 return READ_FAILED;
792 } else if (*bytes_read == 0) {
793 // The pipe has closed...
794 return READ_FAILED;
796 DCHECK(*bytes_read);
798 CloseClientFileDescriptor();
800 // Read any file descriptors from the message.
801 if (!ExtractFileDescriptorsFromMsghdr(&msg))
802 return READ_FAILED;
803 return READ_SUCCEEDED;
806 bool ChannelPosix::ShouldDispatchInputMessage(Message* msg) {
807 return true;
810 // On Posix, we need to fix up the file descriptors before the input message
811 // is dispatched.
813 // This will read from the input_fds_ (READWRITE mode only) and read more
814 // handles from the FD pipe if necessary.
815 bool ChannelPosix::GetNonBrokeredAttachments(Message* msg) {
816 uint16_t header_fds = msg->header()->num_fds;
817 if (!header_fds)
818 return true; // Nothing to do.
820 // The message has file descriptors.
821 const char* error = NULL;
822 if (header_fds > input_fds_.size()) {
823 // The message has been completely received, but we didn't get
824 // enough file descriptors.
825 error = "Message needs unreceived descriptors";
828 if (header_fds > MessageAttachmentSet::kMaxDescriptorsPerMessage)
829 error = "Message requires an excessive number of descriptors";
831 if (error) {
832 LOG(WARNING) << error
833 << " channel:" << this
834 << " message-type:" << msg->type()
835 << " header()->num_fds:" << header_fds;
836 // Abort the connection.
837 ClearInputFDs();
838 return false;
841 // The shenaniganery below with &foo.front() requires input_fds_ to have
842 // contiguous underlying storage (such as a simple array or a std::vector).
843 // This is why the header warns not to make input_fds_ a deque<>.
844 msg->attachment_set()->AddDescriptorsToOwn(&input_fds_.front(), header_fds);
845 input_fds_.erase(input_fds_.begin(), input_fds_.begin() + header_fds);
846 return true;
849 bool ChannelPosix::DidEmptyInputBuffers() {
850 // When the input data buffer is empty, the fds should be too. If this is
851 // not the case, we probably have a rogue renderer which is trying to fill
852 // our descriptor table.
853 return input_fds_.empty();
856 bool ChannelPosix::ExtractFileDescriptorsFromMsghdr(msghdr* msg) {
857 // Check that there are any control messages. On OSX, CMSG_FIRSTHDR will
858 // return an invalid non-NULL pointer in the case that controllen == 0.
859 if (msg->msg_controllen == 0)
860 return true;
862 for (cmsghdr* cmsg = CMSG_FIRSTHDR(msg);
863 cmsg;
864 cmsg = CMSG_NXTHDR(msg, cmsg)) {
865 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
866 unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0);
867 DCHECK_EQ(0U, payload_len % sizeof(int));
868 const int* file_descriptors = reinterpret_cast<int*>(CMSG_DATA(cmsg));
869 unsigned num_file_descriptors = payload_len / 4;
870 input_fds_.insert(input_fds_.end(),
871 file_descriptors,
872 file_descriptors + num_file_descriptors);
874 // Check this after adding the FDs so we don't leak them.
875 if (msg->msg_flags & MSG_CTRUNC) {
876 ClearInputFDs();
877 return false;
880 return true;
884 // No file descriptors found, but that's OK.
885 return true;
888 void ChannelPosix::ClearInputFDs() {
889 for (size_t i = 0; i < input_fds_.size(); ++i) {
890 if (IGNORE_EINTR(close(input_fds_[i])) < 0)
891 PLOG(ERROR) << "close ";
893 input_fds_.clear();
896 void ChannelPosix::QueueCloseFDMessage(int fd, int hops) {
897 switch (hops) {
898 case 1:
899 case 2: {
900 // Create the message
901 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
902 CLOSE_FD_MESSAGE_TYPE,
903 IPC::Message::PRIORITY_NORMAL));
904 if (!msg->WriteInt(hops - 1) || !msg->WriteInt(fd)) {
905 NOTREACHED() << "Unable to pickle close fd.";
907 // Send(msg.release());
908 output_queue_.push(msg.release());
909 break;
912 default:
913 NOTREACHED();
914 break;
918 void ChannelPosix::HandleInternalMessage(const Message& msg) {
919 // The Hello message contains only the process id.
920 base::PickleIterator iter(msg);
922 switch (msg.type()) {
923 default:
924 NOTREACHED();
925 break;
927 case Channel::HELLO_MESSAGE_TYPE:
928 int pid;
929 if (!iter.ReadInt(&pid))
930 NOTREACHED();
932 peer_pid_ = pid;
933 listener()->OnChannelConnected(pid);
934 break;
936 #if defined(OS_MACOSX)
937 case Channel::CLOSE_FD_MESSAGE_TYPE:
938 int fd, hops;
939 if (!iter.ReadInt(&hops))
940 NOTREACHED();
941 if (!iter.ReadInt(&fd))
942 NOTREACHED();
943 if (hops == 0) {
944 if (fds_to_close_.erase(fd) > 0) {
945 if (IGNORE_EINTR(close(fd)) < 0)
946 PLOG(ERROR) << "close";
947 } else {
948 NOTREACHED();
950 } else {
951 QueueCloseFDMessage(fd, hops);
953 break;
954 #endif
958 base::ProcessId ChannelPosix::GetSenderPID() {
959 return GetPeerPID();
962 bool ChannelPosix::IsAttachmentBrokerEndpoint() {
963 return is_attachment_broker_endpoint();
966 void ChannelPosix::Close() {
967 // Close can be called multiple time, so we need to make sure we're
968 // idempotent.
970 ResetToAcceptingConnectionState();
972 if (must_unlink_) {
973 unlink(pipe_name_.c_str());
974 must_unlink_ = false;
977 if (server_listen_pipe_.is_valid()) {
978 #if defined(OS_NACL_NONSFI)
979 LOG(FATAL)
980 << "IPC channels in nacl_helper_nonsfi should not be SERVER mode.";
981 #else
982 server_listen_pipe_.reset();
983 // Unregister libevent for the listening socket and close it.
984 server_listen_connection_watcher_.StopWatchingFileDescriptor();
985 #endif
988 CloseClientFileDescriptor();
991 base::ProcessId ChannelPosix::GetPeerPID() const {
992 return peer_pid_;
995 base::ProcessId ChannelPosix::GetSelfPID() const {
996 return GetHelloMessageProcId();
999 void ChannelPosix::ResetSafely(base::ScopedFD* fd) {
1000 if (!in_dtor_) {
1001 fd->reset();
1002 return;
1005 // crbug.com/449233
1006 // The CL [1] tightened the error check for closing FDs, but it turned
1007 // out that there are existing cases that hit the newly added check.
1008 // ResetSafely() is the workaround for that crash, turning it from
1009 // from PCHECK() to DPCHECK() so that it doesn't crash in production.
1010 // [1] https://crrev.com/ce44fef5fd60dd2be5c587d4b084bdcd36adcee4
1011 int fd_to_close = fd->release();
1012 if (-1 != fd_to_close) {
1013 int rv = IGNORE_EINTR(close(fd_to_close));
1014 DPCHECK(0 == rv);
1018 //------------------------------------------------------------------------------
1019 // Channel's methods
1021 // static
1022 scoped_ptr<Channel> Channel::Create(const IPC::ChannelHandle& channel_handle,
1023 Mode mode,
1024 Listener* listener,
1025 AttachmentBroker* broker) {
1026 return make_scoped_ptr(
1027 new ChannelPosix(channel_handle, mode, listener, broker));
1030 // static
1031 std::string Channel::GenerateVerifiedChannelID(const std::string& prefix) {
1032 // A random name is sufficient validation on posix systems, so we don't need
1033 // an additional shared secret.
1035 std::string id = prefix;
1036 if (!id.empty())
1037 id.append(".");
1039 return id.append(GenerateUniqueRandomChannelID());
1042 bool Channel::IsNamedServerInitialized(
1043 const std::string& channel_id) {
1044 return ChannelPosix::IsNamedServerInitialized(channel_id);
1047 #if defined(OS_LINUX)
1048 // static
1049 void Channel::SetGlobalPid(int pid) {
1050 ChannelPosix::SetGlobalPid(pid);
1052 #endif // OS_LINUX
1054 } // namespace IPC