Home | History | Annotate | Download | only in posix
      1 // Copyright (c) 2011 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 "base/posix/unix_domain_socket_linux.h"
      6 
      7 #include <errno.h>
      8 #include <sys/socket.h>
      9 #include <unistd.h>
     10 
     11 #include <vector>
     12 
     13 #include "base/files/scoped_file.h"
     14 #include "base/logging.h"
     15 #include "base/pickle.h"
     16 #include "base/posix/eintr_wrapper.h"
     17 #include "base/stl_util.h"
     18 #include "build/build_config.h"
     19 
     20 #if !defined(OS_NACL_NONSFI)
     21 #include <sys/uio.h>
     22 #endif
     23 
     24 namespace base {
     25 
     26 const size_t UnixDomainSocket::kMaxFileDescriptors = 16;
     27 
     28 #if !defined(OS_NACL_NONSFI)
     29 // Creates a connected pair of UNIX-domain SOCK_SEQPACKET sockets, and passes
     30 // ownership of the newly allocated file descriptors to |one| and |two|.
     31 // Returns true on success.
     32 static bool CreateSocketPair(ScopedFD* one, ScopedFD* two) {
     33   int raw_socks[2];
     34   if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, raw_socks) == -1)
     35     return false;
     36   one->reset(raw_socks[0]);
     37   two->reset(raw_socks[1]);
     38   return true;
     39 }
     40 
     41 // static
     42 bool UnixDomainSocket::EnableReceiveProcessId(int fd) {
     43   const int enable = 1;
     44   return setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable)) == 0;
     45 }
     46 #endif  // !defined(OS_NACL_NONSFI)
     47 
     48 // static
     49 bool UnixDomainSocket::SendMsg(int fd,
     50                                const void* buf,
     51                                size_t length,
     52                                const std::vector<int>& fds) {
     53   struct msghdr msg = {};
     54   struct iovec iov = { const_cast<void*>(buf), length };
     55   msg.msg_iov = &iov;
     56   msg.msg_iovlen = 1;
     57 
     58   char* control_buffer = NULL;
     59   if (fds.size()) {
     60     const unsigned control_len = CMSG_SPACE(sizeof(int) * fds.size());
     61     control_buffer = new char[control_len];
     62 
     63     struct cmsghdr* cmsg;
     64     msg.msg_control = control_buffer;
     65     msg.msg_controllen = control_len;
     66     cmsg = CMSG_FIRSTHDR(&msg);
     67     cmsg->cmsg_level = SOL_SOCKET;
     68     cmsg->cmsg_type = SCM_RIGHTS;
     69     cmsg->cmsg_len = CMSG_LEN(sizeof(int) * fds.size());
     70     memcpy(CMSG_DATA(cmsg), &fds[0], sizeof(int) * fds.size());
     71     msg.msg_controllen = cmsg->cmsg_len;
     72   }
     73 
     74   // Avoid a SIGPIPE if the other end breaks the connection.
     75   // Due to a bug in the Linux kernel (net/unix/af_unix.c) MSG_NOSIGNAL isn't
     76   // regarded for SOCK_SEQPACKET in the AF_UNIX domain, but it is mandated by
     77   // POSIX.
     78   const int flags = MSG_NOSIGNAL;
     79   const ssize_t r = HANDLE_EINTR(sendmsg(fd, &msg, flags));
     80   const bool ret = static_cast<ssize_t>(length) == r;
     81   delete[] control_buffer;
     82   return ret;
     83 }
     84 
     85 // static
     86 ssize_t UnixDomainSocket::RecvMsg(int fd,
     87                                   void* buf,
     88                                   size_t length,
     89                                   std::vector<ScopedFD>* fds) {
     90   return UnixDomainSocket::RecvMsgWithPid(fd, buf, length, fds, NULL);
     91 }
     92 
     93 // static
     94 ssize_t UnixDomainSocket::RecvMsgWithPid(int fd,
     95                                          void* buf,
     96                                          size_t length,
     97                                          std::vector<ScopedFD>* fds,
     98                                          ProcessId* pid) {
     99   return UnixDomainSocket::RecvMsgWithFlags(fd, buf, length, 0, fds, pid);
    100 }
    101 
    102 // static
    103 ssize_t UnixDomainSocket::RecvMsgWithFlags(int fd,
    104                                            void* buf,
    105                                            size_t length,
    106                                            int flags,
    107                                            std::vector<ScopedFD>* fds,
    108                                            ProcessId* out_pid) {
    109   fds->clear();
    110 
    111   struct msghdr msg = {};
    112   struct iovec iov = { buf, length };
    113   msg.msg_iov = &iov;
    114   msg.msg_iovlen = 1;
    115 
    116   const size_t kControlBufferSize =
    117       CMSG_SPACE(sizeof(int) * kMaxFileDescriptors)
    118 #if !defined(OS_NACL_NONSFI)
    119       // The PNaCl toolchain for Non-SFI binary build does not support ucred.
    120       + CMSG_SPACE(sizeof(struct ucred))
    121 #endif
    122       ;
    123   char control_buffer[kControlBufferSize];
    124   msg.msg_control = control_buffer;
    125   msg.msg_controllen = sizeof(control_buffer);
    126 
    127   const ssize_t r = HANDLE_EINTR(recvmsg(fd, &msg, flags));
    128   if (r == -1)
    129     return -1;
    130 
    131   int* wire_fds = NULL;
    132   unsigned wire_fds_len = 0;
    133   ProcessId pid = -1;
    134 
    135   if (msg.msg_controllen > 0) {
    136     struct cmsghdr* cmsg;
    137     for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
    138       const unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0);
    139       if (cmsg->cmsg_level == SOL_SOCKET &&
    140           cmsg->cmsg_type == SCM_RIGHTS) {
    141         DCHECK_EQ(payload_len % sizeof(int), 0u);
    142         DCHECK_EQ(wire_fds, static_cast<void*>(nullptr));
    143         wire_fds = reinterpret_cast<int*>(CMSG_DATA(cmsg));
    144         wire_fds_len = payload_len / sizeof(int);
    145       }
    146 #if !defined(OS_NACL_NONSFI)
    147       // The PNaCl toolchain for Non-SFI binary build does not support
    148       // SCM_CREDENTIALS.
    149       if (cmsg->cmsg_level == SOL_SOCKET &&
    150           cmsg->cmsg_type == SCM_CREDENTIALS) {
    151         DCHECK_EQ(payload_len, sizeof(struct ucred));
    152         DCHECK_EQ(pid, -1);
    153         pid = reinterpret_cast<struct ucred*>(CMSG_DATA(cmsg))->pid;
    154       }
    155 #endif
    156     }
    157   }
    158 
    159   if (msg.msg_flags & MSG_TRUNC || msg.msg_flags & MSG_CTRUNC) {
    160     for (unsigned i = 0; i < wire_fds_len; ++i)
    161       close(wire_fds[i]);
    162     errno = EMSGSIZE;
    163     return -1;
    164   }
    165 
    166   if (wire_fds) {
    167     for (unsigned i = 0; i < wire_fds_len; ++i)
    168       fds->push_back(ScopedFD(wire_fds[i]));  // TODO(mdempsky): emplace_back
    169   }
    170 
    171   if (out_pid) {
    172     // |pid| will legitimately be -1 if we read EOF, so only DCHECK if we
    173     // actually received a message.  Unfortunately, Linux allows sending zero
    174     // length messages, which are indistinguishable from EOF, so this check
    175     // has false negatives.
    176     if (r > 0 || msg.msg_controllen > 0)
    177       DCHECK_GE(pid, 0);
    178 
    179     *out_pid = pid;
    180   }
    181 
    182   return r;
    183 }
    184 
    185 #if !defined(OS_NACL_NONSFI)
    186 // static
    187 ssize_t UnixDomainSocket::SendRecvMsg(int fd,
    188                                       uint8_t* reply,
    189                                       unsigned max_reply_len,
    190                                       int* result_fd,
    191                                       const Pickle& request) {
    192   return UnixDomainSocket::SendRecvMsgWithFlags(fd, reply, max_reply_len,
    193                                                 0,  /* recvmsg_flags */
    194                                                 result_fd, request);
    195 }
    196 
    197 // static
    198 ssize_t UnixDomainSocket::SendRecvMsgWithFlags(int fd,
    199                                                uint8_t* reply,
    200                                                unsigned max_reply_len,
    201                                                int recvmsg_flags,
    202                                                int* result_fd,
    203                                                const Pickle& request) {
    204   // This socketpair is only used for the IPC and is cleaned up before
    205   // returning.
    206   ScopedFD recv_sock, send_sock;
    207   if (!CreateSocketPair(&recv_sock, &send_sock))
    208     return -1;
    209 
    210   {
    211     std::vector<int> send_fds;
    212     send_fds.push_back(send_sock.get());
    213     if (!SendMsg(fd, request.data(), request.size(), send_fds))
    214       return -1;
    215   }
    216 
    217   // Close the sending end of the socket right away so that if our peer closes
    218   // it before sending a response (e.g., from exiting), RecvMsgWithFlags() will
    219   // return EOF instead of hanging.
    220   send_sock.reset();
    221 
    222   std::vector<ScopedFD> recv_fds;
    223   // When porting to OSX keep in mind it doesn't support MSG_NOSIGNAL, so the
    224   // sender might get a SIGPIPE.
    225   const ssize_t reply_len = RecvMsgWithFlags(
    226       recv_sock.get(), reply, max_reply_len, recvmsg_flags, &recv_fds, NULL);
    227   recv_sock.reset();
    228   if (reply_len == -1)
    229     return -1;
    230 
    231   // If we received more file descriptors than caller expected, then we treat
    232   // that as an error.
    233   if (recv_fds.size() > (result_fd != NULL ? 1 : 0)) {
    234     NOTREACHED();
    235     return -1;
    236   }
    237 
    238   if (result_fd)
    239     *result_fd = recv_fds.empty() ? -1 : recv_fds[0].release();
    240 
    241   return reply_len;
    242 }
    243 #endif  // !defined(OS_NACL_NONSFI)
    244 
    245 }  // namespace base
    246