Clear preference when reset in gesture config UI
[chromium-blink-merge.git] / ipc / ipc_channel_posix.cc
blobd637232b8b4495054201ba79b77a4aea45f82f9f
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"
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <stddef.h>
10 #include <sys/socket.h>
11 #include <sys/stat.h>
12 #include <sys/types.h>
13 #include <sys/un.h>
14 #include <unistd.h>
16 #if defined(OS_OPENBSD)
17 #include <sys/uio.h>
18 #endif
20 #include <map>
21 #include <string>
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_util.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"
45 namespace IPC {
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 //------------------------------------------------------------------------------
62 namespace {
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
89 // this scheme.
91 class PipeMap {
92 public:
93 static PipeMap* GetInstance() {
94 return Singleton<PipeMap>::get();
97 ~PipeMap() {
98 // Shouldn't have left over pipes.
99 DCHECK(map_.empty());
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);
107 if (i == map_.end())
108 return -1;
109 return i->second;
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_);
123 DCHECK_NE(-1, fd);
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;
132 private:
133 base::Lock lock_;
134 typedef std::map<std::string, int> ChannelToFDMap;
135 ChannelToFDMap map_;
137 friend struct DefaultSingletonTraits<PipeMap>;
140 //------------------------------------------------------------------------------
142 bool SocketWriteErrorIsRecoverable() {
143 #if defined(OS_MACOSX)
144 // On OS X if sendmsg() is trying to send fds between processes and there
145 // isn't enough room in the output buffer to send the fd structure over
146 // atomically then EMSGSIZE is returned.
148 // EMSGSIZE presents a problem since the system APIs can only call us when
149 // there's room in the socket buffer and not when there is "enough" room.
151 // The current behavior is to return to the event loop when EMSGSIZE is
152 // received and hopefull service another FD. This is however still
153 // technically a busy wait since the event loop will call us right back until
154 // the receiver has read enough data to allow passing the FD over atomically.
155 return errno == EAGAIN || errno == EMSGSIZE;
156 #else
157 return errno == EAGAIN;
158 #endif // OS_MACOSX
161 } // namespace
162 //------------------------------------------------------------------------------
164 #if defined(OS_LINUX)
165 int Channel::ChannelImpl::global_pid_ = 0;
166 #endif // OS_LINUX
168 Channel::ChannelImpl::ChannelImpl(const IPC::ChannelHandle& channel_handle,
169 Mode mode, Listener* listener)
170 : ChannelReader(listener),
171 mode_(mode),
172 peer_pid_(base::kNullProcessId),
173 is_blocked_on_write_(false),
174 waiting_connect_(true),
175 message_send_bytes_written_(0),
176 server_listen_pipe_(-1),
177 pipe_(-1),
178 client_pipe_(-1),
179 #if defined(IPC_USES_READWRITE)
180 fd_pipe_(-1),
181 remote_fd_pipe_(-1),
182 #endif // IPC_USES_READWRITE
183 pipe_name_(channel_handle.name),
184 must_unlink_(false) {
185 memset(input_cmsg_buf_, 0, sizeof(input_cmsg_buf_));
186 if (!CreatePipe(channel_handle)) {
187 // The pipe may have been closed already.
188 const char *modestr = (mode_ & MODE_SERVER_FLAG) ? "server" : "client";
189 LOG(WARNING) << "Unable to create pipe named \"" << channel_handle.name
190 << "\" in " << modestr << " mode";
194 Channel::ChannelImpl::~ChannelImpl() {
195 Close();
198 bool SocketPair(int* fd1, int* fd2) {
199 int pipe_fds[2];
200 if (socketpair(AF_UNIX, SOCK_STREAM, 0, pipe_fds) != 0) {
201 PLOG(ERROR) << "socketpair()";
202 return false;
205 // Set both ends to be non-blocking.
206 if (fcntl(pipe_fds[0], F_SETFL, O_NONBLOCK) == -1 ||
207 fcntl(pipe_fds[1], F_SETFL, O_NONBLOCK) == -1) {
208 PLOG(ERROR) << "fcntl(O_NONBLOCK)";
209 if (HANDLE_EINTR(close(pipe_fds[0])) < 0)
210 PLOG(ERROR) << "close";
211 if (HANDLE_EINTR(close(pipe_fds[1])) < 0)
212 PLOG(ERROR) << "close";
213 return false;
216 *fd1 = pipe_fds[0];
217 *fd2 = pipe_fds[1];
219 return true;
222 bool Channel::ChannelImpl::CreatePipe(
223 const IPC::ChannelHandle& channel_handle) {
224 DCHECK(server_listen_pipe_ == -1 && pipe_ == -1);
226 // Four possible cases:
227 // 1) It's a channel wrapping a pipe that is given to us.
228 // 2) It's for a named channel, so we create it.
229 // 3) It's for a client that we implement ourself. This is used
230 // in unittesting.
231 // 4) It's the initial IPC channel:
232 // 4a) Client side: Pull the pipe out of the GlobalDescriptors set.
233 // 4b) Server side: create the pipe.
235 int local_pipe = -1;
236 if (channel_handle.socket.fd != -1) {
237 // Case 1 from comment above.
238 local_pipe = channel_handle.socket.fd;
239 #if defined(IPC_USES_READWRITE)
240 // Test the socket passed into us to make sure it is nonblocking.
241 // We don't want to call read/write on a blocking socket.
242 int value = fcntl(local_pipe, F_GETFL);
243 if (value == -1) {
244 PLOG(ERROR) << "fcntl(F_GETFL) " << pipe_name_;
245 return false;
247 if (!(value & O_NONBLOCK)) {
248 LOG(ERROR) << "Socket " << pipe_name_ << " must be O_NONBLOCK";
249 return false;
251 #endif // IPC_USES_READWRITE
252 } else if (mode_ & MODE_NAMED_FLAG) {
253 // Case 2 from comment above.
254 if (mode_ & MODE_SERVER_FLAG) {
255 if (!CreateServerUnixDomainSocket(base::FilePath(pipe_name_),
256 &local_pipe)) {
257 return false;
259 must_unlink_ = true;
260 } else if (mode_ & MODE_CLIENT_FLAG) {
261 if (!CreateClientUnixDomainSocket(base::FilePath(pipe_name_),
262 &local_pipe)) {
263 return false;
265 } else {
266 LOG(ERROR) << "Bad mode: " << mode_;
267 return false;
269 } else {
270 local_pipe = PipeMap::GetInstance()->Lookup(pipe_name_);
271 if (mode_ & MODE_CLIENT_FLAG) {
272 if (local_pipe != -1) {
273 // Case 3 from comment above.
274 // We only allow one connection.
275 local_pipe = HANDLE_EINTR(dup(local_pipe));
276 PipeMap::GetInstance()->Remove(pipe_name_);
277 } else {
278 // Case 4a from comment above.
279 // Guard against inappropriate reuse of the initial IPC channel. If
280 // an IPC channel closes and someone attempts to reuse it by name, the
281 // initial channel must not be recycled here. http://crbug.com/26754.
282 static bool used_initial_channel = false;
283 if (used_initial_channel) {
284 LOG(FATAL) << "Denying attempt to reuse initial IPC channel for "
285 << pipe_name_;
286 return false;
288 used_initial_channel = true;
290 local_pipe =
291 base::GlobalDescriptors::GetInstance()->Get(kPrimaryIPCChannel);
293 } else if (mode_ & MODE_SERVER_FLAG) {
294 // Case 4b from comment above.
295 if (local_pipe != -1) {
296 LOG(ERROR) << "Server already exists for " << pipe_name_;
297 return false;
299 base::AutoLock lock(client_pipe_lock_);
300 if (!SocketPair(&local_pipe, &client_pipe_))
301 return false;
302 PipeMap::GetInstance()->Insert(pipe_name_, client_pipe_);
303 } else {
304 LOG(ERROR) << "Bad mode: " << mode_;
305 return false;
309 #if defined(IPC_USES_READWRITE)
310 // Create a dedicated socketpair() for exchanging file descriptors.
311 // See comments for IPC_USES_READWRITE for details.
312 if (mode_ & MODE_CLIENT_FLAG) {
313 if (!SocketPair(&fd_pipe_, &remote_fd_pipe_)) {
314 return false;
317 #endif // IPC_USES_READWRITE
319 if ((mode_ & MODE_SERVER_FLAG) && (mode_ & MODE_NAMED_FLAG)) {
320 server_listen_pipe_ = local_pipe;
321 local_pipe = -1;
324 pipe_ = local_pipe;
325 return true;
328 bool Channel::ChannelImpl::Connect() {
329 if (server_listen_pipe_ == -1 && pipe_ == -1) {
330 DLOG(INFO) << "Channel creation failed: " << pipe_name_;
331 return false;
334 bool did_connect = true;
335 if (server_listen_pipe_ != -1) {
336 // Watch the pipe for connections, and turn any connections into
337 // active sockets.
338 base::MessageLoopForIO::current()->WatchFileDescriptor(
339 server_listen_pipe_,
340 true,
341 base::MessageLoopForIO::WATCH_READ,
342 &server_listen_connection_watcher_,
343 this);
344 } else {
345 did_connect = AcceptConnection();
347 return did_connect;
350 bool Channel::ChannelImpl::ProcessOutgoingMessages() {
351 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
352 // no connection?
353 if (output_queue_.empty())
354 return true;
356 if (pipe_ == -1)
357 return false;
359 // Write out all the messages we can till the write blocks or there are no
360 // more outgoing messages.
361 while (!output_queue_.empty()) {
362 Message* msg = output_queue_.front();
364 size_t amt_to_write = msg->size() - message_send_bytes_written_;
365 DCHECK_NE(0U, amt_to_write);
366 const char* out_bytes = reinterpret_cast<const char*>(msg->data()) +
367 message_send_bytes_written_;
369 struct msghdr msgh = {0};
370 struct iovec iov = {const_cast<char*>(out_bytes), amt_to_write};
371 msgh.msg_iov = &iov;
372 msgh.msg_iovlen = 1;
373 char buf[CMSG_SPACE(
374 sizeof(int) * FileDescriptorSet::kMaxDescriptorsPerMessage)];
376 ssize_t bytes_written = 1;
377 int fd_written = -1;
379 if (message_send_bytes_written_ == 0 &&
380 !msg->file_descriptor_set()->empty()) {
381 // This is the first chunk of a message which has descriptors to send
382 struct cmsghdr *cmsg;
383 const unsigned num_fds = msg->file_descriptor_set()->size();
385 DCHECK(num_fds <= FileDescriptorSet::kMaxDescriptorsPerMessage);
386 if (msg->file_descriptor_set()->ContainsDirectoryDescriptor()) {
387 LOG(FATAL) << "Panic: attempting to transport directory descriptor over"
388 " IPC. Aborting to maintain sandbox isolation.";
389 // If you have hit this then something tried to send a file descriptor
390 // to a directory over an IPC channel. Since IPC channels span
391 // sandboxes this is very bad: the receiving process can use openat
392 // with ".." elements in the path in order to reach the real
393 // filesystem.
396 msgh.msg_control = buf;
397 msgh.msg_controllen = CMSG_SPACE(sizeof(int) * num_fds);
398 cmsg = CMSG_FIRSTHDR(&msgh);
399 cmsg->cmsg_level = SOL_SOCKET;
400 cmsg->cmsg_type = SCM_RIGHTS;
401 cmsg->cmsg_len = CMSG_LEN(sizeof(int) * num_fds);
402 msg->file_descriptor_set()->GetDescriptors(
403 reinterpret_cast<int*>(CMSG_DATA(cmsg)));
404 msgh.msg_controllen = cmsg->cmsg_len;
406 // DCHECK_LE above already checks that
407 // num_fds < kMaxDescriptorsPerMessage so no danger of overflow.
408 msg->header()->num_fds = static_cast<uint16>(num_fds);
410 #if defined(IPC_USES_READWRITE)
411 if (!IsHelloMessage(*msg)) {
412 // Only the Hello message sends the file descriptor with the message.
413 // Subsequently, we can send file descriptors on the dedicated
414 // fd_pipe_ which makes Seccomp sandbox operation more efficient.
415 struct iovec fd_pipe_iov = { const_cast<char *>(""), 1 };
416 msgh.msg_iov = &fd_pipe_iov;
417 fd_written = fd_pipe_;
418 bytes_written = HANDLE_EINTR(sendmsg(fd_pipe_, &msgh, MSG_DONTWAIT));
419 msgh.msg_iov = &iov;
420 msgh.msg_controllen = 0;
421 if (bytes_written > 0) {
422 msg->file_descriptor_set()->CommitAll();
425 #endif // IPC_USES_READWRITE
428 if (bytes_written == 1) {
429 fd_written = pipe_;
430 #if defined(IPC_USES_READWRITE)
431 if ((mode_ & MODE_CLIENT_FLAG) && IsHelloMessage(*msg)) {
432 DCHECK_EQ(msg->file_descriptor_set()->size(), 1U);
434 if (!msgh.msg_controllen) {
435 bytes_written = HANDLE_EINTR(write(pipe_, out_bytes, amt_to_write));
436 } else
437 #endif // IPC_USES_READWRITE
439 bytes_written = HANDLE_EINTR(sendmsg(pipe_, &msgh, MSG_DONTWAIT));
442 if (bytes_written > 0)
443 msg->file_descriptor_set()->CommitAll();
445 if (bytes_written < 0 && !SocketWriteErrorIsRecoverable()) {
446 #if defined(OS_MACOSX)
447 // On OSX writing to a pipe with no listener returns EPERM.
448 if (errno == EPERM) {
449 Close();
450 return false;
452 #endif // OS_MACOSX
453 if (errno == EPIPE) {
454 Close();
455 return false;
457 PLOG(ERROR) << "pipe error on "
458 << fd_written
459 << " Currently writing message of size: "
460 << msg->size();
461 return false;
464 if (static_cast<size_t>(bytes_written) != amt_to_write) {
465 if (bytes_written > 0) {
466 // If write() fails with EAGAIN then bytes_written will be -1.
467 message_send_bytes_written_ += bytes_written;
470 // Tell libevent to call us back once things are unblocked.
471 is_blocked_on_write_ = true;
472 base::MessageLoopForIO::current()->WatchFileDescriptor(
473 pipe_,
474 false, // One shot
475 base::MessageLoopForIO::WATCH_WRITE,
476 &write_watcher_,
477 this);
478 return true;
479 } else {
480 message_send_bytes_written_ = 0;
482 // Message sent OK!
483 DVLOG(2) << "sent message @" << msg << " on channel @" << this
484 << " with type " << msg->type() << " on fd " << pipe_;
485 delete output_queue_.front();
486 output_queue_.pop();
489 return true;
492 bool Channel::ChannelImpl::Send(Message* message) {
493 DVLOG(2) << "sending message @" << message << " on channel @" << this
494 << " with type " << message->type()
495 << " (" << output_queue_.size() << " in queue)";
497 #ifdef IPC_MESSAGE_LOG_ENABLED
498 Logging::GetInstance()->OnSendMessage(message, "");
499 #endif // IPC_MESSAGE_LOG_ENABLED
501 message->TraceMessageBegin();
502 output_queue_.push(message);
503 if (!is_blocked_on_write_ && !waiting_connect_) {
504 return ProcessOutgoingMessages();
507 return true;
510 int Channel::ChannelImpl::GetClientFileDescriptor() {
511 base::AutoLock lock(client_pipe_lock_);
512 return client_pipe_;
515 int Channel::ChannelImpl::TakeClientFileDescriptor() {
516 base::AutoLock lock(client_pipe_lock_);
517 int fd = client_pipe_;
518 if (client_pipe_ != -1) {
519 PipeMap::GetInstance()->Remove(pipe_name_);
520 client_pipe_ = -1;
522 return fd;
525 void Channel::ChannelImpl::CloseClientFileDescriptor() {
526 base::AutoLock lock(client_pipe_lock_);
527 if (client_pipe_ != -1) {
528 PipeMap::GetInstance()->Remove(pipe_name_);
529 if (HANDLE_EINTR(close(client_pipe_)) < 0)
530 PLOG(ERROR) << "close " << pipe_name_;
531 client_pipe_ = -1;
535 bool Channel::ChannelImpl::AcceptsConnections() const {
536 return server_listen_pipe_ != -1;
539 bool Channel::ChannelImpl::HasAcceptedConnection() const {
540 return AcceptsConnections() && pipe_ != -1;
543 bool Channel::ChannelImpl::GetPeerEuid(uid_t* peer_euid) const {
544 DCHECK(!(mode_ & MODE_SERVER) || HasAcceptedConnection());
545 return IPC::GetPeerEuid(pipe_, peer_euid);
548 void Channel::ChannelImpl::ResetToAcceptingConnectionState() {
549 // Unregister libevent for the unix domain socket and close it.
550 read_watcher_.StopWatchingFileDescriptor();
551 write_watcher_.StopWatchingFileDescriptor();
552 if (pipe_ != -1) {
553 if (HANDLE_EINTR(close(pipe_)) < 0)
554 PLOG(ERROR) << "close pipe_ " << pipe_name_;
555 pipe_ = -1;
557 #if defined(IPC_USES_READWRITE)
558 if (fd_pipe_ != -1) {
559 if (HANDLE_EINTR(close(fd_pipe_)) < 0)
560 PLOG(ERROR) << "close fd_pipe_ " << pipe_name_;
561 fd_pipe_ = -1;
563 if (remote_fd_pipe_ != -1) {
564 if (HANDLE_EINTR(close(remote_fd_pipe_)) < 0)
565 PLOG(ERROR) << "close remote_fd_pipe_ " << pipe_name_;
566 remote_fd_pipe_ = -1;
568 #endif // IPC_USES_READWRITE
570 while (!output_queue_.empty()) {
571 Message* m = output_queue_.front();
572 output_queue_.pop();
573 delete m;
576 // Close any outstanding, received file descriptors.
577 ClearInputFDs();
580 // static
581 bool Channel::ChannelImpl::IsNamedServerInitialized(
582 const std::string& channel_id) {
583 return file_util::PathExists(base::FilePath(channel_id));
586 #if defined(OS_LINUX)
587 // static
588 void Channel::ChannelImpl::SetGlobalPid(int pid) {
589 global_pid_ = pid;
591 #endif // OS_LINUX
593 // Called by libevent when we can read from the pipe without blocking.
594 void Channel::ChannelImpl::OnFileCanReadWithoutBlocking(int fd) {
595 bool send_server_hello_msg = false;
596 if (fd == server_listen_pipe_) {
597 int new_pipe = 0;
598 if (!ServerAcceptConnection(server_listen_pipe_, &new_pipe) ||
599 new_pipe < 0) {
600 Close();
601 listener()->OnChannelListenError();
604 if (pipe_ != -1) {
605 // We already have a connection. We only handle one at a time.
606 // close our new descriptor.
607 if (HANDLE_EINTR(shutdown(new_pipe, SHUT_RDWR)) < 0)
608 DPLOG(ERROR) << "shutdown " << pipe_name_;
609 if (HANDLE_EINTR(close(new_pipe)) < 0)
610 DPLOG(ERROR) << "close " << pipe_name_;
611 listener()->OnChannelDenied();
612 return;
614 pipe_ = new_pipe;
616 if ((mode_ & MODE_OPEN_ACCESS_FLAG) == 0) {
617 // Verify that the IPC channel peer is running as the same user.
618 uid_t client_euid;
619 if (!GetPeerEuid(&client_euid)) {
620 DLOG(ERROR) << "Unable to query client euid";
621 ResetToAcceptingConnectionState();
622 return;
624 if (client_euid != geteuid()) {
625 DLOG(WARNING) << "Client euid is not authorised";
626 ResetToAcceptingConnectionState();
627 return;
631 if (!AcceptConnection()) {
632 NOTREACHED() << "AcceptConnection should not fail on server";
634 send_server_hello_msg = true;
635 waiting_connect_ = false;
636 } else if (fd == pipe_) {
637 if (waiting_connect_ && (mode_ & MODE_SERVER_FLAG)) {
638 send_server_hello_msg = true;
639 waiting_connect_ = false;
641 if (!ProcessIncomingMessages()) {
642 // ClosePipeOnError may delete this object, so we mustn't call
643 // ProcessOutgoingMessages.
644 send_server_hello_msg = false;
645 ClosePipeOnError();
647 } else {
648 NOTREACHED() << "Unknown pipe " << fd;
651 // If we're a server and handshaking, then we want to make sure that we
652 // only send our handshake message after we've processed the client's.
653 // This gives us a chance to kill the client if the incoming handshake
654 // is invalid.
655 if (send_server_hello_msg) {
656 ProcessOutgoingMessages();
660 // Called by libevent when we can write to the pipe without blocking.
661 void Channel::ChannelImpl::OnFileCanWriteWithoutBlocking(int fd) {
662 DCHECK_EQ(pipe_, fd);
663 is_blocked_on_write_ = false;
664 if (!ProcessOutgoingMessages()) {
665 ClosePipeOnError();
669 bool Channel::ChannelImpl::AcceptConnection() {
670 base::MessageLoopForIO::current()->WatchFileDescriptor(
671 pipe_, true, base::MessageLoopForIO::WATCH_READ, &read_watcher_, this);
672 QueueHelloMessage();
674 if (mode_ & MODE_CLIENT_FLAG) {
675 // If we are a client we want to send a hello message out immediately.
676 // In server mode we will send a hello message when we receive one from a
677 // client.
678 waiting_connect_ = false;
679 return ProcessOutgoingMessages();
680 } else if (mode_ & MODE_SERVER_FLAG) {
681 waiting_connect_ = true;
682 return true;
683 } else {
684 NOTREACHED();
685 return false;
689 void Channel::ChannelImpl::ClosePipeOnError() {
690 if (HasAcceptedConnection()) {
691 ResetToAcceptingConnectionState();
692 listener()->OnChannelError();
693 } else {
694 Close();
695 if (AcceptsConnections()) {
696 listener()->OnChannelListenError();
697 } else {
698 listener()->OnChannelError();
703 int Channel::ChannelImpl::GetHelloMessageProcId() {
704 int pid = base::GetCurrentProcId();
705 #if defined(OS_LINUX)
706 // Our process may be in a sandbox with a separate PID namespace.
707 if (global_pid_) {
708 pid = global_pid_;
710 #endif
711 return pid;
714 void Channel::ChannelImpl::QueueHelloMessage() {
715 // Create the Hello message
716 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
717 HELLO_MESSAGE_TYPE,
718 IPC::Message::PRIORITY_NORMAL));
719 if (!msg->WriteInt(GetHelloMessageProcId())) {
720 NOTREACHED() << "Unable to pickle hello message proc id";
722 #if defined(IPC_USES_READWRITE)
723 scoped_ptr<Message> hello;
724 if (remote_fd_pipe_ != -1) {
725 if (!msg->WriteFileDescriptor(base::FileDescriptor(remote_fd_pipe_,
726 false))) {
727 NOTREACHED() << "Unable to pickle hello message file descriptors";
729 DCHECK_EQ(msg->file_descriptor_set()->size(), 1U);
731 #endif // IPC_USES_READWRITE
732 output_queue_.push(msg.release());
735 Channel::ChannelImpl::ReadState Channel::ChannelImpl::ReadData(
736 char* buffer,
737 int buffer_len,
738 int* bytes_read) {
739 if (pipe_ == -1)
740 return READ_FAILED;
742 struct msghdr msg = {0};
744 struct iovec iov = {buffer, static_cast<size_t>(buffer_len)};
745 msg.msg_iov = &iov;
746 msg.msg_iovlen = 1;
748 msg.msg_control = input_cmsg_buf_;
750 // recvmsg() returns 0 if the connection has closed or EAGAIN if no data
751 // is waiting on the pipe.
752 #if defined(IPC_USES_READWRITE)
753 if (fd_pipe_ >= 0) {
754 *bytes_read = HANDLE_EINTR(read(pipe_, buffer, buffer_len));
755 msg.msg_controllen = 0;
756 } else
757 #endif // IPC_USES_READWRITE
759 msg.msg_controllen = sizeof(input_cmsg_buf_);
760 *bytes_read = HANDLE_EINTR(recvmsg(pipe_, &msg, MSG_DONTWAIT));
762 if (*bytes_read < 0) {
763 if (errno == EAGAIN) {
764 return READ_PENDING;
765 #if defined(OS_MACOSX)
766 } else if (errno == EPERM) {
767 // On OSX, reading from a pipe with no listener returns EPERM
768 // treat this as a special case to prevent spurious error messages
769 // to the console.
770 return READ_FAILED;
771 #endif // OS_MACOSX
772 } else if (errno == ECONNRESET || errno == EPIPE) {
773 return READ_FAILED;
774 } else {
775 PLOG(ERROR) << "pipe error (" << pipe_ << ")";
776 return READ_FAILED;
778 } else if (*bytes_read == 0) {
779 // The pipe has closed...
780 return READ_FAILED;
782 DCHECK(*bytes_read);
784 CloseClientFileDescriptor();
786 // Read any file descriptors from the message.
787 if (!ExtractFileDescriptorsFromMsghdr(&msg))
788 return READ_FAILED;
789 return READ_SUCCEEDED;
792 #if defined(IPC_USES_READWRITE)
793 bool Channel::ChannelImpl::ReadFileDescriptorsFromFDPipe() {
794 char dummy;
795 struct iovec fd_pipe_iov = { &dummy, 1 };
797 struct msghdr msg = { 0 };
798 msg.msg_iov = &fd_pipe_iov;
799 msg.msg_iovlen = 1;
800 msg.msg_control = input_cmsg_buf_;
801 msg.msg_controllen = sizeof(input_cmsg_buf_);
802 ssize_t bytes_received = HANDLE_EINTR(recvmsg(fd_pipe_, &msg, MSG_DONTWAIT));
804 if (bytes_received != 1)
805 return true; // No message waiting.
807 if (!ExtractFileDescriptorsFromMsghdr(&msg))
808 return false;
809 return true;
811 #endif
813 // On Posix, we need to fix up the file descriptors before the input message
814 // is dispatched.
816 // This will read from the input_fds_ (READWRITE mode only) and read more
817 // handles from the FD pipe if necessary.
818 bool Channel::ChannelImpl::WillDispatchInputMessage(Message* msg) {
819 uint16 header_fds = msg->header()->num_fds;
820 if (!header_fds)
821 return true; // Nothing to do.
823 // The message has file descriptors.
824 const char* error = NULL;
825 if (header_fds > input_fds_.size()) {
826 // The message has been completely received, but we didn't get
827 // enough file descriptors.
828 #if defined(IPC_USES_READWRITE)
829 if (!ReadFileDescriptorsFromFDPipe())
830 return false;
831 if (header_fds > input_fds_.size())
832 #endif // IPC_USES_READWRITE
833 error = "Message needs unreceived descriptors";
836 if (header_fds > FileDescriptorSet::kMaxDescriptorsPerMessage)
837 error = "Message requires an excessive number of descriptors";
839 if (error) {
840 LOG(WARNING) << error
841 << " channel:" << this
842 << " message-type:" << msg->type()
843 << " header()->num_fds:" << header_fds;
844 // Abort the connection.
845 ClearInputFDs();
846 return false;
849 // The shenaniganery below with &foo.front() requires input_fds_ to have
850 // contiguous underlying storage (such as a simple array or a std::vector).
851 // This is why the header warns not to make input_fds_ a deque<>.
852 msg->file_descriptor_set()->SetDescriptors(&input_fds_.front(),
853 header_fds);
854 input_fds_.erase(input_fds_.begin(), input_fds_.begin() + header_fds);
855 return true;
858 bool Channel::ChannelImpl::DidEmptyInputBuffers() {
859 // When the input data buffer is empty, the fds should be too. If this is
860 // not the case, we probably have a rogue renderer which is trying to fill
861 // our descriptor table.
862 return input_fds_.empty();
865 bool Channel::ChannelImpl::ExtractFileDescriptorsFromMsghdr(msghdr* msg) {
866 // Check that there are any control messages. On OSX, CMSG_FIRSTHDR will
867 // return an invalid non-NULL pointer in the case that controllen == 0.
868 if (msg->msg_controllen == 0)
869 return true;
871 for (cmsghdr* cmsg = CMSG_FIRSTHDR(msg);
872 cmsg;
873 cmsg = CMSG_NXTHDR(msg, cmsg)) {
874 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
875 unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0);
876 DCHECK_EQ(0U, payload_len % sizeof(int));
877 const int* file_descriptors = reinterpret_cast<int*>(CMSG_DATA(cmsg));
878 unsigned num_file_descriptors = payload_len / 4;
879 input_fds_.insert(input_fds_.end(),
880 file_descriptors,
881 file_descriptors + num_file_descriptors);
883 // Check this after adding the FDs so we don't leak them.
884 if (msg->msg_flags & MSG_CTRUNC) {
885 ClearInputFDs();
886 return false;
889 return true;
893 // No file descriptors found, but that's OK.
894 return true;
897 void Channel::ChannelImpl::ClearInputFDs() {
898 for (size_t i = 0; i < input_fds_.size(); ++i) {
899 if (HANDLE_EINTR(close(input_fds_[i])) < 0)
900 PLOG(ERROR) << "close ";
902 input_fds_.clear();
905 void Channel::ChannelImpl::HandleHelloMessage(const Message& msg) {
906 // The Hello message contains only the process id.
907 PickleIterator iter(msg);
908 int pid;
909 if (!msg.ReadInt(&iter, &pid))
910 NOTREACHED();
912 #if defined(IPC_USES_READWRITE)
913 if (mode_ & MODE_SERVER_FLAG) {
914 // With IPC_USES_READWRITE, the Hello message from the client to the
915 // server also contains the fd_pipe_, which will be used for all
916 // subsequent file descriptor passing.
917 DCHECK_EQ(msg.file_descriptor_set()->size(), 1U);
918 base::FileDescriptor descriptor;
919 if (!msg.ReadFileDescriptor(&iter, &descriptor)) {
920 NOTREACHED();
922 fd_pipe_ = descriptor.fd;
923 CHECK(descriptor.auto_close);
925 #endif // IPC_USES_READWRITE
926 peer_pid_ = pid;
927 listener()->OnChannelConnected(pid);
930 void Channel::ChannelImpl::Close() {
931 // Close can be called multiple time, so we need to make sure we're
932 // idempotent.
934 ResetToAcceptingConnectionState();
936 if (must_unlink_) {
937 unlink(pipe_name_.c_str());
938 must_unlink_ = false;
940 if (server_listen_pipe_ != -1) {
941 if (HANDLE_EINTR(close(server_listen_pipe_)) < 0)
942 DPLOG(ERROR) << "close " << server_listen_pipe_;
943 server_listen_pipe_ = -1;
944 // Unregister libevent for the listening socket and close it.
945 server_listen_connection_watcher_.StopWatchingFileDescriptor();
948 CloseClientFileDescriptor();
951 //------------------------------------------------------------------------------
952 // Channel's methods simply call through to ChannelImpl.
953 Channel::Channel(const IPC::ChannelHandle& channel_handle, Mode mode,
954 Listener* listener)
955 : channel_impl_(new ChannelImpl(channel_handle, mode, listener)) {
958 Channel::~Channel() {
959 delete channel_impl_;
962 bool Channel::Connect() {
963 return channel_impl_->Connect();
966 void Channel::Close() {
967 if (channel_impl_)
968 channel_impl_->Close();
971 base::ProcessId Channel::peer_pid() const {
972 return channel_impl_->peer_pid();
975 bool Channel::Send(Message* message) {
976 return channel_impl_->Send(message);
979 int Channel::GetClientFileDescriptor() const {
980 return channel_impl_->GetClientFileDescriptor();
983 int Channel::TakeClientFileDescriptor() {
984 return channel_impl_->TakeClientFileDescriptor();
987 bool Channel::AcceptsConnections() const {
988 return channel_impl_->AcceptsConnections();
991 bool Channel::HasAcceptedConnection() const {
992 return channel_impl_->HasAcceptedConnection();
995 bool Channel::GetPeerEuid(uid_t* peer_euid) const {
996 return channel_impl_->GetPeerEuid(peer_euid);
999 void Channel::ResetToAcceptingConnectionState() {
1000 channel_impl_->ResetToAcceptingConnectionState();
1003 // static
1004 bool Channel::IsNamedServerInitialized(const std::string& channel_id) {
1005 return ChannelImpl::IsNamedServerInitialized(channel_id);
1008 // static
1009 std::string Channel::GenerateVerifiedChannelID(const std::string& prefix) {
1010 // A random name is sufficient validation on posix systems, so we don't need
1011 // an additional shared secret.
1013 std::string id = prefix;
1014 if (!id.empty())
1015 id.append(".");
1017 return id.append(GenerateUniqueRandomChannelID());
1021 #if defined(OS_LINUX)
1022 // static
1023 void Channel::SetGlobalPid(int pid) {
1024 ChannelImpl::SetGlobalPid(pid);
1026 #endif // OS_LINUX
1028 } // namespace IPC