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 output_queue_
.push(message
);
635 if (!is_blocked_on_write_
&& !waiting_connect_
) {
636 return ProcessOutgoingMessages();
642 int Channel::ChannelImpl::GetClientFileDescriptor() {
643 base::AutoLock
lock(client_pipe_lock_
);
647 int Channel::ChannelImpl::TakeClientFileDescriptor() {
648 base::AutoLock
lock(client_pipe_lock_
);
649 int fd
= client_pipe_
;
650 if (client_pipe_
!= -1) {
651 PipeMap::GetInstance()->Remove(pipe_name_
);
657 void Channel::ChannelImpl::CloseClientFileDescriptor() {
658 base::AutoLock
lock(client_pipe_lock_
);
659 if (client_pipe_
!= -1) {
660 PipeMap::GetInstance()->Remove(pipe_name_
);
661 if (HANDLE_EINTR(close(client_pipe_
)) < 0)
662 PLOG(ERROR
) << "close " << pipe_name_
;
667 bool Channel::ChannelImpl::AcceptsConnections() const {
668 return server_listen_pipe_
!= -1;
671 bool Channel::ChannelImpl::HasAcceptedConnection() const {
672 return AcceptsConnections() && pipe_
!= -1;
675 bool Channel::ChannelImpl::GetClientEuid(uid_t
* client_euid
) const {
676 DCHECK(HasAcceptedConnection());
677 #if defined(OS_MACOSX) || defined(OS_OPENBSD)
680 if (getpeereid(pipe_
, &peer_euid
, &peer_gid
) != 0) {
681 PLOG(ERROR
) << "getpeereid " << pipe_
;
684 *client_euid
= peer_euid
;
686 #elif defined(OS_SOLARIS)
690 socklen_t cred_len
= sizeof(cred
);
691 if (getsockopt(pipe_
, SOL_SOCKET
, SO_PEERCRED
, &cred
, &cred_len
) != 0) {
692 PLOG(ERROR
) << "getsockopt " << pipe_
;
695 if (static_cast<unsigned>(cred_len
) < sizeof(cred
)) {
696 NOTREACHED() << "Truncated ucred from SO_PEERCRED?";
699 *client_euid
= cred
.uid
;
704 void Channel::ChannelImpl::ResetToAcceptingConnectionState() {
705 // Unregister libevent for the unix domain socket and close it.
706 read_watcher_
.StopWatchingFileDescriptor();
707 write_watcher_
.StopWatchingFileDescriptor();
709 if (HANDLE_EINTR(close(pipe_
)) < 0)
710 PLOG(ERROR
) << "close pipe_ " << pipe_name_
;
713 #if defined(IPC_USES_READWRITE)
714 if (fd_pipe_
!= -1) {
715 if (HANDLE_EINTR(close(fd_pipe_
)) < 0)
716 PLOG(ERROR
) << "close fd_pipe_ " << pipe_name_
;
719 if (remote_fd_pipe_
!= -1) {
720 if (HANDLE_EINTR(close(remote_fd_pipe_
)) < 0)
721 PLOG(ERROR
) << "close remote_fd_pipe_ " << pipe_name_
;
722 remote_fd_pipe_
= -1;
724 #endif // IPC_USES_READWRITE
726 while (!output_queue_
.empty()) {
727 Message
* m
= output_queue_
.front();
732 // Close any outstanding, received file descriptors.
737 bool Channel::ChannelImpl::IsNamedServerInitialized(
738 const std::string
& channel_id
) {
739 return file_util::PathExists(FilePath(channel_id
));
742 #if defined(OS_LINUX)
744 void Channel::ChannelImpl::SetGlobalPid(int pid
) {
749 // Called by libevent when we can read from the pipe without blocking.
750 void Channel::ChannelImpl::OnFileCanReadWithoutBlocking(int fd
) {
751 bool send_server_hello_msg
= false;
752 if (fd
== server_listen_pipe_
) {
754 if (!ServerAcceptConnection(server_listen_pipe_
, &new_pipe
)) {
756 listener()->OnChannelListenError();
760 // We already have a connection. We only handle one at a time.
761 // close our new descriptor.
762 if (HANDLE_EINTR(shutdown(new_pipe
, SHUT_RDWR
)) < 0)
763 DPLOG(ERROR
) << "shutdown " << pipe_name_
;
764 if (HANDLE_EINTR(close(new_pipe
)) < 0)
765 DPLOG(ERROR
) << "close " << pipe_name_
;
766 listener()->OnChannelDenied();
771 if ((mode_
& MODE_OPEN_ACCESS_FLAG
) == 0) {
772 // Verify that the IPC channel peer is running as the same user.
774 if (!GetClientEuid(&client_euid
)) {
775 DLOG(ERROR
) << "Unable to query client euid";
776 ResetToAcceptingConnectionState();
779 if (client_euid
!= geteuid()) {
780 DLOG(WARNING
) << "Client euid is not authorised";
781 ResetToAcceptingConnectionState();
786 if (!AcceptConnection()) {
787 NOTREACHED() << "AcceptConnection should not fail on server";
789 send_server_hello_msg
= true;
790 waiting_connect_
= false;
791 } else if (fd
== pipe_
) {
792 if (waiting_connect_
&& (mode_
& MODE_SERVER_FLAG
)) {
793 send_server_hello_msg
= true;
794 waiting_connect_
= false;
796 if (!ProcessIncomingMessages()) {
797 // ClosePipeOnError may delete this object, so we mustn't call
798 // ProcessOutgoingMessages.
799 send_server_hello_msg
= false;
803 NOTREACHED() << "Unknown pipe " << fd
;
806 // If we're a server and handshaking, then we want to make sure that we
807 // only send our handshake message after we've processed the client's.
808 // This gives us a chance to kill the client if the incoming handshake
810 if (send_server_hello_msg
) {
811 ProcessOutgoingMessages();
815 // Called by libevent when we can write to the pipe without blocking.
816 void Channel::ChannelImpl::OnFileCanWriteWithoutBlocking(int fd
) {
817 DCHECK_EQ(pipe_
, fd
);
818 is_blocked_on_write_
= false;
819 if (!ProcessOutgoingMessages()) {
824 bool Channel::ChannelImpl::AcceptConnection() {
825 MessageLoopForIO::current()->WatchFileDescriptor(pipe_
,
827 MessageLoopForIO::WATCH_READ
,
832 if (mode_
& MODE_CLIENT_FLAG
) {
833 // If we are a client we want to send a hello message out immediately.
834 // In server mode we will send a hello message when we receive one from a
836 waiting_connect_
= false;
837 return ProcessOutgoingMessages();
838 } else if (mode_
& MODE_SERVER_FLAG
) {
839 waiting_connect_
= true;
847 void Channel::ChannelImpl::ClosePipeOnError() {
848 if (HasAcceptedConnection()) {
849 ResetToAcceptingConnectionState();
850 listener()->OnChannelError();
853 if (AcceptsConnections()) {
854 listener()->OnChannelListenError();
856 listener()->OnChannelError();
861 int Channel::ChannelImpl::GetHelloMessageProcId() {
862 int pid
= base::GetCurrentProcId();
863 #if defined(OS_LINUX)
864 // Our process may be in a sandbox with a separate PID namespace.
872 void Channel::ChannelImpl::QueueHelloMessage() {
873 // Create the Hello message
874 scoped_ptr
<Message
> msg(new Message(MSG_ROUTING_NONE
,
876 IPC::Message::PRIORITY_NORMAL
));
877 if (!msg
->WriteInt(GetHelloMessageProcId())) {
878 NOTREACHED() << "Unable to pickle hello message proc id";
880 #if defined(IPC_USES_READWRITE)
881 scoped_ptr
<Message
> hello
;
882 if (remote_fd_pipe_
!= -1) {
883 if (!msg
->WriteFileDescriptor(base::FileDescriptor(remote_fd_pipe_
,
885 NOTREACHED() << "Unable to pickle hello message file descriptors";
887 DCHECK_EQ(msg
->file_descriptor_set()->size(), 1U);
889 #endif // IPC_USES_READWRITE
890 output_queue_
.push(msg
.release());
893 Channel::ChannelImpl::ReadState
Channel::ChannelImpl::ReadData(
900 struct msghdr msg
= {0};
902 struct iovec iov
= {buffer
, static_cast<size_t>(buffer_len
)};
906 msg
.msg_control
= input_cmsg_buf_
;
908 // recvmsg() returns 0 if the connection has closed or EAGAIN if no data
909 // is waiting on the pipe.
910 #if defined(IPC_USES_READWRITE)
912 *bytes_read
= HANDLE_EINTR(read(pipe_
, buffer
, buffer_len
));
913 msg
.msg_controllen
= 0;
915 #endif // IPC_USES_READWRITE
917 msg
.msg_controllen
= sizeof(input_cmsg_buf_
);
918 *bytes_read
= HANDLE_EINTR(recvmsg(pipe_
, &msg
, MSG_DONTWAIT
));
920 if (*bytes_read
< 0) {
921 if (errno
== EAGAIN
) {
923 #if defined(OS_MACOSX)
924 } else if (errno
== EPERM
) {
925 // On OSX, reading from a pipe with no listener returns EPERM
926 // treat this as a special case to prevent spurious error messages
930 } else if (errno
== ECONNRESET
|| errno
== EPIPE
) {
933 PLOG(ERROR
) << "pipe error (" << pipe_
<< ")";
936 } else if (*bytes_read
== 0) {
937 // The pipe has closed...
942 CloseClientFileDescriptor();
944 // Read any file descriptors from the message.
945 if (!ExtractFileDescriptorsFromMsghdr(&msg
))
947 return READ_SUCCEEDED
;
950 #if defined(IPC_USES_READWRITE)
951 bool Channel::ChannelImpl::ReadFileDescriptorsFromFDPipe() {
953 struct iovec fd_pipe_iov
= { &dummy
, 1 };
955 struct msghdr msg
= { 0 };
956 msg
.msg_iov
= &fd_pipe_iov
;
958 msg
.msg_control
= input_cmsg_buf_
;
959 msg
.msg_controllen
= sizeof(input_cmsg_buf_
);
960 ssize_t bytes_received
= HANDLE_EINTR(recvmsg(fd_pipe_
, &msg
, MSG_DONTWAIT
));
962 if (bytes_received
!= 1)
963 return true; // No message waiting.
965 if (!ExtractFileDescriptorsFromMsghdr(&msg
))
971 // On Posix, we need to fix up the file descriptors before the input message
974 // This will read from the input_fds_ (READWRITE mode only) and read more
975 // handles from the FD pipe if necessary.
976 bool Channel::ChannelImpl::WillDispatchInputMessage(Message
* msg
) {
977 uint16 header_fds
= msg
->header()->num_fds
;
979 return true; // Nothing to do.
981 // The message has file descriptors.
982 const char* error
= NULL
;
983 if (header_fds
> input_fds_
.size()) {
984 // The message has been completely received, but we didn't get
985 // enough file descriptors.
986 #if defined(IPC_USES_READWRITE)
987 if (!ReadFileDescriptorsFromFDPipe())
989 if (header_fds
> input_fds_
.size())
990 #endif // IPC_USES_READWRITE
991 error
= "Message needs unreceived descriptors";
994 if (header_fds
> FileDescriptorSet::kMaxDescriptorsPerMessage
)
995 error
= "Message requires an excessive number of descriptors";
998 LOG(WARNING
) << error
999 << " channel:" << this
1000 << " message-type:" << msg
->type()
1001 << " header()->num_fds:" << header_fds
;
1002 #if defined(CHROMIUM_SELINUX)
1003 LOG(WARNING
) << "In the case of SELinux this can be caused when "
1004 "using a --user-data-dir to which the default "
1005 "policy doesn't give the renderer access to. ";
1006 #endif // CHROMIUM_SELINUX
1007 // Abort the connection.
1012 // The shenaniganery below with &foo.front() requires input_fds_ to have
1013 // contiguous underlying storage (such as a simple array or a std::vector).
1014 // This is why the header warns not to make input_fds_ a deque<>.
1015 msg
->file_descriptor_set()->SetDescriptors(&input_fds_
.front(),
1017 input_fds_
.erase(input_fds_
.begin(), input_fds_
.begin() + header_fds
);
1021 bool Channel::ChannelImpl::DidEmptyInputBuffers() {
1022 // When the input data buffer is empty, the fds should be too. If this is
1023 // not the case, we probably have a rogue renderer which is trying to fill
1024 // our descriptor table.
1025 return input_fds_
.empty();
1028 bool Channel::ChannelImpl::ExtractFileDescriptorsFromMsghdr(msghdr
* msg
) {
1029 // Check that there are any control messages. On OSX, CMSG_FIRSTHDR will
1030 // return an invalid non-NULL pointer in the case that controllen == 0.
1031 if (msg
->msg_controllen
== 0)
1034 for (cmsghdr
* cmsg
= CMSG_FIRSTHDR(msg
);
1036 cmsg
= CMSG_NXTHDR(msg
, cmsg
)) {
1037 if (cmsg
->cmsg_level
== SOL_SOCKET
&& cmsg
->cmsg_type
== SCM_RIGHTS
) {
1038 unsigned payload_len
= cmsg
->cmsg_len
- CMSG_LEN(0);
1039 DCHECK_EQ(0U, payload_len
% sizeof(int));
1040 const int* file_descriptors
= reinterpret_cast<int*>(CMSG_DATA(cmsg
));
1041 unsigned num_file_descriptors
= payload_len
/ 4;
1042 input_fds_
.insert(input_fds_
.end(),
1044 file_descriptors
+ num_file_descriptors
);
1046 // Check this after adding the FDs so we don't leak them.
1047 if (msg
->msg_flags
& MSG_CTRUNC
) {
1056 // No file descriptors found, but that's OK.
1060 void Channel::ChannelImpl::ClearInputFDs() {
1061 for (size_t i
= 0; i
< input_fds_
.size(); ++i
) {
1062 if (HANDLE_EINTR(close(input_fds_
[i
])) < 0)
1063 PLOG(ERROR
) << "close ";
1068 void Channel::ChannelImpl::HandleHelloMessage(const Message
& msg
) {
1069 // The Hello message contains only the process id.
1070 PickleIterator
iter(msg
);
1072 if (!msg
.ReadInt(&iter
, &pid
))
1075 #if defined(IPC_USES_READWRITE)
1076 if (mode_
& MODE_SERVER_FLAG
) {
1077 // With IPC_USES_READWRITE, the Hello message from the client to the
1078 // server also contains the fd_pipe_, which will be used for all
1079 // subsequent file descriptor passing.
1080 DCHECK_EQ(msg
.file_descriptor_set()->size(), 1U);
1081 base::FileDescriptor descriptor
;
1082 if (!msg
.ReadFileDescriptor(&iter
, &descriptor
)) {
1085 fd_pipe_
= descriptor
.fd
;
1086 CHECK(descriptor
.auto_close
);
1088 #endif // IPC_USES_READWRITE
1090 listener()->OnChannelConnected(pid
);
1093 void Channel::ChannelImpl::Close() {
1094 // Close can be called multiple time, so we need to make sure we're
1097 ResetToAcceptingConnectionState();
1100 unlink(pipe_name_
.c_str());
1101 must_unlink_
= false;
1103 if (server_listen_pipe_
!= -1) {
1104 if (HANDLE_EINTR(close(server_listen_pipe_
)) < 0)
1105 DPLOG(ERROR
) << "close " << server_listen_pipe_
;
1106 server_listen_pipe_
= -1;
1107 // Unregister libevent for the listening socket and close it.
1108 server_listen_connection_watcher_
.StopWatchingFileDescriptor();
1111 CloseClientFileDescriptor();
1114 //------------------------------------------------------------------------------
1115 // Channel's methods simply call through to ChannelImpl.
1116 Channel::Channel(const IPC::ChannelHandle
& channel_handle
, Mode mode
,
1118 : channel_impl_(new ChannelImpl(channel_handle
, mode
, listener
)) {
1121 Channel::~Channel() {
1122 delete channel_impl_
;
1125 bool Channel::Connect() {
1126 return channel_impl_
->Connect();
1129 void Channel::Close() {
1131 channel_impl_
->Close();
1134 void Channel::set_listener(Listener
* listener
) {
1135 channel_impl_
->set_listener(listener
);
1138 base::ProcessId
Channel::peer_pid() const {
1139 return channel_impl_
->peer_pid();
1142 bool Channel::Send(Message
* message
) {
1143 return channel_impl_
->Send(message
);
1146 int Channel::GetClientFileDescriptor() const {
1147 return channel_impl_
->GetClientFileDescriptor();
1150 int Channel::TakeClientFileDescriptor() {
1151 return channel_impl_
->TakeClientFileDescriptor();
1154 bool Channel::AcceptsConnections() const {
1155 return channel_impl_
->AcceptsConnections();
1158 bool Channel::HasAcceptedConnection() const {
1159 return channel_impl_
->HasAcceptedConnection();
1162 bool Channel::GetClientEuid(uid_t
* client_euid
) const {
1163 return channel_impl_
->GetClientEuid(client_euid
);
1166 void Channel::ResetToAcceptingConnectionState() {
1167 channel_impl_
->ResetToAcceptingConnectionState();
1171 bool Channel::IsNamedServerInitialized(const std::string
& channel_id
) {
1172 return ChannelImpl::IsNamedServerInitialized(channel_id
);
1176 std::string
Channel::GenerateVerifiedChannelID(const std::string
& prefix
) {
1177 // A random name is sufficient validation on posix systems, so we don't need
1178 // an additional shared secret.
1180 std::string id
= prefix
;
1184 return id
.append(GenerateUniqueRandomChannelID());
1188 #if defined(OS_LINUX)
1190 void Channel::SetGlobalPid(int pid
) {
1191 ChannelImpl::SetGlobalPid(pid
);