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