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/types.h>
11 #include <sys/socket.h>
16 #if defined(OS_OPENBSD)
23 #include "base/command_line.h"
24 #include "base/eintr_wrapper.h"
25 #include "base/file_path.h"
26 #include "base/file_util.h"
27 #include "base/global_descriptors_posix.h"
28 #include "base/location.h"
29 #include "base/logging.h"
30 #include "base/memory/scoped_ptr.h"
31 #include "base/memory/singleton.h"
32 #include "base/process_util.h"
33 #include "base/rand_util.h"
34 #include "base/stl_util.h"
35 #include "base/string_util.h"
36 #include "base/synchronization/lock.h"
37 #include "ipc/ipc_descriptors.h"
38 #include "ipc/ipc_switches.h"
39 #include "ipc/file_descriptor_set_posix.h"
40 #include "ipc/ipc_logging.h"
41 #include "ipc/ipc_message_utils.h"
45 // IPC channels on Windows use named pipes (CreateNamedPipe()) with
46 // channel ids as the pipe names. Channels on POSIX use sockets as
47 // pipes These don't quite line up.
49 // When creating a child subprocess we use a socket pair and the parent side of
50 // the fork arranges it such that the initial control channel ends up on the
51 // magic file descriptor kPrimaryIPCChannel in the child. Future
52 // connections (file descriptors) can then be passed via that
53 // connection via sendmsg().
55 // A POSIX IPC channel can also be set up as a server for a bound UNIX domain
56 // socket, and will handle multiple connect and disconnect sequences. Currently
57 // it is limited to one connection at a time.
59 //------------------------------------------------------------------------------
62 // The PipeMap class works around this quirk related to unit tests:
64 // When running as a server, we install the client socket in a
65 // specific file descriptor number (@kPrimaryIPCChannel). However, we
66 // also have to support the case where we are running unittests in the
67 // same process. (We do not support forking without execing.)
69 // Case 1: normal running
70 // The IPC server object will install a mapping in PipeMap from the
71 // name which it was given to the client pipe. When forking the client, the
72 // GetClientFileDescriptorMapping will ensure that the socket is installed in
73 // the magic slot (@kPrimaryIPCChannel). The client will search for the
74 // mapping, but it won't find any since we are in a new process. Thus the
75 // magic fd number is returned. Once the client connects, the server will
76 // close its copy of the client socket and remove the mapping.
78 // Case 2: unittests - client and server in the same process
79 // The IPC server will install a mapping as before. The client will search
80 // for a mapping and find out. It duplicates the file descriptor and
81 // connects. Once the client connects, the server will close the original
82 // copy of the client socket and remove the mapping. Thus, when the client
83 // object closes, it will close the only remaining copy of the client socket
84 // in the fd table and the server will see EOF on its side.
86 // TODO(port): a client process cannot connect to multiple IPC channels with
91 static PipeMap
* GetInstance() {
92 return Singleton
<PipeMap
>::get();
96 // Shouldn't have left over pipes.
100 // Lookup a given channel id. Return -1 if not found.
101 int Lookup(const std::string
& channel_id
) {
102 base::AutoLock
locked(lock_
);
104 ChannelToFDMap::const_iterator i
= map_
.find(channel_id
);
110 // Remove the mapping for the given channel id. No error is signaled if the
111 // channel_id doesn't exist
112 void Remove(const std::string
& channel_id
) {
113 base::AutoLock
locked(lock_
);
114 map_
.erase(channel_id
);
117 // Insert a mapping from @channel_id to @fd. It's a fatal error to insert a
118 // mapping if one already exists for the given channel_id
119 void Insert(const std::string
& channel_id
, int fd
) {
120 base::AutoLock
locked(lock_
);
123 ChannelToFDMap::const_iterator i
= map_
.find(channel_id
);
124 CHECK(i
== map_
.end()) << "Creating second IPC server (fd " << fd
<< ") "
125 << "for '" << channel_id
<< "' while first "
126 << "(fd " << i
->second
<< ") still exists";
127 map_
[channel_id
] = fd
;
132 typedef std::map
<std::string
, int> ChannelToFDMap
;
135 friend struct DefaultSingletonTraits
<PipeMap
>;
138 //------------------------------------------------------------------------------
139 // Verify that kMaxPipeNameLength is a decent size.
140 COMPILE_ASSERT(sizeof(((sockaddr_un
*)0)->sun_path
) >= kMaxPipeNameLength
,
141 BAD_SUN_PATH_LENGTH
);
143 // Creates a unix domain socket bound to the specified name that is listening
145 bool CreateServerUnixDomainSocket(const std::string
& pipe_name
,
146 int* server_listen_fd
) {
147 DCHECK(server_listen_fd
);
149 if (pipe_name
.length() == 0 || pipe_name
.length() >= kMaxPipeNameLength
) {
150 DLOG(ERROR
) << "pipe_name.length() == " << pipe_name
.length();
155 int fd
= socket(AF_UNIX
, SOCK_STREAM
, 0);
160 // Make socket non-blocking
161 if (fcntl(fd
, F_SETFL
, O_NONBLOCK
) == -1) {
162 PLOG(ERROR
) << "fcntl(O_NONBLOCK) " << pipe_name
;
163 if (HANDLE_EINTR(close(fd
)) < 0)
164 PLOG(ERROR
) << "close " << pipe_name
;
168 // Delete any old FS instances.
169 unlink(pipe_name
.c_str());
171 // Make sure the path we need exists.
172 FilePath
path(pipe_name
);
173 FilePath dir_path
= path
.DirName();
174 if (!file_util::CreateDirectory(dir_path
)) {
175 if (HANDLE_EINTR(close(fd
)) < 0)
176 PLOG(ERROR
) << "close " << pipe_name
;
180 // Create unix_addr structure.
181 struct sockaddr_un unix_addr
;
182 memset(&unix_addr
, 0, sizeof(unix_addr
));
183 unix_addr
.sun_family
= AF_UNIX
;
184 int path_len
= snprintf(unix_addr
.sun_path
, IPC::kMaxPipeNameLength
,
185 "%s", pipe_name
.c_str());
186 DCHECK_EQ(static_cast<int>(pipe_name
.length()), path_len
);
187 size_t unix_addr_len
= offsetof(struct sockaddr_un
,
188 sun_path
) + path_len
+ 1;
191 if (bind(fd
, reinterpret_cast<const sockaddr
*>(&unix_addr
),
192 unix_addr_len
) != 0) {
193 PLOG(ERROR
) << "bind " << pipe_name
;
194 if (HANDLE_EINTR(close(fd
)) < 0)
195 PLOG(ERROR
) << "close " << pipe_name
;
199 // Start listening on the socket.
200 const int listen_queue_length
= 1;
201 if (listen(fd
, listen_queue_length
) != 0) {
202 PLOG(ERROR
) << "listen " << pipe_name
;
203 if (HANDLE_EINTR(close(fd
)) < 0)
204 PLOG(ERROR
) << "close " << pipe_name
;
208 *server_listen_fd
= fd
;
212 // Accept a connection on a socket we are listening to.
213 bool ServerAcceptConnection(int server_listen_fd
, int* server_socket
) {
214 DCHECK(server_socket
);
216 int accept_fd
= HANDLE_EINTR(accept(server_listen_fd
, NULL
, 0));
219 if (fcntl(accept_fd
, F_SETFL
, O_NONBLOCK
) == -1) {
220 PLOG(ERROR
) << "fcntl(O_NONBLOCK) " << accept_fd
;
221 if (HANDLE_EINTR(close(accept_fd
)) < 0)
222 PLOG(ERROR
) << "close " << accept_fd
;
226 *server_socket
= accept_fd
;
230 bool CreateClientUnixDomainSocket(const std::string
& pipe_name
,
231 int* client_socket
) {
232 DCHECK(client_socket
);
233 DCHECK_GT(pipe_name
.length(), 0u);
234 DCHECK_LT(pipe_name
.length(), kMaxPipeNameLength
);
236 if (pipe_name
.length() == 0 || pipe_name
.length() >= kMaxPipeNameLength
) {
241 int fd
= socket(AF_UNIX
, SOCK_STREAM
, 0);
243 PLOG(ERROR
) << "socket " << pipe_name
;
247 // Make socket non-blocking
248 if (fcntl(fd
, F_SETFL
, O_NONBLOCK
) == -1) {
249 PLOG(ERROR
) << "fcntl(O_NONBLOCK) " << pipe_name
;
250 if (HANDLE_EINTR(close(fd
)) < 0)
251 PLOG(ERROR
) << "close " << pipe_name
;
255 // Create server side of socket.
256 struct sockaddr_un server_unix_addr
;
257 memset(&server_unix_addr
, 0, sizeof(server_unix_addr
));
258 server_unix_addr
.sun_family
= AF_UNIX
;
259 int path_len
= snprintf(server_unix_addr
.sun_path
, IPC::kMaxPipeNameLength
,
260 "%s", pipe_name
.c_str());
261 DCHECK_EQ(static_cast<int>(pipe_name
.length()), path_len
);
262 size_t server_unix_addr_len
= offsetof(struct sockaddr_un
,
263 sun_path
) + path_len
+ 1;
265 if (HANDLE_EINTR(connect(fd
, reinterpret_cast<sockaddr
*>(&server_unix_addr
),
266 server_unix_addr_len
)) != 0) {
267 PLOG(ERROR
) << "connect " << pipe_name
;
268 if (HANDLE_EINTR(close(fd
)) < 0)
269 PLOG(ERROR
) << "close " << pipe_name
;
277 bool SocketWriteErrorIsRecoverable() {
278 #if defined(OS_MACOSX)
279 // On OS X if sendmsg() is trying to send fds between processes and there
280 // isn't enough room in the output buffer to send the fd structure over
281 // atomically then EMSGSIZE is returned.
283 // EMSGSIZE presents a problem since the system APIs can only call us when
284 // there's room in the socket buffer and not when there is "enough" room.
286 // The current behavior is to return to the event loop when EMSGSIZE is
287 // received and hopefull service another FD. This is however still
288 // technically a busy wait since the event loop will call us right back until
289 // the receiver has read enough data to allow passing the FD over atomically.
290 return errno
== EAGAIN
|| errno
== EMSGSIZE
;
292 return errno
== EAGAIN
;
297 //------------------------------------------------------------------------------
299 #if defined(OS_LINUX)
300 int Channel::ChannelImpl::global_pid_
= 0;
303 Channel::ChannelImpl::ChannelImpl(const IPC::ChannelHandle
& channel_handle
,
304 Mode mode
, Listener
* listener
)
305 : ChannelReader(listener
),
307 peer_pid_(base::kNullProcessId
),
308 is_blocked_on_write_(false),
309 waiting_connect_(true),
310 message_send_bytes_written_(0),
311 server_listen_pipe_(-1),
314 #if defined(IPC_USES_READWRITE)
317 #endif // IPC_USES_READWRITE
318 pipe_name_(channel_handle
.name
),
319 must_unlink_(false) {
320 memset(input_cmsg_buf_
, 0, sizeof(input_cmsg_buf_
));
321 if (!CreatePipe(channel_handle
)) {
322 // The pipe may have been closed already.
323 const char *modestr
= (mode_
& MODE_SERVER_FLAG
) ? "server" : "client";
324 LOG(WARNING
) << "Unable to create pipe named \"" << channel_handle
.name
325 << "\" in " << modestr
<< " mode";
329 Channel::ChannelImpl::~ChannelImpl() {
333 bool SocketPair(int* fd1
, int* fd2
) {
335 if (socketpair(AF_UNIX
, SOCK_STREAM
, 0, pipe_fds
) != 0) {
336 PLOG(ERROR
) << "socketpair()";
340 // Set both ends to be non-blocking.
341 if (fcntl(pipe_fds
[0], F_SETFL
, O_NONBLOCK
) == -1 ||
342 fcntl(pipe_fds
[1], F_SETFL
, O_NONBLOCK
) == -1) {
343 PLOG(ERROR
) << "fcntl(O_NONBLOCK)";
344 if (HANDLE_EINTR(close(pipe_fds
[0])) < 0)
345 PLOG(ERROR
) << "close";
346 if (HANDLE_EINTR(close(pipe_fds
[1])) < 0)
347 PLOG(ERROR
) << "close";
357 bool Channel::ChannelImpl::CreatePipe(
358 const IPC::ChannelHandle
& channel_handle
) {
359 DCHECK(server_listen_pipe_
== -1 && pipe_
== -1);
361 // Four possible cases:
362 // 1) It's a channel wrapping a pipe that is given to us.
363 // 2) It's for a named channel, so we create it.
364 // 3) It's for a client that we implement ourself. This is used
366 // 4) It's the initial IPC channel:
367 // 4a) Client side: Pull the pipe out of the GlobalDescriptors set.
368 // 4b) Server side: create the pipe.
371 if (channel_handle
.socket
.fd
!= -1) {
372 // Case 1 from comment above.
373 local_pipe
= channel_handle
.socket
.fd
;
374 #if defined(IPC_USES_READWRITE)
375 // Test the socket passed into us to make sure it is nonblocking.
376 // We don't want to call read/write on a blocking socket.
377 int value
= fcntl(local_pipe
, F_GETFL
);
379 PLOG(ERROR
) << "fcntl(F_GETFL) " << pipe_name_
;
382 if (!(value
& O_NONBLOCK
)) {
383 LOG(ERROR
) << "Socket " << pipe_name_
<< " must be O_NONBLOCK";
386 #endif // IPC_USES_READWRITE
387 } else if (mode_
& MODE_NAMED_FLAG
) {
388 // Case 2 from comment above.
389 if (mode_
& MODE_SERVER_FLAG
) {
390 if (!CreateServerUnixDomainSocket(pipe_name_
, &local_pipe
)) {
394 } else if (mode_
& MODE_CLIENT_FLAG
) {
395 if (!CreateClientUnixDomainSocket(pipe_name_
, &local_pipe
)) {
399 LOG(ERROR
) << "Bad mode: " << mode_
;
403 local_pipe
= PipeMap::GetInstance()->Lookup(pipe_name_
);
404 if (mode_
& MODE_CLIENT_FLAG
) {
405 if (local_pipe
!= -1) {
406 // Case 3 from comment above.
407 // We only allow one connection.
408 local_pipe
= HANDLE_EINTR(dup(local_pipe
));
409 PipeMap::GetInstance()->Remove(pipe_name_
);
411 // Case 4a from comment above.
412 // Guard against inappropriate reuse of the initial IPC channel. If
413 // an IPC channel closes and someone attempts to reuse it by name, the
414 // initial channel must not be recycled here. http://crbug.com/26754.
415 static bool used_initial_channel
= false;
416 if (used_initial_channel
) {
417 LOG(FATAL
) << "Denying attempt to reuse initial IPC channel for "
421 used_initial_channel
= true;
424 base::GlobalDescriptors::GetInstance()->Get(kPrimaryIPCChannel
);
426 } else if (mode_
& MODE_SERVER_FLAG
) {
427 // Case 4b from comment above.
428 if (local_pipe
!= -1) {
429 LOG(ERROR
) << "Server already exists for " << pipe_name_
;
432 base::AutoLock
lock(client_pipe_lock_
);
433 if (!SocketPair(&local_pipe
, &client_pipe_
))
435 PipeMap::GetInstance()->Insert(pipe_name_
, client_pipe_
);
437 LOG(ERROR
) << "Bad mode: " << mode_
;
442 #if defined(IPC_USES_READWRITE)
443 // Create a dedicated socketpair() for exchanging file descriptors.
444 // See comments for IPC_USES_READWRITE for details.
445 if (mode_
& MODE_CLIENT_FLAG
) {
446 if (!SocketPair(&fd_pipe_
, &remote_fd_pipe_
)) {
450 #endif // IPC_USES_READWRITE
452 if ((mode_
& MODE_SERVER_FLAG
) && (mode_
& MODE_NAMED_FLAG
)) {
453 server_listen_pipe_
= local_pipe
;
461 bool Channel::ChannelImpl::Connect() {
462 if (server_listen_pipe_
== -1 && pipe_
== -1) {
463 DLOG(INFO
) << "Channel creation failed: " << pipe_name_
;
467 bool did_connect
= true;
468 if (server_listen_pipe_
!= -1) {
469 // Watch the pipe for connections, and turn any connections into
471 MessageLoopForIO::current()->WatchFileDescriptor(
474 MessageLoopForIO::WATCH_READ
,
475 &server_listen_connection_watcher_
,
478 did_connect
= AcceptConnection();
483 bool Channel::ChannelImpl::ProcessOutgoingMessages() {
484 DCHECK(!waiting_connect_
); // Why are we trying to send messages if there's
486 if (output_queue_
.empty())
492 // Write out all the messages we can till the write blocks or there are no
493 // more outgoing messages.
494 while (!output_queue_
.empty()) {
495 Message
* msg
= output_queue_
.front();
497 size_t amt_to_write
= msg
->size() - message_send_bytes_written_
;
498 DCHECK_NE(0U, amt_to_write
);
499 const char* out_bytes
= reinterpret_cast<const char*>(msg
->data()) +
500 message_send_bytes_written_
;
502 struct msghdr msgh
= {0};
503 struct iovec iov
= {const_cast<char*>(out_bytes
), amt_to_write
};
507 sizeof(int) * FileDescriptorSet::kMaxDescriptorsPerMessage
)];
509 ssize_t bytes_written
= 1;
512 if (message_send_bytes_written_
== 0 &&
513 !msg
->file_descriptor_set()->empty()) {
514 // This is the first chunk of a message which has descriptors to send
515 struct cmsghdr
*cmsg
;
516 const unsigned num_fds
= msg
->file_descriptor_set()->size();
518 DCHECK(num_fds
<= FileDescriptorSet::kMaxDescriptorsPerMessage
);
519 if (msg
->file_descriptor_set()->ContainsDirectoryDescriptor()) {
520 LOG(FATAL
) << "Panic: attempting to transport directory descriptor over"
521 " IPC. Aborting to maintain sandbox isolation.";
522 // If you have hit this then something tried to send a file descriptor
523 // to a directory over an IPC channel. Since IPC channels span
524 // sandboxes this is very bad: the receiving process can use openat
525 // with ".." elements in the path in order to reach the real
529 msgh
.msg_control
= buf
;
530 msgh
.msg_controllen
= CMSG_SPACE(sizeof(int) * num_fds
);
531 cmsg
= CMSG_FIRSTHDR(&msgh
);
532 cmsg
->cmsg_level
= SOL_SOCKET
;
533 cmsg
->cmsg_type
= SCM_RIGHTS
;
534 cmsg
->cmsg_len
= CMSG_LEN(sizeof(int) * num_fds
);
535 msg
->file_descriptor_set()->GetDescriptors(
536 reinterpret_cast<int*>(CMSG_DATA(cmsg
)));
537 msgh
.msg_controllen
= cmsg
->cmsg_len
;
539 // DCHECK_LE above already checks that
540 // num_fds < kMaxDescriptorsPerMessage so no danger of overflow.
541 msg
->header()->num_fds
= static_cast<uint16
>(num_fds
);
543 #if defined(IPC_USES_READWRITE)
544 if (!IsHelloMessage(*msg
)) {
545 // Only the Hello message sends the file descriptor with the message.
546 // Subsequently, we can send file descriptors on the dedicated
547 // fd_pipe_ which makes Seccomp sandbox operation more efficient.
548 struct iovec fd_pipe_iov
= { const_cast<char *>(""), 1 };
549 msgh
.msg_iov
= &fd_pipe_iov
;
550 fd_written
= fd_pipe_
;
551 bytes_written
= HANDLE_EINTR(sendmsg(fd_pipe_
, &msgh
, MSG_DONTWAIT
));
553 msgh
.msg_controllen
= 0;
554 if (bytes_written
> 0) {
555 msg
->file_descriptor_set()->CommitAll();
558 #endif // IPC_USES_READWRITE
561 if (bytes_written
== 1) {
563 #if defined(IPC_USES_READWRITE)
564 if ((mode_
& MODE_CLIENT_FLAG
) && IsHelloMessage(*msg
)) {
565 DCHECK_EQ(msg
->file_descriptor_set()->size(), 1U);
567 if (!msgh
.msg_controllen
) {
568 bytes_written
= HANDLE_EINTR(write(pipe_
, out_bytes
, amt_to_write
));
570 #endif // IPC_USES_READWRITE
572 bytes_written
= HANDLE_EINTR(sendmsg(pipe_
, &msgh
, MSG_DONTWAIT
));
575 if (bytes_written
> 0)
576 msg
->file_descriptor_set()->CommitAll();
578 if (bytes_written
< 0 && !SocketWriteErrorIsRecoverable()) {
579 #if defined(OS_MACOSX)
580 // On OSX writing to a pipe with no listener returns EPERM.
581 if (errno
== EPERM
) {
586 if (errno
== EPIPE
) {
590 PLOG(ERROR
) << "pipe error on "
592 << " Currently writing message of size: "
597 if (static_cast<size_t>(bytes_written
) != amt_to_write
) {
598 if (bytes_written
> 0) {
599 // If write() fails with EAGAIN then bytes_written will be -1.
600 message_send_bytes_written_
+= bytes_written
;
603 // Tell libevent to call us back once things are unblocked.
604 is_blocked_on_write_
= true;
605 MessageLoopForIO::current()->WatchFileDescriptor(
608 MessageLoopForIO::WATCH_WRITE
,
613 message_send_bytes_written_
= 0;
616 DVLOG(2) << "sent message @" << msg
<< " on channel @" << this
617 << " with type " << msg
->type() << " on fd " << pipe_
;
618 delete output_queue_
.front();
625 bool Channel::ChannelImpl::Send(Message
* message
) {
626 DVLOG(2) << "sending message @" << message
<< " on channel @" << this
627 << " with type " << message
->type()
628 << " (" << output_queue_
.size() << " in queue)";
630 #ifdef IPC_MESSAGE_LOG_ENABLED
631 Logging::GetInstance()->OnSendMessage(message
, "");
632 #endif // IPC_MESSAGE_LOG_ENABLED
634 message
->TraceMessageBegin();
635 output_queue_
.push(message
);
636 if (!is_blocked_on_write_
&& !waiting_connect_
) {
637 return ProcessOutgoingMessages();
643 int Channel::ChannelImpl::GetClientFileDescriptor() {
644 base::AutoLock
lock(client_pipe_lock_
);
648 int Channel::ChannelImpl::TakeClientFileDescriptor() {
649 base::AutoLock
lock(client_pipe_lock_
);
650 int fd
= client_pipe_
;
651 if (client_pipe_
!= -1) {
652 PipeMap::GetInstance()->Remove(pipe_name_
);
658 void Channel::ChannelImpl::CloseClientFileDescriptor() {
659 base::AutoLock
lock(client_pipe_lock_
);
660 if (client_pipe_
!= -1) {
661 PipeMap::GetInstance()->Remove(pipe_name_
);
662 if (HANDLE_EINTR(close(client_pipe_
)) < 0)
663 PLOG(ERROR
) << "close " << pipe_name_
;
668 bool Channel::ChannelImpl::AcceptsConnections() const {
669 return server_listen_pipe_
!= -1;
672 bool Channel::ChannelImpl::HasAcceptedConnection() const {
673 return AcceptsConnections() && pipe_
!= -1;
676 bool Channel::ChannelImpl::GetClientEuid(uid_t
* client_euid
) const {
677 DCHECK(HasAcceptedConnection());
678 #if defined(OS_MACOSX) || defined(OS_OPENBSD)
681 if (getpeereid(pipe_
, &peer_euid
, &peer_gid
) != 0) {
682 PLOG(ERROR
) << "getpeereid " << pipe_
;
685 *client_euid
= peer_euid
;
687 #elif defined(OS_SOLARIS)
691 socklen_t cred_len
= sizeof(cred
);
692 if (getsockopt(pipe_
, SOL_SOCKET
, SO_PEERCRED
, &cred
, &cred_len
) != 0) {
693 PLOG(ERROR
) << "getsockopt " << pipe_
;
696 if (static_cast<unsigned>(cred_len
) < sizeof(cred
)) {
697 NOTREACHED() << "Truncated ucred from SO_PEERCRED?";
700 *client_euid
= cred
.uid
;
705 void Channel::ChannelImpl::ResetToAcceptingConnectionState() {
706 // Unregister libevent for the unix domain socket and close it.
707 read_watcher_
.StopWatchingFileDescriptor();
708 write_watcher_
.StopWatchingFileDescriptor();
710 if (HANDLE_EINTR(close(pipe_
)) < 0)
711 PLOG(ERROR
) << "close pipe_ " << pipe_name_
;
714 #if defined(IPC_USES_READWRITE)
715 if (fd_pipe_
!= -1) {
716 if (HANDLE_EINTR(close(fd_pipe_
)) < 0)
717 PLOG(ERROR
) << "close fd_pipe_ " << pipe_name_
;
720 if (remote_fd_pipe_
!= -1) {
721 if (HANDLE_EINTR(close(remote_fd_pipe_
)) < 0)
722 PLOG(ERROR
) << "close remote_fd_pipe_ " << pipe_name_
;
723 remote_fd_pipe_
= -1;
725 #endif // IPC_USES_READWRITE
727 while (!output_queue_
.empty()) {
728 Message
* m
= output_queue_
.front();
733 // Close any outstanding, received file descriptors.
738 bool Channel::ChannelImpl::IsNamedServerInitialized(
739 const std::string
& channel_id
) {
740 return file_util::PathExists(FilePath(channel_id
));
743 #if defined(OS_LINUX)
745 void Channel::ChannelImpl::SetGlobalPid(int pid
) {
750 // Called by libevent when we can read from the pipe without blocking.
751 void Channel::ChannelImpl::OnFileCanReadWithoutBlocking(int fd
) {
752 bool send_server_hello_msg
= false;
753 if (fd
== server_listen_pipe_
) {
755 if (!ServerAcceptConnection(server_listen_pipe_
, &new_pipe
)) {
757 listener()->OnChannelListenError();
761 // We already have a connection. We only handle one at a time.
762 // close our new descriptor.
763 if (HANDLE_EINTR(shutdown(new_pipe
, SHUT_RDWR
)) < 0)
764 DPLOG(ERROR
) << "shutdown " << pipe_name_
;
765 if (HANDLE_EINTR(close(new_pipe
)) < 0)
766 DPLOG(ERROR
) << "close " << pipe_name_
;
767 listener()->OnChannelDenied();
772 if ((mode_
& MODE_OPEN_ACCESS_FLAG
) == 0) {
773 // Verify that the IPC channel peer is running as the same user.
775 if (!GetClientEuid(&client_euid
)) {
776 DLOG(ERROR
) << "Unable to query client euid";
777 ResetToAcceptingConnectionState();
780 if (client_euid
!= geteuid()) {
781 DLOG(WARNING
) << "Client euid is not authorised";
782 ResetToAcceptingConnectionState();
787 if (!AcceptConnection()) {
788 NOTREACHED() << "AcceptConnection should not fail on server";
790 send_server_hello_msg
= true;
791 waiting_connect_
= false;
792 } else if (fd
== pipe_
) {
793 if (waiting_connect_
&& (mode_
& MODE_SERVER_FLAG
)) {
794 send_server_hello_msg
= true;
795 waiting_connect_
= false;
797 if (!ProcessIncomingMessages()) {
798 // ClosePipeOnError may delete this object, so we mustn't call
799 // ProcessOutgoingMessages.
800 send_server_hello_msg
= false;
804 NOTREACHED() << "Unknown pipe " << fd
;
807 // If we're a server and handshaking, then we want to make sure that we
808 // only send our handshake message after we've processed the client's.
809 // This gives us a chance to kill the client if the incoming handshake
811 if (send_server_hello_msg
) {
812 ProcessOutgoingMessages();
816 // Called by libevent when we can write to the pipe without blocking.
817 void Channel::ChannelImpl::OnFileCanWriteWithoutBlocking(int fd
) {
818 DCHECK_EQ(pipe_
, fd
);
819 is_blocked_on_write_
= false;
820 if (!ProcessOutgoingMessages()) {
825 bool Channel::ChannelImpl::AcceptConnection() {
826 MessageLoopForIO::current()->WatchFileDescriptor(pipe_
,
828 MessageLoopForIO::WATCH_READ
,
833 if (mode_
& MODE_CLIENT_FLAG
) {
834 // If we are a client we want to send a hello message out immediately.
835 // In server mode we will send a hello message when we receive one from a
837 waiting_connect_
= false;
838 return ProcessOutgoingMessages();
839 } else if (mode_
& MODE_SERVER_FLAG
) {
840 waiting_connect_
= true;
848 void Channel::ChannelImpl::ClosePipeOnError() {
849 if (HasAcceptedConnection()) {
850 ResetToAcceptingConnectionState();
851 listener()->OnChannelError();
854 if (AcceptsConnections()) {
855 listener()->OnChannelListenError();
857 listener()->OnChannelError();
862 int Channel::ChannelImpl::GetHelloMessageProcId() {
863 int pid
= base::GetCurrentProcId();
864 #if defined(OS_LINUX)
865 // Our process may be in a sandbox with a separate PID namespace.
873 void Channel::ChannelImpl::QueueHelloMessage() {
874 // Create the Hello message
875 scoped_ptr
<Message
> msg(new Message(MSG_ROUTING_NONE
,
877 IPC::Message::PRIORITY_NORMAL
));
878 if (!msg
->WriteInt(GetHelloMessageProcId())) {
879 NOTREACHED() << "Unable to pickle hello message proc id";
881 #if defined(IPC_USES_READWRITE)
882 scoped_ptr
<Message
> hello
;
883 if (remote_fd_pipe_
!= -1) {
884 if (!msg
->WriteFileDescriptor(base::FileDescriptor(remote_fd_pipe_
,
886 NOTREACHED() << "Unable to pickle hello message file descriptors";
888 DCHECK_EQ(msg
->file_descriptor_set()->size(), 1U);
890 #endif // IPC_USES_READWRITE
891 output_queue_
.push(msg
.release());
894 Channel::ChannelImpl::ReadState
Channel::ChannelImpl::ReadData(
901 struct msghdr msg
= {0};
903 struct iovec iov
= {buffer
, static_cast<size_t>(buffer_len
)};
907 msg
.msg_control
= input_cmsg_buf_
;
909 // recvmsg() returns 0 if the connection has closed or EAGAIN if no data
910 // is waiting on the pipe.
911 #if defined(IPC_USES_READWRITE)
913 *bytes_read
= HANDLE_EINTR(read(pipe_
, buffer
, buffer_len
));
914 msg
.msg_controllen
= 0;
916 #endif // IPC_USES_READWRITE
918 msg
.msg_controllen
= sizeof(input_cmsg_buf_
);
919 *bytes_read
= HANDLE_EINTR(recvmsg(pipe_
, &msg
, MSG_DONTWAIT
));
921 if (*bytes_read
< 0) {
922 if (errno
== EAGAIN
) {
924 #if defined(OS_MACOSX)
925 } else if (errno
== EPERM
) {
926 // On OSX, reading from a pipe with no listener returns EPERM
927 // treat this as a special case to prevent spurious error messages
931 } else if (errno
== ECONNRESET
|| errno
== EPIPE
) {
934 PLOG(ERROR
) << "pipe error (" << pipe_
<< ")";
937 } else if (*bytes_read
== 0) {
938 // The pipe has closed...
943 CloseClientFileDescriptor();
945 // Read any file descriptors from the message.
946 if (!ExtractFileDescriptorsFromMsghdr(&msg
))
948 return READ_SUCCEEDED
;
951 #if defined(IPC_USES_READWRITE)
952 bool Channel::ChannelImpl::ReadFileDescriptorsFromFDPipe() {
954 struct iovec fd_pipe_iov
= { &dummy
, 1 };
956 struct msghdr msg
= { 0 };
957 msg
.msg_iov
= &fd_pipe_iov
;
959 msg
.msg_control
= input_cmsg_buf_
;
960 msg
.msg_controllen
= sizeof(input_cmsg_buf_
);
961 ssize_t bytes_received
= HANDLE_EINTR(recvmsg(fd_pipe_
, &msg
, MSG_DONTWAIT
));
963 if (bytes_received
!= 1)
964 return true; // No message waiting.
966 if (!ExtractFileDescriptorsFromMsghdr(&msg
))
972 // On Posix, we need to fix up the file descriptors before the input message
975 // This will read from the input_fds_ (READWRITE mode only) and read more
976 // handles from the FD pipe if necessary.
977 bool Channel::ChannelImpl::WillDispatchInputMessage(Message
* msg
) {
978 uint16 header_fds
= msg
->header()->num_fds
;
980 return true; // Nothing to do.
982 // The message has file descriptors.
983 const char* error
= NULL
;
984 if (header_fds
> input_fds_
.size()) {
985 // The message has been completely received, but we didn't get
986 // enough file descriptors.
987 #if defined(IPC_USES_READWRITE)
988 if (!ReadFileDescriptorsFromFDPipe())
990 if (header_fds
> input_fds_
.size())
991 #endif // IPC_USES_READWRITE
992 error
= "Message needs unreceived descriptors";
995 if (header_fds
> FileDescriptorSet::kMaxDescriptorsPerMessage
)
996 error
= "Message requires an excessive number of descriptors";
999 LOG(WARNING
) << error
1000 << " channel:" << this
1001 << " message-type:" << msg
->type()
1002 << " header()->num_fds:" << header_fds
;
1003 #if defined(CHROMIUM_SELINUX)
1004 LOG(WARNING
) << "In the case of SELinux this can be caused when "
1005 "using a --user-data-dir to which the default "
1006 "policy doesn't give the renderer access to. ";
1007 #endif // CHROMIUM_SELINUX
1008 // Abort the connection.
1013 // The shenaniganery below with &foo.front() requires input_fds_ to have
1014 // contiguous underlying storage (such as a simple array or a std::vector).
1015 // This is why the header warns not to make input_fds_ a deque<>.
1016 msg
->file_descriptor_set()->SetDescriptors(&input_fds_
.front(),
1018 input_fds_
.erase(input_fds_
.begin(), input_fds_
.begin() + header_fds
);
1022 bool Channel::ChannelImpl::DidEmptyInputBuffers() {
1023 // When the input data buffer is empty, the fds should be too. If this is
1024 // not the case, we probably have a rogue renderer which is trying to fill
1025 // our descriptor table.
1026 return input_fds_
.empty();
1029 bool Channel::ChannelImpl::ExtractFileDescriptorsFromMsghdr(msghdr
* msg
) {
1030 // Check that there are any control messages. On OSX, CMSG_FIRSTHDR will
1031 // return an invalid non-NULL pointer in the case that controllen == 0.
1032 if (msg
->msg_controllen
== 0)
1035 for (cmsghdr
* cmsg
= CMSG_FIRSTHDR(msg
);
1037 cmsg
= CMSG_NXTHDR(msg
, cmsg
)) {
1038 if (cmsg
->cmsg_level
== SOL_SOCKET
&& cmsg
->cmsg_type
== SCM_RIGHTS
) {
1039 unsigned payload_len
= cmsg
->cmsg_len
- CMSG_LEN(0);
1040 DCHECK_EQ(0U, payload_len
% sizeof(int));
1041 const int* file_descriptors
= reinterpret_cast<int*>(CMSG_DATA(cmsg
));
1042 unsigned num_file_descriptors
= payload_len
/ 4;
1043 input_fds_
.insert(input_fds_
.end(),
1045 file_descriptors
+ num_file_descriptors
);
1047 // Check this after adding the FDs so we don't leak them.
1048 if (msg
->msg_flags
& MSG_CTRUNC
) {
1057 // No file descriptors found, but that's OK.
1061 void Channel::ChannelImpl::ClearInputFDs() {
1062 for (size_t i
= 0; i
< input_fds_
.size(); ++i
) {
1063 if (HANDLE_EINTR(close(input_fds_
[i
])) < 0)
1064 PLOG(ERROR
) << "close ";
1069 void Channel::ChannelImpl::HandleHelloMessage(const Message
& msg
) {
1070 // The Hello message contains only the process id.
1071 PickleIterator
iter(msg
);
1073 if (!msg
.ReadInt(&iter
, &pid
))
1076 #if defined(IPC_USES_READWRITE)
1077 if (mode_
& MODE_SERVER_FLAG
) {
1078 // With IPC_USES_READWRITE, the Hello message from the client to the
1079 // server also contains the fd_pipe_, which will be used for all
1080 // subsequent file descriptor passing.
1081 DCHECK_EQ(msg
.file_descriptor_set()->size(), 1U);
1082 base::FileDescriptor descriptor
;
1083 if (!msg
.ReadFileDescriptor(&iter
, &descriptor
)) {
1086 fd_pipe_
= descriptor
.fd
;
1087 CHECK(descriptor
.auto_close
);
1089 #endif // IPC_USES_READWRITE
1091 listener()->OnChannelConnected(pid
);
1094 void Channel::ChannelImpl::Close() {
1095 // Close can be called multiple time, so we need to make sure we're
1098 ResetToAcceptingConnectionState();
1101 unlink(pipe_name_
.c_str());
1102 must_unlink_
= false;
1104 if (server_listen_pipe_
!= -1) {
1105 if (HANDLE_EINTR(close(server_listen_pipe_
)) < 0)
1106 DPLOG(ERROR
) << "close " << server_listen_pipe_
;
1107 server_listen_pipe_
= -1;
1108 // Unregister libevent for the listening socket and close it.
1109 server_listen_connection_watcher_
.StopWatchingFileDescriptor();
1112 CloseClientFileDescriptor();
1115 //------------------------------------------------------------------------------
1116 // Channel's methods simply call through to ChannelImpl.
1117 Channel::Channel(const IPC::ChannelHandle
& channel_handle
, Mode mode
,
1119 : channel_impl_(new ChannelImpl(channel_handle
, mode
, listener
)) {
1122 Channel::~Channel() {
1123 delete channel_impl_
;
1126 bool Channel::Connect() {
1127 return channel_impl_
->Connect();
1130 void Channel::Close() {
1132 channel_impl_
->Close();
1135 void Channel::set_listener(Listener
* listener
) {
1136 channel_impl_
->set_listener(listener
);
1139 base::ProcessId
Channel::peer_pid() const {
1140 return channel_impl_
->peer_pid();
1143 bool Channel::Send(Message
* message
) {
1144 return channel_impl_
->Send(message
);
1147 int Channel::GetClientFileDescriptor() const {
1148 return channel_impl_
->GetClientFileDescriptor();
1151 int Channel::TakeClientFileDescriptor() {
1152 return channel_impl_
->TakeClientFileDescriptor();
1155 bool Channel::AcceptsConnections() const {
1156 return channel_impl_
->AcceptsConnections();
1159 bool Channel::HasAcceptedConnection() const {
1160 return channel_impl_
->HasAcceptedConnection();
1163 bool Channel::GetClientEuid(uid_t
* client_euid
) const {
1164 return channel_impl_
->GetClientEuid(client_euid
);
1167 void Channel::ResetToAcceptingConnectionState() {
1168 channel_impl_
->ResetToAcceptingConnectionState();
1172 bool Channel::IsNamedServerInitialized(const std::string
& channel_id
) {
1173 return ChannelImpl::IsNamedServerInitialized(channel_id
);
1177 std::string
Channel::GenerateVerifiedChannelID(const std::string
& prefix
) {
1178 // A random name is sufficient validation on posix systems, so we don't need
1179 // an additional shared secret.
1181 std::string id
= prefix
;
1185 return id
.append(GenerateUniqueRandomChannelID());
1189 #if defined(OS_LINUX)
1191 void Channel::SetGlobalPid(int pid
) {
1192 ChannelImpl::SetGlobalPid(pid
);