Fix WebsitePreference::compareTo.
[chromium-blink-merge.git] / ipc / ipc_channel_posix.cc
blob6ba1f607b3d000b0619b8d77b994ce646c205007
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 <unistd.h>
15 #if defined(OS_OPENBSD)
16 #include <sys/uio.h>
17 #endif
19 #if !defined(OS_NACL_NONSFI)
20 #include <sys/un.h>
21 #endif
23 #include <map>
24 #include <string>
26 #include "base/command_line.h"
27 #include "base/files/file_path.h"
28 #include "base/files/file_util.h"
29 #include "base/location.h"
30 #include "base/logging.h"
31 #include "base/memory/scoped_ptr.h"
32 #include "base/memory/singleton.h"
33 #include "base/posix/eintr_wrapper.h"
34 #include "base/posix/global_descriptors.h"
35 #include "base/process/process_handle.h"
36 #include "base/rand_util.h"
37 #include "base/stl_util.h"
38 #include "base/strings/string_util.h"
39 #include "base/synchronization/lock.h"
40 #include "ipc/ipc_descriptors.h"
41 #include "ipc/ipc_listener.h"
42 #include "ipc/ipc_logging.h"
43 #include "ipc/ipc_message_attachment_set.h"
44 #include "ipc/ipc_message_utils.h"
45 #include "ipc/ipc_platform_file_attachment_posix.h"
46 #include "ipc/ipc_switches.h"
47 #include "ipc/unix_domain_socket_util.h"
49 namespace IPC {
51 // IPC channels on Windows use named pipes (CreateNamedPipe()) with
52 // channel ids as the pipe names. Channels on POSIX use sockets as
53 // pipes These don't quite line up.
55 // When creating a child subprocess we use a socket pair and the parent side of
56 // the fork arranges it such that the initial control channel ends up on the
57 // magic file descriptor kPrimaryIPCChannel in the child. Future
58 // connections (file descriptors) can then be passed via that
59 // connection via sendmsg().
61 // A POSIX IPC channel can also be set up as a server for a bound UNIX domain
62 // socket, and will handle multiple connect and disconnect sequences. Currently
63 // it is limited to one connection at a time.
65 //------------------------------------------------------------------------------
66 namespace {
68 // The PipeMap class works around this quirk related to unit tests:
70 // When running as a server, we install the client socket in a
71 // specific file descriptor number (@kPrimaryIPCChannel). However, we
72 // also have to support the case where we are running unittests in the
73 // same process. (We do not support forking without execing.)
75 // Case 1: normal running
76 // The IPC server object will install a mapping in PipeMap from the
77 // name which it was given to the client pipe. When forking the client, the
78 // GetClientFileDescriptorMapping will ensure that the socket is installed in
79 // the magic slot (@kPrimaryIPCChannel). The client will search for the
80 // mapping, but it won't find any since we are in a new process. Thus the
81 // magic fd number is returned. Once the client connects, the server will
82 // close its copy of the client socket and remove the mapping.
84 // Case 2: unittests - client and server in the same process
85 // The IPC server will install a mapping as before. The client will search
86 // for a mapping and find out. It duplicates the file descriptor and
87 // connects. Once the client connects, the server will close the original
88 // copy of the client socket and remove the mapping. Thus, when the client
89 // object closes, it will close the only remaining copy of the client socket
90 // in the fd table and the server will see EOF on its side.
92 // TODO(port): a client process cannot connect to multiple IPC channels with
93 // this scheme.
95 class PipeMap {
96 public:
97 static PipeMap* GetInstance() {
98 return Singleton<PipeMap>::get();
101 ~PipeMap() {
102 // Shouldn't have left over pipes.
103 DCHECK(map_.empty());
106 // Lookup a given channel id. Return -1 if not found.
107 int Lookup(const std::string& channel_id) {
108 base::AutoLock locked(lock_);
110 ChannelToFDMap::const_iterator i = map_.find(channel_id);
111 if (i == map_.end())
112 return -1;
113 return i->second;
116 // Remove the mapping for the given channel id. No error is signaled if the
117 // channel_id doesn't exist
118 void Remove(const std::string& channel_id) {
119 base::AutoLock locked(lock_);
120 map_.erase(channel_id);
123 // Insert a mapping from @channel_id to @fd. It's a fatal error to insert a
124 // mapping if one already exists for the given channel_id
125 void Insert(const std::string& channel_id, int fd) {
126 base::AutoLock locked(lock_);
127 DCHECK_NE(-1, fd);
129 ChannelToFDMap::const_iterator i = map_.find(channel_id);
130 CHECK(i == map_.end()) << "Creating second IPC server (fd " << fd << ") "
131 << "for '" << channel_id << "' while first "
132 << "(fd " << i->second << ") still exists";
133 map_[channel_id] = fd;
136 private:
137 base::Lock lock_;
138 typedef std::map<std::string, int> ChannelToFDMap;
139 ChannelToFDMap map_;
141 friend struct DefaultSingletonTraits<PipeMap>;
142 #if defined(OS_ANDROID)
143 friend void ::IPC::Channel::NotifyProcessForkedForTesting();
144 #endif
147 //------------------------------------------------------------------------------
149 bool SocketWriteErrorIsRecoverable() {
150 #if defined(OS_MACOSX)
151 // On OS X if sendmsg() is trying to send fds between processes and there
152 // isn't enough room in the output buffer to send the fd structure over
153 // atomically then EMSGSIZE is returned.
155 // EMSGSIZE presents a problem since the system APIs can only call us when
156 // there's room in the socket buffer and not when there is "enough" room.
158 // The current behavior is to return to the event loop when EMSGSIZE is
159 // received and hopefull service another FD. This is however still
160 // technically a busy wait since the event loop will call us right back until
161 // the receiver has read enough data to allow passing the FD over atomically.
162 return errno == EAGAIN || errno == EMSGSIZE;
163 #else
164 return errno == EAGAIN;
165 #endif // OS_MACOSX
168 } // namespace
170 #if defined(OS_ANDROID)
171 // When we fork for simple tests on Android, we can't 'exec', so we need to
172 // reset these entries manually to get the expected testing behavior.
173 void Channel::NotifyProcessForkedForTesting() {
174 PipeMap::GetInstance()->map_.clear();
176 #endif
178 //------------------------------------------------------------------------------
180 #if defined(OS_LINUX)
181 int ChannelPosix::global_pid_ = 0;
182 #endif // OS_LINUX
184 ChannelPosix::ChannelPosix(const IPC::ChannelHandle& channel_handle,
185 Mode mode, Listener* listener)
186 : ChannelReader(listener),
187 mode_(mode),
188 peer_pid_(base::kNullProcessId),
189 is_blocked_on_write_(false),
190 waiting_connect_(true),
191 message_send_bytes_written_(0),
192 pipe_name_(channel_handle.name),
193 in_dtor_(false),
194 must_unlink_(false) {
195 memset(input_cmsg_buf_, 0, sizeof(input_cmsg_buf_));
196 if (!CreatePipe(channel_handle)) {
197 // The pipe may have been closed already.
198 const char *modestr = (mode_ & MODE_SERVER_FLAG) ? "server" : "client";
199 LOG(WARNING) << "Unable to create pipe named \"" << channel_handle.name
200 << "\" in " << modestr << " mode";
204 ChannelPosix::~ChannelPosix() {
205 in_dtor_ = true;
206 Close();
209 bool SocketPair(int* fd1, int* fd2) {
210 int pipe_fds[2];
211 if (socketpair(AF_UNIX, SOCK_STREAM, 0, pipe_fds) != 0) {
212 PLOG(ERROR) << "socketpair()";
213 return false;
216 // Set both ends to be non-blocking.
217 if (fcntl(pipe_fds[0], F_SETFL, O_NONBLOCK) == -1 ||
218 fcntl(pipe_fds[1], F_SETFL, O_NONBLOCK) == -1) {
219 PLOG(ERROR) << "fcntl(O_NONBLOCK)";
220 if (IGNORE_EINTR(close(pipe_fds[0])) < 0)
221 PLOG(ERROR) << "close";
222 if (IGNORE_EINTR(close(pipe_fds[1])) < 0)
223 PLOG(ERROR) << "close";
224 return false;
227 *fd1 = pipe_fds[0];
228 *fd2 = pipe_fds[1];
230 return true;
233 bool ChannelPosix::CreatePipe(
234 const IPC::ChannelHandle& channel_handle) {
235 DCHECK(!server_listen_pipe_.is_valid() && !pipe_.is_valid());
237 // Four possible cases:
238 // 1) It's a channel wrapping a pipe that is given to us.
239 // 2) It's for a named channel, so we create it.
240 // 3) It's for a client that we implement ourself. This is used
241 // in single-process unittesting.
242 // 4) It's the initial IPC channel:
243 // 4a) Client side: Pull the pipe out of the GlobalDescriptors set.
244 // 4b) Server side: create the pipe.
246 base::ScopedFD local_pipe;
247 if (channel_handle.socket.fd != -1) {
248 // Case 1 from comment above.
249 local_pipe.reset(channel_handle.socket.fd);
250 #if defined(IPC_USES_READWRITE)
251 // Test the socket passed into us to make sure it is nonblocking.
252 // We don't want to call read/write on a blocking socket.
253 int value = fcntl(local_pipe.get(), F_GETFL);
254 if (value == -1) {
255 PLOG(ERROR) << "fcntl(F_GETFL) " << pipe_name_;
256 return false;
258 if (!(value & O_NONBLOCK)) {
259 LOG(ERROR) << "Socket " << pipe_name_ << " must be O_NONBLOCK";
260 return false;
262 #endif // IPC_USES_READWRITE
263 } else if (mode_ & MODE_NAMED_FLAG) {
264 #if defined(OS_NACL_NONSFI)
265 LOG(FATAL)
266 << "IPC channels in nacl_helper_nonsfi should not be in NAMED mode.";
267 #else
268 // Case 2 from comment above.
269 int local_pipe_fd = -1;
271 if (mode_ & MODE_SERVER_FLAG) {
272 if (!CreateServerUnixDomainSocket(base::FilePath(pipe_name_),
273 &local_pipe_fd)) {
274 return false;
277 must_unlink_ = true;
278 } else if (mode_ & MODE_CLIENT_FLAG) {
279 if (!CreateClientUnixDomainSocket(base::FilePath(pipe_name_),
280 &local_pipe_fd)) {
281 return false;
283 } else {
284 LOG(ERROR) << "Bad mode: " << mode_;
285 return false;
288 local_pipe.reset(local_pipe_fd);
289 #endif // !defined(OS_NACL_NONSFI)
290 } else {
291 local_pipe.reset(PipeMap::GetInstance()->Lookup(pipe_name_));
292 if (mode_ & MODE_CLIENT_FLAG) {
293 if (local_pipe.is_valid()) {
294 // Case 3 from comment above.
295 // We only allow one connection.
296 local_pipe.reset(HANDLE_EINTR(dup(local_pipe.release())));
297 PipeMap::GetInstance()->Remove(pipe_name_);
298 } else {
299 // Case 4a from comment above.
300 // Guard against inappropriate reuse of the initial IPC channel. If
301 // an IPC channel closes and someone attempts to reuse it by name, the
302 // initial channel must not be recycled here. http://crbug.com/26754.
303 static bool used_initial_channel = false;
304 if (used_initial_channel) {
305 LOG(FATAL) << "Denying attempt to reuse initial IPC channel for "
306 << pipe_name_;
307 return false;
309 used_initial_channel = true;
311 local_pipe.reset(
312 base::GlobalDescriptors::GetInstance()->Get(kPrimaryIPCChannel));
314 } else if (mode_ & MODE_SERVER_FLAG) {
315 // Case 4b from comment above.
316 if (local_pipe.is_valid()) {
317 LOG(ERROR) << "Server already exists for " << pipe_name_;
318 // This is a client side pipe registered by other server and
319 // shouldn't be closed.
320 ignore_result(local_pipe.release());
321 return false;
323 base::AutoLock lock(client_pipe_lock_);
324 int local_pipe_fd = -1, client_pipe_fd = -1;
325 if (!SocketPair(&local_pipe_fd, &client_pipe_fd))
326 return false;
327 local_pipe.reset(local_pipe_fd);
328 client_pipe_.reset(client_pipe_fd);
329 PipeMap::GetInstance()->Insert(pipe_name_, client_pipe_fd);
330 } else {
331 LOG(ERROR) << "Bad mode: " << mode_;
332 return false;
336 #if defined(IPC_USES_READWRITE)
337 // Create a dedicated socketpair() for exchanging file descriptors.
338 // See comments for IPC_USES_READWRITE for details.
339 if (mode_ & MODE_CLIENT_FLAG) {
340 int fd_pipe_fd = 1, remote_fd_pipe_fd = -1;
341 if (!SocketPair(&fd_pipe_fd, &remote_fd_pipe_fd)) {
342 return false;
345 fd_pipe_.reset(fd_pipe_fd);
346 remote_fd_pipe_.reset(remote_fd_pipe_fd);
348 #endif // IPC_USES_READWRITE
350 if ((mode_ & MODE_SERVER_FLAG) && (mode_ & MODE_NAMED_FLAG)) {
351 #if defined(OS_NACL_NONSFI)
352 LOG(FATAL) << "IPC channels in nacl_helper_nonsfi "
353 << "should not be in NAMED or SERVER mode.";
354 #else
355 server_listen_pipe_.reset(local_pipe.release());
356 #endif
357 } else {
358 pipe_.reset(local_pipe.release());
360 return true;
363 bool ChannelPosix::Connect() {
364 if (!server_listen_pipe_.is_valid() && !pipe_.is_valid()) {
365 DLOG(WARNING) << "Channel creation failed: " << pipe_name_;
366 return false;
369 bool did_connect = true;
370 if (server_listen_pipe_.is_valid()) {
371 #if defined(OS_NACL_NONSFI)
372 LOG(FATAL) << "IPC channels in nacl_helper_nonsfi "
373 << "should always be in client mode.";
374 #else
375 // Watch the pipe for connections, and turn any connections into
376 // active sockets.
377 base::MessageLoopForIO::current()->WatchFileDescriptor(
378 server_listen_pipe_.get(),
379 true,
380 base::MessageLoopForIO::WATCH_READ,
381 &server_listen_connection_watcher_,
382 this);
383 #endif
384 } else {
385 did_connect = AcceptConnection();
387 return did_connect;
390 void ChannelPosix::CloseFileDescriptors(Message* msg) {
391 #if defined(OS_MACOSX)
392 // There is a bug on OSX which makes it dangerous to close
393 // a file descriptor while it is in transit. So instead we
394 // store the file descriptor in a set and send a message to
395 // the recipient, which is queued AFTER the message that
396 // sent the FD. The recipient will reply to the message,
397 // letting us know that it is now safe to close the file
398 // descriptor. For more information, see:
399 // http://crbug.com/298276
400 std::vector<int> to_close;
401 msg->attachment_set()->ReleaseFDsToClose(&to_close);
402 for (size_t i = 0; i < to_close.size(); i++) {
403 fds_to_close_.insert(to_close[i]);
404 QueueCloseFDMessage(to_close[i], 2);
406 #else
407 msg->attachment_set()->CommitAll();
408 #endif
411 bool ChannelPosix::ProcessOutgoingMessages() {
412 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
413 // no connection?
414 if (output_queue_.empty())
415 return true;
417 if (!pipe_.is_valid())
418 return false;
420 // Write out all the messages we can till the write blocks or there are no
421 // more outgoing messages.
422 while (!output_queue_.empty()) {
423 Message* msg = output_queue_.front();
425 size_t amt_to_write = msg->size() - message_send_bytes_written_;
426 DCHECK_NE(0U, amt_to_write);
427 const char* out_bytes = reinterpret_cast<const char*>(msg->data()) +
428 message_send_bytes_written_;
430 struct msghdr msgh = {0};
431 struct iovec iov = {const_cast<char*>(out_bytes), amt_to_write};
432 msgh.msg_iov = &iov;
433 msgh.msg_iovlen = 1;
434 char buf[CMSG_SPACE(sizeof(int) *
435 MessageAttachmentSet::kMaxDescriptorsPerMessage)];
437 ssize_t bytes_written = 1;
438 int fd_written = -1;
440 if (message_send_bytes_written_ == 0 && !msg->attachment_set()->empty()) {
441 // This is the first chunk of a message which has descriptors to send
442 struct cmsghdr *cmsg;
443 const unsigned num_fds = msg->attachment_set()->size();
445 DCHECK(num_fds <= MessageAttachmentSet::kMaxDescriptorsPerMessage);
446 if (msg->attachment_set()->ContainsDirectoryDescriptor()) {
447 LOG(FATAL) << "Panic: attempting to transport directory descriptor over"
448 " IPC. Aborting to maintain sandbox isolation.";
449 // If you have hit this then something tried to send a file descriptor
450 // to a directory over an IPC channel. Since IPC channels span
451 // sandboxes this is very bad: the receiving process can use openat
452 // with ".." elements in the path in order to reach the real
453 // filesystem.
456 msgh.msg_control = buf;
457 msgh.msg_controllen = CMSG_SPACE(sizeof(int) * num_fds);
458 cmsg = CMSG_FIRSTHDR(&msgh);
459 cmsg->cmsg_level = SOL_SOCKET;
460 cmsg->cmsg_type = SCM_RIGHTS;
461 cmsg->cmsg_len = CMSG_LEN(sizeof(int) * num_fds);
462 msg->attachment_set()->PeekDescriptors(
463 reinterpret_cast<int*>(CMSG_DATA(cmsg)));
464 msgh.msg_controllen = cmsg->cmsg_len;
466 // DCHECK_LE above already checks that
467 // num_fds < kMaxDescriptorsPerMessage so no danger of overflow.
468 msg->header()->num_fds = static_cast<uint16>(num_fds);
470 #if defined(IPC_USES_READWRITE)
471 if (!IsHelloMessage(*msg)) {
472 // Only the Hello message sends the file descriptor with the message.
473 // Subsequently, we can send file descriptors on the dedicated
474 // fd_pipe_ which makes Seccomp sandbox operation more efficient.
475 struct iovec fd_pipe_iov = { const_cast<char *>(""), 1 };
476 msgh.msg_iov = &fd_pipe_iov;
477 fd_written = fd_pipe_.get();
478 bytes_written =
479 HANDLE_EINTR(sendmsg(fd_pipe_.get(), &msgh, MSG_DONTWAIT));
480 msgh.msg_iov = &iov;
481 msgh.msg_controllen = 0;
482 if (bytes_written > 0) {
483 CloseFileDescriptors(msg);
486 #endif // IPC_USES_READWRITE
489 if (bytes_written == 1) {
490 fd_written = pipe_.get();
491 #if defined(IPC_USES_READWRITE)
492 if ((mode_ & MODE_CLIENT_FLAG) && IsHelloMessage(*msg)) {
493 DCHECK_EQ(msg->attachment_set()->size(), 1U);
495 if (!msgh.msg_controllen) {
496 bytes_written =
497 HANDLE_EINTR(write(pipe_.get(), out_bytes, amt_to_write));
498 } else
499 #endif // IPC_USES_READWRITE
501 bytes_written = HANDLE_EINTR(sendmsg(pipe_.get(), &msgh, MSG_DONTWAIT));
504 if (bytes_written > 0)
505 CloseFileDescriptors(msg);
507 if (bytes_written < 0 && !SocketWriteErrorIsRecoverable()) {
508 // We can't close the pipe here, because calling OnChannelError
509 // may destroy this object, and that would be bad if we are
510 // called from Send(). Instead, we return false and hope the
511 // caller will close the pipe. If they do not, the pipe will
512 // still be closed next time OnFileCanReadWithoutBlocking is
513 // called.
514 #if defined(OS_MACOSX)
515 // On OSX writing to a pipe with no listener returns EPERM.
516 if (errno == EPERM) {
517 return false;
519 #endif // OS_MACOSX
520 if (errno == EPIPE) {
521 return false;
523 PLOG(ERROR) << "pipe error on "
524 << fd_written
525 << " Currently writing message of size: "
526 << msg->size();
527 return false;
530 if (static_cast<size_t>(bytes_written) != amt_to_write) {
531 if (bytes_written > 0) {
532 // If write() fails with EAGAIN then bytes_written will be -1.
533 message_send_bytes_written_ += bytes_written;
536 // Tell libevent to call us back once things are unblocked.
537 is_blocked_on_write_ = true;
538 base::MessageLoopForIO::current()->WatchFileDescriptor(
539 pipe_.get(),
540 false, // One shot
541 base::MessageLoopForIO::WATCH_WRITE,
542 &write_watcher_,
543 this);
544 return true;
545 } else {
546 message_send_bytes_written_ = 0;
548 // Message sent OK!
549 DVLOG(2) << "sent message @" << msg << " on channel @" << this
550 << " with type " << msg->type() << " on fd " << pipe_.get();
551 delete output_queue_.front();
552 output_queue_.pop();
555 return true;
558 bool ChannelPosix::Send(Message* message) {
559 DVLOG(2) << "sending message @" << message << " on channel @" << this
560 << " with type " << message->type()
561 << " (" << output_queue_.size() << " in queue)";
563 #ifdef IPC_MESSAGE_LOG_ENABLED
564 Logging::GetInstance()->OnSendMessage(message, "");
565 #endif // IPC_MESSAGE_LOG_ENABLED
567 message->TraceMessageBegin();
568 output_queue_.push(message);
569 if (!is_blocked_on_write_ && !waiting_connect_) {
570 return ProcessOutgoingMessages();
573 return true;
576 int ChannelPosix::GetClientFileDescriptor() const {
577 base::AutoLock lock(client_pipe_lock_);
578 return client_pipe_.get();
581 base::ScopedFD ChannelPosix::TakeClientFileDescriptor() {
582 base::AutoLock lock(client_pipe_lock_);
583 if (!client_pipe_.is_valid())
584 return base::ScopedFD();
585 PipeMap::GetInstance()->Remove(pipe_name_);
586 return client_pipe_.Pass();
589 void ChannelPosix::CloseClientFileDescriptor() {
590 base::AutoLock lock(client_pipe_lock_);
591 if (!client_pipe_.is_valid())
592 return;
593 PipeMap::GetInstance()->Remove(pipe_name_);
594 client_pipe_.reset();
597 bool ChannelPosix::AcceptsConnections() const {
598 return server_listen_pipe_.is_valid();
601 bool ChannelPosix::HasAcceptedConnection() const {
602 return AcceptsConnections() && pipe_.is_valid();
605 #if !defined(OS_NACL_NONSFI)
606 // GetPeerEuid is not supported in nacl_helper_nonsfi.
607 bool ChannelPosix::GetPeerEuid(uid_t* peer_euid) const {
608 DCHECK(!(mode_ & MODE_SERVER) || HasAcceptedConnection());
609 return IPC::GetPeerEuid(pipe_.get(), peer_euid);
611 #endif
613 void ChannelPosix::ResetToAcceptingConnectionState() {
614 // Unregister libevent for the unix domain socket and close it.
615 read_watcher_.StopWatchingFileDescriptor();
616 write_watcher_.StopWatchingFileDescriptor();
617 ResetSafely(&pipe_);
618 #if defined(IPC_USES_READWRITE)
619 fd_pipe_.reset();
620 remote_fd_pipe_.reset();
621 #endif // IPC_USES_READWRITE
623 while (!output_queue_.empty()) {
624 Message* m = output_queue_.front();
625 output_queue_.pop();
626 delete m;
629 // Close any outstanding, received file descriptors.
630 ClearInputFDs();
632 #if defined(OS_MACOSX)
633 // Clear any outstanding, sent file descriptors.
634 for (std::set<int>::iterator i = fds_to_close_.begin();
635 i != fds_to_close_.end();
636 ++i) {
637 if (IGNORE_EINTR(close(*i)) < 0)
638 PLOG(ERROR) << "close";
640 fds_to_close_.clear();
641 #endif
644 // static
645 bool ChannelPosix::IsNamedServerInitialized(
646 const std::string& channel_id) {
647 return base::PathExists(base::FilePath(channel_id));
650 #if defined(OS_LINUX)
651 // static
652 void ChannelPosix::SetGlobalPid(int pid) {
653 global_pid_ = pid;
655 #endif // OS_LINUX
657 // Called by libevent when we can read from the pipe without blocking.
658 void ChannelPosix::OnFileCanReadWithoutBlocking(int fd) {
659 if (fd == server_listen_pipe_.get()) {
660 #if defined(OS_NACL_NONSFI)
661 LOG(FATAL)
662 << "IPC channels in nacl_helper_nonsfi should not be SERVER mode.";
663 #else
664 int new_pipe = 0;
665 if (!ServerAcceptConnection(server_listen_pipe_.get(), &new_pipe) ||
666 new_pipe < 0) {
667 Close();
668 listener()->OnChannelListenError();
671 if (pipe_.is_valid()) {
672 // We already have a connection. We only handle one at a time.
673 // close our new descriptor.
674 if (HANDLE_EINTR(shutdown(new_pipe, SHUT_RDWR)) < 0)
675 DPLOG(ERROR) << "shutdown " << pipe_name_;
676 if (IGNORE_EINTR(close(new_pipe)) < 0)
677 DPLOG(ERROR) << "close " << pipe_name_;
678 listener()->OnChannelDenied();
679 return;
681 pipe_.reset(new_pipe);
683 if ((mode_ & MODE_OPEN_ACCESS_FLAG) == 0) {
684 // Verify that the IPC channel peer is running as the same user.
685 uid_t client_euid;
686 if (!GetPeerEuid(&client_euid)) {
687 DLOG(ERROR) << "Unable to query client euid";
688 ResetToAcceptingConnectionState();
689 return;
691 if (client_euid != geteuid()) {
692 DLOG(WARNING) << "Client euid is not authorised";
693 ResetToAcceptingConnectionState();
694 return;
698 if (!AcceptConnection()) {
699 NOTREACHED() << "AcceptConnection should not fail on server";
701 waiting_connect_ = false;
702 #endif
703 } else if (fd == pipe_) {
704 if (waiting_connect_ && (mode_ & MODE_SERVER_FLAG)) {
705 waiting_connect_ = false;
707 if (!ProcessIncomingMessages()) {
708 // ClosePipeOnError may delete this object, so we mustn't call
709 // ProcessOutgoingMessages.
710 ClosePipeOnError();
711 return;
713 } else {
714 NOTREACHED() << "Unknown pipe " << fd;
717 // If we're a server and handshaking, then we want to make sure that we
718 // only send our handshake message after we've processed the client's.
719 // This gives us a chance to kill the client if the incoming handshake
720 // is invalid. This also flushes any closefd messages.
721 if (!is_blocked_on_write_) {
722 if (!ProcessOutgoingMessages()) {
723 ClosePipeOnError();
728 // Called by libevent when we can write to the pipe without blocking.
729 void ChannelPosix::OnFileCanWriteWithoutBlocking(int fd) {
730 DCHECK_EQ(pipe_.get(), fd);
731 is_blocked_on_write_ = false;
732 if (!ProcessOutgoingMessages()) {
733 ClosePipeOnError();
737 bool ChannelPosix::AcceptConnection() {
738 base::MessageLoopForIO::current()->WatchFileDescriptor(
739 pipe_.get(),
740 true,
741 base::MessageLoopForIO::WATCH_READ,
742 &read_watcher_,
743 this);
744 QueueHelloMessage();
746 if (mode_ & MODE_CLIENT_FLAG) {
747 // If we are a client we want to send a hello message out immediately.
748 // In server mode we will send a hello message when we receive one from a
749 // client.
750 waiting_connect_ = false;
751 return ProcessOutgoingMessages();
752 } else if (mode_ & MODE_SERVER_FLAG) {
753 waiting_connect_ = true;
754 return true;
755 } else {
756 NOTREACHED();
757 return false;
761 void ChannelPosix::ClosePipeOnError() {
762 if (HasAcceptedConnection()) {
763 ResetToAcceptingConnectionState();
764 listener()->OnChannelError();
765 } else {
766 Close();
767 if (AcceptsConnections()) {
768 listener()->OnChannelListenError();
769 } else {
770 listener()->OnChannelError();
775 int ChannelPosix::GetHelloMessageProcId() const {
776 int pid = base::GetCurrentProcId();
777 #if defined(OS_LINUX)
778 // Our process may be in a sandbox with a separate PID namespace.
779 if (global_pid_) {
780 pid = global_pid_;
782 #endif
783 return pid;
786 void ChannelPosix::QueueHelloMessage() {
787 // Create the Hello message
788 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
789 HELLO_MESSAGE_TYPE,
790 IPC::Message::PRIORITY_NORMAL));
791 if (!msg->WriteInt(GetHelloMessageProcId())) {
792 NOTREACHED() << "Unable to pickle hello message proc id";
794 #if defined(IPC_USES_READWRITE)
795 scoped_ptr<Message> hello;
796 if (remote_fd_pipe_.is_valid()) {
797 if (!msg->WriteAttachment(
798 new internal::PlatformFileAttachment(remote_fd_pipe_.get()))) {
799 NOTREACHED() << "Unable to pickle hello message file descriptors";
801 DCHECK_EQ(msg->attachment_set()->size(), 1U);
803 #endif // IPC_USES_READWRITE
804 output_queue_.push(msg.release());
807 ChannelPosix::ReadState ChannelPosix::ReadData(
808 char* buffer,
809 int buffer_len,
810 int* bytes_read) {
811 if (!pipe_.is_valid())
812 return READ_FAILED;
814 struct msghdr msg = {0};
816 struct iovec iov = {buffer, static_cast<size_t>(buffer_len)};
817 msg.msg_iov = &iov;
818 msg.msg_iovlen = 1;
820 msg.msg_control = input_cmsg_buf_;
822 // recvmsg() returns 0 if the connection has closed or EAGAIN if no data
823 // is waiting on the pipe.
824 #if defined(IPC_USES_READWRITE)
825 if (fd_pipe_.is_valid()) {
826 *bytes_read = HANDLE_EINTR(read(pipe_.get(), buffer, buffer_len));
827 msg.msg_controllen = 0;
828 } else
829 #endif // IPC_USES_READWRITE
831 msg.msg_controllen = sizeof(input_cmsg_buf_);
832 *bytes_read = HANDLE_EINTR(recvmsg(pipe_.get(), &msg, MSG_DONTWAIT));
834 if (*bytes_read < 0) {
835 if (errno == EAGAIN) {
836 return READ_PENDING;
837 #if defined(OS_MACOSX)
838 } else if (errno == EPERM) {
839 // On OSX, reading from a pipe with no listener returns EPERM
840 // treat this as a special case to prevent spurious error messages
841 // to the console.
842 return READ_FAILED;
843 #endif // OS_MACOSX
844 } else if (errno == ECONNRESET || errno == EPIPE) {
845 return READ_FAILED;
846 } else {
847 PLOG(ERROR) << "pipe error (" << pipe_.get() << ")";
848 return READ_FAILED;
850 } else if (*bytes_read == 0) {
851 // The pipe has closed...
852 return READ_FAILED;
854 DCHECK(*bytes_read);
856 CloseClientFileDescriptor();
858 // Read any file descriptors from the message.
859 if (!ExtractFileDescriptorsFromMsghdr(&msg))
860 return READ_FAILED;
861 return READ_SUCCEEDED;
864 #if defined(IPC_USES_READWRITE)
865 bool ChannelPosix::ReadFileDescriptorsFromFDPipe() {
866 char dummy;
867 struct iovec fd_pipe_iov = { &dummy, 1 };
869 struct msghdr msg = { 0 };
870 msg.msg_iov = &fd_pipe_iov;
871 msg.msg_iovlen = 1;
872 msg.msg_control = input_cmsg_buf_;
873 msg.msg_controllen = sizeof(input_cmsg_buf_);
874 ssize_t bytes_received =
875 HANDLE_EINTR(recvmsg(fd_pipe_.get(), &msg, MSG_DONTWAIT));
877 if (bytes_received != 1)
878 return true; // No message waiting.
880 if (!ExtractFileDescriptorsFromMsghdr(&msg))
881 return false;
882 return true;
884 #endif
886 // On Posix, we need to fix up the file descriptors before the input message
887 // is dispatched.
889 // This will read from the input_fds_ (READWRITE mode only) and read more
890 // handles from the FD pipe if necessary.
891 bool ChannelPosix::WillDispatchInputMessage(Message* msg) {
892 uint16 header_fds = msg->header()->num_fds;
893 if (!header_fds)
894 return true; // Nothing to do.
896 // The message has file descriptors.
897 const char* error = NULL;
898 if (header_fds > input_fds_.size()) {
899 // The message has been completely received, but we didn't get
900 // enough file descriptors.
901 #if defined(IPC_USES_READWRITE)
902 if (!ReadFileDescriptorsFromFDPipe())
903 return false;
904 if (header_fds > input_fds_.size())
905 #endif // IPC_USES_READWRITE
906 error = "Message needs unreceived descriptors";
909 if (header_fds > MessageAttachmentSet::kMaxDescriptorsPerMessage)
910 error = "Message requires an excessive number of descriptors";
912 if (error) {
913 LOG(WARNING) << error
914 << " channel:" << this
915 << " message-type:" << msg->type()
916 << " header()->num_fds:" << header_fds;
917 // Abort the connection.
918 ClearInputFDs();
919 return false;
922 // The shenaniganery below with &foo.front() requires input_fds_ to have
923 // contiguous underlying storage (such as a simple array or a std::vector).
924 // This is why the header warns not to make input_fds_ a deque<>.
925 msg->attachment_set()->AddDescriptorsToOwn(&input_fds_.front(), header_fds);
926 input_fds_.erase(input_fds_.begin(), input_fds_.begin() + header_fds);
927 return true;
930 bool ChannelPosix::DidEmptyInputBuffers() {
931 // When the input data buffer is empty, the fds should be too. If this is
932 // not the case, we probably have a rogue renderer which is trying to fill
933 // our descriptor table.
934 return input_fds_.empty();
937 bool ChannelPosix::ExtractFileDescriptorsFromMsghdr(msghdr* msg) {
938 // Check that there are any control messages. On OSX, CMSG_FIRSTHDR will
939 // return an invalid non-NULL pointer in the case that controllen == 0.
940 if (msg->msg_controllen == 0)
941 return true;
943 for (cmsghdr* cmsg = CMSG_FIRSTHDR(msg);
944 cmsg;
945 cmsg = CMSG_NXTHDR(msg, cmsg)) {
946 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
947 unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0);
948 DCHECK_EQ(0U, payload_len % sizeof(int));
949 const int* file_descriptors = reinterpret_cast<int*>(CMSG_DATA(cmsg));
950 unsigned num_file_descriptors = payload_len / 4;
951 input_fds_.insert(input_fds_.end(),
952 file_descriptors,
953 file_descriptors + num_file_descriptors);
955 // Check this after adding the FDs so we don't leak them.
956 if (msg->msg_flags & MSG_CTRUNC) {
957 ClearInputFDs();
958 return false;
961 return true;
965 // No file descriptors found, but that's OK.
966 return true;
969 void ChannelPosix::ClearInputFDs() {
970 for (size_t i = 0; i < input_fds_.size(); ++i) {
971 if (IGNORE_EINTR(close(input_fds_[i])) < 0)
972 PLOG(ERROR) << "close ";
974 input_fds_.clear();
977 void ChannelPosix::QueueCloseFDMessage(int fd, int hops) {
978 switch (hops) {
979 case 1:
980 case 2: {
981 // Create the message
982 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
983 CLOSE_FD_MESSAGE_TYPE,
984 IPC::Message::PRIORITY_NORMAL));
985 if (!msg->WriteInt(hops - 1) || !msg->WriteInt(fd)) {
986 NOTREACHED() << "Unable to pickle close fd.";
988 // Send(msg.release());
989 output_queue_.push(msg.release());
990 break;
993 default:
994 NOTREACHED();
995 break;
999 void ChannelPosix::HandleInternalMessage(const Message& msg) {
1000 // The Hello message contains only the process id.
1001 PickleIterator iter(msg);
1003 switch (msg.type()) {
1004 default:
1005 NOTREACHED();
1006 break;
1008 case Channel::HELLO_MESSAGE_TYPE:
1009 int pid;
1010 if (!iter.ReadInt(&pid))
1011 NOTREACHED();
1013 #if defined(IPC_USES_READWRITE)
1014 if (mode_ & MODE_SERVER_FLAG) {
1015 // With IPC_USES_READWRITE, the Hello message from the client to the
1016 // server also contains the fd_pipe_, which will be used for all
1017 // subsequent file descriptor passing.
1018 DCHECK_EQ(msg.attachment_set()->size(), 1U);
1019 scoped_refptr<MessageAttachment> attachment;
1020 if (!msg.ReadAttachment(&iter, &attachment)) {
1021 NOTREACHED();
1023 fd_pipe_.reset(attachment->TakePlatformFile());
1025 #endif // IPC_USES_READWRITE
1026 peer_pid_ = pid;
1027 listener()->OnChannelConnected(pid);
1028 break;
1030 #if defined(OS_MACOSX)
1031 case Channel::CLOSE_FD_MESSAGE_TYPE:
1032 int fd, hops;
1033 if (!iter.ReadInt(&hops))
1034 NOTREACHED();
1035 if (!iter.ReadInt(&fd))
1036 NOTREACHED();
1037 if (hops == 0) {
1038 if (fds_to_close_.erase(fd) > 0) {
1039 if (IGNORE_EINTR(close(fd)) < 0)
1040 PLOG(ERROR) << "close";
1041 } else {
1042 NOTREACHED();
1044 } else {
1045 QueueCloseFDMessage(fd, hops);
1047 break;
1048 #endif
1052 void ChannelPosix::Close() {
1053 // Close can be called multiple time, so we need to make sure we're
1054 // idempotent.
1056 ResetToAcceptingConnectionState();
1058 if (must_unlink_) {
1059 unlink(pipe_name_.c_str());
1060 must_unlink_ = false;
1063 if (server_listen_pipe_.is_valid()) {
1064 #if defined(OS_NACL_NONSFI)
1065 LOG(FATAL)
1066 << "IPC channels in nacl_helper_nonsfi should not be SERVER mode.";
1067 #else
1068 server_listen_pipe_.reset();
1069 // Unregister libevent for the listening socket and close it.
1070 server_listen_connection_watcher_.StopWatchingFileDescriptor();
1071 #endif
1074 CloseClientFileDescriptor();
1077 base::ProcessId ChannelPosix::GetPeerPID() const {
1078 return peer_pid_;
1081 base::ProcessId ChannelPosix::GetSelfPID() const {
1082 return GetHelloMessageProcId();
1085 void ChannelPosix::ResetSafely(base::ScopedFD* fd) {
1086 if (!in_dtor_) {
1087 fd->reset();
1088 return;
1091 // crbug.com/449233
1092 // The CL [1] tightened the error check for closing FDs, but it turned
1093 // out that there are existing cases that hit the newly added check.
1094 // ResetSafely() is the workaround for that crash, turning it from
1095 // from PCHECK() to DPCHECK() so that it doesn't crash in production.
1096 // [1] https://crrev.com/ce44fef5fd60dd2be5c587d4b084bdcd36adcee4
1097 int fd_to_close = fd->release();
1098 if (-1 != fd_to_close) {
1099 int rv = IGNORE_EINTR(close(fd_to_close));
1100 DPCHECK(0 == rv);
1104 //------------------------------------------------------------------------------
1105 // Channel's methods
1107 // static
1108 scoped_ptr<Channel> Channel::Create(
1109 const IPC::ChannelHandle &channel_handle, Mode mode, Listener* listener) {
1110 return make_scoped_ptr(new ChannelPosix(channel_handle, mode, listener));
1113 // static
1114 std::string Channel::GenerateVerifiedChannelID(const std::string& prefix) {
1115 // A random name is sufficient validation on posix systems, so we don't need
1116 // an additional shared secret.
1118 std::string id = prefix;
1119 if (!id.empty())
1120 id.append(".");
1122 return id.append(GenerateUniqueRandomChannelID());
1126 bool Channel::IsNamedServerInitialized(
1127 const std::string& channel_id) {
1128 return ChannelPosix::IsNamedServerInitialized(channel_id);
1131 #if defined(OS_LINUX)
1132 // static
1133 void Channel::SetGlobalPid(int pid) {
1134 ChannelPosix::SetGlobalPid(pid);
1136 #endif // OS_LINUX
1138 } // namespace IPC