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"
10 #include <sys/socket.h>
12 #include <sys/types.h>
15 #if defined(OS_OPENBSD)
19 #if !defined(OS_NACL_NONSFI)
26 #include "base/command_line.h"
27 #include "base/files/file_path.h"
28 #include "base/files/file_util.h"
29 #include "base/location.h"
30 #include "base/logging.h"
31 #include "base/memory/scoped_ptr.h"
32 #include "base/memory/singleton.h"
33 #include "base/posix/eintr_wrapper.h"
34 #include "base/posix/global_descriptors.h"
35 #include "base/process/process_handle.h"
36 #include "base/rand_util.h"
37 #include "base/stl_util.h"
38 #include "base/strings/string_util.h"
39 #include "base/synchronization/lock.h"
40 #include "ipc/ipc_descriptors.h"
41 #include "ipc/ipc_listener.h"
42 #include "ipc/ipc_logging.h"
43 #include "ipc/ipc_message_attachment_set.h"
44 #include "ipc/ipc_message_utils.h"
45 #include "ipc/ipc_platform_file_attachment_posix.h"
46 #include "ipc/ipc_switches.h"
47 #include "ipc/unix_domain_socket_util.h"
51 // IPC channels on Windows use named pipes (CreateNamedPipe()) with
52 // channel ids as the pipe names. Channels on POSIX use sockets as
53 // pipes These don't quite line up.
55 // When creating a child subprocess we use a socket pair and the parent side of
56 // the fork arranges it such that the initial control channel ends up on the
57 // magic file descriptor kPrimaryIPCChannel in the child. Future
58 // connections (file descriptors) can then be passed via that
59 // connection via sendmsg().
61 // A POSIX IPC channel can also be set up as a server for a bound UNIX domain
62 // socket, and will handle multiple connect and disconnect sequences. Currently
63 // it is limited to one connection at a time.
65 //------------------------------------------------------------------------------
68 // The PipeMap class works around this quirk related to unit tests:
70 // When running as a server, we install the client socket in a
71 // specific file descriptor number (@kPrimaryIPCChannel). However, we
72 // also have to support the case where we are running unittests in the
73 // same process. (We do not support forking without execing.)
75 // Case 1: normal running
76 // The IPC server object will install a mapping in PipeMap from the
77 // name which it was given to the client pipe. When forking the client, the
78 // GetClientFileDescriptorMapping will ensure that the socket is installed in
79 // the magic slot (@kPrimaryIPCChannel). The client will search for the
80 // mapping, but it won't find any since we are in a new process. Thus the
81 // magic fd number is returned. Once the client connects, the server will
82 // close its copy of the client socket and remove the mapping.
84 // Case 2: unittests - client and server in the same process
85 // The IPC server will install a mapping as before. The client will search
86 // for a mapping and find out. It duplicates the file descriptor and
87 // connects. Once the client connects, the server will close the original
88 // copy of the client socket and remove the mapping. Thus, when the client
89 // object closes, it will close the only remaining copy of the client socket
90 // in the fd table and the server will see EOF on its side.
92 // TODO(port): a client process cannot connect to multiple IPC channels with
97 static PipeMap
* GetInstance() {
98 return Singleton
<PipeMap
>::get();
102 // Shouldn't have left over pipes.
103 DCHECK(map_
.empty());
106 // Lookup a given channel id. Return -1 if not found.
107 int Lookup(const std::string
& channel_id
) {
108 base::AutoLock
locked(lock_
);
110 ChannelToFDMap::const_iterator i
= map_
.find(channel_id
);
116 // Remove the mapping for the given channel id. No error is signaled if the
117 // channel_id doesn't exist
118 void Remove(const std::string
& channel_id
) {
119 base::AutoLock
locked(lock_
);
120 map_
.erase(channel_id
);
123 // Insert a mapping from @channel_id to @fd. It's a fatal error to insert a
124 // mapping if one already exists for the given channel_id
125 void Insert(const std::string
& channel_id
, int fd
) {
126 base::AutoLock
locked(lock_
);
129 ChannelToFDMap::const_iterator i
= map_
.find(channel_id
);
130 CHECK(i
== map_
.end()) << "Creating second IPC server (fd " << fd
<< ") "
131 << "for '" << channel_id
<< "' while first "
132 << "(fd " << i
->second
<< ") still exists";
133 map_
[channel_id
] = fd
;
138 typedef std::map
<std::string
, int> ChannelToFDMap
;
141 friend struct DefaultSingletonTraits
<PipeMap
>;
142 #if defined(OS_ANDROID)
143 friend void ::IPC::Channel::NotifyProcessForkedForTesting();
147 //------------------------------------------------------------------------------
149 bool SocketWriteErrorIsRecoverable() {
150 #if defined(OS_MACOSX)
151 // On OS X if sendmsg() is trying to send fds between processes and there
152 // isn't enough room in the output buffer to send the fd structure over
153 // atomically then EMSGSIZE is returned.
155 // EMSGSIZE presents a problem since the system APIs can only call us when
156 // there's room in the socket buffer and not when there is "enough" room.
158 // The current behavior is to return to the event loop when EMSGSIZE is
159 // received and hopefull service another FD. This is however still
160 // technically a busy wait since the event loop will call us right back until
161 // the receiver has read enough data to allow passing the FD over atomically.
162 return errno
== EAGAIN
|| errno
== EMSGSIZE
;
164 return errno
== EAGAIN
;
170 #if defined(OS_ANDROID)
171 // When we fork for simple tests on Android, we can't 'exec', so we need to
172 // reset these entries manually to get the expected testing behavior.
173 void Channel::NotifyProcessForkedForTesting() {
174 PipeMap::GetInstance()->map_
.clear();
178 //------------------------------------------------------------------------------
180 #if defined(OS_LINUX)
181 int ChannelPosix::global_pid_
= 0;
184 ChannelPosix::ChannelPosix(const IPC::ChannelHandle
& channel_handle
,
185 Mode mode
, Listener
* listener
)
186 : ChannelReader(listener
),
188 peer_pid_(base::kNullProcessId
),
189 is_blocked_on_write_(false),
190 waiting_connect_(true),
191 message_send_bytes_written_(0),
192 pipe_name_(channel_handle
.name
),
194 must_unlink_(false) {
195 memset(input_cmsg_buf_
, 0, sizeof(input_cmsg_buf_
));
196 if (!CreatePipe(channel_handle
)) {
197 // The pipe may have been closed already.
198 const char *modestr
= (mode_
& MODE_SERVER_FLAG
) ? "server" : "client";
199 LOG(WARNING
) << "Unable to create pipe named \"" << channel_handle
.name
200 << "\" in " << modestr
<< " mode";
204 ChannelPosix::~ChannelPosix() {
209 bool SocketPair(int* fd1
, int* fd2
) {
211 if (socketpair(AF_UNIX
, SOCK_STREAM
, 0, pipe_fds
) != 0) {
212 PLOG(ERROR
) << "socketpair()";
216 // Set both ends to be non-blocking.
217 if (fcntl(pipe_fds
[0], F_SETFL
, O_NONBLOCK
) == -1 ||
218 fcntl(pipe_fds
[1], F_SETFL
, O_NONBLOCK
) == -1) {
219 PLOG(ERROR
) << "fcntl(O_NONBLOCK)";
220 if (IGNORE_EINTR(close(pipe_fds
[0])) < 0)
221 PLOG(ERROR
) << "close";
222 if (IGNORE_EINTR(close(pipe_fds
[1])) < 0)
223 PLOG(ERROR
) << "close";
233 bool ChannelPosix::CreatePipe(
234 const IPC::ChannelHandle
& channel_handle
) {
235 DCHECK(!server_listen_pipe_
.is_valid() && !pipe_
.is_valid());
237 // Four possible cases:
238 // 1) It's a channel wrapping a pipe that is given to us.
239 // 2) It's for a named channel, so we create it.
240 // 3) It's for a client that we implement ourself. This is used
241 // in single-process unittesting.
242 // 4) It's the initial IPC channel:
243 // 4a) Client side: Pull the pipe out of the GlobalDescriptors set.
244 // 4b) Server side: create the pipe.
246 base::ScopedFD local_pipe
;
247 if (channel_handle
.socket
.fd
!= -1) {
248 // Case 1 from comment above.
249 local_pipe
.reset(channel_handle
.socket
.fd
);
250 #if defined(IPC_USES_READWRITE)
251 // Test the socket passed into us to make sure it is nonblocking.
252 // We don't want to call read/write on a blocking socket.
253 int value
= fcntl(local_pipe
.get(), F_GETFL
);
255 PLOG(ERROR
) << "fcntl(F_GETFL) " << pipe_name_
;
258 if (!(value
& O_NONBLOCK
)) {
259 LOG(ERROR
) << "Socket " << pipe_name_
<< " must be O_NONBLOCK";
262 #endif // IPC_USES_READWRITE
263 } else if (mode_
& MODE_NAMED_FLAG
) {
264 #if defined(OS_NACL_NONSFI)
266 << "IPC channels in nacl_helper_nonsfi should not be in NAMED mode.";
268 // Case 2 from comment above.
269 int local_pipe_fd
= -1;
271 if (mode_
& MODE_SERVER_FLAG
) {
272 if (!CreateServerUnixDomainSocket(base::FilePath(pipe_name_
),
278 } else if (mode_
& MODE_CLIENT_FLAG
) {
279 if (!CreateClientUnixDomainSocket(base::FilePath(pipe_name_
),
284 LOG(ERROR
) << "Bad mode: " << mode_
;
288 local_pipe
.reset(local_pipe_fd
);
289 #endif // !defined(OS_NACL_NONSFI)
291 local_pipe
.reset(PipeMap::GetInstance()->Lookup(pipe_name_
));
292 if (mode_
& MODE_CLIENT_FLAG
) {
293 if (local_pipe
.is_valid()) {
294 // Case 3 from comment above.
295 // We only allow one connection.
296 local_pipe
.reset(HANDLE_EINTR(dup(local_pipe
.release())));
297 PipeMap::GetInstance()->Remove(pipe_name_
);
299 // Case 4a from comment above.
300 // Guard against inappropriate reuse of the initial IPC channel. If
301 // an IPC channel closes and someone attempts to reuse it by name, the
302 // initial channel must not be recycled here. http://crbug.com/26754.
303 static bool used_initial_channel
= false;
304 if (used_initial_channel
) {
305 LOG(FATAL
) << "Denying attempt to reuse initial IPC channel for "
309 used_initial_channel
= true;
312 base::GlobalDescriptors::GetInstance()->Get(kPrimaryIPCChannel
));
314 } else if (mode_
& MODE_SERVER_FLAG
) {
315 // Case 4b from comment above.
316 if (local_pipe
.is_valid()) {
317 LOG(ERROR
) << "Server already exists for " << pipe_name_
;
318 // This is a client side pipe registered by other server and
319 // shouldn't be closed.
320 ignore_result(local_pipe
.release());
323 base::AutoLock
lock(client_pipe_lock_
);
324 int local_pipe_fd
= -1, client_pipe_fd
= -1;
325 if (!SocketPair(&local_pipe_fd
, &client_pipe_fd
))
327 local_pipe
.reset(local_pipe_fd
);
328 client_pipe_
.reset(client_pipe_fd
);
329 PipeMap::GetInstance()->Insert(pipe_name_
, client_pipe_fd
);
331 LOG(ERROR
) << "Bad mode: " << mode_
;
336 #if defined(IPC_USES_READWRITE)
337 // Create a dedicated socketpair() for exchanging file descriptors.
338 // See comments for IPC_USES_READWRITE for details.
339 if (mode_
& MODE_CLIENT_FLAG
) {
340 int fd_pipe_fd
= 1, remote_fd_pipe_fd
= -1;
341 if (!SocketPair(&fd_pipe_fd
, &remote_fd_pipe_fd
)) {
345 fd_pipe_
.reset(fd_pipe_fd
);
346 remote_fd_pipe_
.reset(remote_fd_pipe_fd
);
348 #endif // IPC_USES_READWRITE
350 if ((mode_
& MODE_SERVER_FLAG
) && (mode_
& MODE_NAMED_FLAG
)) {
351 #if defined(OS_NACL_NONSFI)
352 LOG(FATAL
) << "IPC channels in nacl_helper_nonsfi "
353 << "should not be in NAMED or SERVER mode.";
355 server_listen_pipe_
.reset(local_pipe
.release());
358 pipe_
.reset(local_pipe
.release());
363 bool ChannelPosix::Connect() {
364 if (!server_listen_pipe_
.is_valid() && !pipe_
.is_valid()) {
365 DLOG(WARNING
) << "Channel creation failed: " << pipe_name_
;
369 bool did_connect
= true;
370 if (server_listen_pipe_
.is_valid()) {
371 #if defined(OS_NACL_NONSFI)
372 LOG(FATAL
) << "IPC channels in nacl_helper_nonsfi "
373 << "should always be in client mode.";
375 // Watch the pipe for connections, and turn any connections into
377 base::MessageLoopForIO::current()->WatchFileDescriptor(
378 server_listen_pipe_
.get(),
380 base::MessageLoopForIO::WATCH_READ
,
381 &server_listen_connection_watcher_
,
385 did_connect
= AcceptConnection();
390 void ChannelPosix::CloseFileDescriptors(Message
* msg
) {
391 #if defined(OS_MACOSX)
392 // There is a bug on OSX which makes it dangerous to close
393 // a file descriptor while it is in transit. So instead we
394 // store the file descriptor in a set and send a message to
395 // the recipient, which is queued AFTER the message that
396 // sent the FD. The recipient will reply to the message,
397 // letting us know that it is now safe to close the file
398 // descriptor. For more information, see:
399 // http://crbug.com/298276
400 std::vector
<int> to_close
;
401 msg
->attachment_set()->ReleaseFDsToClose(&to_close
);
402 for (size_t i
= 0; i
< to_close
.size(); i
++) {
403 fds_to_close_
.insert(to_close
[i
]);
404 QueueCloseFDMessage(to_close
[i
], 2);
407 msg
->attachment_set()->CommitAll();
411 bool ChannelPosix::ProcessOutgoingMessages() {
412 DCHECK(!waiting_connect_
); // Why are we trying to send messages if there's
414 if (output_queue_
.empty())
417 if (!pipe_
.is_valid())
420 // Write out all the messages we can till the write blocks or there are no
421 // more outgoing messages.
422 while (!output_queue_
.empty()) {
423 Message
* msg
= output_queue_
.front();
425 size_t amt_to_write
= msg
->size() - message_send_bytes_written_
;
426 DCHECK_NE(0U, amt_to_write
);
427 const char* out_bytes
= reinterpret_cast<const char*>(msg
->data()) +
428 message_send_bytes_written_
;
430 struct msghdr msgh
= {0};
431 struct iovec iov
= {const_cast<char*>(out_bytes
), amt_to_write
};
434 char buf
[CMSG_SPACE(sizeof(int) *
435 MessageAttachmentSet::kMaxDescriptorsPerMessage
)];
437 ssize_t bytes_written
= 1;
440 if (message_send_bytes_written_
== 0 && !msg
->attachment_set()->empty()) {
441 // This is the first chunk of a message which has descriptors to send
442 struct cmsghdr
*cmsg
;
443 const unsigned num_fds
= msg
->attachment_set()->size();
445 DCHECK(num_fds
<= MessageAttachmentSet::kMaxDescriptorsPerMessage
);
446 if (msg
->attachment_set()->ContainsDirectoryDescriptor()) {
447 LOG(FATAL
) << "Panic: attempting to transport directory descriptor over"
448 " IPC. Aborting to maintain sandbox isolation.";
449 // If you have hit this then something tried to send a file descriptor
450 // to a directory over an IPC channel. Since IPC channels span
451 // sandboxes this is very bad: the receiving process can use openat
452 // with ".." elements in the path in order to reach the real
456 msgh
.msg_control
= buf
;
457 msgh
.msg_controllen
= CMSG_SPACE(sizeof(int) * num_fds
);
458 cmsg
= CMSG_FIRSTHDR(&msgh
);
459 cmsg
->cmsg_level
= SOL_SOCKET
;
460 cmsg
->cmsg_type
= SCM_RIGHTS
;
461 cmsg
->cmsg_len
= CMSG_LEN(sizeof(int) * num_fds
);
462 msg
->attachment_set()->PeekDescriptors(
463 reinterpret_cast<int*>(CMSG_DATA(cmsg
)));
464 msgh
.msg_controllen
= cmsg
->cmsg_len
;
466 // DCHECK_LE above already checks that
467 // num_fds < kMaxDescriptorsPerMessage so no danger of overflow.
468 msg
->header()->num_fds
= static_cast<uint16
>(num_fds
);
470 #if defined(IPC_USES_READWRITE)
471 if (!IsHelloMessage(*msg
)) {
472 // Only the Hello message sends the file descriptor with the message.
473 // Subsequently, we can send file descriptors on the dedicated
474 // fd_pipe_ which makes Seccomp sandbox operation more efficient.
475 struct iovec fd_pipe_iov
= { const_cast<char *>(""), 1 };
476 msgh
.msg_iov
= &fd_pipe_iov
;
477 fd_written
= fd_pipe_
.get();
479 HANDLE_EINTR(sendmsg(fd_pipe_
.get(), &msgh
, MSG_DONTWAIT
));
481 msgh
.msg_controllen
= 0;
482 if (bytes_written
> 0) {
483 CloseFileDescriptors(msg
);
486 #endif // IPC_USES_READWRITE
489 if (bytes_written
== 1) {
490 fd_written
= pipe_
.get();
491 #if defined(IPC_USES_READWRITE)
492 if ((mode_
& MODE_CLIENT_FLAG
) && IsHelloMessage(*msg
)) {
493 DCHECK_EQ(msg
->attachment_set()->size(), 1U);
495 if (!msgh
.msg_controllen
) {
497 HANDLE_EINTR(write(pipe_
.get(), out_bytes
, amt_to_write
));
499 #endif // IPC_USES_READWRITE
501 bytes_written
= HANDLE_EINTR(sendmsg(pipe_
.get(), &msgh
, MSG_DONTWAIT
));
504 if (bytes_written
> 0)
505 CloseFileDescriptors(msg
);
507 if (bytes_written
< 0 && !SocketWriteErrorIsRecoverable()) {
508 // We can't close the pipe here, because calling OnChannelError
509 // may destroy this object, and that would be bad if we are
510 // called from Send(). Instead, we return false and hope the
511 // caller will close the pipe. If they do not, the pipe will
512 // still be closed next time OnFileCanReadWithoutBlocking is
514 #if defined(OS_MACOSX)
515 // On OSX writing to a pipe with no listener returns EPERM.
516 if (errno
== EPERM
) {
520 if (errno
== EPIPE
) {
523 PLOG(ERROR
) << "pipe error on "
525 << " Currently writing message of size: "
530 if (static_cast<size_t>(bytes_written
) != amt_to_write
) {
531 if (bytes_written
> 0) {
532 // If write() fails with EAGAIN then bytes_written will be -1.
533 message_send_bytes_written_
+= bytes_written
;
536 // Tell libevent to call us back once things are unblocked.
537 is_blocked_on_write_
= true;
538 base::MessageLoopForIO::current()->WatchFileDescriptor(
541 base::MessageLoopForIO::WATCH_WRITE
,
546 message_send_bytes_written_
= 0;
549 DVLOG(2) << "sent message @" << msg
<< " on channel @" << this
550 << " with type " << msg
->type() << " on fd " << pipe_
.get();
551 delete output_queue_
.front();
558 bool ChannelPosix::Send(Message
* message
) {
559 DCHECK(!message
->HasMojoHandles());
560 DVLOG(2) << "sending message @" << message
<< " on channel @" << this
561 << " with type " << message
->type()
562 << " (" << output_queue_
.size() << " in queue)";
564 #ifdef IPC_MESSAGE_LOG_ENABLED
565 Logging::GetInstance()->OnSendMessage(message
, "");
566 #endif // IPC_MESSAGE_LOG_ENABLED
568 message
->TraceMessageBegin();
569 output_queue_
.push(message
);
570 if (!is_blocked_on_write_
&& !waiting_connect_
) {
571 return ProcessOutgoingMessages();
577 int ChannelPosix::GetClientFileDescriptor() const {
578 base::AutoLock
lock(client_pipe_lock_
);
579 return client_pipe_
.get();
582 base::ScopedFD
ChannelPosix::TakeClientFileDescriptor() {
583 base::AutoLock
lock(client_pipe_lock_
);
584 if (!client_pipe_
.is_valid())
585 return base::ScopedFD();
586 PipeMap::GetInstance()->Remove(pipe_name_
);
587 return client_pipe_
.Pass();
590 void ChannelPosix::CloseClientFileDescriptor() {
591 base::AutoLock
lock(client_pipe_lock_
);
592 if (!client_pipe_
.is_valid())
594 PipeMap::GetInstance()->Remove(pipe_name_
);
595 client_pipe_
.reset();
598 bool ChannelPosix::AcceptsConnections() const {
599 return server_listen_pipe_
.is_valid();
602 bool ChannelPosix::HasAcceptedConnection() const {
603 return AcceptsConnections() && pipe_
.is_valid();
606 #if !defined(OS_NACL_NONSFI)
607 // GetPeerEuid is not supported in nacl_helper_nonsfi.
608 bool ChannelPosix::GetPeerEuid(uid_t
* peer_euid
) const {
609 DCHECK(!(mode_
& MODE_SERVER
) || HasAcceptedConnection());
610 return IPC::GetPeerEuid(pipe_
.get(), peer_euid
);
614 void ChannelPosix::ResetToAcceptingConnectionState() {
615 // Unregister libevent for the unix domain socket and close it.
616 read_watcher_
.StopWatchingFileDescriptor();
617 write_watcher_
.StopWatchingFileDescriptor();
619 #if defined(IPC_USES_READWRITE)
621 remote_fd_pipe_
.reset();
622 #endif // IPC_USES_READWRITE
624 while (!output_queue_
.empty()) {
625 Message
* m
= output_queue_
.front();
630 // Close any outstanding, received file descriptors.
633 #if defined(OS_MACOSX)
634 // Clear any outstanding, sent file descriptors.
635 for (std::set
<int>::iterator i
= fds_to_close_
.begin();
636 i
!= fds_to_close_
.end();
638 if (IGNORE_EINTR(close(*i
)) < 0)
639 PLOG(ERROR
) << "close";
641 fds_to_close_
.clear();
646 bool ChannelPosix::IsNamedServerInitialized(
647 const std::string
& channel_id
) {
648 return base::PathExists(base::FilePath(channel_id
));
651 #if defined(OS_LINUX)
653 void ChannelPosix::SetGlobalPid(int pid
) {
658 // Called by libevent when we can read from the pipe without blocking.
659 void ChannelPosix::OnFileCanReadWithoutBlocking(int fd
) {
660 if (fd
== server_listen_pipe_
.get()) {
661 #if defined(OS_NACL_NONSFI)
663 << "IPC channels in nacl_helper_nonsfi should not be SERVER mode.";
666 if (!ServerAcceptConnection(server_listen_pipe_
.get(), &new_pipe
) ||
669 listener()->OnChannelListenError();
672 if (pipe_
.is_valid()) {
673 // We already have a connection. We only handle one at a time.
674 // close our new descriptor.
675 if (HANDLE_EINTR(shutdown(new_pipe
, SHUT_RDWR
)) < 0)
676 DPLOG(ERROR
) << "shutdown " << pipe_name_
;
677 if (IGNORE_EINTR(close(new_pipe
)) < 0)
678 DPLOG(ERROR
) << "close " << pipe_name_
;
679 listener()->OnChannelDenied();
682 pipe_
.reset(new_pipe
);
684 if ((mode_
& MODE_OPEN_ACCESS_FLAG
) == 0) {
685 // Verify that the IPC channel peer is running as the same user.
687 if (!GetPeerEuid(&client_euid
)) {
688 DLOG(ERROR
) << "Unable to query client euid";
689 ResetToAcceptingConnectionState();
692 if (client_euid
!= geteuid()) {
693 DLOG(WARNING
) << "Client euid is not authorised";
694 ResetToAcceptingConnectionState();
699 if (!AcceptConnection()) {
700 NOTREACHED() << "AcceptConnection should not fail on server";
702 waiting_connect_
= false;
704 } else if (fd
== pipe_
) {
705 if (waiting_connect_
&& (mode_
& MODE_SERVER_FLAG
)) {
706 waiting_connect_
= false;
708 if (!ProcessIncomingMessages()) {
709 // ClosePipeOnError may delete this object, so we mustn't call
710 // ProcessOutgoingMessages.
715 NOTREACHED() << "Unknown pipe " << fd
;
718 // If we're a server and handshaking, then we want to make sure that we
719 // only send our handshake message after we've processed the client's.
720 // This gives us a chance to kill the client if the incoming handshake
721 // is invalid. This also flushes any closefd messages.
722 if (!is_blocked_on_write_
) {
723 if (!ProcessOutgoingMessages()) {
729 // Called by libevent when we can write to the pipe without blocking.
730 void ChannelPosix::OnFileCanWriteWithoutBlocking(int fd
) {
731 DCHECK_EQ(pipe_
.get(), fd
);
732 is_blocked_on_write_
= false;
733 if (!ProcessOutgoingMessages()) {
738 bool ChannelPosix::AcceptConnection() {
739 base::MessageLoopForIO::current()->WatchFileDescriptor(
742 base::MessageLoopForIO::WATCH_READ
,
747 if (mode_
& MODE_CLIENT_FLAG
) {
748 // If we are a client we want to send a hello message out immediately.
749 // In server mode we will send a hello message when we receive one from a
751 waiting_connect_
= false;
752 return ProcessOutgoingMessages();
753 } else if (mode_
& MODE_SERVER_FLAG
) {
754 waiting_connect_
= true;
762 void ChannelPosix::ClosePipeOnError() {
763 if (HasAcceptedConnection()) {
764 ResetToAcceptingConnectionState();
765 listener()->OnChannelError();
768 if (AcceptsConnections()) {
769 listener()->OnChannelListenError();
771 listener()->OnChannelError();
776 int ChannelPosix::GetHelloMessageProcId() const {
777 #if defined(OS_NACL_NONSFI)
778 // In nacl_helper_nonsfi, getpid() invoked by GetCurrentProcId() is not
779 // allowed and would cause a SIGSYS crash because of the seccomp sandbox.
782 int pid
= base::GetCurrentProcId();
783 #if defined(OS_LINUX)
784 // Our process may be in a sandbox with a separate PID namespace.
788 #endif // defined(OS_LINUX)
790 #endif // defined(OS_NACL_NONSFI)
793 void ChannelPosix::QueueHelloMessage() {
794 // Create the Hello message
795 scoped_ptr
<Message
> msg(new Message(MSG_ROUTING_NONE
,
797 IPC::Message::PRIORITY_NORMAL
));
798 if (!msg
->WriteInt(GetHelloMessageProcId())) {
799 NOTREACHED() << "Unable to pickle hello message proc id";
801 #if defined(IPC_USES_READWRITE)
802 scoped_ptr
<Message
> hello
;
803 if (remote_fd_pipe_
.is_valid()) {
804 if (!msg
->WriteAttachment(
805 new internal::PlatformFileAttachment(remote_fd_pipe_
.get()))) {
806 NOTREACHED() << "Unable to pickle hello message file descriptors";
808 DCHECK_EQ(msg
->attachment_set()->size(), 1U);
810 #endif // IPC_USES_READWRITE
811 output_queue_
.push(msg
.release());
814 ChannelPosix::ReadState
ChannelPosix::ReadData(
818 if (!pipe_
.is_valid())
821 struct msghdr msg
= {0};
823 struct iovec iov
= {buffer
, static_cast<size_t>(buffer_len
)};
827 msg
.msg_control
= input_cmsg_buf_
;
829 // recvmsg() returns 0 if the connection has closed or EAGAIN if no data
830 // is waiting on the pipe.
831 #if defined(IPC_USES_READWRITE)
832 if (fd_pipe_
.is_valid()) {
833 *bytes_read
= HANDLE_EINTR(read(pipe_
.get(), buffer
, buffer_len
));
834 msg
.msg_controllen
= 0;
836 #endif // IPC_USES_READWRITE
838 msg
.msg_controllen
= sizeof(input_cmsg_buf_
);
839 *bytes_read
= HANDLE_EINTR(recvmsg(pipe_
.get(), &msg
, MSG_DONTWAIT
));
841 if (*bytes_read
< 0) {
842 if (errno
== EAGAIN
) {
844 #if defined(OS_MACOSX)
845 } else if (errno
== EPERM
) {
846 // On OSX, reading from a pipe with no listener returns EPERM
847 // treat this as a special case to prevent spurious error messages
851 } else if (errno
== ECONNRESET
|| errno
== EPIPE
) {
854 PLOG(ERROR
) << "pipe error (" << pipe_
.get() << ")";
857 } else if (*bytes_read
== 0) {
858 // The pipe has closed...
863 CloseClientFileDescriptor();
865 // Read any file descriptors from the message.
866 if (!ExtractFileDescriptorsFromMsghdr(&msg
))
868 return READ_SUCCEEDED
;
871 #if defined(IPC_USES_READWRITE)
872 bool ChannelPosix::ReadFileDescriptorsFromFDPipe() {
874 struct iovec fd_pipe_iov
= { &dummy
, 1 };
876 struct msghdr msg
= { 0 };
877 msg
.msg_iov
= &fd_pipe_iov
;
879 msg
.msg_control
= input_cmsg_buf_
;
880 msg
.msg_controllen
= sizeof(input_cmsg_buf_
);
881 ssize_t bytes_received
=
882 HANDLE_EINTR(recvmsg(fd_pipe_
.get(), &msg
, MSG_DONTWAIT
));
884 if (bytes_received
!= 1)
885 return true; // No message waiting.
887 if (!ExtractFileDescriptorsFromMsghdr(&msg
))
893 // On Posix, we need to fix up the file descriptors before the input message
896 // This will read from the input_fds_ (READWRITE mode only) and read more
897 // handles from the FD pipe if necessary.
898 bool ChannelPosix::WillDispatchInputMessage(Message
* msg
) {
899 uint16 header_fds
= msg
->header()->num_fds
;
901 return true; // Nothing to do.
903 // The message has file descriptors.
904 const char* error
= NULL
;
905 if (header_fds
> input_fds_
.size()) {
906 // The message has been completely received, but we didn't get
907 // enough file descriptors.
908 #if defined(IPC_USES_READWRITE)
909 if (!ReadFileDescriptorsFromFDPipe())
911 if (header_fds
> input_fds_
.size())
912 #endif // IPC_USES_READWRITE
913 error
= "Message needs unreceived descriptors";
916 if (header_fds
> MessageAttachmentSet::kMaxDescriptorsPerMessage
)
917 error
= "Message requires an excessive number of descriptors";
920 LOG(WARNING
) << error
921 << " channel:" << this
922 << " message-type:" << msg
->type()
923 << " header()->num_fds:" << header_fds
;
924 // Abort the connection.
929 // The shenaniganery below with &foo.front() requires input_fds_ to have
930 // contiguous underlying storage (such as a simple array or a std::vector).
931 // This is why the header warns not to make input_fds_ a deque<>.
932 msg
->attachment_set()->AddDescriptorsToOwn(&input_fds_
.front(), header_fds
);
933 input_fds_
.erase(input_fds_
.begin(), input_fds_
.begin() + header_fds
);
937 bool ChannelPosix::DidEmptyInputBuffers() {
938 // When the input data buffer is empty, the fds should be too. If this is
939 // not the case, we probably have a rogue renderer which is trying to fill
940 // our descriptor table.
941 return input_fds_
.empty();
944 bool ChannelPosix::ExtractFileDescriptorsFromMsghdr(msghdr
* msg
) {
945 // Check that there are any control messages. On OSX, CMSG_FIRSTHDR will
946 // return an invalid non-NULL pointer in the case that controllen == 0.
947 if (msg
->msg_controllen
== 0)
950 for (cmsghdr
* cmsg
= CMSG_FIRSTHDR(msg
);
952 cmsg
= CMSG_NXTHDR(msg
, cmsg
)) {
953 if (cmsg
->cmsg_level
== SOL_SOCKET
&& cmsg
->cmsg_type
== SCM_RIGHTS
) {
954 unsigned payload_len
= cmsg
->cmsg_len
- CMSG_LEN(0);
955 DCHECK_EQ(0U, payload_len
% sizeof(int));
956 const int* file_descriptors
= reinterpret_cast<int*>(CMSG_DATA(cmsg
));
957 unsigned num_file_descriptors
= payload_len
/ 4;
958 input_fds_
.insert(input_fds_
.end(),
960 file_descriptors
+ num_file_descriptors
);
962 // Check this after adding the FDs so we don't leak them.
963 if (msg
->msg_flags
& MSG_CTRUNC
) {
972 // No file descriptors found, but that's OK.
976 void ChannelPosix::ClearInputFDs() {
977 for (size_t i
= 0; i
< input_fds_
.size(); ++i
) {
978 if (IGNORE_EINTR(close(input_fds_
[i
])) < 0)
979 PLOG(ERROR
) << "close ";
984 void ChannelPosix::QueueCloseFDMessage(int fd
, int hops
) {
988 // Create the message
989 scoped_ptr
<Message
> msg(new Message(MSG_ROUTING_NONE
,
990 CLOSE_FD_MESSAGE_TYPE
,
991 IPC::Message::PRIORITY_NORMAL
));
992 if (!msg
->WriteInt(hops
- 1) || !msg
->WriteInt(fd
)) {
993 NOTREACHED() << "Unable to pickle close fd.";
995 // Send(msg.release());
996 output_queue_
.push(msg
.release());
1006 void ChannelPosix::HandleInternalMessage(const Message
& msg
) {
1007 // The Hello message contains only the process id.
1008 PickleIterator
iter(msg
);
1010 switch (msg
.type()) {
1015 case Channel::HELLO_MESSAGE_TYPE
:
1017 if (!iter
.ReadInt(&pid
))
1020 #if defined(IPC_USES_READWRITE)
1021 if (mode_
& MODE_SERVER_FLAG
) {
1022 // With IPC_USES_READWRITE, the Hello message from the client to the
1023 // server also contains the fd_pipe_, which will be used for all
1024 // subsequent file descriptor passing.
1025 DCHECK_EQ(msg
.attachment_set()->size(), 1U);
1026 scoped_refptr
<MessageAttachment
> attachment
;
1027 if (!msg
.ReadAttachment(&iter
, &attachment
)) {
1030 fd_pipe_
.reset(attachment
->TakePlatformFile());
1032 #endif // IPC_USES_READWRITE
1034 listener()->OnChannelConnected(pid
);
1037 #if defined(OS_MACOSX)
1038 case Channel::CLOSE_FD_MESSAGE_TYPE
:
1040 if (!iter
.ReadInt(&hops
))
1042 if (!iter
.ReadInt(&fd
))
1045 if (fds_to_close_
.erase(fd
) > 0) {
1046 if (IGNORE_EINTR(close(fd
)) < 0)
1047 PLOG(ERROR
) << "close";
1052 QueueCloseFDMessage(fd
, hops
);
1059 void ChannelPosix::Close() {
1060 // Close can be called multiple time, so we need to make sure we're
1063 ResetToAcceptingConnectionState();
1066 unlink(pipe_name_
.c_str());
1067 must_unlink_
= false;
1070 if (server_listen_pipe_
.is_valid()) {
1071 #if defined(OS_NACL_NONSFI)
1073 << "IPC channels in nacl_helper_nonsfi should not be SERVER mode.";
1075 server_listen_pipe_
.reset();
1076 // Unregister libevent for the listening socket and close it.
1077 server_listen_connection_watcher_
.StopWatchingFileDescriptor();
1081 CloseClientFileDescriptor();
1084 base::ProcessId
ChannelPosix::GetPeerPID() const {
1088 base::ProcessId
ChannelPosix::GetSelfPID() const {
1089 return GetHelloMessageProcId();
1092 void ChannelPosix::ResetSafely(base::ScopedFD
* fd
) {
1099 // The CL [1] tightened the error check for closing FDs, but it turned
1100 // out that there are existing cases that hit the newly added check.
1101 // ResetSafely() is the workaround for that crash, turning it from
1102 // from PCHECK() to DPCHECK() so that it doesn't crash in production.
1103 // [1] https://crrev.com/ce44fef5fd60dd2be5c587d4b084bdcd36adcee4
1104 int fd_to_close
= fd
->release();
1105 if (-1 != fd_to_close
) {
1106 int rv
= IGNORE_EINTR(close(fd_to_close
));
1111 //------------------------------------------------------------------------------
1112 // Channel's methods
1115 scoped_ptr
<Channel
> Channel::Create(
1116 const IPC::ChannelHandle
&channel_handle
, Mode mode
, Listener
* listener
) {
1117 return make_scoped_ptr(new ChannelPosix(channel_handle
, mode
, listener
));
1121 std::string
Channel::GenerateVerifiedChannelID(const std::string
& prefix
) {
1122 // A random name is sufficient validation on posix systems, so we don't need
1123 // an additional shared secret.
1125 std::string id
= prefix
;
1129 return id
.append(GenerateUniqueRandomChannelID());
1133 bool Channel::IsNamedServerInitialized(
1134 const std::string
& channel_id
) {
1135 return ChannelPosix::IsNamedServerInitialized(channel_id
);
1138 #if defined(OS_LINUX)
1140 void Channel::SetGlobalPid(int pid
) {
1141 ChannelPosix::SetGlobalPid(pid
);