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