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>
16 #if defined(OS_OPENBSD)
23 #include "base/command_line.h"
24 #include "base/file_util.h"
25 #include "base/files/file_path.h"
26 #include "base/location.h"
27 #include "base/logging.h"
28 #include "base/memory/scoped_ptr.h"
29 #include "base/memory/singleton.h"
30 #include "base/posix/eintr_wrapper.h"
31 #include "base/posix/global_descriptors.h"
32 #include "base/process/process_handle.h"
33 #include "base/rand_util.h"
34 #include "base/stl_util.h"
35 #include "base/strings/string_util.h"
36 #include "base/synchronization/lock.h"
37 #include "ipc/file_descriptor_set_posix.h"
38 #include "ipc/ipc_descriptors.h"
39 #include "ipc/ipc_listener.h"
40 #include "ipc/ipc_logging.h"
41 #include "ipc/ipc_message_utils.h"
42 #include "ipc/ipc_switches.h"
43 #include "ipc/unix_domain_socket_util.h"
47 // IPC channels on Windows use named pipes (CreateNamedPipe()) with
48 // channel ids as the pipe names. Channels on POSIX use sockets as
49 // pipes These don't quite line up.
51 // When creating a child subprocess we use a socket pair and the parent side of
52 // the fork arranges it such that the initial control channel ends up on the
53 // magic file descriptor kPrimaryIPCChannel in the child. Future
54 // connections (file descriptors) can then be passed via that
55 // connection via sendmsg().
57 // A POSIX IPC channel can also be set up as a server for a bound UNIX domain
58 // socket, and will handle multiple connect and disconnect sequences. Currently
59 // it is limited to one connection at a time.
61 //------------------------------------------------------------------------------
64 // The PipeMap class works around this quirk related to unit tests:
66 // When running as a server, we install the client socket in a
67 // specific file descriptor number (@kPrimaryIPCChannel). However, we
68 // also have to support the case where we are running unittests in the
69 // same process. (We do not support forking without execing.)
71 // Case 1: normal running
72 // The IPC server object will install a mapping in PipeMap from the
73 // name which it was given to the client pipe. When forking the client, the
74 // GetClientFileDescriptorMapping will ensure that the socket is installed in
75 // the magic slot (@kPrimaryIPCChannel). The client will search for the
76 // mapping, but it won't find any since we are in a new process. Thus the
77 // magic fd number is returned. Once the client connects, the server will
78 // close its copy of the client socket and remove the mapping.
80 // Case 2: unittests - client and server in the same process
81 // The IPC server will install a mapping as before. The client will search
82 // for a mapping and find out. It duplicates the file descriptor and
83 // connects. Once the client connects, the server will close the original
84 // copy of the client socket and remove the mapping. Thus, when the client
85 // object closes, it will close the only remaining copy of the client socket
86 // in the fd table and the server will see EOF on its side.
88 // TODO(port): a client process cannot connect to multiple IPC channels with
93 static PipeMap
* GetInstance() {
94 return Singleton
<PipeMap
>::get();
98 // Shouldn't have left over pipes.
102 // Lookup a given channel id. Return -1 if not found.
103 int Lookup(const std::string
& channel_id
) {
104 base::AutoLock
locked(lock_
);
106 ChannelToFDMap::const_iterator i
= map_
.find(channel_id
);
112 // Remove the mapping for the given channel id. No error is signaled if the
113 // channel_id doesn't exist
114 void Remove(const std::string
& channel_id
) {
115 base::AutoLock
locked(lock_
);
116 map_
.erase(channel_id
);
119 // Insert a mapping from @channel_id to @fd. It's a fatal error to insert a
120 // mapping if one already exists for the given channel_id
121 void Insert(const std::string
& channel_id
, int fd
) {
122 base::AutoLock
locked(lock_
);
125 ChannelToFDMap::const_iterator i
= map_
.find(channel_id
);
126 CHECK(i
== map_
.end()) << "Creating second IPC server (fd " << fd
<< ") "
127 << "for '" << channel_id
<< "' while first "
128 << "(fd " << i
->second
<< ") still exists";
129 map_
[channel_id
] = fd
;
134 typedef std::map
<std::string
, int> ChannelToFDMap
;
137 friend struct DefaultSingletonTraits
<PipeMap
>;
138 #if defined(OS_ANDROID)
139 friend void ::IPC::Channel::NotifyProcessForkedForTesting();
143 //------------------------------------------------------------------------------
145 bool SocketWriteErrorIsRecoverable() {
146 #if defined(OS_MACOSX)
147 // On OS X if sendmsg() is trying to send fds between processes and there
148 // isn't enough room in the output buffer to send the fd structure over
149 // atomically then EMSGSIZE is returned.
151 // EMSGSIZE presents a problem since the system APIs can only call us when
152 // there's room in the socket buffer and not when there is "enough" room.
154 // The current behavior is to return to the event loop when EMSGSIZE is
155 // received and hopefull service another FD. This is however still
156 // technically a busy wait since the event loop will call us right back until
157 // the receiver has read enough data to allow passing the FD over atomically.
158 return errno
== EAGAIN
|| errno
== EMSGSIZE
;
160 return errno
== EAGAIN
;
166 #if defined(OS_ANDROID)
167 // When we fork for simple tests on Android, we can't 'exec', so we need to
168 // reset these entries manually to get the expected testing behavior.
169 void Channel::NotifyProcessForkedForTesting() {
170 PipeMap::GetInstance()->map_
.clear();
174 //------------------------------------------------------------------------------
176 #if defined(OS_LINUX)
177 int ChannelPosix::global_pid_
= 0;
180 ChannelPosix::ChannelPosix(const IPC::ChannelHandle
& channel_handle
,
181 Mode mode
, Listener
* listener
)
182 : ChannelReader(listener
),
184 peer_pid_(base::kNullProcessId
),
185 is_blocked_on_write_(false),
186 waiting_connect_(true),
187 message_send_bytes_written_(0),
188 server_listen_pipe_(-1),
191 #if defined(IPC_USES_READWRITE)
194 #endif // IPC_USES_READWRITE
195 pipe_name_(channel_handle
.name
),
196 must_unlink_(false) {
197 memset(input_cmsg_buf_
, 0, sizeof(input_cmsg_buf_
));
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() {
210 bool SocketPair(int* fd1
, int* fd2
) {
212 if (socketpair(AF_UNIX
, SOCK_STREAM
, 0, pipe_fds
) != 0) {
213 PLOG(ERROR
) << "socketpair()";
217 // Set both ends to be non-blocking.
218 if (fcntl(pipe_fds
[0], F_SETFL
, O_NONBLOCK
) == -1 ||
219 fcntl(pipe_fds
[1], F_SETFL
, O_NONBLOCK
) == -1) {
220 PLOG(ERROR
) << "fcntl(O_NONBLOCK)";
221 if (IGNORE_EINTR(close(pipe_fds
[0])) < 0)
222 PLOG(ERROR
) << "close";
223 if (IGNORE_EINTR(close(pipe_fds
[1])) < 0)
224 PLOG(ERROR
) << "close";
234 bool ChannelPosix::CreatePipe(
235 const IPC::ChannelHandle
& channel_handle
) {
236 DCHECK(server_listen_pipe_
== -1 && pipe_
== -1);
238 // Four possible cases:
239 // 1) It's a channel wrapping a pipe that is given to us.
240 // 2) It's for a named channel, so we create it.
241 // 3) It's for a client that we implement ourself. This is used
242 // in single-process unittesting.
243 // 4) It's the initial IPC channel:
244 // 4a) Client side: Pull the pipe out of the GlobalDescriptors set.
245 // 4b) Server side: create the pipe.
248 if (channel_handle
.socket
.fd
!= -1) {
249 // Case 1 from comment above.
250 local_pipe
= channel_handle
.socket
.fd
;
251 #if defined(IPC_USES_READWRITE)
252 // Test the socket passed into us to make sure it is nonblocking.
253 // We don't want to call read/write on a blocking socket.
254 int value
= fcntl(local_pipe
, F_GETFL
);
256 PLOG(ERROR
) << "fcntl(F_GETFL) " << pipe_name_
;
259 if (!(value
& O_NONBLOCK
)) {
260 LOG(ERROR
) << "Socket " << pipe_name_
<< " must be O_NONBLOCK";
263 #endif // IPC_USES_READWRITE
264 } else if (mode_
& MODE_NAMED_FLAG
) {
265 // Case 2 from comment above.
266 if (mode_
& MODE_SERVER_FLAG
) {
267 if (!CreateServerUnixDomainSocket(base::FilePath(pipe_name_
),
272 } else if (mode_
& MODE_CLIENT_FLAG
) {
273 if (!CreateClientUnixDomainSocket(base::FilePath(pipe_name_
),
278 LOG(ERROR
) << "Bad mode: " << mode_
;
282 local_pipe
= PipeMap::GetInstance()->Lookup(pipe_name_
);
283 if (mode_
& MODE_CLIENT_FLAG
) {
284 if (local_pipe
!= -1) {
285 // Case 3 from comment above.
286 // We only allow one connection.
287 local_pipe
= HANDLE_EINTR(dup(local_pipe
));
288 PipeMap::GetInstance()->Remove(pipe_name_
);
290 // Case 4a from comment above.
291 // Guard against inappropriate reuse of the initial IPC channel. If
292 // an IPC channel closes and someone attempts to reuse it by name, the
293 // initial channel must not be recycled here. http://crbug.com/26754.
294 static bool used_initial_channel
= false;
295 if (used_initial_channel
) {
296 LOG(FATAL
) << "Denying attempt to reuse initial IPC channel for "
300 used_initial_channel
= true;
303 base::GlobalDescriptors::GetInstance()->Get(kPrimaryIPCChannel
);
305 } else if (mode_
& MODE_SERVER_FLAG
) {
306 // Case 4b from comment above.
307 if (local_pipe
!= -1) {
308 LOG(ERROR
) << "Server already exists for " << pipe_name_
;
311 base::AutoLock
lock(client_pipe_lock_
);
312 if (!SocketPair(&local_pipe
, &client_pipe_
))
314 PipeMap::GetInstance()->Insert(pipe_name_
, client_pipe_
);
316 LOG(ERROR
) << "Bad mode: " << mode_
;
321 #if defined(IPC_USES_READWRITE)
322 // Create a dedicated socketpair() for exchanging file descriptors.
323 // See comments for IPC_USES_READWRITE for details.
324 if (mode_
& MODE_CLIENT_FLAG
) {
325 if (!SocketPair(&fd_pipe_
, &remote_fd_pipe_
)) {
329 #endif // IPC_USES_READWRITE
331 if ((mode_
& MODE_SERVER_FLAG
) && (mode_
& MODE_NAMED_FLAG
)) {
332 server_listen_pipe_
= local_pipe
;
340 bool ChannelPosix::Connect() {
341 if (server_listen_pipe_
== -1 && pipe_
== -1) {
342 DLOG(WARNING
) << "Channel creation failed: " << pipe_name_
;
346 bool did_connect
= true;
347 if (server_listen_pipe_
!= -1) {
348 // Watch the pipe for connections, and turn any connections into
350 base::MessageLoopForIO::current()->WatchFileDescriptor(
353 base::MessageLoopForIO::WATCH_READ
,
354 &server_listen_connection_watcher_
,
357 did_connect
= AcceptConnection();
362 void ChannelPosix::CloseFileDescriptors(Message
* msg
) {
363 #if defined(OS_MACOSX)
364 // There is a bug on OSX which makes it dangerous to close
365 // a file descriptor while it is in transit. So instead we
366 // store the file descriptor in a set and send a message to
367 // the recipient, which is queued AFTER the message that
368 // sent the FD. The recipient will reply to the message,
369 // letting us know that it is now safe to close the file
370 // descriptor. For more information, see:
371 // http://crbug.com/298276
372 std::vector
<int> to_close
;
373 msg
->file_descriptor_set()->ReleaseFDsToClose(&to_close
);
374 for (size_t i
= 0; i
< to_close
.size(); i
++) {
375 fds_to_close_
.insert(to_close
[i
]);
376 QueueCloseFDMessage(to_close
[i
], 2);
379 msg
->file_descriptor_set()->CommitAll();
383 bool ChannelPosix::ProcessOutgoingMessages() {
384 DCHECK(!waiting_connect_
); // Why are we trying to send messages if there's
386 if (output_queue_
.empty())
392 // Write out all the messages we can till the write blocks or there are no
393 // more outgoing messages.
394 while (!output_queue_
.empty()) {
395 Message
* msg
= output_queue_
.front();
397 size_t amt_to_write
= msg
->size() - message_send_bytes_written_
;
398 DCHECK_NE(0U, amt_to_write
);
399 const char* out_bytes
= reinterpret_cast<const char*>(msg
->data()) +
400 message_send_bytes_written_
;
402 struct msghdr msgh
= {0};
403 struct iovec iov
= {const_cast<char*>(out_bytes
), amt_to_write
};
407 sizeof(int) * FileDescriptorSet::kMaxDescriptorsPerMessage
)];
409 ssize_t bytes_written
= 1;
412 if (message_send_bytes_written_
== 0 &&
413 !msg
->file_descriptor_set()->empty()) {
414 // This is the first chunk of a message which has descriptors to send
415 struct cmsghdr
*cmsg
;
416 const unsigned num_fds
= msg
->file_descriptor_set()->size();
418 DCHECK(num_fds
<= FileDescriptorSet::kMaxDescriptorsPerMessage
);
419 if (msg
->file_descriptor_set()->ContainsDirectoryDescriptor()) {
420 LOG(FATAL
) << "Panic: attempting to transport directory descriptor over"
421 " IPC. Aborting to maintain sandbox isolation.";
422 // If you have hit this then something tried to send a file descriptor
423 // to a directory over an IPC channel. Since IPC channels span
424 // sandboxes this is very bad: the receiving process can use openat
425 // with ".." elements in the path in order to reach the real
429 msgh
.msg_control
= buf
;
430 msgh
.msg_controllen
= CMSG_SPACE(sizeof(int) * num_fds
);
431 cmsg
= CMSG_FIRSTHDR(&msgh
);
432 cmsg
->cmsg_level
= SOL_SOCKET
;
433 cmsg
->cmsg_type
= SCM_RIGHTS
;
434 cmsg
->cmsg_len
= CMSG_LEN(sizeof(int) * num_fds
);
435 msg
->file_descriptor_set()->GetDescriptors(
436 reinterpret_cast<int*>(CMSG_DATA(cmsg
)));
437 msgh
.msg_controllen
= cmsg
->cmsg_len
;
439 // DCHECK_LE above already checks that
440 // num_fds < kMaxDescriptorsPerMessage so no danger of overflow.
441 msg
->header()->num_fds
= static_cast<uint16
>(num_fds
);
443 #if defined(IPC_USES_READWRITE)
444 if (!IsHelloMessage(*msg
)) {
445 // Only the Hello message sends the file descriptor with the message.
446 // Subsequently, we can send file descriptors on the dedicated
447 // fd_pipe_ which makes Seccomp sandbox operation more efficient.
448 struct iovec fd_pipe_iov
= { const_cast<char *>(""), 1 };
449 msgh
.msg_iov
= &fd_pipe_iov
;
450 fd_written
= fd_pipe_
;
451 bytes_written
= HANDLE_EINTR(sendmsg(fd_pipe_
, &msgh
, MSG_DONTWAIT
));
453 msgh
.msg_controllen
= 0;
454 if (bytes_written
> 0) {
455 CloseFileDescriptors(msg
);
458 #endif // IPC_USES_READWRITE
461 if (bytes_written
== 1) {
463 #if defined(IPC_USES_READWRITE)
464 if ((mode_
& MODE_CLIENT_FLAG
) && IsHelloMessage(*msg
)) {
465 DCHECK_EQ(msg
->file_descriptor_set()->size(), 1U);
467 if (!msgh
.msg_controllen
) {
468 bytes_written
= HANDLE_EINTR(write(pipe_
, out_bytes
, amt_to_write
));
470 #endif // IPC_USES_READWRITE
472 bytes_written
= HANDLE_EINTR(sendmsg(pipe_
, &msgh
, MSG_DONTWAIT
));
475 if (bytes_written
> 0)
476 CloseFileDescriptors(msg
);
478 if (bytes_written
< 0 && !SocketWriteErrorIsRecoverable()) {
479 // We can't close the pipe here, because calling OnChannelError
480 // may destroy this object, and that would be bad if we are
481 // called from Send(). Instead, we return false and hope the
482 // caller will close the pipe. If they do not, the pipe will
483 // still be closed next time OnFileCanReadWithoutBlocking is
485 #if defined(OS_MACOSX)
486 // On OSX writing to a pipe with no listener returns EPERM.
487 if (errno
== EPERM
) {
491 if (errno
== EPIPE
) {
494 PLOG(ERROR
) << "pipe error on "
496 << " Currently writing message of size: "
501 if (static_cast<size_t>(bytes_written
) != amt_to_write
) {
502 if (bytes_written
> 0) {
503 // If write() fails with EAGAIN then bytes_written will be -1.
504 message_send_bytes_written_
+= bytes_written
;
507 // Tell libevent to call us back once things are unblocked.
508 is_blocked_on_write_
= true;
509 base::MessageLoopForIO::current()->WatchFileDescriptor(
512 base::MessageLoopForIO::WATCH_WRITE
,
517 message_send_bytes_written_
= 0;
520 DVLOG(2) << "sent message @" << msg
<< " on channel @" << this
521 << " with type " << msg
->type() << " on fd " << pipe_
;
522 delete output_queue_
.front();
529 bool ChannelPosix::Send(Message
* message
) {
530 DVLOG(2) << "sending message @" << message
<< " on channel @" << this
531 << " with type " << message
->type()
532 << " (" << output_queue_
.size() << " in queue)";
534 #ifdef IPC_MESSAGE_LOG_ENABLED
535 Logging::GetInstance()->OnSendMessage(message
, "");
536 #endif // IPC_MESSAGE_LOG_ENABLED
538 message
->TraceMessageBegin();
539 output_queue_
.push(message
);
540 if (!is_blocked_on_write_
&& !waiting_connect_
) {
541 return ProcessOutgoingMessages();
547 int ChannelPosix::GetClientFileDescriptor() const {
548 base::AutoLock
lock(client_pipe_lock_
);
552 int ChannelPosix::TakeClientFileDescriptor() {
553 base::AutoLock
lock(client_pipe_lock_
);
554 int fd
= client_pipe_
;
555 if (client_pipe_
!= -1) {
556 PipeMap::GetInstance()->Remove(pipe_name_
);
562 void ChannelPosix::CloseClientFileDescriptor() {
563 base::AutoLock
lock(client_pipe_lock_
);
564 if (client_pipe_
!= -1) {
565 PipeMap::GetInstance()->Remove(pipe_name_
);
566 if (IGNORE_EINTR(close(client_pipe_
)) < 0)
567 PLOG(ERROR
) << "close " << pipe_name_
;
572 bool ChannelPosix::AcceptsConnections() const {
573 return server_listen_pipe_
!= -1;
576 bool ChannelPosix::HasAcceptedConnection() const {
577 return AcceptsConnections() && pipe_
!= -1;
580 bool ChannelPosix::GetPeerEuid(uid_t
* peer_euid
) const {
581 DCHECK(!(mode_
& MODE_SERVER
) || HasAcceptedConnection());
582 return IPC::GetPeerEuid(pipe_
, peer_euid
);
585 void ChannelPosix::ResetToAcceptingConnectionState() {
586 // Unregister libevent for the unix domain socket and close it.
587 read_watcher_
.StopWatchingFileDescriptor();
588 write_watcher_
.StopWatchingFileDescriptor();
590 if (IGNORE_EINTR(close(pipe_
)) < 0)
591 PLOG(ERROR
) << "close pipe_ " << pipe_name_
;
594 #if defined(IPC_USES_READWRITE)
595 if (fd_pipe_
!= -1) {
596 if (IGNORE_EINTR(close(fd_pipe_
)) < 0)
597 PLOG(ERROR
) << "close fd_pipe_ " << pipe_name_
;
600 if (remote_fd_pipe_
!= -1) {
601 if (IGNORE_EINTR(close(remote_fd_pipe_
)) < 0)
602 PLOG(ERROR
) << "close remote_fd_pipe_ " << pipe_name_
;
603 remote_fd_pipe_
= -1;
605 #endif // IPC_USES_READWRITE
607 while (!output_queue_
.empty()) {
608 Message
* m
= output_queue_
.front();
613 // Close any outstanding, received file descriptors.
616 #if defined(OS_MACOSX)
617 // Clear any outstanding, sent file descriptors.
618 for (std::set
<int>::iterator i
= fds_to_close_
.begin();
619 i
!= fds_to_close_
.end();
621 if (IGNORE_EINTR(close(*i
)) < 0)
622 PLOG(ERROR
) << "close";
624 fds_to_close_
.clear();
629 bool ChannelPosix::IsNamedServerInitialized(
630 const std::string
& channel_id
) {
631 return base::PathExists(base::FilePath(channel_id
));
634 #if defined(OS_LINUX)
636 void ChannelPosix::SetGlobalPid(int pid
) {
641 // Called by libevent when we can read from the pipe without blocking.
642 void ChannelPosix::OnFileCanReadWithoutBlocking(int fd
) {
643 if (fd
== server_listen_pipe_
) {
645 if (!ServerAcceptConnection(server_listen_pipe_
, &new_pipe
) ||
648 listener()->OnChannelListenError();
652 // We already have a connection. We only handle one at a time.
653 // close our new descriptor.
654 if (HANDLE_EINTR(shutdown(new_pipe
, SHUT_RDWR
)) < 0)
655 DPLOG(ERROR
) << "shutdown " << pipe_name_
;
656 if (IGNORE_EINTR(close(new_pipe
)) < 0)
657 DPLOG(ERROR
) << "close " << pipe_name_
;
658 listener()->OnChannelDenied();
663 if ((mode_
& MODE_OPEN_ACCESS_FLAG
) == 0) {
664 // Verify that the IPC channel peer is running as the same user.
666 if (!GetPeerEuid(&client_euid
)) {
667 DLOG(ERROR
) << "Unable to query client euid";
668 ResetToAcceptingConnectionState();
671 if (client_euid
!= geteuid()) {
672 DLOG(WARNING
) << "Client euid is not authorised";
673 ResetToAcceptingConnectionState();
678 if (!AcceptConnection()) {
679 NOTREACHED() << "AcceptConnection should not fail on server";
681 waiting_connect_
= false;
682 } else if (fd
== pipe_
) {
683 if (waiting_connect_
&& (mode_
& MODE_SERVER_FLAG
)) {
684 waiting_connect_
= false;
686 if (!ProcessIncomingMessages()) {
687 // ClosePipeOnError may delete this object, so we mustn't call
688 // ProcessOutgoingMessages.
693 NOTREACHED() << "Unknown pipe " << fd
;
696 // If we're a server and handshaking, then we want to make sure that we
697 // only send our handshake message after we've processed the client's.
698 // This gives us a chance to kill the client if the incoming handshake
699 // is invalid. This also flushes any closefd messages.
700 if (!is_blocked_on_write_
) {
701 if (!ProcessOutgoingMessages()) {
707 // Called by libevent when we can write to the pipe without blocking.
708 void ChannelPosix::OnFileCanWriteWithoutBlocking(int fd
) {
709 DCHECK_EQ(pipe_
, fd
);
710 is_blocked_on_write_
= false;
711 if (!ProcessOutgoingMessages()) {
716 bool ChannelPosix::AcceptConnection() {
717 base::MessageLoopForIO::current()->WatchFileDescriptor(
718 pipe_
, true, base::MessageLoopForIO::WATCH_READ
, &read_watcher_
, this);
721 if (mode_
& MODE_CLIENT_FLAG
) {
722 // If we are a client we want to send a hello message out immediately.
723 // In server mode we will send a hello message when we receive one from a
725 waiting_connect_
= false;
726 return ProcessOutgoingMessages();
727 } else if (mode_
& MODE_SERVER_FLAG
) {
728 waiting_connect_
= true;
736 void ChannelPosix::ClosePipeOnError() {
737 if (HasAcceptedConnection()) {
738 ResetToAcceptingConnectionState();
739 listener()->OnChannelError();
742 if (AcceptsConnections()) {
743 listener()->OnChannelListenError();
745 listener()->OnChannelError();
750 int ChannelPosix::GetHelloMessageProcId() const {
751 int pid
= base::GetCurrentProcId();
752 #if defined(OS_LINUX)
753 // Our process may be in a sandbox with a separate PID namespace.
761 void ChannelPosix::QueueHelloMessage() {
762 // Create the Hello message
763 scoped_ptr
<Message
> msg(new Message(MSG_ROUTING_NONE
,
765 IPC::Message::PRIORITY_NORMAL
));
766 if (!msg
->WriteInt(GetHelloMessageProcId())) {
767 NOTREACHED() << "Unable to pickle hello message proc id";
769 #if defined(IPC_USES_READWRITE)
770 scoped_ptr
<Message
> hello
;
771 if (remote_fd_pipe_
!= -1) {
772 if (!msg
->WriteFileDescriptor(base::FileDescriptor(remote_fd_pipe_
,
774 NOTREACHED() << "Unable to pickle hello message file descriptors";
776 DCHECK_EQ(msg
->file_descriptor_set()->size(), 1U);
778 #endif // IPC_USES_READWRITE
779 output_queue_
.push(msg
.release());
782 ChannelPosix::ReadState
ChannelPosix::ReadData(
789 struct msghdr msg
= {0};
791 struct iovec iov
= {buffer
, static_cast<size_t>(buffer_len
)};
795 msg
.msg_control
= input_cmsg_buf_
;
797 // recvmsg() returns 0 if the connection has closed or EAGAIN if no data
798 // is waiting on the pipe.
799 #if defined(IPC_USES_READWRITE)
801 *bytes_read
= HANDLE_EINTR(read(pipe_
, buffer
, buffer_len
));
802 msg
.msg_controllen
= 0;
804 #endif // IPC_USES_READWRITE
806 msg
.msg_controllen
= sizeof(input_cmsg_buf_
);
807 *bytes_read
= HANDLE_EINTR(recvmsg(pipe_
, &msg
, MSG_DONTWAIT
));
809 if (*bytes_read
< 0) {
810 if (errno
== EAGAIN
) {
812 #if defined(OS_MACOSX)
813 } else if (errno
== EPERM
) {
814 // On OSX, reading from a pipe with no listener returns EPERM
815 // treat this as a special case to prevent spurious error messages
819 } else if (errno
== ECONNRESET
|| errno
== EPIPE
) {
822 PLOG(ERROR
) << "pipe error (" << pipe_
<< ")";
825 } else if (*bytes_read
== 0) {
826 // The pipe has closed...
831 CloseClientFileDescriptor();
833 // Read any file descriptors from the message.
834 if (!ExtractFileDescriptorsFromMsghdr(&msg
))
836 return READ_SUCCEEDED
;
839 #if defined(IPC_USES_READWRITE)
840 bool ChannelPosix::ReadFileDescriptorsFromFDPipe() {
842 struct iovec fd_pipe_iov
= { &dummy
, 1 };
844 struct msghdr msg
= { 0 };
845 msg
.msg_iov
= &fd_pipe_iov
;
847 msg
.msg_control
= input_cmsg_buf_
;
848 msg
.msg_controllen
= sizeof(input_cmsg_buf_
);
849 ssize_t bytes_received
= HANDLE_EINTR(recvmsg(fd_pipe_
, &msg
, MSG_DONTWAIT
));
851 if (bytes_received
!= 1)
852 return true; // No message waiting.
854 if (!ExtractFileDescriptorsFromMsghdr(&msg
))
860 // On Posix, we need to fix up the file descriptors before the input message
863 // This will read from the input_fds_ (READWRITE mode only) and read more
864 // handles from the FD pipe if necessary.
865 bool ChannelPosix::WillDispatchInputMessage(Message
* msg
) {
866 uint16 header_fds
= msg
->header()->num_fds
;
868 return true; // Nothing to do.
870 // The message has file descriptors.
871 const char* error
= NULL
;
872 if (header_fds
> input_fds_
.size()) {
873 // The message has been completely received, but we didn't get
874 // enough file descriptors.
875 #if defined(IPC_USES_READWRITE)
876 if (!ReadFileDescriptorsFromFDPipe())
878 if (header_fds
> input_fds_
.size())
879 #endif // IPC_USES_READWRITE
880 error
= "Message needs unreceived descriptors";
883 if (header_fds
> FileDescriptorSet::kMaxDescriptorsPerMessage
)
884 error
= "Message requires an excessive number of descriptors";
887 LOG(WARNING
) << error
888 << " channel:" << this
889 << " message-type:" << msg
->type()
890 << " header()->num_fds:" << header_fds
;
891 // Abort the connection.
896 // The shenaniganery below with &foo.front() requires input_fds_ to have
897 // contiguous underlying storage (such as a simple array or a std::vector).
898 // This is why the header warns not to make input_fds_ a deque<>.
899 msg
->file_descriptor_set()->SetDescriptors(&input_fds_
.front(),
901 input_fds_
.erase(input_fds_
.begin(), input_fds_
.begin() + header_fds
);
905 bool ChannelPosix::DidEmptyInputBuffers() {
906 // When the input data buffer is empty, the fds should be too. If this is
907 // not the case, we probably have a rogue renderer which is trying to fill
908 // our descriptor table.
909 return input_fds_
.empty();
912 bool ChannelPosix::ExtractFileDescriptorsFromMsghdr(msghdr
* msg
) {
913 // Check that there are any control messages. On OSX, CMSG_FIRSTHDR will
914 // return an invalid non-NULL pointer in the case that controllen == 0.
915 if (msg
->msg_controllen
== 0)
918 for (cmsghdr
* cmsg
= CMSG_FIRSTHDR(msg
);
920 cmsg
= CMSG_NXTHDR(msg
, cmsg
)) {
921 if (cmsg
->cmsg_level
== SOL_SOCKET
&& cmsg
->cmsg_type
== SCM_RIGHTS
) {
922 unsigned payload_len
= cmsg
->cmsg_len
- CMSG_LEN(0);
923 DCHECK_EQ(0U, payload_len
% sizeof(int));
924 const int* file_descriptors
= reinterpret_cast<int*>(CMSG_DATA(cmsg
));
925 unsigned num_file_descriptors
= payload_len
/ 4;
926 input_fds_
.insert(input_fds_
.end(),
928 file_descriptors
+ num_file_descriptors
);
930 // Check this after adding the FDs so we don't leak them.
931 if (msg
->msg_flags
& MSG_CTRUNC
) {
940 // No file descriptors found, but that's OK.
944 void ChannelPosix::ClearInputFDs() {
945 for (size_t i
= 0; i
< input_fds_
.size(); ++i
) {
946 if (IGNORE_EINTR(close(input_fds_
[i
])) < 0)
947 PLOG(ERROR
) << "close ";
952 void ChannelPosix::QueueCloseFDMessage(int fd
, int hops
) {
956 // Create the message
957 scoped_ptr
<Message
> msg(new Message(MSG_ROUTING_NONE
,
958 CLOSE_FD_MESSAGE_TYPE
,
959 IPC::Message::PRIORITY_NORMAL
));
960 if (!msg
->WriteInt(hops
- 1) || !msg
->WriteInt(fd
)) {
961 NOTREACHED() << "Unable to pickle close fd.";
963 // Send(msg.release());
964 output_queue_
.push(msg
.release());
974 void ChannelPosix::HandleInternalMessage(const Message
& msg
) {
975 // The Hello message contains only the process id.
976 PickleIterator
iter(msg
);
978 switch (msg
.type()) {
983 case Channel::HELLO_MESSAGE_TYPE
:
985 if (!msg
.ReadInt(&iter
, &pid
))
988 #if defined(IPC_USES_READWRITE)
989 if (mode_
& MODE_SERVER_FLAG
) {
990 // With IPC_USES_READWRITE, the Hello message from the client to the
991 // server also contains the fd_pipe_, which will be used for all
992 // subsequent file descriptor passing.
993 DCHECK_EQ(msg
.file_descriptor_set()->size(), 1U);
994 base::FileDescriptor descriptor
;
995 if (!msg
.ReadFileDescriptor(&iter
, &descriptor
)) {
998 fd_pipe_
= descriptor
.fd
;
999 CHECK(descriptor
.auto_close
);
1001 #endif // IPC_USES_READWRITE
1003 listener()->OnChannelConnected(pid
);
1006 #if defined(OS_MACOSX)
1007 case Channel::CLOSE_FD_MESSAGE_TYPE
:
1009 if (!msg
.ReadInt(&iter
, &hops
))
1011 if (!msg
.ReadInt(&iter
, &fd
))
1014 if (fds_to_close_
.erase(fd
) > 0) {
1015 if (IGNORE_EINTR(close(fd
)) < 0)
1016 PLOG(ERROR
) << "close";
1021 QueueCloseFDMessage(fd
, hops
);
1028 void ChannelPosix::Close() {
1029 // Close can be called multiple time, so we need to make sure we're
1032 ResetToAcceptingConnectionState();
1035 unlink(pipe_name_
.c_str());
1036 must_unlink_
= false;
1038 if (server_listen_pipe_
!= -1) {
1039 if (IGNORE_EINTR(close(server_listen_pipe_
)) < 0)
1040 DPLOG(ERROR
) << "close " << server_listen_pipe_
;
1041 server_listen_pipe_
= -1;
1042 // Unregister libevent for the listening socket and close it.
1043 server_listen_connection_watcher_
.StopWatchingFileDescriptor();
1046 CloseClientFileDescriptor();
1049 base::ProcessId
ChannelPosix::GetPeerPID() const {
1053 base::ProcessId
ChannelPosix::GetSelfPID() const {
1054 return GetHelloMessageProcId();
1057 ChannelHandle
ChannelPosix::TakePipeHandle() {
1058 ChannelHandle handle
= ChannelHandle(pipe_name_
,
1059 base::FileDescriptor(pipe_
, false));
1064 //------------------------------------------------------------------------------
1065 // Channel's methods
1068 scoped_ptr
<Channel
> Channel::Create(
1069 const IPC::ChannelHandle
&channel_handle
, Mode mode
, Listener
* listener
) {
1070 return make_scoped_ptr(new ChannelPosix(
1071 channel_handle
, mode
, listener
)).PassAs
<Channel
>();
1075 std::string
Channel::GenerateVerifiedChannelID(const std::string
& prefix
) {
1076 // A random name is sufficient validation on posix systems, so we don't need
1077 // an additional shared secret.
1079 std::string id
= prefix
;
1083 return id
.append(GenerateUniqueRandomChannelID());
1087 bool Channel::IsNamedServerInitialized(
1088 const std::string
& channel_id
) {
1089 return ChannelPosix::IsNamedServerInitialized(channel_id
);
1092 #if defined(OS_LINUX)
1094 void Channel::SetGlobalPid(int pid
) {
1095 ChannelPosix::SetGlobalPid(pid
);