Omnibox - Control HQP's HUP-Like Scoring Mode via Field Trial
[chromium-blink-merge.git] / ipc / ipc_channel_posix.cc
bloba76ef8ae0fc88513e9753277310b8646bd50c568
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 } else if (mode_ & MODE_NAMED_FLAG) {
251 #if defined(OS_NACL_NONSFI)
252 LOG(FATAL)
253 << "IPC channels in nacl_helper_nonsfi should not be in NAMED mode.";
254 #else
255 // Case 2 from comment above.
256 int local_pipe_fd = -1;
258 if (mode_ & MODE_SERVER_FLAG) {
259 if (!CreateServerUnixDomainSocket(base::FilePath(pipe_name_),
260 &local_pipe_fd)) {
261 return false;
264 must_unlink_ = true;
265 } else if (mode_ & MODE_CLIENT_FLAG) {
266 if (!CreateClientUnixDomainSocket(base::FilePath(pipe_name_),
267 &local_pipe_fd)) {
268 return false;
270 } else {
271 LOG(ERROR) << "Bad mode: " << mode_;
272 return false;
275 local_pipe.reset(local_pipe_fd);
276 #endif // !defined(OS_NACL_NONSFI)
277 } else {
278 local_pipe.reset(PipeMap::GetInstance()->Lookup(pipe_name_));
279 if (mode_ & MODE_CLIENT_FLAG) {
280 if (local_pipe.is_valid()) {
281 // Case 3 from comment above.
282 // We only allow one connection.
283 local_pipe.reset(HANDLE_EINTR(dup(local_pipe.release())));
284 PipeMap::GetInstance()->Remove(pipe_name_);
285 } else {
286 // Case 4a from comment above.
287 // Guard against inappropriate reuse of the initial IPC channel. If
288 // an IPC channel closes and someone attempts to reuse it by name, the
289 // initial channel must not be recycled here. http://crbug.com/26754.
290 static bool used_initial_channel = false;
291 if (used_initial_channel) {
292 LOG(FATAL) << "Denying attempt to reuse initial IPC channel for "
293 << pipe_name_;
294 return false;
296 used_initial_channel = true;
298 local_pipe.reset(
299 base::GlobalDescriptors::GetInstance()->Get(kPrimaryIPCChannel));
301 } else if (mode_ & MODE_SERVER_FLAG) {
302 // Case 4b from comment above.
303 if (local_pipe.is_valid()) {
304 LOG(ERROR) << "Server already exists for " << pipe_name_;
305 // This is a client side pipe registered by other server and
306 // shouldn't be closed.
307 ignore_result(local_pipe.release());
308 return false;
310 base::AutoLock lock(client_pipe_lock_);
311 int local_pipe_fd = -1, client_pipe_fd = -1;
312 if (!SocketPair(&local_pipe_fd, &client_pipe_fd))
313 return false;
314 local_pipe.reset(local_pipe_fd);
315 client_pipe_.reset(client_pipe_fd);
316 PipeMap::GetInstance()->Insert(pipe_name_, client_pipe_fd);
317 } else {
318 LOG(ERROR) << "Bad mode: " << mode_;
319 return false;
323 if ((mode_ & MODE_SERVER_FLAG) && (mode_ & MODE_NAMED_FLAG)) {
324 #if defined(OS_NACL_NONSFI)
325 LOG(FATAL) << "IPC channels in nacl_helper_nonsfi "
326 << "should not be in NAMED or SERVER mode.";
327 #else
328 server_listen_pipe_.reset(local_pipe.release());
329 #endif
330 } else {
331 pipe_.reset(local_pipe.release());
333 return true;
336 bool ChannelPosix::Connect() {
337 if (!server_listen_pipe_.is_valid() && !pipe_.is_valid()) {
338 DLOG(WARNING) << "Channel creation failed: " << pipe_name_;
339 return false;
342 bool did_connect = true;
343 if (server_listen_pipe_.is_valid()) {
344 #if defined(OS_NACL_NONSFI)
345 LOG(FATAL) << "IPC channels in nacl_helper_nonsfi "
346 << "should always be in client mode.";
347 #else
348 // Watch the pipe for connections, and turn any connections into
349 // active sockets.
350 base::MessageLoopForIO::current()->WatchFileDescriptor(
351 server_listen_pipe_.get(),
352 true,
353 base::MessageLoopForIO::WATCH_READ,
354 &server_listen_connection_watcher_,
355 this);
356 #endif
357 } else {
358 did_connect = AcceptConnection();
360 return did_connect;
363 void ChannelPosix::CloseFileDescriptors(Message* msg) {
364 #if defined(OS_MACOSX)
365 // There is a bug on OSX which makes it dangerous to close
366 // a file descriptor while it is in transit. So instead we
367 // store the file descriptor in a set and send a message to
368 // the recipient, which is queued AFTER the message that
369 // sent the FD. The recipient will reply to the message,
370 // letting us know that it is now safe to close the file
371 // descriptor. For more information, see:
372 // http://crbug.com/298276
373 std::vector<int> to_close;
374 msg->attachment_set()->ReleaseFDsToClose(&to_close);
375 for (size_t i = 0; i < to_close.size(); i++) {
376 fds_to_close_.insert(to_close[i]);
377 QueueCloseFDMessage(to_close[i], 2);
379 #else
380 msg->attachment_set()->CommitAll();
381 #endif
384 bool ChannelPosix::ProcessOutgoingMessages() {
385 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
386 // no connection?
387 if (output_queue_.empty())
388 return true;
390 if (!pipe_.is_valid())
391 return false;
393 // Write out all the messages we can till the write blocks or there are no
394 // more outgoing messages.
395 while (!output_queue_.empty()) {
396 Message* msg = output_queue_.front();
398 size_t amt_to_write = msg->size() - message_send_bytes_written_;
399 DCHECK_NE(0U, amt_to_write);
400 const char* out_bytes = reinterpret_cast<const char*>(msg->data()) +
401 message_send_bytes_written_;
403 struct msghdr msgh = {0};
404 struct iovec iov = {const_cast<char*>(out_bytes), amt_to_write};
405 msgh.msg_iov = &iov;
406 msgh.msg_iovlen = 1;
407 char buf[CMSG_SPACE(sizeof(int) *
408 MessageAttachmentSet::kMaxDescriptorsPerMessage)];
410 ssize_t bytes_written = 1;
411 int fd_written = -1;
413 if (message_send_bytes_written_ == 0 && !msg->attachment_set()->empty()) {
414 // This is the first chunk of a message which has descriptors to send
415 struct cmsghdr *cmsg;
416 const unsigned num_fds = msg->attachment_set()->size();
418 DCHECK(num_fds <= MessageAttachmentSet::kMaxDescriptorsPerMessage);
419 if (msg->attachment_set()->ContainsDirectoryDescriptor()) {
420 LOG(FATAL) << "Panic: attempting to transport directory descriptor over"
421 " IPC. Aborting to maintain sandbox isolation.";
422 // If you have hit this then something tried to send a file descriptor
423 // to a directory over an IPC channel. Since IPC channels span
424 // sandboxes this is very bad: the receiving process can use openat
425 // with ".." elements in the path in order to reach the real
426 // filesystem.
429 msgh.msg_control = buf;
430 msgh.msg_controllen = CMSG_SPACE(sizeof(int) * num_fds);
431 cmsg = CMSG_FIRSTHDR(&msgh);
432 cmsg->cmsg_level = SOL_SOCKET;
433 cmsg->cmsg_type = SCM_RIGHTS;
434 cmsg->cmsg_len = CMSG_LEN(sizeof(int) * num_fds);
435 msg->attachment_set()->PeekDescriptors(
436 reinterpret_cast<int*>(CMSG_DATA(cmsg)));
437 msgh.msg_controllen = cmsg->cmsg_len;
439 // DCHECK_LE above already checks that
440 // num_fds < kMaxDescriptorsPerMessage so no danger of overflow.
441 msg->header()->num_fds = static_cast<uint16>(num_fds);
444 if (bytes_written == 1) {
445 fd_written = pipe_.get();
446 bytes_written = HANDLE_EINTR(sendmsg(pipe_.get(), &msgh, MSG_DONTWAIT));
448 if (bytes_written > 0)
449 CloseFileDescriptors(msg);
451 if (bytes_written < 0 && !SocketWriteErrorIsRecoverable()) {
452 // We can't close the pipe here, because calling OnChannelError
453 // may destroy this object, and that would be bad if we are
454 // called from Send(). Instead, we return false and hope the
455 // caller will close the pipe. If they do not, the pipe will
456 // still be closed next time OnFileCanReadWithoutBlocking is
457 // called.
458 #if defined(OS_MACOSX)
459 // On OSX writing to a pipe with no listener returns EPERM.
460 if (errno == EPERM) {
461 return false;
463 #endif // OS_MACOSX
464 if (errno == EPIPE) {
465 return false;
467 PLOG(ERROR) << "pipe error on "
468 << fd_written
469 << " Currently writing message of size: "
470 << msg->size();
471 return false;
474 if (static_cast<size_t>(bytes_written) != amt_to_write) {
475 if (bytes_written > 0) {
476 // If write() fails with EAGAIN then bytes_written will be -1.
477 message_send_bytes_written_ += bytes_written;
480 // Tell libevent to call us back once things are unblocked.
481 is_blocked_on_write_ = true;
482 base::MessageLoopForIO::current()->WatchFileDescriptor(
483 pipe_.get(),
484 false, // One shot
485 base::MessageLoopForIO::WATCH_WRITE,
486 &write_watcher_,
487 this);
488 return true;
489 } else {
490 message_send_bytes_written_ = 0;
492 // Message sent OK!
493 DVLOG(2) << "sent message @" << msg << " on channel @" << this
494 << " with type " << msg->type() << " on fd " << pipe_.get();
495 delete output_queue_.front();
496 output_queue_.pop();
499 return true;
502 bool ChannelPosix::Send(Message* message) {
503 DCHECK(!message->HasMojoHandles());
504 DVLOG(2) << "sending message @" << message << " on channel @" << this
505 << " with type " << message->type()
506 << " (" << output_queue_.size() << " in queue)";
508 #ifdef IPC_MESSAGE_LOG_ENABLED
509 Logging::GetInstance()->OnSendMessage(message, "");
510 #endif // IPC_MESSAGE_LOG_ENABLED
512 message->TraceMessageBegin();
513 output_queue_.push(message);
514 if (!is_blocked_on_write_ && !waiting_connect_) {
515 return ProcessOutgoingMessages();
518 return true;
521 int ChannelPosix::GetClientFileDescriptor() const {
522 base::AutoLock lock(client_pipe_lock_);
523 return client_pipe_.get();
526 base::ScopedFD ChannelPosix::TakeClientFileDescriptor() {
527 base::AutoLock lock(client_pipe_lock_);
528 if (!client_pipe_.is_valid())
529 return base::ScopedFD();
530 PipeMap::GetInstance()->Remove(pipe_name_);
531 return client_pipe_.Pass();
534 void ChannelPosix::CloseClientFileDescriptor() {
535 base::AutoLock lock(client_pipe_lock_);
536 if (!client_pipe_.is_valid())
537 return;
538 PipeMap::GetInstance()->Remove(pipe_name_);
539 client_pipe_.reset();
542 bool ChannelPosix::AcceptsConnections() const {
543 return server_listen_pipe_.is_valid();
546 bool ChannelPosix::HasAcceptedConnection() const {
547 return AcceptsConnections() && pipe_.is_valid();
550 #if !defined(OS_NACL_NONSFI)
551 // GetPeerEuid is not supported in nacl_helper_nonsfi.
552 bool ChannelPosix::GetPeerEuid(uid_t* peer_euid) const {
553 DCHECK(!(mode_ & MODE_SERVER) || HasAcceptedConnection());
554 return IPC::GetPeerEuid(pipe_.get(), peer_euid);
556 #endif
558 void ChannelPosix::ResetToAcceptingConnectionState() {
559 // Unregister libevent for the unix domain socket and close it.
560 read_watcher_.StopWatchingFileDescriptor();
561 write_watcher_.StopWatchingFileDescriptor();
562 ResetSafely(&pipe_);
564 while (!output_queue_.empty()) {
565 Message* m = output_queue_.front();
566 output_queue_.pop();
567 delete m;
570 // Close any outstanding, received file descriptors.
571 ClearInputFDs();
573 #if defined(OS_MACOSX)
574 // Clear any outstanding, sent file descriptors.
575 for (std::set<int>::iterator i = fds_to_close_.begin();
576 i != fds_to_close_.end();
577 ++i) {
578 if (IGNORE_EINTR(close(*i)) < 0)
579 PLOG(ERROR) << "close";
581 fds_to_close_.clear();
582 #endif
585 // static
586 bool ChannelPosix::IsNamedServerInitialized(
587 const std::string& channel_id) {
588 return base::PathExists(base::FilePath(channel_id));
591 #if defined(OS_LINUX)
592 // static
593 void ChannelPosix::SetGlobalPid(int pid) {
594 global_pid_ = pid;
596 #endif // OS_LINUX
598 // Called by libevent when we can read from the pipe without blocking.
599 void ChannelPosix::OnFileCanReadWithoutBlocking(int fd) {
600 if (fd == server_listen_pipe_.get()) {
601 #if defined(OS_NACL_NONSFI)
602 LOG(FATAL)
603 << "IPC channels in nacl_helper_nonsfi should not be SERVER mode.";
604 #else
605 int new_pipe = 0;
606 if (!ServerAcceptConnection(server_listen_pipe_.get(), &new_pipe) ||
607 new_pipe < 0) {
608 Close();
609 listener()->OnChannelListenError();
612 if (pipe_.is_valid()) {
613 // We already have a connection. We only handle one at a time.
614 // close our new descriptor.
615 if (HANDLE_EINTR(shutdown(new_pipe, SHUT_RDWR)) < 0)
616 DPLOG(ERROR) << "shutdown " << pipe_name_;
617 if (IGNORE_EINTR(close(new_pipe)) < 0)
618 DPLOG(ERROR) << "close " << pipe_name_;
619 listener()->OnChannelDenied();
620 return;
622 pipe_.reset(new_pipe);
624 if ((mode_ & MODE_OPEN_ACCESS_FLAG) == 0) {
625 // Verify that the IPC channel peer is running as the same user.
626 uid_t client_euid;
627 if (!GetPeerEuid(&client_euid)) {
628 DLOG(ERROR) << "Unable to query client euid";
629 ResetToAcceptingConnectionState();
630 return;
632 if (client_euid != geteuid()) {
633 DLOG(WARNING) << "Client euid is not authorised";
634 ResetToAcceptingConnectionState();
635 return;
639 if (!AcceptConnection()) {
640 NOTREACHED() << "AcceptConnection should not fail on server";
642 waiting_connect_ = false;
643 #endif
644 } else if (fd == pipe_) {
645 if (waiting_connect_ && (mode_ & MODE_SERVER_FLAG)) {
646 waiting_connect_ = false;
648 if (!ProcessIncomingMessages()) {
649 // ClosePipeOnError may delete this object, so we mustn't call
650 // ProcessOutgoingMessages.
651 ClosePipeOnError();
652 return;
654 } else {
655 NOTREACHED() << "Unknown pipe " << fd;
658 // If we're a server and handshaking, then we want to make sure that we
659 // only send our handshake message after we've processed the client's.
660 // This gives us a chance to kill the client if the incoming handshake
661 // is invalid. This also flushes any closefd messages.
662 if (!is_blocked_on_write_) {
663 if (!ProcessOutgoingMessages()) {
664 ClosePipeOnError();
669 // Called by libevent when we can write to the pipe without blocking.
670 void ChannelPosix::OnFileCanWriteWithoutBlocking(int fd) {
671 DCHECK_EQ(pipe_.get(), fd);
672 is_blocked_on_write_ = false;
673 if (!ProcessOutgoingMessages()) {
674 ClosePipeOnError();
678 bool ChannelPosix::AcceptConnection() {
679 base::MessageLoopForIO::current()->WatchFileDescriptor(
680 pipe_.get(),
681 true,
682 base::MessageLoopForIO::WATCH_READ,
683 &read_watcher_,
684 this);
685 QueueHelloMessage();
687 if (mode_ & MODE_CLIENT_FLAG) {
688 // If we are a client we want to send a hello message out immediately.
689 // In server mode we will send a hello message when we receive one from a
690 // client.
691 waiting_connect_ = false;
692 return ProcessOutgoingMessages();
693 } else if (mode_ & MODE_SERVER_FLAG) {
694 waiting_connect_ = true;
695 return true;
696 } else {
697 NOTREACHED();
698 return false;
702 void ChannelPosix::ClosePipeOnError() {
703 if (HasAcceptedConnection()) {
704 ResetToAcceptingConnectionState();
705 listener()->OnChannelError();
706 } else {
707 Close();
708 if (AcceptsConnections()) {
709 listener()->OnChannelListenError();
710 } else {
711 listener()->OnChannelError();
716 int ChannelPosix::GetHelloMessageProcId() const {
717 #if defined(OS_NACL_NONSFI)
718 // In nacl_helper_nonsfi, getpid() invoked by GetCurrentProcId() is not
719 // allowed and would cause a SIGSYS crash because of the seccomp sandbox.
720 return -1;
721 #else
722 int pid = base::GetCurrentProcId();
723 #if defined(OS_LINUX)
724 // Our process may be in a sandbox with a separate PID namespace.
725 if (global_pid_) {
726 pid = global_pid_;
728 #endif // defined(OS_LINUX)
729 return pid;
730 #endif // defined(OS_NACL_NONSFI)
733 void ChannelPosix::QueueHelloMessage() {
734 // Create the Hello message
735 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
736 HELLO_MESSAGE_TYPE,
737 IPC::Message::PRIORITY_NORMAL));
738 if (!msg->WriteInt(GetHelloMessageProcId())) {
739 NOTREACHED() << "Unable to pickle hello message proc id";
741 output_queue_.push(msg.release());
744 ChannelPosix::ReadState ChannelPosix::ReadData(
745 char* buffer,
746 int buffer_len,
747 int* bytes_read) {
748 if (!pipe_.is_valid())
749 return READ_FAILED;
751 struct msghdr msg = {0};
753 struct iovec iov = {buffer, static_cast<size_t>(buffer_len)};
754 msg.msg_iov = &iov;
755 msg.msg_iovlen = 1;
757 msg.msg_control = input_cmsg_buf_;
759 // recvmsg() returns 0 if the connection has closed or EAGAIN if no data
760 // is waiting on the pipe.
761 msg.msg_controllen = sizeof(input_cmsg_buf_);
762 *bytes_read = HANDLE_EINTR(recvmsg(pipe_.get(), &msg, MSG_DONTWAIT));
764 if (*bytes_read < 0) {
765 if (errno == EAGAIN) {
766 return READ_PENDING;
767 #if defined(OS_MACOSX)
768 } else if (errno == EPERM) {
769 // On OSX, reading from a pipe with no listener returns EPERM
770 // treat this as a special case to prevent spurious error messages
771 // to the console.
772 return READ_FAILED;
773 #endif // OS_MACOSX
774 } else if (errno == ECONNRESET || errno == EPIPE) {
775 return READ_FAILED;
776 } else {
777 PLOG(ERROR) << "pipe error (" << pipe_.get() << ")";
778 return READ_FAILED;
780 } else if (*bytes_read == 0) {
781 // The pipe has closed...
782 return READ_FAILED;
784 DCHECK(*bytes_read);
786 CloseClientFileDescriptor();
788 // Read any file descriptors from the message.
789 if (!ExtractFileDescriptorsFromMsghdr(&msg))
790 return READ_FAILED;
791 return READ_SUCCEEDED;
794 // On Posix, we need to fix up the file descriptors before the input message
795 // is dispatched.
797 // This will read from the input_fds_ (READWRITE mode only) and read more
798 // handles from the FD pipe if necessary.
799 bool ChannelPosix::WillDispatchInputMessage(Message* msg) {
800 uint16 header_fds = msg->header()->num_fds;
801 if (!header_fds)
802 return true; // Nothing to do.
804 // The message has file descriptors.
805 const char* error = NULL;
806 if (header_fds > input_fds_.size()) {
807 // The message has been completely received, but we didn't get
808 // enough file descriptors.
809 error = "Message needs unreceived descriptors";
812 if (header_fds > MessageAttachmentSet::kMaxDescriptorsPerMessage)
813 error = "Message requires an excessive number of descriptors";
815 if (error) {
816 LOG(WARNING) << error
817 << " channel:" << this
818 << " message-type:" << msg->type()
819 << " header()->num_fds:" << header_fds;
820 // Abort the connection.
821 ClearInputFDs();
822 return false;
825 // The shenaniganery below with &foo.front() requires input_fds_ to have
826 // contiguous underlying storage (such as a simple array or a std::vector).
827 // This is why the header warns not to make input_fds_ a deque<>.
828 msg->attachment_set()->AddDescriptorsToOwn(&input_fds_.front(), header_fds);
829 input_fds_.erase(input_fds_.begin(), input_fds_.begin() + header_fds);
830 return true;
833 bool ChannelPosix::DidEmptyInputBuffers() {
834 // When the input data buffer is empty, the fds should be too. If this is
835 // not the case, we probably have a rogue renderer which is trying to fill
836 // our descriptor table.
837 return input_fds_.empty();
840 bool ChannelPosix::ExtractFileDescriptorsFromMsghdr(msghdr* msg) {
841 // Check that there are any control messages. On OSX, CMSG_FIRSTHDR will
842 // return an invalid non-NULL pointer in the case that controllen == 0.
843 if (msg->msg_controllen == 0)
844 return true;
846 for (cmsghdr* cmsg = CMSG_FIRSTHDR(msg);
847 cmsg;
848 cmsg = CMSG_NXTHDR(msg, cmsg)) {
849 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
850 unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0);
851 DCHECK_EQ(0U, payload_len % sizeof(int));
852 const int* file_descriptors = reinterpret_cast<int*>(CMSG_DATA(cmsg));
853 unsigned num_file_descriptors = payload_len / 4;
854 input_fds_.insert(input_fds_.end(),
855 file_descriptors,
856 file_descriptors + num_file_descriptors);
858 // Check this after adding the FDs so we don't leak them.
859 if (msg->msg_flags & MSG_CTRUNC) {
860 ClearInputFDs();
861 return false;
864 return true;
868 // No file descriptors found, but that's OK.
869 return true;
872 void ChannelPosix::ClearInputFDs() {
873 for (size_t i = 0; i < input_fds_.size(); ++i) {
874 if (IGNORE_EINTR(close(input_fds_[i])) < 0)
875 PLOG(ERROR) << "close ";
877 input_fds_.clear();
880 void ChannelPosix::QueueCloseFDMessage(int fd, int hops) {
881 switch (hops) {
882 case 1:
883 case 2: {
884 // Create the message
885 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
886 CLOSE_FD_MESSAGE_TYPE,
887 IPC::Message::PRIORITY_NORMAL));
888 if (!msg->WriteInt(hops - 1) || !msg->WriteInt(fd)) {
889 NOTREACHED() << "Unable to pickle close fd.";
891 // Send(msg.release());
892 output_queue_.push(msg.release());
893 break;
896 default:
897 NOTREACHED();
898 break;
902 void ChannelPosix::HandleInternalMessage(const Message& msg) {
903 // The Hello message contains only the process id.
904 PickleIterator iter(msg);
906 switch (msg.type()) {
907 default:
908 NOTREACHED();
909 break;
911 case Channel::HELLO_MESSAGE_TYPE:
912 int pid;
913 if (!iter.ReadInt(&pid))
914 NOTREACHED();
916 peer_pid_ = pid;
917 listener()->OnChannelConnected(pid);
918 break;
920 #if defined(OS_MACOSX)
921 case Channel::CLOSE_FD_MESSAGE_TYPE:
922 int fd, hops;
923 if (!iter.ReadInt(&hops))
924 NOTREACHED();
925 if (!iter.ReadInt(&fd))
926 NOTREACHED();
927 if (hops == 0) {
928 if (fds_to_close_.erase(fd) > 0) {
929 if (IGNORE_EINTR(close(fd)) < 0)
930 PLOG(ERROR) << "close";
931 } else {
932 NOTREACHED();
934 } else {
935 QueueCloseFDMessage(fd, hops);
937 break;
938 #endif
942 void ChannelPosix::Close() {
943 // Close can be called multiple time, so we need to make sure we're
944 // idempotent.
946 ResetToAcceptingConnectionState();
948 if (must_unlink_) {
949 unlink(pipe_name_.c_str());
950 must_unlink_ = false;
953 if (server_listen_pipe_.is_valid()) {
954 #if defined(OS_NACL_NONSFI)
955 LOG(FATAL)
956 << "IPC channels in nacl_helper_nonsfi should not be SERVER mode.";
957 #else
958 server_listen_pipe_.reset();
959 // Unregister libevent for the listening socket and close it.
960 server_listen_connection_watcher_.StopWatchingFileDescriptor();
961 #endif
964 CloseClientFileDescriptor();
967 base::ProcessId ChannelPosix::GetPeerPID() const {
968 return peer_pid_;
971 base::ProcessId ChannelPosix::GetSelfPID() const {
972 return GetHelloMessageProcId();
975 void ChannelPosix::ResetSafely(base::ScopedFD* fd) {
976 if (!in_dtor_) {
977 fd->reset();
978 return;
981 // crbug.com/449233
982 // The CL [1] tightened the error check for closing FDs, but it turned
983 // out that there are existing cases that hit the newly added check.
984 // ResetSafely() is the workaround for that crash, turning it from
985 // from PCHECK() to DPCHECK() so that it doesn't crash in production.
986 // [1] https://crrev.com/ce44fef5fd60dd2be5c587d4b084bdcd36adcee4
987 int fd_to_close = fd->release();
988 if (-1 != fd_to_close) {
989 int rv = IGNORE_EINTR(close(fd_to_close));
990 DPCHECK(0 == rv);
994 //------------------------------------------------------------------------------
995 // Channel's methods
997 // static
998 scoped_ptr<Channel> Channel::Create(
999 const IPC::ChannelHandle &channel_handle, Mode mode, Listener* listener) {
1000 return make_scoped_ptr(new ChannelPosix(channel_handle, mode, listener));
1003 // static
1004 std::string Channel::GenerateVerifiedChannelID(const std::string& prefix) {
1005 // A random name is sufficient validation on posix systems, so we don't need
1006 // an additional shared secret.
1008 std::string id = prefix;
1009 if (!id.empty())
1010 id.append(".");
1012 return id.append(GenerateUniqueRandomChannelID());
1015 bool Channel::IsNamedServerInitialized(
1016 const std::string& channel_id) {
1017 return ChannelPosix::IsNamedServerInitialized(channel_id);
1020 #if defined(OS_LINUX)
1021 // static
1022 void Channel::SetGlobalPid(int pid) {
1023 ChannelPosix::SetGlobalPid(pid);
1025 #endif // OS_LINUX
1027 } // namespace IPC