1 /*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 #include "common/libs/fs/shared_fd.h"
17
18 #include <sys/types.h>
19 #include <sys/stat.h>
20 #include <sys/mman.h>
21 #include <sys/syscall.h>
22 #include <cstddef>
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <netinet/in.h>
26 #include <unistd.h>
27 #include <algorithm>
28 #include <vector>
29
30 #include "common/libs/glog/logging.h"
31 #include "common/libs/fs/shared_select.h"
32
33 // #define ENABLE_GCE_SHARED_FD_LOGGING 1
34
35 namespace {
36 using cvd::SharedFDSet;
37
MarkAll(const SharedFDSet & input,fd_set * dest,int * max_index)38 void MarkAll(const SharedFDSet& input, fd_set* dest, int* max_index) {
39 for (SharedFDSet::const_iterator it = input.begin(); it != input.end();
40 ++it) {
41 (*it)->Set(dest, max_index);
42 }
43 }
44
CheckMarked(fd_set * in_out_mask,SharedFDSet * in_out_set)45 void CheckMarked(fd_set* in_out_mask, SharedFDSet* in_out_set) {
46 if (!in_out_set) {
47 return;
48 }
49 SharedFDSet save;
50 save.swap(in_out_set);
51 for (SharedFDSet::iterator it = save.begin(); it != save.end(); ++it) {
52 if ((*it)->IsSet(in_out_mask)) {
53 in_out_set->Set(*it);
54 }
55 }
56 }
57
58 /*
59 * Android currently has host prebuilts of glibc 2.15 and 2.17, but
60 * memfd_create was only added in glibc 2.27. It was defined in Linux 3.17,
61 * so we consider it safe to use the low-level arbitrary syscall wrapper.
62 */
63 #ifndef __NR_memfd_create
64 # if defined(__x86_64__)
65 # define __NR_memfd_create 319
66 # elif defined(__i386__)
67 # define __NR_memfd_create 356
68 # elif defined(__aarch64__)
69 # define __NR_memfd_create 279
70 # else
71 /* No interest in other architectures. */
72 # error "Unknown architecture."
73 # endif
74 #endif
75
memfd_create_wrapper(const char * name,unsigned int flags)76 int memfd_create_wrapper(const char* name, unsigned int flags) {
77 #ifdef CUTTLEFISH_HOST
78 // TODO(schuffelen): Use memfd_create with a newer host libc.
79 return syscall(__NR_memfd_create, name, flags);
80 #else
81 return memfd_create(name, flags);
82 #endif
83 }
84
85 } // namespace
86
87 namespace cvd {
88
CopyFrom(FileInstance & in,size_t length)89 bool FileInstance::CopyFrom(FileInstance& in, size_t length) {
90 std::vector<char> buffer(8192);
91 while (length > 0) {
92 ssize_t num_read = in.Read(buffer.data(), std::min(buffer.size(), length));
93 length -= num_read;
94 if (num_read <= 0) {
95 return false;
96 }
97 if (Write(buffer.data(), num_read) != num_read) {
98 // The caller will have to log an appropriate message.
99 return false;
100 }
101 }
102 return true;
103 }
104
Close()105 void FileInstance::Close() {
106 std::stringstream message;
107 if (fd_ == -1) {
108 errno_ = EBADF;
109 } else if (close(fd_) == -1) {
110 errno_ = errno;
111 if (identity_.size()) {
112 message << __FUNCTION__ << ": " << identity_ << " failed (" << StrError() << ")";
113 std::string message_str = message.str();
114 Log(message_str.c_str());
115 }
116 } else {
117 if (identity_.size()) {
118 message << __FUNCTION__ << ": " << identity_ << "succeeded";
119 std::string message_str = message.str();
120 Log(message_str.c_str());
121 }
122 }
123 fd_ = -1;
124 }
125
IsSet(fd_set * in) const126 bool FileInstance::IsSet(fd_set* in) const {
127 if (IsOpen() && FD_ISSET(fd_, in)) {
128 return true;
129 }
130 return false;
131 }
132
133 #if ENABLE_GCE_SHARED_FD_LOGGING
Log(const char * message)134 void FileInstance::Log(const char* message) {
135 LOG(INFO) << message;
136 }
137 #else
Log(const char *)138 void FileInstance::Log(const char*) {}
139 #endif
140
Set(fd_set * dest,int * max_index) const141 void FileInstance::Set(fd_set* dest, int* max_index) const {
142 if (!IsOpen()) {
143 return;
144 }
145 if (fd_ >= *max_index) {
146 *max_index = fd_ + 1;
147 }
148 FD_SET(fd_, dest);
149 }
150
Select(SharedFDSet * read_set,SharedFDSet * write_set,SharedFDSet * error_set,struct timeval * timeout)151 int Select(SharedFDSet* read_set, SharedFDSet* write_set,
152 SharedFDSet* error_set, struct timeval* timeout) {
153 int max_index = 0;
154 fd_set readfds;
155 FD_ZERO(&readfds);
156 if (read_set) {
157 MarkAll(*read_set, &readfds, &max_index);
158 }
159 fd_set writefds;
160 FD_ZERO(&writefds);
161 if (write_set) {
162 MarkAll(*write_set, &writefds, &max_index);
163 }
164 fd_set errorfds;
165 FD_ZERO(&errorfds);
166 if (error_set) {
167 MarkAll(*error_set, &errorfds, &max_index);
168 }
169
170 int rval = TEMP_FAILURE_RETRY(
171 select(max_index, &readfds, &writefds, &errorfds, timeout));
172 FileInstance::Log("select\n");
173 CheckMarked(&readfds, read_set);
174 CheckMarked(&writefds, write_set);
175 CheckMarked(&errorfds, error_set);
176 return rval;
177 }
178
MakeAddress(const char * name,bool abstract,struct sockaddr_un * dest,socklen_t * len)179 static void MakeAddress(const char* name, bool abstract,
180 struct sockaddr_un* dest, socklen_t* len) {
181 memset(dest, 0, sizeof(*dest));
182 dest->sun_family = AF_UNIX;
183 // sun_path is NOT expected to be nul-terminated.
184 // See man 7 unix.
185 size_t namelen;
186 if (abstract) {
187 // ANDROID_SOCKET_NAMESPACE_ABSTRACT
188 namelen = strlen(name);
189 CHECK_LE(namelen, sizeof(dest->sun_path) - 1)
190 << "MakeAddress failed. Name=" << name << " is longer than allowed.";
191 dest->sun_path[0] = 0;
192 memcpy(dest->sun_path + 1, name, namelen);
193 } else {
194 // ANDROID_SOCKET_NAMESPACE_RESERVED
195 // ANDROID_SOCKET_NAMESPACE_FILESYSTEM
196 // TODO(pinghao): Distinguish between them?
197 namelen = strlen(name);
198 CHECK_LE(namelen, sizeof(dest->sun_path))
199 << "MakeAddress failed. Name=" << name << " is longer than allowed.";
200 strncpy(dest->sun_path, name, strlen(name));
201 }
202 *len = namelen + offsetof(struct sockaddr_un, sun_path) + 1;
203 }
204
Accept(const FileInstance & listener,struct sockaddr * addr,socklen_t * addrlen)205 SharedFD SharedFD::Accept(const FileInstance& listener, struct sockaddr* addr,
206 socklen_t* addrlen) {
207 return SharedFD(
208 std::shared_ptr<FileInstance>(listener.Accept(addr, addrlen)));
209 }
210
Accept(const FileInstance & listener)211 SharedFD SharedFD::Accept(const FileInstance& listener) {
212 return SharedFD::Accept(listener, NULL, NULL);
213 }
214
Dup(int unmanaged_fd)215 SharedFD SharedFD::Dup(int unmanaged_fd) {
216 int fd = fcntl(unmanaged_fd, F_DUPFD_CLOEXEC, 3);
217 int error_num = errno;
218 return SharedFD(std::shared_ptr<FileInstance>(new FileInstance(fd, error_num)));
219 }
220
Pipe(SharedFD * fd0,SharedFD * fd1)221 bool SharedFD::Pipe(SharedFD* fd0, SharedFD* fd1) {
222 int fds[2];
223 int rval = pipe(fds);
224 if (rval != -1) {
225 (*fd0) = std::shared_ptr<FileInstance>(new FileInstance(fds[0], errno));
226 (*fd1) = std::shared_ptr<FileInstance>(new FileInstance(fds[1], errno));
227 return true;
228 }
229 return false;
230 }
231
Event(int initval,int flags)232 SharedFD SharedFD::Event(int initval, int flags) {
233 int fd = eventfd(initval, flags);
234 return std::shared_ptr<FileInstance>(new FileInstance(fd, errno));
235 }
236
MemfdCreate(const std::string & name,unsigned int flags)237 SharedFD SharedFD::MemfdCreate(const std::string& name, unsigned int flags) {
238 int fd = memfd_create_wrapper(name.c_str(), flags);
239 int error_num = errno;
240 return std::shared_ptr<FileInstance>(new FileInstance(fd, error_num));
241 }
242
SocketPair(int domain,int type,int protocol,SharedFD * fd0,SharedFD * fd1)243 bool SharedFD::SocketPair(int domain, int type, int protocol,
244 SharedFD* fd0, SharedFD* fd1) {
245 int fds[2];
246 int rval = socketpair(domain, type, protocol, fds);
247 if (rval != -1) {
248 (*fd0) = std::shared_ptr<FileInstance>(new FileInstance(fds[0], errno));
249 (*fd1) = std::shared_ptr<FileInstance>(new FileInstance(fds[1], errno));
250 return true;
251 }
252 return false;
253 }
254
Open(const std::string & path,int flags,mode_t mode)255 SharedFD SharedFD::Open(const std::string& path, int flags, mode_t mode) {
256 int fd = TEMP_FAILURE_RETRY(open(path.c_str(), flags, mode));
257 if (fd == -1) {
258 return SharedFD(std::shared_ptr<FileInstance>(new FileInstance(fd, errno)));
259 } else {
260 return SharedFD(std::shared_ptr<FileInstance>(new FileInstance(fd, 0)));
261 }
262 }
263
Creat(const std::string & path,mode_t mode)264 SharedFD SharedFD::Creat(const std::string& path, mode_t mode) {
265 return SharedFD::Open(path, O_CREAT|O_WRONLY|O_TRUNC, mode);
266 }
267
Socket(int domain,int socket_type,int protocol)268 SharedFD SharedFD::Socket(int domain, int socket_type, int protocol) {
269 int fd = TEMP_FAILURE_RETRY(socket(domain, socket_type, protocol));
270 if (fd == -1) {
271 return SharedFD(std::shared_ptr<FileInstance>(new FileInstance(fd, errno)));
272 } else {
273 return SharedFD(std::shared_ptr<FileInstance>(new FileInstance(fd, 0)));
274 }
275 }
276
ErrorFD(int error)277 SharedFD SharedFD::ErrorFD(int error) {
278 return SharedFD(std::shared_ptr<FileInstance>(new FileInstance(-1, error)));
279 }
280
SocketLocalClient(const std::string & name,bool abstract,int in_type)281 SharedFD SharedFD::SocketLocalClient(const std::string& name, bool abstract,
282 int in_type) {
283 struct sockaddr_un addr;
284 socklen_t addrlen;
285 MakeAddress(name.c_str(), abstract, &addr, &addrlen);
286 SharedFD rval = SharedFD::Socket(PF_UNIX, in_type, 0);
287 if (!rval->IsOpen()) {
288 return rval;
289 }
290 if (rval->Connect(reinterpret_cast<sockaddr*>(&addr), addrlen) == -1) {
291 return SharedFD::ErrorFD(rval->GetErrno());
292 }
293 return rval;
294 }
295
SocketLocalClient(int port,int type)296 SharedFD SharedFD::SocketLocalClient(int port, int type) {
297 sockaddr_in addr{};
298 addr.sin_family = AF_INET;
299 addr.sin_port = htons(port);
300 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
301 SharedFD rval = SharedFD::Socket(AF_INET, type, 0);
302 if (!rval->IsOpen()) {
303 return rval;
304 }
305 if (rval->Connect(reinterpret_cast<const sockaddr*>(&addr),
306 sizeof addr) < 0) {
307 return SharedFD::ErrorFD(rval->GetErrno());
308 }
309 return rval;
310 }
311
SocketLocalServer(int port,int type)312 SharedFD SharedFD::SocketLocalServer(int port, int type) {
313 struct sockaddr_in addr;
314 memset(&addr, 0, sizeof(addr));
315 addr.sin_family = AF_INET;
316 addr.sin_port = htons(port);
317 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
318 SharedFD rval = SharedFD::Socket(AF_INET, type, 0);
319 if(!rval->IsOpen()) {
320 return rval;
321 }
322 int n = 1;
323 if (rval->SetSockOpt(SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1) {
324 LOG(ERROR) << "SetSockOpt failed " << rval->StrError();
325 return SharedFD::ErrorFD(rval->GetErrno());
326 }
327 if(rval->Bind(reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) < 0) {
328 LOG(ERROR) << "Bind failed " << rval->StrError();
329 return SharedFD::ErrorFD(rval->GetErrno());
330 }
331 if (type == SOCK_STREAM) {
332 if (rval->Listen(4) < 0) {
333 LOG(ERROR) << "Listen failed " << rval->StrError();
334 return SharedFD::ErrorFD(rval->GetErrno());
335 }
336 }
337 return rval;
338 }
339
SocketLocalServer(const std::string & name,bool abstract,int in_type,mode_t mode)340 SharedFD SharedFD::SocketLocalServer(const std::string& name, bool abstract,
341 int in_type, mode_t mode) {
342 // DO NOT UNLINK addr.sun_path. It does NOT have to be null-terminated.
343 // See man 7 unix for more details.
344 if (!abstract) (void)unlink(name.c_str());
345
346 struct sockaddr_un addr;
347 socklen_t addrlen;
348 MakeAddress(name.c_str(), abstract, &addr, &addrlen);
349 SharedFD rval = SharedFD::Socket(PF_UNIX, in_type, 0);
350 if (!rval->IsOpen()) {
351 return rval;
352 }
353
354 int n = 1;
355 if (rval->SetSockOpt(SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1) {
356 LOG(ERROR) << "SetSockOpt failed " << rval->StrError();
357 return SharedFD::ErrorFD(rval->GetErrno());
358 }
359 if (rval->Bind(reinterpret_cast<sockaddr*>(&addr), addrlen) == -1) {
360 LOG(ERROR) << "Bind failed; name=" << name << ": " << rval->StrError();
361 return SharedFD::ErrorFD(rval->GetErrno());
362 }
363
364 /* Only the bottom bits are really the socket type; there are flags too. */
365 constexpr int SOCK_TYPE_MASK = 0xf;
366
367 // Connection oriented sockets: start listening.
368 if ((in_type & SOCK_TYPE_MASK) == SOCK_STREAM) {
369 // Follows the default from socket_local_server
370 if (rval->Listen(1) == -1) {
371 LOG(ERROR) << "Listen failed: " << rval->StrError();
372 return SharedFD::ErrorFD(rval->GetErrno());
373 }
374 }
375
376 if (!abstract) {
377 if (TEMP_FAILURE_RETRY(chmod(name.c_str(), mode)) == -1) {
378 LOG(ERROR) << "chmod failed: " << strerror(errno);
379 // However, continue since we do have a listening socket
380 }
381 }
382 return rval;
383 }
384
VsockServer(unsigned int port,int type)385 SharedFD SharedFD::VsockServer(unsigned int port, int type) {
386 auto vsock = cvd::SharedFD::Socket(AF_VSOCK, type, 0);
387 if (!vsock->IsOpen()) {
388 return vsock;
389 }
390 sockaddr_vm addr{};
391 addr.svm_family = AF_VSOCK;
392 addr.svm_port = port;
393 addr.svm_cid = VMADDR_CID_ANY;
394 auto casted_addr = reinterpret_cast<sockaddr*>(&addr);
395 if (vsock->Bind(casted_addr, sizeof(addr)) == -1) {
396 LOG(ERROR) << "Bind failed (" << vsock->StrError() << ")";
397 return SharedFD::ErrorFD(vsock->GetErrno());
398 }
399 if (type == SOCK_STREAM) {
400 if (vsock->Listen(4) < 0) {
401 LOG(ERROR) << "Listen failed (" << vsock->StrError() << ")";
402 return SharedFD::ErrorFD(vsock->GetErrno());
403 }
404 }
405 return vsock;
406 }
407
VsockServer(int type)408 SharedFD SharedFD::VsockServer(int type) {
409 return VsockServer(VMADDR_PORT_ANY, type);
410 }
411
VsockClient(unsigned int cid,unsigned int port,int type)412 SharedFD SharedFD::VsockClient(unsigned int cid, unsigned int port, int type) {
413 auto vsock = cvd::SharedFD::Socket(AF_VSOCK, type, 0);
414 if (!vsock->IsOpen()) {
415 return vsock;
416 }
417 sockaddr_vm addr{};
418 addr.svm_family = AF_VSOCK;
419 addr.svm_port = port;
420 addr.svm_cid = cid;
421 auto casted_addr = reinterpret_cast<sockaddr*>(&addr);
422 if (vsock->Connect(casted_addr, sizeof(addr)) == -1) {
423 return SharedFD::ErrorFD(vsock->GetErrno());
424 }
425 return vsock;
426 }
427
428 } // namespace cvd
429