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
,
187 AttachmentBroker
* broker
)
188 : ChannelReader(listener
),
190 peer_pid_(base::kNullProcessId
),
191 is_blocked_on_write_(false),
192 waiting_connect_(true),
193 message_send_bytes_written_(0),
194 pipe_name_(channel_handle
.name
),
198 if (!CreatePipe(channel_handle
)) {
199 // The pipe may have been closed already.
200 const char *modestr
= (mode_
& MODE_SERVER_FLAG
) ? "server" : "client";
201 LOG(WARNING
) << "Unable to create pipe named \"" << channel_handle
.name
202 << "\" in " << modestr
<< " mode";
206 ChannelPosix::~ChannelPosix() {
211 bool SocketPair(int* fd1
, int* fd2
) {
213 if (socketpair(AF_UNIX
, SOCK_STREAM
, 0, pipe_fds
) != 0) {
214 PLOG(ERROR
) << "socketpair()";
218 // Set both ends to be non-blocking.
219 if (fcntl(pipe_fds
[0], F_SETFL
, O_NONBLOCK
) == -1 ||
220 fcntl(pipe_fds
[1], F_SETFL
, O_NONBLOCK
) == -1) {
221 PLOG(ERROR
) << "fcntl(O_NONBLOCK)";
222 if (IGNORE_EINTR(close(pipe_fds
[0])) < 0)
223 PLOG(ERROR
) << "close";
224 if (IGNORE_EINTR(close(pipe_fds
[1])) < 0)
225 PLOG(ERROR
) << "close";
235 bool ChannelPosix::CreatePipe(
236 const IPC::ChannelHandle
& channel_handle
) {
237 DCHECK(!server_listen_pipe_
.is_valid() && !pipe_
.is_valid());
239 // Four possible cases:
240 // 1) It's a channel wrapping a pipe that is given to us.
241 // 2) It's for a named channel, so we create it.
242 // 3) It's for a client that we implement ourself. This is used
243 // in single-process unittesting.
244 // 4) It's the initial IPC channel:
245 // 4a) Client side: Pull the pipe out of the GlobalDescriptors set.
246 // 4b) Server side: create the pipe.
248 base::ScopedFD local_pipe
;
249 if (channel_handle
.socket
.fd
!= -1) {
250 // Case 1 from comment above.
251 local_pipe
.reset(channel_handle
.socket
.fd
);
252 } else if (mode_
& MODE_NAMED_FLAG
) {
253 #if defined(OS_NACL_NONSFI)
255 << "IPC channels in nacl_helper_nonsfi should not be in NAMED mode.";
257 // Case 2 from comment above.
258 int local_pipe_fd
= -1;
260 if (mode_
& MODE_SERVER_FLAG
) {
261 if (!CreateServerUnixDomainSocket(base::FilePath(pipe_name_
),
267 } else if (mode_
& MODE_CLIENT_FLAG
) {
268 if (!CreateClientUnixDomainSocket(base::FilePath(pipe_name_
),
273 LOG(ERROR
) << "Bad mode: " << mode_
;
277 local_pipe
.reset(local_pipe_fd
);
278 #endif // !defined(OS_NACL_NONSFI)
280 local_pipe
.reset(PipeMap::GetInstance()->Lookup(pipe_name_
));
281 if (mode_
& MODE_CLIENT_FLAG
) {
282 if (local_pipe
.is_valid()) {
283 // Case 3 from comment above.
284 // We only allow one connection.
285 local_pipe
.reset(HANDLE_EINTR(dup(local_pipe
.release())));
286 PipeMap::GetInstance()->Remove(pipe_name_
);
288 // Case 4a from comment above.
289 // Guard against inappropriate reuse of the initial IPC channel. If
290 // an IPC channel closes and someone attempts to reuse it by name, the
291 // initial channel must not be recycled here. http://crbug.com/26754.
292 static bool used_initial_channel
= false;
293 if (used_initial_channel
) {
294 LOG(FATAL
) << "Denying attempt to reuse initial IPC channel for "
298 used_initial_channel
= true;
301 base::GlobalDescriptors::GetInstance()->Get(kPrimaryIPCChannel
));
303 } else if (mode_
& MODE_SERVER_FLAG
) {
304 // Case 4b from comment above.
305 if (local_pipe
.is_valid()) {
306 LOG(ERROR
) << "Server already exists for " << pipe_name_
;
307 // This is a client side pipe registered by other server and
308 // shouldn't be closed.
309 ignore_result(local_pipe
.release());
312 base::AutoLock
lock(client_pipe_lock_
);
313 int local_pipe_fd
= -1, client_pipe_fd
= -1;
314 if (!SocketPair(&local_pipe_fd
, &client_pipe_fd
))
316 local_pipe
.reset(local_pipe_fd
);
317 client_pipe_
.reset(client_pipe_fd
);
318 PipeMap::GetInstance()->Insert(pipe_name_
, client_pipe_fd
);
320 LOG(ERROR
) << "Bad mode: " << mode_
;
325 if ((mode_
& MODE_SERVER_FLAG
) && (mode_
& MODE_NAMED_FLAG
)) {
326 #if defined(OS_NACL_NONSFI)
327 LOG(FATAL
) << "IPC channels in nacl_helper_nonsfi "
328 << "should not be in NAMED or SERVER mode.";
330 server_listen_pipe_
.reset(local_pipe
.release());
333 pipe_
.reset(local_pipe
.release());
338 bool ChannelPosix::Connect() {
339 if (!server_listen_pipe_
.is_valid() && !pipe_
.is_valid()) {
340 DLOG(WARNING
) << "Channel creation failed: " << pipe_name_
;
344 bool did_connect
= true;
345 if (server_listen_pipe_
.is_valid()) {
346 #if defined(OS_NACL_NONSFI)
347 LOG(FATAL
) << "IPC channels in nacl_helper_nonsfi "
348 << "should always be in client mode.";
350 // Watch the pipe for connections, and turn any connections into
352 base::MessageLoopForIO::current()->WatchFileDescriptor(
353 server_listen_pipe_
.get(),
355 base::MessageLoopForIO::WATCH_READ
,
356 &server_listen_connection_watcher_
,
360 did_connect
= AcceptConnection();
365 void ChannelPosix::CloseFileDescriptors(Message
* msg
) {
366 #if defined(OS_MACOSX)
367 // There is a bug on OSX which makes it dangerous to close
368 // a file descriptor while it is in transit. So instead we
369 // store the file descriptor in a set and send a message to
370 // the recipient, which is queued AFTER the message that
371 // sent the FD. The recipient will reply to the message,
372 // letting us know that it is now safe to close the file
373 // descriptor. For more information, see:
374 // http://crbug.com/298276
375 std::vector
<int> to_close
;
376 msg
->attachment_set()->ReleaseFDsToClose(&to_close
);
377 for (size_t i
= 0; i
< to_close
.size(); i
++) {
378 fds_to_close_
.insert(to_close
[i
]);
379 QueueCloseFDMessage(to_close
[i
], 2);
382 msg
->attachment_set()->CommitAll();
386 bool ChannelPosix::ProcessOutgoingMessages() {
387 DCHECK(!waiting_connect_
); // Why are we trying to send messages if there's
389 if (output_queue_
.empty())
392 if (!pipe_
.is_valid())
395 // Write out all the messages we can till the write blocks or there are no
396 // more outgoing messages.
397 while (!output_queue_
.empty()) {
398 Message
* msg
= output_queue_
.front();
400 size_t amt_to_write
= msg
->size() - message_send_bytes_written_
;
401 DCHECK_NE(0U, amt_to_write
);
402 const char* out_bytes
= reinterpret_cast<const char*>(msg
->data()) +
403 message_send_bytes_written_
;
405 struct msghdr msgh
= {0};
406 struct iovec iov
= {const_cast<char*>(out_bytes
), amt_to_write
};
409 char buf
[CMSG_SPACE(sizeof(int) *
410 MessageAttachmentSet::kMaxDescriptorsPerMessage
)];
412 ssize_t bytes_written
= 1;
415 if (message_send_bytes_written_
== 0 && !msg
->attachment_set()->empty()) {
416 // This is the first chunk of a message which has descriptors to send
417 struct cmsghdr
*cmsg
;
418 const unsigned num_fds
= msg
->attachment_set()->size();
420 DCHECK(num_fds
<= MessageAttachmentSet::kMaxDescriptorsPerMessage
);
421 if (msg
->attachment_set()->ContainsDirectoryDescriptor()) {
422 LOG(FATAL
) << "Panic: attempting to transport directory descriptor over"
423 " IPC. Aborting to maintain sandbox isolation.";
424 // If you have hit this then something tried to send a file descriptor
425 // to a directory over an IPC channel. Since IPC channels span
426 // sandboxes this is very bad: the receiving process can use openat
427 // with ".." elements in the path in order to reach the real
431 msgh
.msg_control
= buf
;
432 msgh
.msg_controllen
= CMSG_SPACE(sizeof(int) * num_fds
);
433 cmsg
= CMSG_FIRSTHDR(&msgh
);
434 cmsg
->cmsg_level
= SOL_SOCKET
;
435 cmsg
->cmsg_type
= SCM_RIGHTS
;
436 cmsg
->cmsg_len
= CMSG_LEN(sizeof(int) * num_fds
);
437 msg
->attachment_set()->PeekDescriptors(
438 reinterpret_cast<int*>(CMSG_DATA(cmsg
)));
439 msgh
.msg_controllen
= cmsg
->cmsg_len
;
441 // DCHECK_LE above already checks that
442 // num_fds < kMaxDescriptorsPerMessage so no danger of overflow.
443 msg
->header()->num_fds
= static_cast<uint16
>(num_fds
);
446 if (bytes_written
== 1) {
447 fd_written
= pipe_
.get();
448 bytes_written
= HANDLE_EINTR(sendmsg(pipe_
.get(), &msgh
, MSG_DONTWAIT
));
450 if (bytes_written
> 0)
451 CloseFileDescriptors(msg
);
453 if (bytes_written
< 0 && !SocketWriteErrorIsRecoverable()) {
454 // We can't close the pipe here, because calling OnChannelError
455 // may destroy this object, and that would be bad if we are
456 // called from Send(). Instead, we return false and hope the
457 // caller will close the pipe. If they do not, the pipe will
458 // still be closed next time OnFileCanReadWithoutBlocking is
460 #if defined(OS_MACOSX)
461 // On OSX writing to a pipe with no listener returns EPERM.
462 if (errno
== EPERM
) {
466 if (errno
== EPIPE
) {
469 PLOG(ERROR
) << "pipe error on "
471 << " Currently writing message of size: "
476 if (static_cast<size_t>(bytes_written
) != amt_to_write
) {
477 if (bytes_written
> 0) {
478 // If write() fails with EAGAIN then bytes_written will be -1.
479 message_send_bytes_written_
+= bytes_written
;
482 // Tell libevent to call us back once things are unblocked.
483 is_blocked_on_write_
= true;
484 base::MessageLoopForIO::current()->WatchFileDescriptor(
487 base::MessageLoopForIO::WATCH_WRITE
,
492 message_send_bytes_written_
= 0;
495 DVLOG(2) << "sent message @" << msg
<< " on channel @" << this
496 << " with type " << msg
->type() << " on fd " << pipe_
.get();
497 delete output_queue_
.front();
504 bool ChannelPosix::Send(Message
* message
) {
505 DCHECK(!message
->HasMojoHandles());
506 DVLOG(2) << "sending message @" << message
<< " on channel @" << this
507 << " with type " << message
->type()
508 << " (" << output_queue_
.size() << " in queue)";
510 #ifdef IPC_MESSAGE_LOG_ENABLED
511 Logging::GetInstance()->OnSendMessage(message
, "");
512 #endif // IPC_MESSAGE_LOG_ENABLED
514 message
->TraceMessageBegin();
515 output_queue_
.push(message
);
516 if (!is_blocked_on_write_
&& !waiting_connect_
) {
517 return ProcessOutgoingMessages();
523 AttachmentBroker
* ChannelPosix::GetAttachmentBroker() {
527 int ChannelPosix::GetClientFileDescriptor() const {
528 base::AutoLock
lock(client_pipe_lock_
);
529 return client_pipe_
.get();
532 base::ScopedFD
ChannelPosix::TakeClientFileDescriptor() {
533 base::AutoLock
lock(client_pipe_lock_
);
534 if (!client_pipe_
.is_valid())
535 return base::ScopedFD();
536 PipeMap::GetInstance()->Remove(pipe_name_
);
537 return client_pipe_
.Pass();
540 void ChannelPosix::CloseClientFileDescriptor() {
541 base::AutoLock
lock(client_pipe_lock_
);
542 if (!client_pipe_
.is_valid())
544 PipeMap::GetInstance()->Remove(pipe_name_
);
545 client_pipe_
.reset();
548 bool ChannelPosix::AcceptsConnections() const {
549 return server_listen_pipe_
.is_valid();
552 bool ChannelPosix::HasAcceptedConnection() const {
553 return AcceptsConnections() && pipe_
.is_valid();
556 #if !defined(OS_NACL_NONSFI)
557 // GetPeerEuid is not supported in nacl_helper_nonsfi.
558 bool ChannelPosix::GetPeerEuid(uid_t
* peer_euid
) const {
559 DCHECK(!(mode_
& MODE_SERVER
) || HasAcceptedConnection());
560 return IPC::GetPeerEuid(pipe_
.get(), peer_euid
);
564 void ChannelPosix::ResetToAcceptingConnectionState() {
565 // Unregister libevent for the unix domain socket and close it.
566 read_watcher_
.StopWatchingFileDescriptor();
567 write_watcher_
.StopWatchingFileDescriptor();
570 while (!output_queue_
.empty()) {
571 Message
* m
= output_queue_
.front();
573 CloseFileDescriptors(m
);
577 // Close any outstanding, received file descriptors.
580 #if defined(OS_MACOSX)
581 // Clear any outstanding, sent file descriptors.
582 for (std::set
<int>::iterator i
= fds_to_close_
.begin();
583 i
!= fds_to_close_
.end();
585 if (IGNORE_EINTR(close(*i
)) < 0)
586 PLOG(ERROR
) << "close";
588 fds_to_close_
.clear();
593 bool ChannelPosix::IsNamedServerInitialized(
594 const std::string
& channel_id
) {
595 return base::PathExists(base::FilePath(channel_id
));
598 #if defined(OS_LINUX)
600 void ChannelPosix::SetGlobalPid(int pid
) {
605 // Called by libevent when we can read from the pipe without blocking.
606 void ChannelPosix::OnFileCanReadWithoutBlocking(int fd
) {
607 if (fd
== server_listen_pipe_
.get()) {
608 #if defined(OS_NACL_NONSFI)
610 << "IPC channels in nacl_helper_nonsfi should not be SERVER mode.";
613 if (!ServerAcceptConnection(server_listen_pipe_
.get(), &new_pipe
) ||
616 listener()->OnChannelListenError();
619 if (pipe_
.is_valid()) {
620 // We already have a connection. We only handle one at a time.
621 // close our new descriptor.
622 if (HANDLE_EINTR(shutdown(new_pipe
, SHUT_RDWR
)) < 0)
623 DPLOG(ERROR
) << "shutdown " << pipe_name_
;
624 if (IGNORE_EINTR(close(new_pipe
)) < 0)
625 DPLOG(ERROR
) << "close " << pipe_name_
;
626 listener()->OnChannelDenied();
629 pipe_
.reset(new_pipe
);
631 if ((mode_
& MODE_OPEN_ACCESS_FLAG
) == 0) {
632 // Verify that the IPC channel peer is running as the same user.
634 if (!GetPeerEuid(&client_euid
)) {
635 DLOG(ERROR
) << "Unable to query client euid";
636 ResetToAcceptingConnectionState();
639 if (client_euid
!= geteuid()) {
640 DLOG(WARNING
) << "Client euid is not authorised";
641 ResetToAcceptingConnectionState();
646 if (!AcceptConnection()) {
647 NOTREACHED() << "AcceptConnection should not fail on server";
649 waiting_connect_
= false;
651 } else if (fd
== pipe_
) {
652 if (waiting_connect_
&& (mode_
& MODE_SERVER_FLAG
)) {
653 waiting_connect_
= false;
655 if (!ProcessIncomingMessages()) {
656 // ClosePipeOnError may delete this object, so we mustn't call
657 // ProcessOutgoingMessages.
662 NOTREACHED() << "Unknown pipe " << fd
;
665 // If we're a server and handshaking, then we want to make sure that we
666 // only send our handshake message after we've processed the client's.
667 // This gives us a chance to kill the client if the incoming handshake
668 // is invalid. This also flushes any closefd messages.
669 if (!is_blocked_on_write_
) {
670 if (!ProcessOutgoingMessages()) {
676 // Called by libevent when we can write to the pipe without blocking.
677 void ChannelPosix::OnFileCanWriteWithoutBlocking(int fd
) {
678 DCHECK_EQ(pipe_
.get(), fd
);
679 is_blocked_on_write_
= false;
680 if (!ProcessOutgoingMessages()) {
685 bool ChannelPosix::AcceptConnection() {
686 base::MessageLoopForIO::current()->WatchFileDescriptor(
689 base::MessageLoopForIO::WATCH_READ
,
694 if (mode_
& MODE_CLIENT_FLAG
) {
695 // If we are a client we want to send a hello message out immediately.
696 // In server mode we will send a hello message when we receive one from a
698 waiting_connect_
= false;
699 return ProcessOutgoingMessages();
700 } else if (mode_
& MODE_SERVER_FLAG
) {
701 waiting_connect_
= true;
709 void ChannelPosix::ClosePipeOnError() {
710 if (HasAcceptedConnection()) {
711 ResetToAcceptingConnectionState();
712 listener()->OnChannelError();
715 if (AcceptsConnections()) {
716 listener()->OnChannelListenError();
718 listener()->OnChannelError();
723 int ChannelPosix::GetHelloMessageProcId() const {
724 #if defined(OS_NACL_NONSFI)
725 // In nacl_helper_nonsfi, getpid() invoked by GetCurrentProcId() is not
726 // allowed and would cause a SIGSYS crash because of the seccomp sandbox.
729 int pid
= base::GetCurrentProcId();
730 #if defined(OS_LINUX)
731 // Our process may be in a sandbox with a separate PID namespace.
735 #endif // defined(OS_LINUX)
737 #endif // defined(OS_NACL_NONSFI)
740 void ChannelPosix::QueueHelloMessage() {
741 // Create the Hello message
742 scoped_ptr
<Message
> msg(new Message(MSG_ROUTING_NONE
,
744 IPC::Message::PRIORITY_NORMAL
));
745 if (!msg
->WriteInt(GetHelloMessageProcId())) {
746 NOTREACHED() << "Unable to pickle hello message proc id";
748 output_queue_
.push(msg
.release());
751 ChannelPosix::ReadState
ChannelPosix::ReadData(
755 if (!pipe_
.is_valid())
758 struct msghdr msg
= {0};
760 struct iovec iov
= {buffer
, static_cast<size_t>(buffer_len
)};
764 char input_cmsg_buf
[kMaxReadFDBuffer
];
765 msg
.msg_control
= input_cmsg_buf
;
767 // recvmsg() returns 0 if the connection has closed or EAGAIN if no data
768 // is waiting on the pipe.
769 msg
.msg_controllen
= sizeof(input_cmsg_buf
);
770 *bytes_read
= HANDLE_EINTR(recvmsg(pipe_
.get(), &msg
, MSG_DONTWAIT
));
772 if (*bytes_read
< 0) {
773 if (errno
== EAGAIN
) {
775 #if defined(OS_MACOSX)
776 } else if (errno
== EPERM
) {
777 // On OSX, reading from a pipe with no listener returns EPERM
778 // treat this as a special case to prevent spurious error messages
782 } else if (errno
== ECONNRESET
|| errno
== EPIPE
) {
785 PLOG(ERROR
) << "pipe error (" << pipe_
.get() << ")";
788 } else if (*bytes_read
== 0) {
789 // The pipe has closed...
794 CloseClientFileDescriptor();
796 // Read any file descriptors from the message.
797 if (!ExtractFileDescriptorsFromMsghdr(&msg
))
799 return READ_SUCCEEDED
;
802 // On Posix, we need to fix up the file descriptors before the input message
805 // This will read from the input_fds_ (READWRITE mode only) and read more
806 // handles from the FD pipe if necessary.
807 bool ChannelPosix::WillDispatchInputMessage(Message
* msg
) {
808 uint16 header_fds
= msg
->header()->num_fds
;
810 return true; // Nothing to do.
812 // The message has file descriptors.
813 const char* error
= NULL
;
814 if (header_fds
> input_fds_
.size()) {
815 // The message has been completely received, but we didn't get
816 // enough file descriptors.
817 error
= "Message needs unreceived descriptors";
820 if (header_fds
> MessageAttachmentSet::kMaxDescriptorsPerMessage
)
821 error
= "Message requires an excessive number of descriptors";
824 LOG(WARNING
) << error
825 << " channel:" << this
826 << " message-type:" << msg
->type()
827 << " header()->num_fds:" << header_fds
;
828 // Abort the connection.
833 // The shenaniganery below with &foo.front() requires input_fds_ to have
834 // contiguous underlying storage (such as a simple array or a std::vector).
835 // This is why the header warns not to make input_fds_ a deque<>.
836 msg
->attachment_set()->AddDescriptorsToOwn(&input_fds_
.front(), header_fds
);
837 input_fds_
.erase(input_fds_
.begin(), input_fds_
.begin() + header_fds
);
841 bool ChannelPosix::DidEmptyInputBuffers() {
842 // When the input data buffer is empty, the fds should be too. If this is
843 // not the case, we probably have a rogue renderer which is trying to fill
844 // our descriptor table.
845 return input_fds_
.empty();
848 bool ChannelPosix::ExtractFileDescriptorsFromMsghdr(msghdr
* msg
) {
849 // Check that there are any control messages. On OSX, CMSG_FIRSTHDR will
850 // return an invalid non-NULL pointer in the case that controllen == 0.
851 if (msg
->msg_controllen
== 0)
854 for (cmsghdr
* cmsg
= CMSG_FIRSTHDR(msg
);
856 cmsg
= CMSG_NXTHDR(msg
, cmsg
)) {
857 if (cmsg
->cmsg_level
== SOL_SOCKET
&& cmsg
->cmsg_type
== SCM_RIGHTS
) {
858 unsigned payload_len
= cmsg
->cmsg_len
- CMSG_LEN(0);
859 DCHECK_EQ(0U, payload_len
% sizeof(int));
860 const int* file_descriptors
= reinterpret_cast<int*>(CMSG_DATA(cmsg
));
861 unsigned num_file_descriptors
= payload_len
/ 4;
862 input_fds_
.insert(input_fds_
.end(),
864 file_descriptors
+ num_file_descriptors
);
866 // Check this after adding the FDs so we don't leak them.
867 if (msg
->msg_flags
& MSG_CTRUNC
) {
876 // No file descriptors found, but that's OK.
880 void ChannelPosix::ClearInputFDs() {
881 for (size_t i
= 0; i
< input_fds_
.size(); ++i
) {
882 if (IGNORE_EINTR(close(input_fds_
[i
])) < 0)
883 PLOG(ERROR
) << "close ";
888 void ChannelPosix::QueueCloseFDMessage(int fd
, int hops
) {
892 // Create the message
893 scoped_ptr
<Message
> msg(new Message(MSG_ROUTING_NONE
,
894 CLOSE_FD_MESSAGE_TYPE
,
895 IPC::Message::PRIORITY_NORMAL
));
896 if (!msg
->WriteInt(hops
- 1) || !msg
->WriteInt(fd
)) {
897 NOTREACHED() << "Unable to pickle close fd.";
899 // Send(msg.release());
900 output_queue_
.push(msg
.release());
910 void ChannelPosix::HandleInternalMessage(const Message
& msg
) {
911 // The Hello message contains only the process id.
912 base::PickleIterator
iter(msg
);
914 switch (msg
.type()) {
919 case Channel::HELLO_MESSAGE_TYPE
:
921 if (!iter
.ReadInt(&pid
))
925 listener()->OnChannelConnected(pid
);
928 #if defined(OS_MACOSX)
929 case Channel::CLOSE_FD_MESSAGE_TYPE
:
931 if (!iter
.ReadInt(&hops
))
933 if (!iter
.ReadInt(&fd
))
936 if (fds_to_close_
.erase(fd
) > 0) {
937 if (IGNORE_EINTR(close(fd
)) < 0)
938 PLOG(ERROR
) << "close";
943 QueueCloseFDMessage(fd
, hops
);
950 void ChannelPosix::Close() {
951 // Close can be called multiple time, so we need to make sure we're
954 ResetToAcceptingConnectionState();
957 unlink(pipe_name_
.c_str());
958 must_unlink_
= false;
961 if (server_listen_pipe_
.is_valid()) {
962 #if defined(OS_NACL_NONSFI)
964 << "IPC channels in nacl_helper_nonsfi should not be SERVER mode.";
966 server_listen_pipe_
.reset();
967 // Unregister libevent for the listening socket and close it.
968 server_listen_connection_watcher_
.StopWatchingFileDescriptor();
972 CloseClientFileDescriptor();
975 base::ProcessId
ChannelPosix::GetPeerPID() const {
979 base::ProcessId
ChannelPosix::GetSelfPID() const {
980 return GetHelloMessageProcId();
983 void ChannelPosix::ResetSafely(base::ScopedFD
* fd
) {
990 // The CL [1] tightened the error check for closing FDs, but it turned
991 // out that there are existing cases that hit the newly added check.
992 // ResetSafely() is the workaround for that crash, turning it from
993 // from PCHECK() to DPCHECK() so that it doesn't crash in production.
994 // [1] https://crrev.com/ce44fef5fd60dd2be5c587d4b084bdcd36adcee4
995 int fd_to_close
= fd
->release();
996 if (-1 != fd_to_close
) {
997 int rv
= IGNORE_EINTR(close(fd_to_close
));
1002 //------------------------------------------------------------------------------
1003 // Channel's methods
1006 scoped_ptr
<Channel
> Channel::Create(const IPC::ChannelHandle
& channel_handle
,
1009 AttachmentBroker
* broker
) {
1010 return make_scoped_ptr(
1011 new ChannelPosix(channel_handle
, mode
, listener
, broker
));
1015 std::string
Channel::GenerateVerifiedChannelID(const std::string
& prefix
) {
1016 // A random name is sufficient validation on posix systems, so we don't need
1017 // an additional shared secret.
1019 std::string id
= prefix
;
1023 return id
.append(GenerateUniqueRandomChannelID());
1026 bool Channel::IsNamedServerInitialized(
1027 const std::string
& channel_id
) {
1028 return ChannelPosix::IsNamedServerInitialized(channel_id
);
1031 #if defined(OS_LINUX)
1033 void Channel::SetGlobalPid(int pid
) {
1034 ChannelPosix::SetGlobalPid(pid
);