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 #if defined(OS_NACL_NONSFI)
777 // In nacl_helper_nonsfi, getpid() invoked by GetCurrentProcId() is not
778 // allowed and would cause a SIGSYS crash because of the seccomp sandbox.
781 int pid
= base::GetCurrentProcId();
782 #if defined(OS_LINUX)
783 // Our process may be in a sandbox with a separate PID namespace.
787 #endif // defined(OS_LINUX)
789 #endif // defined(OS_NACL_NONSFI)
792 void ChannelPosix::QueueHelloMessage() {
793 // Create the Hello message
794 scoped_ptr
<Message
> msg(new Message(MSG_ROUTING_NONE
,
796 IPC::Message::PRIORITY_NORMAL
));
797 if (!msg
->WriteInt(GetHelloMessageProcId())) {
798 NOTREACHED() << "Unable to pickle hello message proc id";
800 #if defined(IPC_USES_READWRITE)
801 scoped_ptr
<Message
> hello
;
802 if (remote_fd_pipe_
.is_valid()) {
803 if (!msg
->WriteAttachment(
804 new internal::PlatformFileAttachment(remote_fd_pipe_
.get()))) {
805 NOTREACHED() << "Unable to pickle hello message file descriptors";
807 DCHECK_EQ(msg
->attachment_set()->size(), 1U);
809 #endif // IPC_USES_READWRITE
810 output_queue_
.push(msg
.release());
813 ChannelPosix::ReadState
ChannelPosix::ReadData(
817 if (!pipe_
.is_valid())
820 struct msghdr msg
= {0};
822 struct iovec iov
= {buffer
, static_cast<size_t>(buffer_len
)};
826 msg
.msg_control
= input_cmsg_buf_
;
828 // recvmsg() returns 0 if the connection has closed or EAGAIN if no data
829 // is waiting on the pipe.
830 #if defined(IPC_USES_READWRITE)
831 if (fd_pipe_
.is_valid()) {
832 *bytes_read
= HANDLE_EINTR(read(pipe_
.get(), buffer
, buffer_len
));
833 msg
.msg_controllen
= 0;
835 #endif // IPC_USES_READWRITE
837 msg
.msg_controllen
= sizeof(input_cmsg_buf_
);
838 *bytes_read
= HANDLE_EINTR(recvmsg(pipe_
.get(), &msg
, MSG_DONTWAIT
));
840 if (*bytes_read
< 0) {
841 if (errno
== EAGAIN
) {
843 #if defined(OS_MACOSX)
844 } else if (errno
== EPERM
) {
845 // On OSX, reading from a pipe with no listener returns EPERM
846 // treat this as a special case to prevent spurious error messages
850 } else if (errno
== ECONNRESET
|| errno
== EPIPE
) {
853 PLOG(ERROR
) << "pipe error (" << pipe_
.get() << ")";
856 } else if (*bytes_read
== 0) {
857 // The pipe has closed...
862 CloseClientFileDescriptor();
864 // Read any file descriptors from the message.
865 if (!ExtractFileDescriptorsFromMsghdr(&msg
))
867 return READ_SUCCEEDED
;
870 #if defined(IPC_USES_READWRITE)
871 bool ChannelPosix::ReadFileDescriptorsFromFDPipe() {
873 struct iovec fd_pipe_iov
= { &dummy
, 1 };
875 struct msghdr msg
= { 0 };
876 msg
.msg_iov
= &fd_pipe_iov
;
878 msg
.msg_control
= input_cmsg_buf_
;
879 msg
.msg_controllen
= sizeof(input_cmsg_buf_
);
880 ssize_t bytes_received
=
881 HANDLE_EINTR(recvmsg(fd_pipe_
.get(), &msg
, MSG_DONTWAIT
));
883 if (bytes_received
!= 1)
884 return true; // No message waiting.
886 if (!ExtractFileDescriptorsFromMsghdr(&msg
))
892 // On Posix, we need to fix up the file descriptors before the input message
895 // This will read from the input_fds_ (READWRITE mode only) and read more
896 // handles from the FD pipe if necessary.
897 bool ChannelPosix::WillDispatchInputMessage(Message
* msg
) {
898 uint16 header_fds
= msg
->header()->num_fds
;
900 return true; // Nothing to do.
902 // The message has file descriptors.
903 const char* error
= NULL
;
904 if (header_fds
> input_fds_
.size()) {
905 // The message has been completely received, but we didn't get
906 // enough file descriptors.
907 #if defined(IPC_USES_READWRITE)
908 if (!ReadFileDescriptorsFromFDPipe())
910 if (header_fds
> input_fds_
.size())
911 #endif // IPC_USES_READWRITE
912 error
= "Message needs unreceived descriptors";
915 if (header_fds
> MessageAttachmentSet::kMaxDescriptorsPerMessage
)
916 error
= "Message requires an excessive number of descriptors";
919 LOG(WARNING
) << error
920 << " channel:" << this
921 << " message-type:" << msg
->type()
922 << " header()->num_fds:" << header_fds
;
923 // Abort the connection.
928 // The shenaniganery below with &foo.front() requires input_fds_ to have
929 // contiguous underlying storage (such as a simple array or a std::vector).
930 // This is why the header warns not to make input_fds_ a deque<>.
931 msg
->attachment_set()->AddDescriptorsToOwn(&input_fds_
.front(), header_fds
);
932 input_fds_
.erase(input_fds_
.begin(), input_fds_
.begin() + header_fds
);
936 bool ChannelPosix::DidEmptyInputBuffers() {
937 // When the input data buffer is empty, the fds should be too. If this is
938 // not the case, we probably have a rogue renderer which is trying to fill
939 // our descriptor table.
940 return input_fds_
.empty();
943 bool ChannelPosix::ExtractFileDescriptorsFromMsghdr(msghdr
* msg
) {
944 // Check that there are any control messages. On OSX, CMSG_FIRSTHDR will
945 // return an invalid non-NULL pointer in the case that controllen == 0.
946 if (msg
->msg_controllen
== 0)
949 for (cmsghdr
* cmsg
= CMSG_FIRSTHDR(msg
);
951 cmsg
= CMSG_NXTHDR(msg
, cmsg
)) {
952 if (cmsg
->cmsg_level
== SOL_SOCKET
&& cmsg
->cmsg_type
== SCM_RIGHTS
) {
953 unsigned payload_len
= cmsg
->cmsg_len
- CMSG_LEN(0);
954 DCHECK_EQ(0U, payload_len
% sizeof(int));
955 const int* file_descriptors
= reinterpret_cast<int*>(CMSG_DATA(cmsg
));
956 unsigned num_file_descriptors
= payload_len
/ 4;
957 input_fds_
.insert(input_fds_
.end(),
959 file_descriptors
+ num_file_descriptors
);
961 // Check this after adding the FDs so we don't leak them.
962 if (msg
->msg_flags
& MSG_CTRUNC
) {
971 // No file descriptors found, but that's OK.
975 void ChannelPosix::ClearInputFDs() {
976 for (size_t i
= 0; i
< input_fds_
.size(); ++i
) {
977 if (IGNORE_EINTR(close(input_fds_
[i
])) < 0)
978 PLOG(ERROR
) << "close ";
983 void ChannelPosix::QueueCloseFDMessage(int fd
, int hops
) {
987 // Create the message
988 scoped_ptr
<Message
> msg(new Message(MSG_ROUTING_NONE
,
989 CLOSE_FD_MESSAGE_TYPE
,
990 IPC::Message::PRIORITY_NORMAL
));
991 if (!msg
->WriteInt(hops
- 1) || !msg
->WriteInt(fd
)) {
992 NOTREACHED() << "Unable to pickle close fd.";
994 // Send(msg.release());
995 output_queue_
.push(msg
.release());
1005 void ChannelPosix::HandleInternalMessage(const Message
& msg
) {
1006 // The Hello message contains only the process id.
1007 PickleIterator
iter(msg
);
1009 switch (msg
.type()) {
1014 case Channel::HELLO_MESSAGE_TYPE
:
1016 if (!iter
.ReadInt(&pid
))
1019 #if defined(IPC_USES_READWRITE)
1020 if (mode_
& MODE_SERVER_FLAG
) {
1021 // With IPC_USES_READWRITE, the Hello message from the client to the
1022 // server also contains the fd_pipe_, which will be used for all
1023 // subsequent file descriptor passing.
1024 DCHECK_EQ(msg
.attachment_set()->size(), 1U);
1025 scoped_refptr
<MessageAttachment
> attachment
;
1026 if (!msg
.ReadAttachment(&iter
, &attachment
)) {
1029 fd_pipe_
.reset(attachment
->TakePlatformFile());
1031 #endif // IPC_USES_READWRITE
1033 listener()->OnChannelConnected(pid
);
1036 #if defined(OS_MACOSX)
1037 case Channel::CLOSE_FD_MESSAGE_TYPE
:
1039 if (!iter
.ReadInt(&hops
))
1041 if (!iter
.ReadInt(&fd
))
1044 if (fds_to_close_
.erase(fd
) > 0) {
1045 if (IGNORE_EINTR(close(fd
)) < 0)
1046 PLOG(ERROR
) << "close";
1051 QueueCloseFDMessage(fd
, hops
);
1058 void ChannelPosix::Close() {
1059 // Close can be called multiple time, so we need to make sure we're
1062 ResetToAcceptingConnectionState();
1065 unlink(pipe_name_
.c_str());
1066 must_unlink_
= false;
1069 if (server_listen_pipe_
.is_valid()) {
1070 #if defined(OS_NACL_NONSFI)
1072 << "IPC channels in nacl_helper_nonsfi should not be SERVER mode.";
1074 server_listen_pipe_
.reset();
1075 // Unregister libevent for the listening socket and close it.
1076 server_listen_connection_watcher_
.StopWatchingFileDescriptor();
1080 CloseClientFileDescriptor();
1083 base::ProcessId
ChannelPosix::GetPeerPID() const {
1087 base::ProcessId
ChannelPosix::GetSelfPID() const {
1088 return GetHelloMessageProcId();
1091 void ChannelPosix::ResetSafely(base::ScopedFD
* fd
) {
1098 // The CL [1] tightened the error check for closing FDs, but it turned
1099 // out that there are existing cases that hit the newly added check.
1100 // ResetSafely() is the workaround for that crash, turning it from
1101 // from PCHECK() to DPCHECK() so that it doesn't crash in production.
1102 // [1] https://crrev.com/ce44fef5fd60dd2be5c587d4b084bdcd36adcee4
1103 int fd_to_close
= fd
->release();
1104 if (-1 != fd_to_close
) {
1105 int rv
= IGNORE_EINTR(close(fd_to_close
));
1110 //------------------------------------------------------------------------------
1111 // Channel's methods
1114 scoped_ptr
<Channel
> Channel::Create(
1115 const IPC::ChannelHandle
&channel_handle
, Mode mode
, Listener
* listener
) {
1116 return make_scoped_ptr(new ChannelPosix(channel_handle
, mode
, listener
));
1120 std::string
Channel::GenerateVerifiedChannelID(const std::string
& prefix
) {
1121 // A random name is sufficient validation on posix systems, so we don't need
1122 // an additional shared secret.
1124 std::string id
= prefix
;
1128 return id
.append(GenerateUniqueRandomChannelID());
1132 bool Channel::IsNamedServerInitialized(
1133 const std::string
& channel_id
) {
1134 return ChannelPosix::IsNamedServerInitialized(channel_id
);
1137 #if defined(OS_LINUX)
1139 void Channel::SetGlobalPid(int pid
) {
1140 ChannelPosix::SetGlobalPid(pid
);