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 DVLOG(2) << "sending message @" << message
<< " on channel @" << this
560 << " with type " << message
->type()
561 << " (" << output_queue_
.size() << " in queue)";
563 #ifdef IPC_MESSAGE_LOG_ENABLED
564 Logging::GetInstance()->OnSendMessage(message
, "");
565 #endif // IPC_MESSAGE_LOG_ENABLED
567 message
->TraceMessageBegin();
568 output_queue_
.push(message
);
569 if (!is_blocked_on_write_
&& !waiting_connect_
) {
570 return ProcessOutgoingMessages();
576 int ChannelPosix::GetClientFileDescriptor() const {
577 base::AutoLock
lock(client_pipe_lock_
);
578 return client_pipe_
.get();
581 base::ScopedFD
ChannelPosix::TakeClientFileDescriptor() {
582 base::AutoLock
lock(client_pipe_lock_
);
583 if (!client_pipe_
.is_valid())
584 return base::ScopedFD();
585 PipeMap::GetInstance()->Remove(pipe_name_
);
586 return client_pipe_
.Pass();
589 void ChannelPosix::CloseClientFileDescriptor() {
590 base::AutoLock
lock(client_pipe_lock_
);
591 if (!client_pipe_
.is_valid())
593 PipeMap::GetInstance()->Remove(pipe_name_
);
594 client_pipe_
.reset();
597 bool ChannelPosix::AcceptsConnections() const {
598 return server_listen_pipe_
.is_valid();
601 bool ChannelPosix::HasAcceptedConnection() const {
602 return AcceptsConnections() && pipe_
.is_valid();
605 #if !defined(OS_NACL_NONSFI)
606 // GetPeerEuid is not supported in nacl_helper_nonsfi.
607 bool ChannelPosix::GetPeerEuid(uid_t
* peer_euid
) const {
608 DCHECK(!(mode_
& MODE_SERVER
) || HasAcceptedConnection());
609 return IPC::GetPeerEuid(pipe_
.get(), peer_euid
);
613 void ChannelPosix::ResetToAcceptingConnectionState() {
614 // Unregister libevent for the unix domain socket and close it.
615 read_watcher_
.StopWatchingFileDescriptor();
616 write_watcher_
.StopWatchingFileDescriptor();
618 #if defined(IPC_USES_READWRITE)
620 remote_fd_pipe_
.reset();
621 #endif // IPC_USES_READWRITE
623 while (!output_queue_
.empty()) {
624 Message
* m
= output_queue_
.front();
629 // Close any outstanding, received file descriptors.
632 #if defined(OS_MACOSX)
633 // Clear any outstanding, sent file descriptors.
634 for (std::set
<int>::iterator i
= fds_to_close_
.begin();
635 i
!= fds_to_close_
.end();
637 if (IGNORE_EINTR(close(*i
)) < 0)
638 PLOG(ERROR
) << "close";
640 fds_to_close_
.clear();
645 bool ChannelPosix::IsNamedServerInitialized(
646 const std::string
& channel_id
) {
647 return base::PathExists(base::FilePath(channel_id
));
650 #if defined(OS_LINUX)
652 void ChannelPosix::SetGlobalPid(int pid
) {
657 // Called by libevent when we can read from the pipe without blocking.
658 void ChannelPosix::OnFileCanReadWithoutBlocking(int fd
) {
659 if (fd
== server_listen_pipe_
.get()) {
660 #if defined(OS_NACL_NONSFI)
662 << "IPC channels in nacl_helper_nonsfi should not be SERVER mode.";
665 if (!ServerAcceptConnection(server_listen_pipe_
.get(), &new_pipe
) ||
668 listener()->OnChannelListenError();
671 if (pipe_
.is_valid()) {
672 // We already have a connection. We only handle one at a time.
673 // close our new descriptor.
674 if (HANDLE_EINTR(shutdown(new_pipe
, SHUT_RDWR
)) < 0)
675 DPLOG(ERROR
) << "shutdown " << pipe_name_
;
676 if (IGNORE_EINTR(close(new_pipe
)) < 0)
677 DPLOG(ERROR
) << "close " << pipe_name_
;
678 listener()->OnChannelDenied();
681 pipe_
.reset(new_pipe
);
683 if ((mode_
& MODE_OPEN_ACCESS_FLAG
) == 0) {
684 // Verify that the IPC channel peer is running as the same user.
686 if (!GetPeerEuid(&client_euid
)) {
687 DLOG(ERROR
) << "Unable to query client euid";
688 ResetToAcceptingConnectionState();
691 if (client_euid
!= geteuid()) {
692 DLOG(WARNING
) << "Client euid is not authorised";
693 ResetToAcceptingConnectionState();
698 if (!AcceptConnection()) {
699 NOTREACHED() << "AcceptConnection should not fail on server";
701 waiting_connect_
= false;
703 } else if (fd
== pipe_
) {
704 if (waiting_connect_
&& (mode_
& MODE_SERVER_FLAG
)) {
705 waiting_connect_
= false;
707 if (!ProcessIncomingMessages()) {
708 // ClosePipeOnError may delete this object, so we mustn't call
709 // ProcessOutgoingMessages.
714 NOTREACHED() << "Unknown pipe " << fd
;
717 // If we're a server and handshaking, then we want to make sure that we
718 // only send our handshake message after we've processed the client's.
719 // This gives us a chance to kill the client if the incoming handshake
720 // is invalid. This also flushes any closefd messages.
721 if (!is_blocked_on_write_
) {
722 if (!ProcessOutgoingMessages()) {
728 // Called by libevent when we can write to the pipe without blocking.
729 void ChannelPosix::OnFileCanWriteWithoutBlocking(int fd
) {
730 DCHECK_EQ(pipe_
.get(), fd
);
731 is_blocked_on_write_
= false;
732 if (!ProcessOutgoingMessages()) {
737 bool ChannelPosix::AcceptConnection() {
738 base::MessageLoopForIO::current()->WatchFileDescriptor(
741 base::MessageLoopForIO::WATCH_READ
,
746 if (mode_
& MODE_CLIENT_FLAG
) {
747 // If we are a client we want to send a hello message out immediately.
748 // In server mode we will send a hello message when we receive one from a
750 waiting_connect_
= false;
751 return ProcessOutgoingMessages();
752 } else if (mode_
& MODE_SERVER_FLAG
) {
753 waiting_connect_
= true;
761 void ChannelPosix::ClosePipeOnError() {
762 if (HasAcceptedConnection()) {
763 ResetToAcceptingConnectionState();
764 listener()->OnChannelError();
767 if (AcceptsConnections()) {
768 listener()->OnChannelListenError();
770 listener()->OnChannelError();
775 int ChannelPosix::GetHelloMessageProcId() const {
776 int pid
= base::GetCurrentProcId();
777 #if defined(OS_LINUX)
778 // Our process may be in a sandbox with a separate PID namespace.
786 void ChannelPosix::QueueHelloMessage() {
787 // Create the Hello message
788 scoped_ptr
<Message
> msg(new Message(MSG_ROUTING_NONE
,
790 IPC::Message::PRIORITY_NORMAL
));
791 if (!msg
->WriteInt(GetHelloMessageProcId())) {
792 NOTREACHED() << "Unable to pickle hello message proc id";
794 #if defined(IPC_USES_READWRITE)
795 scoped_ptr
<Message
> hello
;
796 if (remote_fd_pipe_
.is_valid()) {
797 if (!msg
->WriteAttachment(
798 new internal::PlatformFileAttachment(remote_fd_pipe_
.get()))) {
799 NOTREACHED() << "Unable to pickle hello message file descriptors";
801 DCHECK_EQ(msg
->attachment_set()->size(), 1U);
803 #endif // IPC_USES_READWRITE
804 output_queue_
.push(msg
.release());
807 ChannelPosix::ReadState
ChannelPosix::ReadData(
811 if (!pipe_
.is_valid())
814 struct msghdr msg
= {0};
816 struct iovec iov
= {buffer
, static_cast<size_t>(buffer_len
)};
820 msg
.msg_control
= input_cmsg_buf_
;
822 // recvmsg() returns 0 if the connection has closed or EAGAIN if no data
823 // is waiting on the pipe.
824 #if defined(IPC_USES_READWRITE)
825 if (fd_pipe_
.is_valid()) {
826 *bytes_read
= HANDLE_EINTR(read(pipe_
.get(), buffer
, buffer_len
));
827 msg
.msg_controllen
= 0;
829 #endif // IPC_USES_READWRITE
831 msg
.msg_controllen
= sizeof(input_cmsg_buf_
);
832 *bytes_read
= HANDLE_EINTR(recvmsg(pipe_
.get(), &msg
, MSG_DONTWAIT
));
834 if (*bytes_read
< 0) {
835 if (errno
== EAGAIN
) {
837 #if defined(OS_MACOSX)
838 } else if (errno
== EPERM
) {
839 // On OSX, reading from a pipe with no listener returns EPERM
840 // treat this as a special case to prevent spurious error messages
844 } else if (errno
== ECONNRESET
|| errno
== EPIPE
) {
847 PLOG(ERROR
) << "pipe error (" << pipe_
.get() << ")";
850 } else if (*bytes_read
== 0) {
851 // The pipe has closed...
856 CloseClientFileDescriptor();
858 // Read any file descriptors from the message.
859 if (!ExtractFileDescriptorsFromMsghdr(&msg
))
861 return READ_SUCCEEDED
;
864 #if defined(IPC_USES_READWRITE)
865 bool ChannelPosix::ReadFileDescriptorsFromFDPipe() {
867 struct iovec fd_pipe_iov
= { &dummy
, 1 };
869 struct msghdr msg
= { 0 };
870 msg
.msg_iov
= &fd_pipe_iov
;
872 msg
.msg_control
= input_cmsg_buf_
;
873 msg
.msg_controllen
= sizeof(input_cmsg_buf_
);
874 ssize_t bytes_received
=
875 HANDLE_EINTR(recvmsg(fd_pipe_
.get(), &msg
, MSG_DONTWAIT
));
877 if (bytes_received
!= 1)
878 return true; // No message waiting.
880 if (!ExtractFileDescriptorsFromMsghdr(&msg
))
886 // On Posix, we need to fix up the file descriptors before the input message
889 // This will read from the input_fds_ (READWRITE mode only) and read more
890 // handles from the FD pipe if necessary.
891 bool ChannelPosix::WillDispatchInputMessage(Message
* msg
) {
892 uint16 header_fds
= msg
->header()->num_fds
;
894 return true; // Nothing to do.
896 // The message has file descriptors.
897 const char* error
= NULL
;
898 if (header_fds
> input_fds_
.size()) {
899 // The message has been completely received, but we didn't get
900 // enough file descriptors.
901 #if defined(IPC_USES_READWRITE)
902 if (!ReadFileDescriptorsFromFDPipe())
904 if (header_fds
> input_fds_
.size())
905 #endif // IPC_USES_READWRITE
906 error
= "Message needs unreceived descriptors";
909 if (header_fds
> MessageAttachmentSet::kMaxDescriptorsPerMessage
)
910 error
= "Message requires an excessive number of descriptors";
913 LOG(WARNING
) << error
914 << " channel:" << this
915 << " message-type:" << msg
->type()
916 << " header()->num_fds:" << header_fds
;
917 // Abort the connection.
922 // The shenaniganery below with &foo.front() requires input_fds_ to have
923 // contiguous underlying storage (such as a simple array or a std::vector).
924 // This is why the header warns not to make input_fds_ a deque<>.
925 msg
->attachment_set()->AddDescriptorsToOwn(&input_fds_
.front(), header_fds
);
926 input_fds_
.erase(input_fds_
.begin(), input_fds_
.begin() + header_fds
);
930 bool ChannelPosix::DidEmptyInputBuffers() {
931 // When the input data buffer is empty, the fds should be too. If this is
932 // not the case, we probably have a rogue renderer which is trying to fill
933 // our descriptor table.
934 return input_fds_
.empty();
937 bool ChannelPosix::ExtractFileDescriptorsFromMsghdr(msghdr
* msg
) {
938 // Check that there are any control messages. On OSX, CMSG_FIRSTHDR will
939 // return an invalid non-NULL pointer in the case that controllen == 0.
940 if (msg
->msg_controllen
== 0)
943 for (cmsghdr
* cmsg
= CMSG_FIRSTHDR(msg
);
945 cmsg
= CMSG_NXTHDR(msg
, cmsg
)) {
946 if (cmsg
->cmsg_level
== SOL_SOCKET
&& cmsg
->cmsg_type
== SCM_RIGHTS
) {
947 unsigned payload_len
= cmsg
->cmsg_len
- CMSG_LEN(0);
948 DCHECK_EQ(0U, payload_len
% sizeof(int));
949 const int* file_descriptors
= reinterpret_cast<int*>(CMSG_DATA(cmsg
));
950 unsigned num_file_descriptors
= payload_len
/ 4;
951 input_fds_
.insert(input_fds_
.end(),
953 file_descriptors
+ num_file_descriptors
);
955 // Check this after adding the FDs so we don't leak them.
956 if (msg
->msg_flags
& MSG_CTRUNC
) {
965 // No file descriptors found, but that's OK.
969 void ChannelPosix::ClearInputFDs() {
970 for (size_t i
= 0; i
< input_fds_
.size(); ++i
) {
971 if (IGNORE_EINTR(close(input_fds_
[i
])) < 0)
972 PLOG(ERROR
) << "close ";
977 void ChannelPosix::QueueCloseFDMessage(int fd
, int hops
) {
981 // Create the message
982 scoped_ptr
<Message
> msg(new Message(MSG_ROUTING_NONE
,
983 CLOSE_FD_MESSAGE_TYPE
,
984 IPC::Message::PRIORITY_NORMAL
));
985 if (!msg
->WriteInt(hops
- 1) || !msg
->WriteInt(fd
)) {
986 NOTREACHED() << "Unable to pickle close fd.";
988 // Send(msg.release());
989 output_queue_
.push(msg
.release());
999 void ChannelPosix::HandleInternalMessage(const Message
& msg
) {
1000 // The Hello message contains only the process id.
1001 PickleIterator
iter(msg
);
1003 switch (msg
.type()) {
1008 case Channel::HELLO_MESSAGE_TYPE
:
1010 if (!iter
.ReadInt(&pid
))
1013 #if defined(IPC_USES_READWRITE)
1014 if (mode_
& MODE_SERVER_FLAG
) {
1015 // With IPC_USES_READWRITE, the Hello message from the client to the
1016 // server also contains the fd_pipe_, which will be used for all
1017 // subsequent file descriptor passing.
1018 DCHECK_EQ(msg
.attachment_set()->size(), 1U);
1019 scoped_refptr
<MessageAttachment
> attachment
;
1020 if (!msg
.ReadAttachment(&iter
, &attachment
)) {
1023 fd_pipe_
.reset(attachment
->TakePlatformFile());
1025 #endif // IPC_USES_READWRITE
1027 listener()->OnChannelConnected(pid
);
1030 #if defined(OS_MACOSX)
1031 case Channel::CLOSE_FD_MESSAGE_TYPE
:
1033 if (!iter
.ReadInt(&hops
))
1035 if (!iter
.ReadInt(&fd
))
1038 if (fds_to_close_
.erase(fd
) > 0) {
1039 if (IGNORE_EINTR(close(fd
)) < 0)
1040 PLOG(ERROR
) << "close";
1045 QueueCloseFDMessage(fd
, hops
);
1052 void ChannelPosix::Close() {
1053 // Close can be called multiple time, so we need to make sure we're
1056 ResetToAcceptingConnectionState();
1059 unlink(pipe_name_
.c_str());
1060 must_unlink_
= false;
1063 if (server_listen_pipe_
.is_valid()) {
1064 #if defined(OS_NACL_NONSFI)
1066 << "IPC channels in nacl_helper_nonsfi should not be SERVER mode.";
1068 server_listen_pipe_
.reset();
1069 // Unregister libevent for the listening socket and close it.
1070 server_listen_connection_watcher_
.StopWatchingFileDescriptor();
1074 CloseClientFileDescriptor();
1077 base::ProcessId
ChannelPosix::GetPeerPID() const {
1081 base::ProcessId
ChannelPosix::GetSelfPID() const {
1082 return GetHelloMessageProcId();
1085 void ChannelPosix::ResetSafely(base::ScopedFD
* fd
) {
1092 // The CL [1] tightened the error check for closing FDs, but it turned
1093 // out that there are existing cases that hit the newly added check.
1094 // ResetSafely() is the workaround for that crash, turning it from
1095 // from PCHECK() to DPCHECK() so that it doesn't crash in production.
1096 // [1] https://crrev.com/ce44fef5fd60dd2be5c587d4b084bdcd36adcee4
1097 int fd_to_close
= fd
->release();
1098 if (-1 != fd_to_close
) {
1099 int rv
= IGNORE_EINTR(close(fd_to_close
));
1104 //------------------------------------------------------------------------------
1105 // Channel's methods
1108 scoped_ptr
<Channel
> Channel::Create(
1109 const IPC::ChannelHandle
&channel_handle
, Mode mode
, Listener
* listener
) {
1110 return make_scoped_ptr(new ChannelPosix(channel_handle
, mode
, listener
));
1114 std::string
Channel::GenerateVerifiedChannelID(const std::string
& prefix
) {
1115 // A random name is sufficient validation on posix systems, so we don't need
1116 // an additional shared secret.
1118 std::string id
= prefix
;
1122 return id
.append(GenerateUniqueRandomChannelID());
1126 bool Channel::IsNamedServerInitialized(
1127 const std::string
& channel_id
) {
1128 return ChannelPosix::IsNamedServerInitialized(channel_id
);
1131 #if defined(OS_LINUX)
1133 void Channel::SetGlobalPid(int pid
) {
1134 ChannelPosix::SetGlobalPid(pid
);