Add comments about handling of some memory messages.
[chromium-blink-merge.git] / ipc / ipc_channel_posix.cc
blob233968712cdde419c6746b1bb0a1e3e90c1dbb7a
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() { return base::Singleton<PipeMap>::get(); }
100 ~PipeMap() {
101 // Shouldn't have left over pipes.
102 DCHECK(map_.empty());
105 // Lookup a given channel id. Return -1 if not found.
106 int Lookup(const std::string& channel_id) {
107 base::AutoLock locked(lock_);
109 ChannelToFDMap::const_iterator i = map_.find(channel_id);
110 if (i == map_.end())
111 return -1;
112 return i->second;
115 // Remove the mapping for the given channel id. No error is signaled if the
116 // channel_id doesn't exist
117 void Remove(const std::string& channel_id) {
118 base::AutoLock locked(lock_);
119 map_.erase(channel_id);
122 // Insert a mapping from @channel_id to @fd. It's a fatal error to insert a
123 // mapping if one already exists for the given channel_id
124 void Insert(const std::string& channel_id, int fd) {
125 base::AutoLock locked(lock_);
126 DCHECK_NE(-1, fd);
128 ChannelToFDMap::const_iterator i = map_.find(channel_id);
129 CHECK(i == map_.end()) << "Creating second IPC server (fd " << fd << ") "
130 << "for '" << channel_id << "' while first "
131 << "(fd " << i->second << ") still exists";
132 map_[channel_id] = fd;
135 private:
136 base::Lock lock_;
137 typedef std::map<std::string, int> ChannelToFDMap;
138 ChannelToFDMap map_;
140 friend struct base::DefaultSingletonTraits<PipeMap>;
141 #if defined(OS_ANDROID)
142 friend void ::IPC::Channel::NotifyProcessForkedForTesting();
143 #endif
146 //------------------------------------------------------------------------------
148 bool SocketWriteErrorIsRecoverable() {
149 #if defined(OS_MACOSX)
150 // On OS X if sendmsg() is trying to send fds between processes and there
151 // isn't enough room in the output buffer to send the fd structure over
152 // atomically then EMSGSIZE is returned.
154 // EMSGSIZE presents a problem since the system APIs can only call us when
155 // there's room in the socket buffer and not when there is "enough" room.
157 // The current behavior is to return to the event loop when EMSGSIZE is
158 // received and hopefull service another FD. This is however still
159 // technically a busy wait since the event loop will call us right back until
160 // the receiver has read enough data to allow passing the FD over atomically.
161 return errno == EAGAIN || errno == EMSGSIZE;
162 #else
163 return errno == EAGAIN;
164 #endif // OS_MACOSX
167 } // namespace
169 #if defined(OS_ANDROID)
170 // When we fork for simple tests on Android, we can't 'exec', so we need to
171 // reset these entries manually to get the expected testing behavior.
172 void Channel::NotifyProcessForkedForTesting() {
173 PipeMap::GetInstance()->map_.clear();
175 #endif
177 //------------------------------------------------------------------------------
179 #if defined(OS_LINUX)
180 int ChannelPosix::global_pid_ = 0;
181 #endif // OS_LINUX
183 ChannelPosix::ChannelPosix(const IPC::ChannelHandle& channel_handle,
184 Mode mode,
185 Listener* listener,
186 AttachmentBroker* broker)
187 : ChannelReader(listener),
188 mode_(mode),
189 peer_pid_(base::kNullProcessId),
190 is_blocked_on_write_(false),
191 waiting_connect_(true),
192 message_send_bytes_written_(0),
193 pipe_name_(channel_handle.name),
194 in_dtor_(false),
195 must_unlink_(false),
196 broker_(broker) {
197 if (!CreatePipe(channel_handle)) {
198 // The pipe may have been closed already.
199 const char *modestr = (mode_ & MODE_SERVER_FLAG) ? "server" : "client";
200 LOG(WARNING) << "Unable to create pipe named \"" << channel_handle.name
201 << "\" in " << modestr << " mode";
205 ChannelPosix::~ChannelPosix() {
206 in_dtor_ = true;
207 CleanUp();
208 Close();
211 bool SocketPair(int* fd1, int* fd2) {
212 int pipe_fds[2];
213 if (socketpair(AF_UNIX, SOCK_STREAM, 0, pipe_fds) != 0) {
214 PLOG(ERROR) << "socketpair()";
215 return false;
218 // Set both ends to be non-blocking.
219 if (fcntl(pipe_fds[0], F_SETFL, O_NONBLOCK) == -1 ||
220 fcntl(pipe_fds[1], F_SETFL, O_NONBLOCK) == -1) {
221 PLOG(ERROR) << "fcntl(O_NONBLOCK)";
222 if (IGNORE_EINTR(close(pipe_fds[0])) < 0)
223 PLOG(ERROR) << "close";
224 if (IGNORE_EINTR(close(pipe_fds[1])) < 0)
225 PLOG(ERROR) << "close";
226 return false;
229 *fd1 = pipe_fds[0];
230 *fd2 = pipe_fds[1];
232 return true;
235 bool ChannelPosix::CreatePipe(
236 const IPC::ChannelHandle& channel_handle) {
237 DCHECK(!server_listen_pipe_.is_valid() && !pipe_.is_valid());
239 // Four possible cases:
240 // 1) It's a channel wrapping a pipe that is given to us.
241 // 2) It's for a named channel, so we create it.
242 // 3) It's for a client that we implement ourself. This is used
243 // in single-process unittesting.
244 // 4) It's the initial IPC channel:
245 // 4a) Client side: Pull the pipe out of the GlobalDescriptors set.
246 // 4b) Server side: create the pipe.
248 base::ScopedFD local_pipe;
249 if (channel_handle.socket.fd != -1) {
250 // Case 1 from comment above.
251 local_pipe.reset(channel_handle.socket.fd);
252 } else if (mode_ & MODE_NAMED_FLAG) {
253 #if defined(OS_NACL_NONSFI)
254 LOG(FATAL)
255 << "IPC channels in nacl_helper_nonsfi should not be in NAMED mode.";
256 #else
257 // Case 2 from comment above.
258 int local_pipe_fd = -1;
260 if (mode_ & MODE_SERVER_FLAG) {
261 if (!CreateServerUnixDomainSocket(base::FilePath(pipe_name_),
262 &local_pipe_fd)) {
263 return false;
266 must_unlink_ = true;
267 } else if (mode_ & MODE_CLIENT_FLAG) {
268 if (!CreateClientUnixDomainSocket(base::FilePath(pipe_name_),
269 &local_pipe_fd)) {
270 return false;
272 } else {
273 LOG(ERROR) << "Bad mode: " << mode_;
274 return false;
277 local_pipe.reset(local_pipe_fd);
278 #endif // !defined(OS_NACL_NONSFI)
279 } else {
280 local_pipe.reset(PipeMap::GetInstance()->Lookup(pipe_name_));
281 if (mode_ & MODE_CLIENT_FLAG) {
282 if (local_pipe.is_valid()) {
283 // Case 3 from comment above.
284 // We only allow one connection.
285 local_pipe.reset(HANDLE_EINTR(dup(local_pipe.release())));
286 PipeMap::GetInstance()->Remove(pipe_name_);
287 } else {
288 // Case 4a from comment above.
289 // Guard against inappropriate reuse of the initial IPC channel. If
290 // an IPC channel closes and someone attempts to reuse it by name, the
291 // initial channel must not be recycled here. http://crbug.com/26754.
292 static bool used_initial_channel = false;
293 if (used_initial_channel) {
294 LOG(FATAL) << "Denying attempt to reuse initial IPC channel for "
295 << pipe_name_;
296 return false;
298 used_initial_channel = true;
300 local_pipe.reset(
301 base::GlobalDescriptors::GetInstance()->Get(kPrimaryIPCChannel));
303 } else if (mode_ & MODE_SERVER_FLAG) {
304 // Case 4b from comment above.
305 if (local_pipe.is_valid()) {
306 LOG(ERROR) << "Server already exists for " << pipe_name_;
307 // This is a client side pipe registered by other server and
308 // shouldn't be closed.
309 ignore_result(local_pipe.release());
310 return false;
312 base::AutoLock lock(client_pipe_lock_);
313 int local_pipe_fd = -1, client_pipe_fd = -1;
314 if (!SocketPair(&local_pipe_fd, &client_pipe_fd))
315 return false;
316 local_pipe.reset(local_pipe_fd);
317 client_pipe_.reset(client_pipe_fd);
318 PipeMap::GetInstance()->Insert(pipe_name_, client_pipe_fd);
319 } else {
320 LOG(ERROR) << "Bad mode: " << mode_;
321 return false;
325 if ((mode_ & MODE_SERVER_FLAG) && (mode_ & MODE_NAMED_FLAG)) {
326 #if defined(OS_NACL_NONSFI)
327 LOG(FATAL) << "IPC channels in nacl_helper_nonsfi "
328 << "should not be in NAMED or SERVER mode.";
329 #else
330 server_listen_pipe_.reset(local_pipe.release());
331 #endif
332 } else {
333 pipe_.reset(local_pipe.release());
335 return true;
338 bool ChannelPosix::Connect() {
339 if (!server_listen_pipe_.is_valid() && !pipe_.is_valid()) {
340 DLOG(WARNING) << "Channel creation failed: " << pipe_name_;
341 return false;
344 bool did_connect = true;
345 if (server_listen_pipe_.is_valid()) {
346 #if defined(OS_NACL_NONSFI)
347 LOG(FATAL) << "IPC channels in nacl_helper_nonsfi "
348 << "should always be in client mode.";
349 #else
350 // Watch the pipe for connections, and turn any connections into
351 // active sockets.
352 base::MessageLoopForIO::current()->WatchFileDescriptor(
353 server_listen_pipe_.get(),
354 true,
355 base::MessageLoopForIO::WATCH_READ,
356 &server_listen_connection_watcher_,
357 this);
358 #endif
359 } else {
360 did_connect = AcceptConnection();
362 return did_connect;
365 void ChannelPosix::CloseFileDescriptors(Message* msg) {
366 #if defined(OS_MACOSX)
367 // There is a bug on OSX which makes it dangerous to close
368 // a file descriptor while it is in transit. So instead we
369 // store the file descriptor in a set and send a message to
370 // the recipient, which is queued AFTER the message that
371 // sent the FD. The recipient will reply to the message,
372 // letting us know that it is now safe to close the file
373 // descriptor. For more information, see:
374 // http://crbug.com/298276
375 std::vector<int> to_close;
376 msg->attachment_set()->ReleaseFDsToClose(&to_close);
377 for (size_t i = 0; i < to_close.size(); i++) {
378 fds_to_close_.insert(to_close[i]);
379 QueueCloseFDMessage(to_close[i], 2);
381 #else
382 msg->attachment_set()->CommitAll();
383 #endif
386 bool ChannelPosix::ProcessOutgoingMessages() {
387 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
388 // no connection?
389 if (output_queue_.empty())
390 return true;
392 if (!pipe_.is_valid())
393 return false;
395 // Write out all the messages we can till the write blocks or there are no
396 // more outgoing messages.
397 while (!output_queue_.empty()) {
398 Message* msg = output_queue_.front();
400 size_t amt_to_write = msg->size() - message_send_bytes_written_;
401 DCHECK_NE(0U, amt_to_write);
402 const char* out_bytes = reinterpret_cast<const char*>(msg->data()) +
403 message_send_bytes_written_;
405 struct msghdr msgh = {0};
406 struct iovec iov = {const_cast<char*>(out_bytes), amt_to_write};
407 msgh.msg_iov = &iov;
408 msgh.msg_iovlen = 1;
409 char buf[CMSG_SPACE(sizeof(int) *
410 MessageAttachmentSet::kMaxDescriptorsPerMessage)];
412 ssize_t bytes_written = 1;
413 int fd_written = -1;
415 if (message_send_bytes_written_ == 0 && !msg->attachment_set()->empty()) {
416 // This is the first chunk of a message which has descriptors to send
417 struct cmsghdr *cmsg;
418 const unsigned num_fds = msg->attachment_set()->size();
420 DCHECK(num_fds <= MessageAttachmentSet::kMaxDescriptorsPerMessage);
421 if (msg->attachment_set()->ContainsDirectoryDescriptor()) {
422 LOG(FATAL) << "Panic: attempting to transport directory descriptor over"
423 " IPC. Aborting to maintain sandbox isolation.";
424 // If you have hit this then something tried to send a file descriptor
425 // to a directory over an IPC channel. Since IPC channels span
426 // sandboxes this is very bad: the receiving process can use openat
427 // with ".." elements in the path in order to reach the real
428 // filesystem.
431 msgh.msg_control = buf;
432 msgh.msg_controllen = CMSG_SPACE(sizeof(int) * num_fds);
433 cmsg = CMSG_FIRSTHDR(&msgh);
434 cmsg->cmsg_level = SOL_SOCKET;
435 cmsg->cmsg_type = SCM_RIGHTS;
436 cmsg->cmsg_len = CMSG_LEN(sizeof(int) * num_fds);
437 msg->attachment_set()->PeekDescriptors(
438 reinterpret_cast<int*>(CMSG_DATA(cmsg)));
439 msgh.msg_controllen = cmsg->cmsg_len;
441 // DCHECK_LE above already checks that
442 // num_fds < kMaxDescriptorsPerMessage so no danger of overflow.
443 msg->header()->num_fds = static_cast<uint16_t>(num_fds);
446 if (bytes_written == 1) {
447 fd_written = pipe_.get();
448 bytes_written = HANDLE_EINTR(sendmsg(pipe_.get(), &msgh, MSG_DONTWAIT));
450 if (bytes_written > 0)
451 CloseFileDescriptors(msg);
453 if (bytes_written < 0 && !SocketWriteErrorIsRecoverable()) {
454 // We can't close the pipe here, because calling OnChannelError
455 // may destroy this object, and that would be bad if we are
456 // called from Send(). Instead, we return false and hope the
457 // caller will close the pipe. If they do not, the pipe will
458 // still be closed next time OnFileCanReadWithoutBlocking is
459 // called.
460 #if defined(OS_MACOSX)
461 // On OSX writing to a pipe with no listener returns EPERM.
462 if (errno == EPERM) {
463 return false;
465 #endif // OS_MACOSX
466 if (errno == EPIPE) {
467 return false;
469 PLOG(ERROR) << "pipe error on "
470 << fd_written
471 << " Currently writing message of size: "
472 << msg->size();
473 return false;
476 if (static_cast<size_t>(bytes_written) != amt_to_write) {
477 if (bytes_written > 0) {
478 // If write() fails with EAGAIN then bytes_written will be -1.
479 message_send_bytes_written_ += bytes_written;
482 // Tell libevent to call us back once things are unblocked.
483 is_blocked_on_write_ = true;
484 base::MessageLoopForIO::current()->WatchFileDescriptor(
485 pipe_.get(),
486 false, // One shot
487 base::MessageLoopForIO::WATCH_WRITE,
488 &write_watcher_,
489 this);
490 return true;
491 } else {
492 message_send_bytes_written_ = 0;
494 // Message sent OK!
495 DVLOG(2) << "sent message @" << msg << " on channel @" << this
496 << " with type " << msg->type() << " on fd " << pipe_.get();
497 delete output_queue_.front();
498 output_queue_.pop();
501 return true;
504 bool ChannelPosix::Send(Message* message) {
505 DCHECK(!message->HasMojoHandles());
506 DVLOG(2) << "sending message @" << message << " on channel @" << this
507 << " with type " << message->type()
508 << " (" << output_queue_.size() << " in queue)";
510 #ifdef IPC_MESSAGE_LOG_ENABLED
511 Logging::GetInstance()->OnSendMessage(message, "");
512 #endif // IPC_MESSAGE_LOG_ENABLED
514 TRACE_EVENT_WITH_FLOW0(TRACE_DISABLED_BY_DEFAULT("ipc.flow"),
515 "ChannelPosix::Send",
516 message->flags(),
517 TRACE_EVENT_FLAG_FLOW_OUT);
518 output_queue_.push(message);
519 if (!is_blocked_on_write_ && !waiting_connect_) {
520 return ProcessOutgoingMessages();
523 return true;
526 AttachmentBroker* ChannelPosix::GetAttachmentBroker() {
527 return broker_;
530 int ChannelPosix::GetClientFileDescriptor() const {
531 base::AutoLock lock(client_pipe_lock_);
532 return client_pipe_.get();
535 base::ScopedFD ChannelPosix::TakeClientFileDescriptor() {
536 base::AutoLock lock(client_pipe_lock_);
537 if (!client_pipe_.is_valid())
538 return base::ScopedFD();
539 PipeMap::GetInstance()->Remove(pipe_name_);
540 return client_pipe_.Pass();
543 void ChannelPosix::CloseClientFileDescriptor() {
544 base::AutoLock lock(client_pipe_lock_);
545 if (!client_pipe_.is_valid())
546 return;
547 PipeMap::GetInstance()->Remove(pipe_name_);
548 client_pipe_.reset();
551 bool ChannelPosix::AcceptsConnections() const {
552 return server_listen_pipe_.is_valid();
555 bool ChannelPosix::HasAcceptedConnection() const {
556 return AcceptsConnections() && pipe_.is_valid();
559 #if !defined(OS_NACL_NONSFI)
560 // GetPeerEuid is not supported in nacl_helper_nonsfi.
561 bool ChannelPosix::GetPeerEuid(uid_t* peer_euid) const {
562 DCHECK(!(mode_ & MODE_SERVER) || HasAcceptedConnection());
563 return IPC::GetPeerEuid(pipe_.get(), peer_euid);
565 #endif
567 void ChannelPosix::ResetToAcceptingConnectionState() {
568 // Unregister libevent for the unix domain socket and close it.
569 read_watcher_.StopWatchingFileDescriptor();
570 write_watcher_.StopWatchingFileDescriptor();
571 ResetSafely(&pipe_);
573 while (!output_queue_.empty()) {
574 Message* m = output_queue_.front();
575 output_queue_.pop();
576 CloseFileDescriptors(m);
577 delete m;
580 // Close any outstanding, received file descriptors.
581 ClearInputFDs();
583 #if defined(OS_MACOSX)
584 // Clear any outstanding, sent file descriptors.
585 for (std::set<int>::iterator i = fds_to_close_.begin();
586 i != fds_to_close_.end();
587 ++i) {
588 if (IGNORE_EINTR(close(*i)) < 0)
589 PLOG(ERROR) << "close";
591 fds_to_close_.clear();
592 #endif
595 // static
596 bool ChannelPosix::IsNamedServerInitialized(
597 const std::string& channel_id) {
598 return base::PathExists(base::FilePath(channel_id));
601 #if defined(OS_LINUX)
602 // static
603 void ChannelPosix::SetGlobalPid(int pid) {
604 global_pid_ = pid;
606 #endif // OS_LINUX
608 // Called by libevent when we can read from the pipe without blocking.
609 void ChannelPosix::OnFileCanReadWithoutBlocking(int fd) {
610 if (fd == server_listen_pipe_.get()) {
611 #if defined(OS_NACL_NONSFI)
612 LOG(FATAL)
613 << "IPC channels in nacl_helper_nonsfi should not be SERVER mode.";
614 #else
615 int new_pipe = 0;
616 if (!ServerAcceptConnection(server_listen_pipe_.get(), &new_pipe) ||
617 new_pipe < 0) {
618 Close();
619 listener()->OnChannelListenError();
622 if (pipe_.is_valid()) {
623 // We already have a connection. We only handle one at a time.
624 // close our new descriptor.
625 if (HANDLE_EINTR(shutdown(new_pipe, SHUT_RDWR)) < 0)
626 DPLOG(ERROR) << "shutdown " << pipe_name_;
627 if (IGNORE_EINTR(close(new_pipe)) < 0)
628 DPLOG(ERROR) << "close " << pipe_name_;
629 listener()->OnChannelDenied();
630 return;
632 pipe_.reset(new_pipe);
634 if ((mode_ & MODE_OPEN_ACCESS_FLAG) == 0) {
635 // Verify that the IPC channel peer is running as the same user.
636 uid_t client_euid;
637 if (!GetPeerEuid(&client_euid)) {
638 DLOG(ERROR) << "Unable to query client euid";
639 ResetToAcceptingConnectionState();
640 return;
642 if (client_euid != geteuid()) {
643 DLOG(WARNING) << "Client euid is not authorised";
644 ResetToAcceptingConnectionState();
645 return;
649 if (!AcceptConnection()) {
650 NOTREACHED() << "AcceptConnection should not fail on server";
652 waiting_connect_ = false;
653 #endif
654 } else if (fd == pipe_) {
655 if (waiting_connect_ && (mode_ & MODE_SERVER_FLAG)) {
656 waiting_connect_ = false;
658 if (ProcessIncomingMessages() == DISPATCH_ERROR) {
659 // ClosePipeOnError may delete this object, so we mustn't call
660 // ProcessOutgoingMessages.
661 ClosePipeOnError();
662 return;
664 } else {
665 NOTREACHED() << "Unknown pipe " << fd;
668 // If we're a server and handshaking, then we want to make sure that we
669 // only send our handshake message after we've processed the client's.
670 // This gives us a chance to kill the client if the incoming handshake
671 // is invalid. This also flushes any closefd messages.
672 if (!is_blocked_on_write_) {
673 if (!ProcessOutgoingMessages()) {
674 ClosePipeOnError();
679 // Called by libevent when we can write to the pipe without blocking.
680 void ChannelPosix::OnFileCanWriteWithoutBlocking(int fd) {
681 DCHECK_EQ(pipe_.get(), fd);
682 is_blocked_on_write_ = false;
683 if (!ProcessOutgoingMessages()) {
684 ClosePipeOnError();
688 bool ChannelPosix::AcceptConnection() {
689 base::MessageLoopForIO::current()->WatchFileDescriptor(
690 pipe_.get(),
691 true,
692 base::MessageLoopForIO::WATCH_READ,
693 &read_watcher_,
694 this);
695 QueueHelloMessage();
697 if (mode_ & MODE_CLIENT_FLAG) {
698 // If we are a client we want to send a hello message out immediately.
699 // In server mode we will send a hello message when we receive one from a
700 // client.
701 waiting_connect_ = false;
702 return ProcessOutgoingMessages();
703 } else if (mode_ & MODE_SERVER_FLAG) {
704 waiting_connect_ = true;
705 return true;
706 } else {
707 NOTREACHED();
708 return false;
712 void ChannelPosix::ClosePipeOnError() {
713 if (HasAcceptedConnection()) {
714 ResetToAcceptingConnectionState();
715 listener()->OnChannelError();
716 } else {
717 Close();
718 if (AcceptsConnections()) {
719 listener()->OnChannelListenError();
720 } else {
721 listener()->OnChannelError();
726 int ChannelPosix::GetHelloMessageProcId() const {
727 #if defined(OS_NACL_NONSFI)
728 // In nacl_helper_nonsfi, getpid() invoked by GetCurrentProcId() is not
729 // allowed and would cause a SIGSYS crash because of the seccomp sandbox.
730 return -1;
731 #else
732 int pid = base::GetCurrentProcId();
733 #if defined(OS_LINUX)
734 // Our process may be in a sandbox with a separate PID namespace.
735 if (global_pid_) {
736 pid = global_pid_;
738 #endif // defined(OS_LINUX)
739 return pid;
740 #endif // defined(OS_NACL_NONSFI)
743 void ChannelPosix::QueueHelloMessage() {
744 // Create the Hello message
745 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
746 HELLO_MESSAGE_TYPE,
747 IPC::Message::PRIORITY_NORMAL));
748 if (!msg->WriteInt(GetHelloMessageProcId())) {
749 NOTREACHED() << "Unable to pickle hello message proc id";
751 output_queue_.push(msg.release());
754 ChannelPosix::ReadState ChannelPosix::ReadData(
755 char* buffer,
756 int buffer_len,
757 int* bytes_read) {
758 if (!pipe_.is_valid())
759 return READ_FAILED;
761 struct msghdr msg = {0};
763 struct iovec iov = {buffer, static_cast<size_t>(buffer_len)};
764 msg.msg_iov = &iov;
765 msg.msg_iovlen = 1;
767 char input_cmsg_buf[kMaxReadFDBuffer];
768 msg.msg_control = input_cmsg_buf;
770 // recvmsg() returns 0 if the connection has closed or EAGAIN if no data
771 // is waiting on the pipe.
772 msg.msg_controllen = sizeof(input_cmsg_buf);
773 *bytes_read = HANDLE_EINTR(recvmsg(pipe_.get(), &msg, MSG_DONTWAIT));
775 if (*bytes_read < 0) {
776 if (errno == EAGAIN) {
777 return READ_PENDING;
778 #if defined(OS_MACOSX)
779 } else if (errno == EPERM) {
780 // On OSX, reading from a pipe with no listener returns EPERM
781 // treat this as a special case to prevent spurious error messages
782 // to the console.
783 return READ_FAILED;
784 #endif // OS_MACOSX
785 } else if (errno == ECONNRESET || errno == EPIPE) {
786 return READ_FAILED;
787 } else {
788 PLOG(ERROR) << "pipe error (" << pipe_.get() << ")";
789 return READ_FAILED;
791 } else if (*bytes_read == 0) {
792 // The pipe has closed...
793 return READ_FAILED;
795 DCHECK(*bytes_read);
797 CloseClientFileDescriptor();
799 // Read any file descriptors from the message.
800 if (!ExtractFileDescriptorsFromMsghdr(&msg))
801 return READ_FAILED;
802 return READ_SUCCEEDED;
805 bool ChannelPosix::ShouldDispatchInputMessage(Message* msg) {
806 return true;
809 // On Posix, we need to fix up the file descriptors before the input message
810 // is dispatched.
812 // This will read from the input_fds_ (READWRITE mode only) and read more
813 // handles from the FD pipe if necessary.
814 bool ChannelPosix::GetNonBrokeredAttachments(Message* msg) {
815 uint16_t header_fds = msg->header()->num_fds;
816 if (!header_fds)
817 return true; // Nothing to do.
819 // The message has file descriptors.
820 const char* error = NULL;
821 if (header_fds > input_fds_.size()) {
822 // The message has been completely received, but we didn't get
823 // enough file descriptors.
824 error = "Message needs unreceived descriptors";
827 if (header_fds > MessageAttachmentSet::kMaxDescriptorsPerMessage)
828 error = "Message requires an excessive number of descriptors";
830 if (error) {
831 LOG(WARNING) << error
832 << " channel:" << this
833 << " message-type:" << msg->type()
834 << " header()->num_fds:" << header_fds;
835 // Abort the connection.
836 ClearInputFDs();
837 return false;
840 // The shenaniganery below with &foo.front() requires input_fds_ to have
841 // contiguous underlying storage (such as a simple array or a std::vector).
842 // This is why the header warns not to make input_fds_ a deque<>.
843 msg->attachment_set()->AddDescriptorsToOwn(&input_fds_.front(), header_fds);
844 input_fds_.erase(input_fds_.begin(), input_fds_.begin() + header_fds);
845 return true;
848 bool ChannelPosix::DidEmptyInputBuffers() {
849 // When the input data buffer is empty, the fds should be too. If this is
850 // not the case, we probably have a rogue renderer which is trying to fill
851 // our descriptor table.
852 return input_fds_.empty();
855 bool ChannelPosix::ExtractFileDescriptorsFromMsghdr(msghdr* msg) {
856 // Check that there are any control messages. On OSX, CMSG_FIRSTHDR will
857 // return an invalid non-NULL pointer in the case that controllen == 0.
858 if (msg->msg_controllen == 0)
859 return true;
861 for (cmsghdr* cmsg = CMSG_FIRSTHDR(msg);
862 cmsg;
863 cmsg = CMSG_NXTHDR(msg, cmsg)) {
864 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
865 unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0);
866 DCHECK_EQ(0U, payload_len % sizeof(int));
867 const int* file_descriptors = reinterpret_cast<int*>(CMSG_DATA(cmsg));
868 unsigned num_file_descriptors = payload_len / 4;
869 input_fds_.insert(input_fds_.end(),
870 file_descriptors,
871 file_descriptors + num_file_descriptors);
873 // Check this after adding the FDs so we don't leak them.
874 if (msg->msg_flags & MSG_CTRUNC) {
875 ClearInputFDs();
876 return false;
879 return true;
883 // No file descriptors found, but that's OK.
884 return true;
887 void ChannelPosix::ClearInputFDs() {
888 for (size_t i = 0; i < input_fds_.size(); ++i) {
889 if (IGNORE_EINTR(close(input_fds_[i])) < 0)
890 PLOG(ERROR) << "close ";
892 input_fds_.clear();
895 void ChannelPosix::QueueCloseFDMessage(int fd, int hops) {
896 switch (hops) {
897 case 1:
898 case 2: {
899 // Create the message
900 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
901 CLOSE_FD_MESSAGE_TYPE,
902 IPC::Message::PRIORITY_NORMAL));
903 if (!msg->WriteInt(hops - 1) || !msg->WriteInt(fd)) {
904 NOTREACHED() << "Unable to pickle close fd.";
906 // Send(msg.release());
907 output_queue_.push(msg.release());
908 break;
911 default:
912 NOTREACHED();
913 break;
917 void ChannelPosix::HandleInternalMessage(const Message& msg) {
918 // The Hello message contains only the process id.
919 base::PickleIterator iter(msg);
921 switch (msg.type()) {
922 default:
923 NOTREACHED();
924 break;
926 case Channel::HELLO_MESSAGE_TYPE:
927 int pid;
928 if (!iter.ReadInt(&pid))
929 NOTREACHED();
931 peer_pid_ = pid;
932 listener()->OnChannelConnected(pid);
933 break;
935 #if defined(OS_MACOSX)
936 case Channel::CLOSE_FD_MESSAGE_TYPE:
937 int fd, hops;
938 if (!iter.ReadInt(&hops))
939 NOTREACHED();
940 if (!iter.ReadInt(&fd))
941 NOTREACHED();
942 if (hops == 0) {
943 if (fds_to_close_.erase(fd) > 0) {
944 if (IGNORE_EINTR(close(fd)) < 0)
945 PLOG(ERROR) << "close";
946 } else {
947 NOTREACHED();
949 } else {
950 QueueCloseFDMessage(fd, hops);
952 break;
953 #endif
957 base::ProcessId ChannelPosix::GetSenderPID() {
958 return GetPeerPID();
961 bool ChannelPosix::IsAttachmentBrokerEndpoint() {
962 return is_attachment_broker_endpoint();
965 void ChannelPosix::Close() {
966 // Close can be called multiple time, so we need to make sure we're
967 // idempotent.
969 ResetToAcceptingConnectionState();
971 if (must_unlink_) {
972 unlink(pipe_name_.c_str());
973 must_unlink_ = false;
976 if (server_listen_pipe_.is_valid()) {
977 #if defined(OS_NACL_NONSFI)
978 LOG(FATAL)
979 << "IPC channels in nacl_helper_nonsfi should not be SERVER mode.";
980 #else
981 server_listen_pipe_.reset();
982 // Unregister libevent for the listening socket and close it.
983 server_listen_connection_watcher_.StopWatchingFileDescriptor();
984 #endif
987 CloseClientFileDescriptor();
990 base::ProcessId ChannelPosix::GetPeerPID() const {
991 return peer_pid_;
994 base::ProcessId ChannelPosix::GetSelfPID() const {
995 return GetHelloMessageProcId();
998 void ChannelPosix::ResetSafely(base::ScopedFD* fd) {
999 if (!in_dtor_) {
1000 fd->reset();
1001 return;
1004 // crbug.com/449233
1005 // The CL [1] tightened the error check for closing FDs, but it turned
1006 // out that there are existing cases that hit the newly added check.
1007 // ResetSafely() is the workaround for that crash, turning it from
1008 // from PCHECK() to DPCHECK() so that it doesn't crash in production.
1009 // [1] https://crrev.com/ce44fef5fd60dd2be5c587d4b084bdcd36adcee4
1010 int fd_to_close = fd->release();
1011 if (-1 != fd_to_close) {
1012 int rv = IGNORE_EINTR(close(fd_to_close));
1013 DPCHECK(0 == rv);
1017 //------------------------------------------------------------------------------
1018 // Channel's methods
1020 // static
1021 scoped_ptr<Channel> Channel::Create(const IPC::ChannelHandle& channel_handle,
1022 Mode mode,
1023 Listener* listener,
1024 AttachmentBroker* broker) {
1025 return make_scoped_ptr(
1026 new ChannelPosix(channel_handle, mode, listener, broker));
1029 // static
1030 std::string Channel::GenerateVerifiedChannelID(const std::string& prefix) {
1031 // A random name is sufficient validation on posix systems, so we don't need
1032 // an additional shared secret.
1034 std::string id = prefix;
1035 if (!id.empty())
1036 id.append(".");
1038 return id.append(GenerateUniqueRandomChannelID());
1041 bool Channel::IsNamedServerInitialized(
1042 const std::string& channel_id) {
1043 return ChannelPosix::IsNamedServerInitialized(channel_id);
1046 #if defined(OS_LINUX)
1047 // static
1048 void Channel::SetGlobalPid(int pid) {
1049 ChannelPosix::SetGlobalPid(pid);
1051 #endif // OS_LINUX
1053 } // namespace IPC