Pass correct flags for use_lto==1 with Clang.
[chromium-blink-merge.git] / ipc / ipc_channel_posix.cc
blob1989669d1363e6c770c281b093ba9107852be793
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_switches.h"
46 #include "ipc/unix_domain_socket_util.h"
48 namespace IPC {
50 // IPC channels on Windows use named pipes (CreateNamedPipe()) with
51 // channel ids as the pipe names. Channels on POSIX use sockets as
52 // pipes These don't quite line up.
54 // When creating a child subprocess we use a socket pair and the parent side of
55 // the fork arranges it such that the initial control channel ends up on the
56 // magic file descriptor kPrimaryIPCChannel in the child. Future
57 // connections (file descriptors) can then be passed via that
58 // connection via sendmsg().
60 // A POSIX IPC channel can also be set up as a server for a bound UNIX domain
61 // socket, and will handle multiple connect and disconnect sequences. Currently
62 // it is limited to one connection at a time.
64 //------------------------------------------------------------------------------
65 namespace {
67 // The PipeMap class works around this quirk related to unit tests:
69 // When running as a server, we install the client socket in a
70 // specific file descriptor number (@kPrimaryIPCChannel). However, we
71 // also have to support the case where we are running unittests in the
72 // same process. (We do not support forking without execing.)
74 // Case 1: normal running
75 // The IPC server object will install a mapping in PipeMap from the
76 // name which it was given to the client pipe. When forking the client, the
77 // GetClientFileDescriptorMapping will ensure that the socket is installed in
78 // the magic slot (@kPrimaryIPCChannel). The client will search for the
79 // mapping, but it won't find any since we are in a new process. Thus the
80 // magic fd number is returned. Once the client connects, the server will
81 // close its copy of the client socket and remove the mapping.
83 // Case 2: unittests - client and server in the same process
84 // The IPC server will install a mapping as before. The client will search
85 // for a mapping and find out. It duplicates the file descriptor and
86 // connects. Once the client connects, the server will close the original
87 // copy of the client socket and remove the mapping. Thus, when the client
88 // object closes, it will close the only remaining copy of the client socket
89 // in the fd table and the server will see EOF on its side.
91 // TODO(port): a client process cannot connect to multiple IPC channels with
92 // this scheme.
94 class PipeMap {
95 public:
96 static PipeMap* GetInstance() {
97 return Singleton<PipeMap>::get();
100 ~PipeMap() {
101 // Shouldn't have left over pipes.
102 DCHECK(map_.empty());
105 // Lookup a given channel id. Return -1 if not found.
106 int Lookup(const std::string& channel_id) {
107 base::AutoLock locked(lock_);
109 ChannelToFDMap::const_iterator i = map_.find(channel_id);
110 if (i == map_.end())
111 return -1;
112 return i->second;
115 // Remove the mapping for the given channel id. No error is signaled if the
116 // channel_id doesn't exist
117 void Remove(const std::string& channel_id) {
118 base::AutoLock locked(lock_);
119 map_.erase(channel_id);
122 // Insert a mapping from @channel_id to @fd. It's a fatal error to insert a
123 // mapping if one already exists for the given channel_id
124 void Insert(const std::string& channel_id, int fd) {
125 base::AutoLock locked(lock_);
126 DCHECK_NE(-1, fd);
128 ChannelToFDMap::const_iterator i = map_.find(channel_id);
129 CHECK(i == map_.end()) << "Creating second IPC server (fd " << fd << ") "
130 << "for '" << channel_id << "' while first "
131 << "(fd " << i->second << ") still exists";
132 map_[channel_id] = fd;
135 private:
136 base::Lock lock_;
137 typedef std::map<std::string, int> ChannelToFDMap;
138 ChannelToFDMap map_;
140 friend struct DefaultSingletonTraits<PipeMap>;
141 #if defined(OS_ANDROID)
142 friend void ::IPC::Channel::NotifyProcessForkedForTesting();
143 #endif
146 //------------------------------------------------------------------------------
148 bool SocketWriteErrorIsRecoverable() {
149 #if defined(OS_MACOSX)
150 // On OS X if sendmsg() is trying to send fds between processes and there
151 // isn't enough room in the output buffer to send the fd structure over
152 // atomically then EMSGSIZE is returned.
154 // EMSGSIZE presents a problem since the system APIs can only call us when
155 // there's room in the socket buffer and not when there is "enough" room.
157 // The current behavior is to return to the event loop when EMSGSIZE is
158 // received and hopefull service another FD. This is however still
159 // technically a busy wait since the event loop will call us right back until
160 // the receiver has read enough data to allow passing the FD over atomically.
161 return errno == EAGAIN || errno == EMSGSIZE;
162 #else
163 return errno == EAGAIN;
164 #endif // OS_MACOSX
167 } // namespace
169 #if defined(OS_ANDROID)
170 // When we fork for simple tests on Android, we can't 'exec', so we need to
171 // reset these entries manually to get the expected testing behavior.
172 void Channel::NotifyProcessForkedForTesting() {
173 PipeMap::GetInstance()->map_.clear();
175 #endif
177 //------------------------------------------------------------------------------
179 #if defined(OS_LINUX)
180 int ChannelPosix::global_pid_ = 0;
181 #endif // OS_LINUX
183 ChannelPosix::ChannelPosix(const IPC::ChannelHandle& channel_handle,
184 Mode mode, Listener* listener)
185 : ChannelReader(listener),
186 mode_(mode),
187 peer_pid_(base::kNullProcessId),
188 is_blocked_on_write_(false),
189 waiting_connect_(true),
190 message_send_bytes_written_(0),
191 pipe_name_(channel_handle.name),
192 in_dtor_(false),
193 must_unlink_(false) {
194 memset(input_cmsg_buf_, 0, sizeof(input_cmsg_buf_));
195 if (!CreatePipe(channel_handle)) {
196 // The pipe may have been closed already.
197 const char *modestr = (mode_ & MODE_SERVER_FLAG) ? "server" : "client";
198 LOG(WARNING) << "Unable to create pipe named \"" << channel_handle.name
199 << "\" in " << modestr << " mode";
203 ChannelPosix::~ChannelPosix() {
204 in_dtor_ = true;
205 Close();
208 bool SocketPair(int* fd1, int* fd2) {
209 int pipe_fds[2];
210 if (socketpair(AF_UNIX, SOCK_STREAM, 0, pipe_fds) != 0) {
211 PLOG(ERROR) << "socketpair()";
212 return false;
215 // Set both ends to be non-blocking.
216 if (fcntl(pipe_fds[0], F_SETFL, O_NONBLOCK) == -1 ||
217 fcntl(pipe_fds[1], F_SETFL, O_NONBLOCK) == -1) {
218 PLOG(ERROR) << "fcntl(O_NONBLOCK)";
219 if (IGNORE_EINTR(close(pipe_fds[0])) < 0)
220 PLOG(ERROR) << "close";
221 if (IGNORE_EINTR(close(pipe_fds[1])) < 0)
222 PLOG(ERROR) << "close";
223 return false;
226 *fd1 = pipe_fds[0];
227 *fd2 = pipe_fds[1];
229 return true;
232 bool ChannelPosix::CreatePipe(
233 const IPC::ChannelHandle& channel_handle) {
234 DCHECK(!server_listen_pipe_.is_valid() && !pipe_.is_valid());
236 // Four possible cases:
237 // 1) It's a channel wrapping a pipe that is given to us.
238 // 2) It's for a named channel, so we create it.
239 // 3) It's for a client that we implement ourself. This is used
240 // in single-process unittesting.
241 // 4) It's the initial IPC channel:
242 // 4a) Client side: Pull the pipe out of the GlobalDescriptors set.
243 // 4b) Server side: create the pipe.
245 base::ScopedFD local_pipe;
246 if (channel_handle.socket.fd != -1) {
247 // Case 1 from comment above.
248 local_pipe.reset(channel_handle.socket.fd);
249 #if defined(IPC_USES_READWRITE)
250 // Test the socket passed into us to make sure it is nonblocking.
251 // We don't want to call read/write on a blocking socket.
252 int value = fcntl(local_pipe.get(), F_GETFL);
253 if (value == -1) {
254 PLOG(ERROR) << "fcntl(F_GETFL) " << pipe_name_;
255 return false;
257 if (!(value & O_NONBLOCK)) {
258 LOG(ERROR) << "Socket " << pipe_name_ << " must be O_NONBLOCK";
259 return false;
261 #endif // IPC_USES_READWRITE
262 } else if (mode_ & MODE_NAMED_FLAG) {
263 #if defined(OS_NACL_NONSFI)
264 LOG(FATAL)
265 << "IPC channels in nacl_helper_nonsfi should not be in NAMED mode.";
266 #else
267 // Case 2 from comment above.
268 int local_pipe_fd = -1;
270 if (mode_ & MODE_SERVER_FLAG) {
271 if (!CreateServerUnixDomainSocket(base::FilePath(pipe_name_),
272 &local_pipe_fd)) {
273 return false;
276 must_unlink_ = true;
277 } else if (mode_ & MODE_CLIENT_FLAG) {
278 if (!CreateClientUnixDomainSocket(base::FilePath(pipe_name_),
279 &local_pipe_fd)) {
280 return false;
282 } else {
283 LOG(ERROR) << "Bad mode: " << mode_;
284 return false;
287 local_pipe.reset(local_pipe_fd);
288 #endif // !defined(OS_NACL_NONSFI)
289 } else {
290 local_pipe.reset(PipeMap::GetInstance()->Lookup(pipe_name_));
291 if (mode_ & MODE_CLIENT_FLAG) {
292 if (local_pipe.is_valid()) {
293 // Case 3 from comment above.
294 // We only allow one connection.
295 local_pipe.reset(HANDLE_EINTR(dup(local_pipe.release())));
296 PipeMap::GetInstance()->Remove(pipe_name_);
297 } else {
298 // Case 4a from comment above.
299 // Guard against inappropriate reuse of the initial IPC channel. If
300 // an IPC channel closes and someone attempts to reuse it by name, the
301 // initial channel must not be recycled here. http://crbug.com/26754.
302 static bool used_initial_channel = false;
303 if (used_initial_channel) {
304 LOG(FATAL) << "Denying attempt to reuse initial IPC channel for "
305 << pipe_name_;
306 return false;
308 used_initial_channel = true;
310 local_pipe.reset(
311 base::GlobalDescriptors::GetInstance()->Get(kPrimaryIPCChannel));
313 } else if (mode_ & MODE_SERVER_FLAG) {
314 // Case 4b from comment above.
315 if (local_pipe.is_valid()) {
316 LOG(ERROR) << "Server already exists for " << pipe_name_;
317 // This is a client side pipe registered by other server and
318 // shouldn't be closed.
319 ignore_result(local_pipe.release());
320 return false;
322 base::AutoLock lock(client_pipe_lock_);
323 int local_pipe_fd = -1, client_pipe_fd = -1;
324 if (!SocketPair(&local_pipe_fd, &client_pipe_fd))
325 return false;
326 local_pipe.reset(local_pipe_fd);
327 client_pipe_.reset(client_pipe_fd);
328 PipeMap::GetInstance()->Insert(pipe_name_, client_pipe_fd);
329 } else {
330 LOG(ERROR) << "Bad mode: " << mode_;
331 return false;
335 #if defined(IPC_USES_READWRITE)
336 // Create a dedicated socketpair() for exchanging file descriptors.
337 // See comments for IPC_USES_READWRITE for details.
338 if (mode_ & MODE_CLIENT_FLAG) {
339 int fd_pipe_fd = 1, remote_fd_pipe_fd = -1;
340 if (!SocketPair(&fd_pipe_fd, &remote_fd_pipe_fd)) {
341 return false;
344 fd_pipe_.reset(fd_pipe_fd);
345 remote_fd_pipe_.reset(remote_fd_pipe_fd);
347 #endif // IPC_USES_READWRITE
349 if ((mode_ & MODE_SERVER_FLAG) && (mode_ & MODE_NAMED_FLAG)) {
350 #if defined(OS_NACL_NONSFI)
351 LOG(FATAL) << "IPC channels in nacl_helper_nonsfi "
352 << "should not be in NAMED or SERVER mode.";
353 #else
354 server_listen_pipe_.reset(local_pipe.release());
355 #endif
356 } else {
357 pipe_.reset(local_pipe.release());
359 return true;
362 bool ChannelPosix::Connect() {
363 if (!server_listen_pipe_.is_valid() && !pipe_.is_valid()) {
364 DLOG(WARNING) << "Channel creation failed: " << pipe_name_;
365 return false;
368 bool did_connect = true;
369 if (server_listen_pipe_.is_valid()) {
370 #if defined(OS_NACL_NONSFI)
371 LOG(FATAL) << "IPC channels in nacl_helper_nonsfi "
372 << "should always be in client mode.";
373 #else
374 // Watch the pipe for connections, and turn any connections into
375 // active sockets.
376 base::MessageLoopForIO::current()->WatchFileDescriptor(
377 server_listen_pipe_.get(),
378 true,
379 base::MessageLoopForIO::WATCH_READ,
380 &server_listen_connection_watcher_,
381 this);
382 #endif
383 } else {
384 did_connect = AcceptConnection();
386 return did_connect;
389 void ChannelPosix::CloseFileDescriptors(Message* msg) {
390 #if defined(OS_MACOSX)
391 // There is a bug on OSX which makes it dangerous to close
392 // a file descriptor while it is in transit. So instead we
393 // store the file descriptor in a set and send a message to
394 // the recipient, which is queued AFTER the message that
395 // sent the FD. The recipient will reply to the message,
396 // letting us know that it is now safe to close the file
397 // descriptor. For more information, see:
398 // http://crbug.com/298276
399 std::vector<int> to_close;
400 msg->attachment_set()->ReleaseFDsToClose(&to_close);
401 for (size_t i = 0; i < to_close.size(); i++) {
402 fds_to_close_.insert(to_close[i]);
403 QueueCloseFDMessage(to_close[i], 2);
405 #else
406 msg->attachment_set()->CommitAll();
407 #endif
410 bool ChannelPosix::ProcessOutgoingMessages() {
411 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
412 // no connection?
413 if (output_queue_.empty())
414 return true;
416 if (!pipe_.is_valid())
417 return false;
419 // Write out all the messages we can till the write blocks or there are no
420 // more outgoing messages.
421 while (!output_queue_.empty()) {
422 Message* msg = output_queue_.front();
424 size_t amt_to_write = msg->size() - message_send_bytes_written_;
425 DCHECK_NE(0U, amt_to_write);
426 const char* out_bytes = reinterpret_cast<const char*>(msg->data()) +
427 message_send_bytes_written_;
429 struct msghdr msgh = {0};
430 struct iovec iov = {const_cast<char*>(out_bytes), amt_to_write};
431 msgh.msg_iov = &iov;
432 msgh.msg_iovlen = 1;
433 char buf[CMSG_SPACE(sizeof(int) *
434 MessageAttachmentSet::kMaxDescriptorsPerMessage)];
436 ssize_t bytes_written = 1;
437 int fd_written = -1;
439 if (message_send_bytes_written_ == 0 && !msg->attachment_set()->empty()) {
440 // This is the first chunk of a message which has descriptors to send
441 struct cmsghdr *cmsg;
442 const unsigned num_fds = msg->attachment_set()->size();
444 DCHECK(num_fds <= MessageAttachmentSet::kMaxDescriptorsPerMessage);
445 if (msg->attachment_set()->ContainsDirectoryDescriptor()) {
446 LOG(FATAL) << "Panic: attempting to transport directory descriptor over"
447 " IPC. Aborting to maintain sandbox isolation.";
448 // If you have hit this then something tried to send a file descriptor
449 // to a directory over an IPC channel. Since IPC channels span
450 // sandboxes this is very bad: the receiving process can use openat
451 // with ".." elements in the path in order to reach the real
452 // filesystem.
455 msgh.msg_control = buf;
456 msgh.msg_controllen = CMSG_SPACE(sizeof(int) * num_fds);
457 cmsg = CMSG_FIRSTHDR(&msgh);
458 cmsg->cmsg_level = SOL_SOCKET;
459 cmsg->cmsg_type = SCM_RIGHTS;
460 cmsg->cmsg_len = CMSG_LEN(sizeof(int) * num_fds);
461 msg->attachment_set()->PeekDescriptors(
462 reinterpret_cast<int*>(CMSG_DATA(cmsg)));
463 msgh.msg_controllen = cmsg->cmsg_len;
465 // DCHECK_LE above already checks that
466 // num_fds < kMaxDescriptorsPerMessage so no danger of overflow.
467 msg->header()->num_fds = static_cast<uint16>(num_fds);
469 #if defined(IPC_USES_READWRITE)
470 if (!IsHelloMessage(*msg)) {
471 // Only the Hello message sends the file descriptor with the message.
472 // Subsequently, we can send file descriptors on the dedicated
473 // fd_pipe_ which makes Seccomp sandbox operation more efficient.
474 struct iovec fd_pipe_iov = { const_cast<char *>(""), 1 };
475 msgh.msg_iov = &fd_pipe_iov;
476 fd_written = fd_pipe_.get();
477 bytes_written =
478 HANDLE_EINTR(sendmsg(fd_pipe_.get(), &msgh, MSG_DONTWAIT));
479 msgh.msg_iov = &iov;
480 msgh.msg_controllen = 0;
481 if (bytes_written > 0) {
482 CloseFileDescriptors(msg);
485 #endif // IPC_USES_READWRITE
488 if (bytes_written == 1) {
489 fd_written = pipe_.get();
490 #if defined(IPC_USES_READWRITE)
491 if ((mode_ & MODE_CLIENT_FLAG) && IsHelloMessage(*msg)) {
492 DCHECK_EQ(msg->attachment_set()->size(), 1U);
494 if (!msgh.msg_controllen) {
495 bytes_written =
496 HANDLE_EINTR(write(pipe_.get(), out_bytes, amt_to_write));
497 } else
498 #endif // IPC_USES_READWRITE
500 bytes_written = HANDLE_EINTR(sendmsg(pipe_.get(), &msgh, MSG_DONTWAIT));
503 if (bytes_written > 0)
504 CloseFileDescriptors(msg);
506 if (bytes_written < 0 && !SocketWriteErrorIsRecoverable()) {
507 // We can't close the pipe here, because calling OnChannelError
508 // may destroy this object, and that would be bad if we are
509 // called from Send(). Instead, we return false and hope the
510 // caller will close the pipe. If they do not, the pipe will
511 // still be closed next time OnFileCanReadWithoutBlocking is
512 // called.
513 #if defined(OS_MACOSX)
514 // On OSX writing to a pipe with no listener returns EPERM.
515 if (errno == EPERM) {
516 return false;
518 #endif // OS_MACOSX
519 if (errno == EPIPE) {
520 return false;
522 PLOG(ERROR) << "pipe error on "
523 << fd_written
524 << " Currently writing message of size: "
525 << msg->size();
526 return false;
529 if (static_cast<size_t>(bytes_written) != amt_to_write) {
530 if (bytes_written > 0) {
531 // If write() fails with EAGAIN then bytes_written will be -1.
532 message_send_bytes_written_ += bytes_written;
535 // Tell libevent to call us back once things are unblocked.
536 is_blocked_on_write_ = true;
537 base::MessageLoopForIO::current()->WatchFileDescriptor(
538 pipe_.get(),
539 false, // One shot
540 base::MessageLoopForIO::WATCH_WRITE,
541 &write_watcher_,
542 this);
543 return true;
544 } else {
545 message_send_bytes_written_ = 0;
547 // Message sent OK!
548 DVLOG(2) << "sent message @" << msg << " on channel @" << this
549 << " with type " << msg->type() << " on fd " << pipe_.get();
550 delete output_queue_.front();
551 output_queue_.pop();
554 return true;
557 bool ChannelPosix::Send(Message* message) {
558 DVLOG(2) << "sending message @" << message << " on channel @" << this
559 << " with type " << message->type()
560 << " (" << output_queue_.size() << " in queue)";
562 #ifdef IPC_MESSAGE_LOG_ENABLED
563 Logging::GetInstance()->OnSendMessage(message, "");
564 #endif // IPC_MESSAGE_LOG_ENABLED
566 message->TraceMessageBegin();
567 output_queue_.push(message);
568 if (!is_blocked_on_write_ && !waiting_connect_) {
569 return ProcessOutgoingMessages();
572 return true;
575 int ChannelPosix::GetClientFileDescriptor() const {
576 base::AutoLock lock(client_pipe_lock_);
577 return client_pipe_.get();
580 base::ScopedFD ChannelPosix::TakeClientFileDescriptor() {
581 base::AutoLock lock(client_pipe_lock_);
582 if (!client_pipe_.is_valid())
583 return base::ScopedFD();
584 PipeMap::GetInstance()->Remove(pipe_name_);
585 return client_pipe_.Pass();
588 void ChannelPosix::CloseClientFileDescriptor() {
589 base::AutoLock lock(client_pipe_lock_);
590 if (!client_pipe_.is_valid())
591 return;
592 PipeMap::GetInstance()->Remove(pipe_name_);
593 client_pipe_.reset();
596 bool ChannelPosix::AcceptsConnections() const {
597 return server_listen_pipe_.is_valid();
600 bool ChannelPosix::HasAcceptedConnection() const {
601 return AcceptsConnections() && pipe_.is_valid();
604 #if !defined(OS_NACL_NONSFI)
605 // GetPeerEuid is not supported in nacl_helper_nonsfi.
606 bool ChannelPosix::GetPeerEuid(uid_t* peer_euid) const {
607 DCHECK(!(mode_ & MODE_SERVER) || HasAcceptedConnection());
608 return IPC::GetPeerEuid(pipe_.get(), peer_euid);
610 #endif
612 void ChannelPosix::ResetToAcceptingConnectionState() {
613 // Unregister libevent for the unix domain socket and close it.
614 read_watcher_.StopWatchingFileDescriptor();
615 write_watcher_.StopWatchingFileDescriptor();
616 ResetSafely(&pipe_);
617 #if defined(IPC_USES_READWRITE)
618 fd_pipe_.reset();
619 remote_fd_pipe_.reset();
620 #endif // IPC_USES_READWRITE
622 while (!output_queue_.empty()) {
623 Message* m = output_queue_.front();
624 output_queue_.pop();
625 delete m;
628 // Close any outstanding, received file descriptors.
629 ClearInputFDs();
631 #if defined(OS_MACOSX)
632 // Clear any outstanding, sent file descriptors.
633 for (std::set<int>::iterator i = fds_to_close_.begin();
634 i != fds_to_close_.end();
635 ++i) {
636 if (IGNORE_EINTR(close(*i)) < 0)
637 PLOG(ERROR) << "close";
639 fds_to_close_.clear();
640 #endif
643 // static
644 bool ChannelPosix::IsNamedServerInitialized(
645 const std::string& channel_id) {
646 return base::PathExists(base::FilePath(channel_id));
649 #if defined(OS_LINUX)
650 // static
651 void ChannelPosix::SetGlobalPid(int pid) {
652 global_pid_ = pid;
654 #endif // OS_LINUX
656 // Called by libevent when we can read from the pipe without blocking.
657 void ChannelPosix::OnFileCanReadWithoutBlocking(int fd) {
658 if (fd == server_listen_pipe_.get()) {
659 #if defined(OS_NACL_NONSFI)
660 LOG(FATAL)
661 << "IPC channels in nacl_helper_nonsfi should not be SERVER mode.";
662 #else
663 int new_pipe = 0;
664 if (!ServerAcceptConnection(server_listen_pipe_.get(), &new_pipe) ||
665 new_pipe < 0) {
666 Close();
667 listener()->OnChannelListenError();
670 if (pipe_.is_valid()) {
671 // We already have a connection. We only handle one at a time.
672 // close our new descriptor.
673 if (HANDLE_EINTR(shutdown(new_pipe, SHUT_RDWR)) < 0)
674 DPLOG(ERROR) << "shutdown " << pipe_name_;
675 if (IGNORE_EINTR(close(new_pipe)) < 0)
676 DPLOG(ERROR) << "close " << pipe_name_;
677 listener()->OnChannelDenied();
678 return;
680 pipe_.reset(new_pipe);
682 if ((mode_ & MODE_OPEN_ACCESS_FLAG) == 0) {
683 // Verify that the IPC channel peer is running as the same user.
684 uid_t client_euid;
685 if (!GetPeerEuid(&client_euid)) {
686 DLOG(ERROR) << "Unable to query client euid";
687 ResetToAcceptingConnectionState();
688 return;
690 if (client_euid != geteuid()) {
691 DLOG(WARNING) << "Client euid is not authorised";
692 ResetToAcceptingConnectionState();
693 return;
697 if (!AcceptConnection()) {
698 NOTREACHED() << "AcceptConnection should not fail on server";
700 waiting_connect_ = false;
701 #endif
702 } else if (fd == pipe_) {
703 if (waiting_connect_ && (mode_ & MODE_SERVER_FLAG)) {
704 waiting_connect_ = false;
706 if (!ProcessIncomingMessages()) {
707 // ClosePipeOnError may delete this object, so we mustn't call
708 // ProcessOutgoingMessages.
709 ClosePipeOnError();
710 return;
712 } else {
713 NOTREACHED() << "Unknown pipe " << fd;
716 // If we're a server and handshaking, then we want to make sure that we
717 // only send our handshake message after we've processed the client's.
718 // This gives us a chance to kill the client if the incoming handshake
719 // is invalid. This also flushes any closefd messages.
720 if (!is_blocked_on_write_) {
721 if (!ProcessOutgoingMessages()) {
722 ClosePipeOnError();
727 // Called by libevent when we can write to the pipe without blocking.
728 void ChannelPosix::OnFileCanWriteWithoutBlocking(int fd) {
729 DCHECK_EQ(pipe_.get(), fd);
730 is_blocked_on_write_ = false;
731 if (!ProcessOutgoingMessages()) {
732 ClosePipeOnError();
736 bool ChannelPosix::AcceptConnection() {
737 base::MessageLoopForIO::current()->WatchFileDescriptor(
738 pipe_.get(),
739 true,
740 base::MessageLoopForIO::WATCH_READ,
741 &read_watcher_,
742 this);
743 QueueHelloMessage();
745 if (mode_ & MODE_CLIENT_FLAG) {
746 // If we are a client we want to send a hello message out immediately.
747 // In server mode we will send a hello message when we receive one from a
748 // client.
749 waiting_connect_ = false;
750 return ProcessOutgoingMessages();
751 } else if (mode_ & MODE_SERVER_FLAG) {
752 waiting_connect_ = true;
753 return true;
754 } else {
755 NOTREACHED();
756 return false;
760 void ChannelPosix::ClosePipeOnError() {
761 if (HasAcceptedConnection()) {
762 ResetToAcceptingConnectionState();
763 listener()->OnChannelError();
764 } else {
765 Close();
766 if (AcceptsConnections()) {
767 listener()->OnChannelListenError();
768 } else {
769 listener()->OnChannelError();
774 int ChannelPosix::GetHelloMessageProcId() const {
775 int pid = base::GetCurrentProcId();
776 #if defined(OS_LINUX)
777 // Our process may be in a sandbox with a separate PID namespace.
778 if (global_pid_) {
779 pid = global_pid_;
781 #endif
782 return pid;
785 void ChannelPosix::QueueHelloMessage() {
786 // Create the Hello message
787 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
788 HELLO_MESSAGE_TYPE,
789 IPC::Message::PRIORITY_NORMAL));
790 if (!msg->WriteInt(GetHelloMessageProcId())) {
791 NOTREACHED() << "Unable to pickle hello message proc id";
793 #if defined(IPC_USES_READWRITE)
794 scoped_ptr<Message> hello;
795 if (remote_fd_pipe_.is_valid()) {
796 if (!msg->WriteBorrowingFile(remote_fd_pipe_.get())) {
797 NOTREACHED() << "Unable to pickle hello message file descriptors";
799 DCHECK_EQ(msg->attachment_set()->size(), 1U);
801 #endif // IPC_USES_READWRITE
802 output_queue_.push(msg.release());
805 ChannelPosix::ReadState ChannelPosix::ReadData(
806 char* buffer,
807 int buffer_len,
808 int* bytes_read) {
809 if (!pipe_.is_valid())
810 return READ_FAILED;
812 struct msghdr msg = {0};
814 struct iovec iov = {buffer, static_cast<size_t>(buffer_len)};
815 msg.msg_iov = &iov;
816 msg.msg_iovlen = 1;
818 msg.msg_control = input_cmsg_buf_;
820 // recvmsg() returns 0 if the connection has closed or EAGAIN if no data
821 // is waiting on the pipe.
822 #if defined(IPC_USES_READWRITE)
823 if (fd_pipe_.is_valid()) {
824 *bytes_read = HANDLE_EINTR(read(pipe_.get(), buffer, buffer_len));
825 msg.msg_controllen = 0;
826 } else
827 #endif // IPC_USES_READWRITE
829 msg.msg_controllen = sizeof(input_cmsg_buf_);
830 *bytes_read = HANDLE_EINTR(recvmsg(pipe_.get(), &msg, MSG_DONTWAIT));
832 if (*bytes_read < 0) {
833 if (errno == EAGAIN) {
834 return READ_PENDING;
835 #if defined(OS_MACOSX)
836 } else if (errno == EPERM) {
837 // On OSX, reading from a pipe with no listener returns EPERM
838 // treat this as a special case to prevent spurious error messages
839 // to the console.
840 return READ_FAILED;
841 #endif // OS_MACOSX
842 } else if (errno == ECONNRESET || errno == EPIPE) {
843 return READ_FAILED;
844 } else {
845 PLOG(ERROR) << "pipe error (" << pipe_.get() << ")";
846 return READ_FAILED;
848 } else if (*bytes_read == 0) {
849 // The pipe has closed...
850 return READ_FAILED;
852 DCHECK(*bytes_read);
854 CloseClientFileDescriptor();
856 // Read any file descriptors from the message.
857 if (!ExtractFileDescriptorsFromMsghdr(&msg))
858 return READ_FAILED;
859 return READ_SUCCEEDED;
862 #if defined(IPC_USES_READWRITE)
863 bool ChannelPosix::ReadFileDescriptorsFromFDPipe() {
864 char dummy;
865 struct iovec fd_pipe_iov = { &dummy, 1 };
867 struct msghdr msg = { 0 };
868 msg.msg_iov = &fd_pipe_iov;
869 msg.msg_iovlen = 1;
870 msg.msg_control = input_cmsg_buf_;
871 msg.msg_controllen = sizeof(input_cmsg_buf_);
872 ssize_t bytes_received =
873 HANDLE_EINTR(recvmsg(fd_pipe_.get(), &msg, MSG_DONTWAIT));
875 if (bytes_received != 1)
876 return true; // No message waiting.
878 if (!ExtractFileDescriptorsFromMsghdr(&msg))
879 return false;
880 return true;
882 #endif
884 // On Posix, we need to fix up the file descriptors before the input message
885 // is dispatched.
887 // This will read from the input_fds_ (READWRITE mode only) and read more
888 // handles from the FD pipe if necessary.
889 bool ChannelPosix::WillDispatchInputMessage(Message* msg) {
890 uint16 header_fds = msg->header()->num_fds;
891 if (!header_fds)
892 return true; // Nothing to do.
894 // The message has file descriptors.
895 const char* error = NULL;
896 if (header_fds > input_fds_.size()) {
897 // The message has been completely received, but we didn't get
898 // enough file descriptors.
899 #if defined(IPC_USES_READWRITE)
900 if (!ReadFileDescriptorsFromFDPipe())
901 return false;
902 if (header_fds > input_fds_.size())
903 #endif // IPC_USES_READWRITE
904 error = "Message needs unreceived descriptors";
907 if (header_fds > MessageAttachmentSet::kMaxDescriptorsPerMessage)
908 error = "Message requires an excessive number of descriptors";
910 if (error) {
911 LOG(WARNING) << error
912 << " channel:" << this
913 << " message-type:" << msg->type()
914 << " header()->num_fds:" << header_fds;
915 // Abort the connection.
916 ClearInputFDs();
917 return false;
920 // The shenaniganery below with &foo.front() requires input_fds_ to have
921 // contiguous underlying storage (such as a simple array or a std::vector).
922 // This is why the header warns not to make input_fds_ a deque<>.
923 msg->attachment_set()->AddDescriptorsToOwn(&input_fds_.front(), header_fds);
924 input_fds_.erase(input_fds_.begin(), input_fds_.begin() + header_fds);
925 return true;
928 bool ChannelPosix::DidEmptyInputBuffers() {
929 // When the input data buffer is empty, the fds should be too. If this is
930 // not the case, we probably have a rogue renderer which is trying to fill
931 // our descriptor table.
932 return input_fds_.empty();
935 bool ChannelPosix::ExtractFileDescriptorsFromMsghdr(msghdr* msg) {
936 // Check that there are any control messages. On OSX, CMSG_FIRSTHDR will
937 // return an invalid non-NULL pointer in the case that controllen == 0.
938 if (msg->msg_controllen == 0)
939 return true;
941 for (cmsghdr* cmsg = CMSG_FIRSTHDR(msg);
942 cmsg;
943 cmsg = CMSG_NXTHDR(msg, cmsg)) {
944 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
945 unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0);
946 DCHECK_EQ(0U, payload_len % sizeof(int));
947 const int* file_descriptors = reinterpret_cast<int*>(CMSG_DATA(cmsg));
948 unsigned num_file_descriptors = payload_len / 4;
949 input_fds_.insert(input_fds_.end(),
950 file_descriptors,
951 file_descriptors + num_file_descriptors);
953 // Check this after adding the FDs so we don't leak them.
954 if (msg->msg_flags & MSG_CTRUNC) {
955 ClearInputFDs();
956 return false;
959 return true;
963 // No file descriptors found, but that's OK.
964 return true;
967 void ChannelPosix::ClearInputFDs() {
968 for (size_t i = 0; i < input_fds_.size(); ++i) {
969 if (IGNORE_EINTR(close(input_fds_[i])) < 0)
970 PLOG(ERROR) << "close ";
972 input_fds_.clear();
975 void ChannelPosix::QueueCloseFDMessage(int fd, int hops) {
976 switch (hops) {
977 case 1:
978 case 2: {
979 // Create the message
980 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
981 CLOSE_FD_MESSAGE_TYPE,
982 IPC::Message::PRIORITY_NORMAL));
983 if (!msg->WriteInt(hops - 1) || !msg->WriteInt(fd)) {
984 NOTREACHED() << "Unable to pickle close fd.";
986 // Send(msg.release());
987 output_queue_.push(msg.release());
988 break;
991 default:
992 NOTREACHED();
993 break;
997 void ChannelPosix::HandleInternalMessage(const Message& msg) {
998 // The Hello message contains only the process id.
999 PickleIterator iter(msg);
1001 switch (msg.type()) {
1002 default:
1003 NOTREACHED();
1004 break;
1006 case Channel::HELLO_MESSAGE_TYPE:
1007 int pid;
1008 if (!iter.ReadInt(&pid))
1009 NOTREACHED();
1011 #if defined(IPC_USES_READWRITE)
1012 if (mode_ & MODE_SERVER_FLAG) {
1013 // With IPC_USES_READWRITE, the Hello message from the client to the
1014 // server also contains the fd_pipe_, which will be used for all
1015 // subsequent file descriptor passing.
1016 DCHECK_EQ(msg.attachment_set()->size(), 1U);
1017 base::ScopedFD descriptor;
1018 if (!msg.ReadFile(&iter, &descriptor)) {
1019 NOTREACHED();
1021 fd_pipe_.reset(descriptor.release());
1023 #endif // IPC_USES_READWRITE
1024 peer_pid_ = pid;
1025 listener()->OnChannelConnected(pid);
1026 break;
1028 #if defined(OS_MACOSX)
1029 case Channel::CLOSE_FD_MESSAGE_TYPE:
1030 int fd, hops;
1031 if (!iter.ReadInt(&hops))
1032 NOTREACHED();
1033 if (!iter.ReadInt(&fd))
1034 NOTREACHED();
1035 if (hops == 0) {
1036 if (fds_to_close_.erase(fd) > 0) {
1037 if (IGNORE_EINTR(close(fd)) < 0)
1038 PLOG(ERROR) << "close";
1039 } else {
1040 NOTREACHED();
1042 } else {
1043 QueueCloseFDMessage(fd, hops);
1045 break;
1046 #endif
1050 void ChannelPosix::Close() {
1051 // Close can be called multiple time, so we need to make sure we're
1052 // idempotent.
1054 ResetToAcceptingConnectionState();
1056 if (must_unlink_) {
1057 unlink(pipe_name_.c_str());
1058 must_unlink_ = false;
1061 if (server_listen_pipe_.is_valid()) {
1062 #if defined(OS_NACL_NONSFI)
1063 LOG(FATAL)
1064 << "IPC channels in nacl_helper_nonsfi should not be SERVER mode.";
1065 #else
1066 server_listen_pipe_.reset();
1067 // Unregister libevent for the listening socket and close it.
1068 server_listen_connection_watcher_.StopWatchingFileDescriptor();
1069 #endif
1072 CloseClientFileDescriptor();
1075 base::ProcessId ChannelPosix::GetPeerPID() const {
1076 return peer_pid_;
1079 base::ProcessId ChannelPosix::GetSelfPID() const {
1080 return GetHelloMessageProcId();
1083 void ChannelPosix::ResetSafely(base::ScopedFD* fd) {
1084 if (!in_dtor_) {
1085 fd->reset();
1086 return;
1089 // crbug.com/449233
1090 // The CL [1] tightened the error check for closing FDs, but it turned
1091 // out that there are existing cases that hit the newly added check.
1092 // ResetSafely() is the workaround for that crash, turning it from
1093 // from PCHECK() to DPCHECK() so that it doesn't crash in production.
1094 // [1] https://crrev.com/ce44fef5fd60dd2be5c587d4b084bdcd36adcee4
1095 int fd_to_close = fd->release();
1096 if (-1 != fd_to_close) {
1097 int rv = IGNORE_EINTR(close(fd_to_close));
1098 DPCHECK(0 == rv);
1102 //------------------------------------------------------------------------------
1103 // Channel's methods
1105 // static
1106 scoped_ptr<Channel> Channel::Create(
1107 const IPC::ChannelHandle &channel_handle, Mode mode, Listener* listener) {
1108 return make_scoped_ptr(new ChannelPosix(channel_handle, mode, listener));
1111 // static
1112 std::string Channel::GenerateVerifiedChannelID(const std::string& prefix) {
1113 // A random name is sufficient validation on posix systems, so we don't need
1114 // an additional shared secret.
1116 std::string id = prefix;
1117 if (!id.empty())
1118 id.append(".");
1120 return id.append(GenerateUniqueRandomChannelID());
1124 bool Channel::IsNamedServerInitialized(
1125 const std::string& channel_id) {
1126 return ChannelPosix::IsNamedServerInitialized(channel_id);
1129 #if defined(OS_LINUX)
1130 // static
1131 void Channel::SetGlobalPid(int pid) {
1132 ChannelPosix::SetGlobalPid(pid);
1134 #endif // OS_LINUX
1136 } // namespace IPC