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