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