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 <arpa/inet.h>
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <net/if.h>
22 #include <netinet/in.h>
23 #include <poll.h>
24 #include <sys/file.h>
25 #include <sys/mman.h>
26 #include <sys/stat.h>
27 #include <sys/syscall.h>
28 #include <sys/types.h>
29 #include <unistd.h>
30 #include <cstddef>
31
32 #include <algorithm>
33 #include <sstream>
34 #include <vector>
35
36 #include <android-base/file.h>
37 #include <android-base/logging.h>
38
39 #include "common/libs/fs/shared_buf.h"
40 #include "common/libs/fs/shared_select.h"
41 #include "common/libs/utils/result.h"
42
43 // #define ENABLE_GCE_SHARED_FD_LOGGING 1
44
45 namespace cuttlefish {
46
47 namespace {
48
MarkAll(const SharedFDSet & input,fd_set * dest,int * max_index)49 void MarkAll(const SharedFDSet& input, fd_set* dest, int* max_index) {
50 for (SharedFDSet::const_iterator it = input.begin(); it != input.end();
51 ++it) {
52 (*it)->Set(dest, max_index);
53 }
54 }
55
CheckMarked(fd_set * in_out_mask,SharedFDSet * in_out_set)56 void CheckMarked(fd_set* in_out_mask, SharedFDSet* in_out_set) {
57 if (!in_out_set) {
58 return;
59 }
60 SharedFDSet save;
61 save.swap(in_out_set);
62 for (SharedFDSet::iterator it = save.begin(); it != save.end(); ++it) {
63 if ((*it)->IsSet(in_out_mask)) {
64 in_out_set->Set(*it);
65 }
66 }
67 }
68
69 /*
70 * Android currently has host prebuilts of glibc 2.15 and 2.17, but
71 * memfd_create was only added in glibc 2.27. It was defined in Linux 3.17,
72 * so we consider it safe to use the low-level arbitrary syscall wrapper.
73 */
74 #ifndef __NR_memfd_create
75 # if defined(__x86_64__)
76 # define __NR_memfd_create 319
77 # elif defined(__i386__)
78 # define __NR_memfd_create 356
79 # elif defined(__aarch64__)
80 # define __NR_memfd_create 279
81 # else
82 /* No interest in other architectures. */
83 # error "Unknown architecture."
84 # endif
85 #endif
86
memfd_create_wrapper(const char * name,unsigned int flags)87 int memfd_create_wrapper(const char* name, unsigned int flags) {
88 #ifdef __linux__
89 #ifdef CUTTLEFISH_HOST
90 // TODO(schuffelen): Use memfd_create with a newer host libc.
91 return syscall(__NR_memfd_create, name, flags);
92 #else
93 return memfd_create(name, flags);
94 #endif
95 #else
96 (void)flags;
97 return shm_open(name, O_RDWR);
98 #endif
99 }
100
IsRegularFile(const int fd)101 bool IsRegularFile(const int fd) {
102 struct stat info;
103 if (fstat(fd, &info) < 0) {
104 return false;
105 }
106 return S_ISREG(info.st_mode);
107 }
108
109 constexpr size_t kPreferredBufferSize = 8192;
110
111 } // namespace
112
CopyFrom(FileInstance & in,size_t length,FileInstance * stop)113 bool FileInstance::CopyFrom(FileInstance& in, size_t length, FileInstance* stop) {
114 std::vector<char> buffer(kPreferredBufferSize);
115 while (length > 0) {
116 int nfds = stop == nullptr ? 2 : 3;
117 // Wait until either in becomes readable or our fd closes.
118 constexpr ssize_t IN = 0;
119 constexpr ssize_t OUT = 1;
120 constexpr ssize_t STOP = 2;
121 struct pollfd pollfds[3];
122 pollfds[IN].fd = in.fd_;
123 pollfds[IN].events = POLLIN;
124 pollfds[IN].revents = 0;
125 pollfds[OUT].fd = fd_;
126 pollfds[OUT].events = 0;
127 pollfds[OUT].revents = 0;
128 if (stop) {
129 pollfds[STOP].fd = stop->fd_;
130 pollfds[STOP].events = POLLIN;
131 pollfds[STOP].revents = 0;
132 }
133 int res = poll(pollfds, nfds, -1 /* indefinitely */);
134 if (res < 0) {
135 errno_ = errno;
136 return false;
137 }
138 if (stop && pollfds[STOP].revents & POLLIN) {
139 return false;
140 }
141 if (pollfds[OUT].revents != 0) {
142 // destination was either closed, invalid or errored, either way there is no
143 // point in continuing.
144 return false;
145 }
146
147 ssize_t num_read = in.Read(buffer.data(), std::min(buffer.size(), length));
148 if (num_read <= 0) {
149 return false;
150 }
151 length -= num_read;
152
153 ssize_t written = 0;
154 do {
155 // No need to use poll for writes: even if the source closes, the data
156 // needs to be delivered to the other side.
157 auto res = Write(buffer.data(), num_read);
158 if (res <= 0) {
159 // The caller will have to log an appropriate message.
160 return false;
161 }
162 written += res;
163 } while(written < num_read);
164 }
165 return true;
166 }
167
CopyAllFrom(FileInstance & in,FileInstance * stop)168 bool FileInstance::CopyAllFrom(FileInstance& in, FileInstance* stop) {
169 // FileInstance may have been constructed with a non-zero errno_ value because
170 // the errno variable is not zeroed out before.
171 errno_ = 0;
172 in.errno_ = 0;
173 while (CopyFrom(in, kPreferredBufferSize, stop)) {
174 }
175 // Only return false if there was an actual error.
176 return !GetErrno() && !in.GetErrno();
177 }
178
Close()179 void FileInstance::Close() {
180 std::stringstream message;
181 if (fd_ == -1) {
182 errno_ = EBADF;
183 } else if (close(fd_) == -1) {
184 errno_ = errno;
185 if (identity_.size()) {
186 message << __FUNCTION__ << ": " << identity_ << " failed (" << StrError() << ")";
187 std::string message_str = message.str();
188 Log(message_str.c_str());
189 }
190 } else {
191 if (identity_.size()) {
192 message << __FUNCTION__ << ": " << identity_ << "succeeded";
193 std::string message_str = message.str();
194 Log(message_str.c_str());
195 }
196 }
197 fd_ = -1;
198 }
199
Chmod(mode_t mode)200 bool FileInstance::Chmod(mode_t mode) {
201 int original_error = errno;
202 int ret = fchmod(fd_, mode);
203 if (ret != 0) {
204 errno_ = errno;
205 }
206 errno = original_error;
207 return ret == 0;
208 }
209
ConnectWithTimeout(const struct sockaddr * addr,socklen_t addrlen,struct timeval * timeout)210 int FileInstance::ConnectWithTimeout(const struct sockaddr* addr,
211 socklen_t addrlen,
212 struct timeval* timeout) {
213 int original_flags = Fcntl(F_GETFL, 0);
214 if (original_flags == -1) {
215 LOG(ERROR) << "Could not get current file descriptor flags: " << StrError();
216 return -1;
217 }
218 if (Fcntl(F_SETFL, original_flags | O_NONBLOCK) == -1) {
219 LOG(ERROR) << "Failed to set O_NONBLOCK: " << StrError();
220 return -1;
221 }
222
223 auto connect_res = Connect(
224 addr, addrlen); // This will return immediately because of O_NONBLOCK
225
226 if (connect_res == 0) { // Immediate success
227 if (Fcntl(F_SETFL, original_flags) == -1) {
228 LOG(ERROR) << "Failed to restore original flags: " << StrError();
229 return -1;
230 }
231 return 0;
232 }
233
234 if (GetErrno() != EAGAIN && GetErrno() != EINPROGRESS) {
235 LOG(DEBUG) << "Immediate connection failure: " << StrError();
236 if (Fcntl(F_SETFL, original_flags) == -1) {
237 LOG(ERROR) << "Failed to restore original flags: " << StrError();
238 }
239 return -1;
240 }
241
242 fd_set fdset;
243 FD_ZERO(&fdset);
244 FD_SET(fd_, &fdset);
245
246 int select_res = select(fd_ + 1, nullptr, &fdset, nullptr, timeout);
247
248 if (Fcntl(F_SETFL, original_flags) == -1) {
249 LOG(ERROR) << "Failed to restore original flags: " << StrError();
250 return -1;
251 }
252
253 if (select_res != 1) {
254 LOG(ERROR) << "Did not connect within the timeout";
255 return -1;
256 }
257
258 int so_error;
259 socklen_t len = sizeof(so_error);
260 if (GetSockOpt(SOL_SOCKET, SO_ERROR, &so_error, &len) == -1) {
261 LOG(ERROR) << "Failed to get socket options: " << StrError();
262 return -1;
263 }
264
265 if (so_error != 0) {
266 LOG(ERROR) << "Failure in opening socket: " << so_error;
267 errno_ = so_error;
268 return -1;
269 }
270 errno_ = 0;
271 return 0;
272 }
273
IsSet(fd_set * in) const274 bool FileInstance::IsSet(fd_set* in) const {
275 if (IsOpen() && FD_ISSET(fd_, in)) {
276 return true;
277 }
278 return false;
279 }
280
281 #if ENABLE_GCE_SHARED_FD_LOGGING
Log(const char * message)282 void FileInstance::Log(const char* message) {
283 LOG(INFO) << message;
284 }
285 #else
Log(const char *)286 void FileInstance::Log(const char*) {}
287 #endif
288
Set(fd_set * dest,int * max_index) const289 void FileInstance::Set(fd_set* dest, int* max_index) const {
290 if (!IsOpen()) {
291 return;
292 }
293 if (fd_ >= *max_index) {
294 *max_index = fd_ + 1;
295 }
296 FD_SET(fd_, dest);
297 }
298
Select(SharedFDSet * read_set,SharedFDSet * write_set,SharedFDSet * error_set,struct timeval * timeout)299 int Select(SharedFDSet* read_set, SharedFDSet* write_set,
300 SharedFDSet* error_set, struct timeval* timeout) {
301 int max_index = 0;
302 fd_set readfds;
303 FD_ZERO(&readfds);
304 if (read_set) {
305 MarkAll(*read_set, &readfds, &max_index);
306 }
307 fd_set writefds;
308 FD_ZERO(&writefds);
309 if (write_set) {
310 MarkAll(*write_set, &writefds, &max_index);
311 }
312 fd_set errorfds;
313 FD_ZERO(&errorfds);
314 if (error_set) {
315 MarkAll(*error_set, &errorfds, &max_index);
316 }
317
318 int rval = TEMP_FAILURE_RETRY(
319 select(max_index, &readfds, &writefds, &errorfds, timeout));
320 FileInstance::Log("select\n");
321 CheckMarked(&readfds, read_set);
322 CheckMarked(&writefds, write_set);
323 CheckMarked(&errorfds, error_set);
324 return rval;
325 }
326
SharedFD(SharedFD && other)327 SharedFD::SharedFD(SharedFD&& other) {
328 value_ = std::move(other.value_);
329 other.value_.reset(new FileInstance(-1, EBADF));
330 }
331
operator =(SharedFD && other)332 SharedFD& SharedFD::operator=(SharedFD&& other) {
333 value_ = std::move(other.value_);
334 other.value_.reset(new FileInstance(-1, EBADF));
335 return *this;
336 }
337
Poll(std::vector<PollSharedFd> & fds,int timeout)338 int SharedFD::Poll(std::vector<PollSharedFd>& fds, int timeout) {
339 return Poll(fds.data(), fds.size(), timeout);
340 }
341
Poll(PollSharedFd * fds,size_t num_fds,int timeout)342 int SharedFD::Poll(PollSharedFd* fds, size_t num_fds, int timeout) {
343 std::vector<pollfd> native_pollfds(num_fds);
344 for (size_t i = 0; i < num_fds; i++) {
345 native_pollfds[i].fd = fds[i].fd->fd_;
346 native_pollfds[i].events = fds[i].events;
347 native_pollfds[i].revents = 0;
348 }
349 int ret = poll(native_pollfds.data(), native_pollfds.size(), timeout);
350 for (size_t i = 0; i < num_fds; i++) {
351 fds[i].revents = native_pollfds[i].revents;
352 }
353 return ret;
354 }
355
MakeAddress(const char * name,bool abstract,struct sockaddr_un * dest,socklen_t * len)356 static void MakeAddress(const char* name, bool abstract,
357 struct sockaddr_un* dest, socklen_t* len) {
358 memset(dest, 0, sizeof(*dest));
359 dest->sun_family = AF_UNIX;
360 // sun_path is NOT expected to be nul-terminated.
361 // See man 7 unix.
362 size_t namelen;
363 if (abstract) {
364 // ANDROID_SOCKET_NAMESPACE_ABSTRACT
365 namelen = strlen(name);
366 CHECK_LE(namelen, sizeof(dest->sun_path) - 1)
367 << "MakeAddress failed. Name=" << name << " is longer than allowed.";
368 dest->sun_path[0] = 0;
369 memcpy(dest->sun_path + 1, name, namelen);
370 } else {
371 // ANDROID_SOCKET_NAMESPACE_RESERVED
372 // ANDROID_SOCKET_NAMESPACE_FILESYSTEM
373 // TODO(pinghao): Distinguish between them?
374 namelen = strlen(name);
375 CHECK_LE(namelen, sizeof(dest->sun_path))
376 << "MakeAddress failed. Name=" << name << " is longer than allowed.";
377 strncpy(dest->sun_path, name, strlen(name));
378 }
379 *len = namelen + offsetof(struct sockaddr_un, sun_path) + 1;
380 }
381
Accept(const FileInstance & listener,struct sockaddr * addr,socklen_t * addrlen)382 SharedFD SharedFD::Accept(const FileInstance& listener, struct sockaddr* addr,
383 socklen_t* addrlen) {
384 return SharedFD(
385 std::shared_ptr<FileInstance>(listener.Accept(addr, addrlen)));
386 }
387
Accept(const FileInstance & listener)388 SharedFD SharedFD::Accept(const FileInstance& listener) {
389 return SharedFD::Accept(listener, NULL, NULL);
390 }
391
Dup(int unmanaged_fd)392 SharedFD SharedFD::Dup(int unmanaged_fd) {
393 int fd = fcntl(unmanaged_fd, F_DUPFD_CLOEXEC, 3);
394 int error_num = errno;
395 return SharedFD(std::shared_ptr<FileInstance>(new FileInstance(fd, error_num)));
396 }
397
Pipe(SharedFD * fd0,SharedFD * fd1)398 bool SharedFD::Pipe(SharedFD* fd0, SharedFD* fd1) {
399 int fds[2];
400 #ifdef __linux__
401 int rval = pipe2(fds, O_CLOEXEC);
402 #else
403 int rval = pipe(fds);
404 #endif
405 if (rval != -1) {
406 (*fd0) = std::shared_ptr<FileInstance>(new FileInstance(fds[0], errno));
407 (*fd1) = std::shared_ptr<FileInstance>(new FileInstance(fds[1], errno));
408 return true;
409 }
410 return false;
411 }
412
413 #ifdef __linux__
Event(int initval,int flags)414 SharedFD SharedFD::Event(int initval, int flags) {
415 int fd = eventfd(initval, flags);
416 return std::shared_ptr<FileInstance>(new FileInstance(fd, errno));
417 }
418 #endif
419
MemfdCreate(const std::string & name,unsigned int flags)420 SharedFD SharedFD::MemfdCreate(const std::string& name, unsigned int flags) {
421 int fd = memfd_create_wrapper(name.c_str(), flags);
422 int error_num = errno;
423 return std::shared_ptr<FileInstance>(new FileInstance(fd, error_num));
424 }
425
MemfdCreateWithData(const std::string & name,const std::string & data,unsigned int flags)426 SharedFD SharedFD::MemfdCreateWithData(const std::string& name, const std::string& data, unsigned int flags) {
427 auto memfd = MemfdCreate(name, flags);
428 if (WriteAll(memfd, data) != data.size()) {
429 return ErrorFD(errno);
430 }
431 if (memfd->LSeek(0, SEEK_SET) != 0) {
432 return ErrorFD(memfd->GetErrno());
433 }
434 if (!memfd->Chmod(0700)) {
435 return ErrorFD(memfd->GetErrno());
436 }
437 return memfd;
438 }
439
SocketPair(int domain,int type,int protocol,SharedFD * fd0,SharedFD * fd1)440 bool SharedFD::SocketPair(int domain, int type, int protocol,
441 SharedFD* fd0, SharedFD* fd1) {
442 int fds[2];
443 int rval = socketpair(domain, type, protocol, fds);
444 if (rval != -1) {
445 (*fd0) = std::shared_ptr<FileInstance>(new FileInstance(fds[0], errno));
446 (*fd1) = std::shared_ptr<FileInstance>(new FileInstance(fds[1], errno));
447 return true;
448 }
449 return false;
450 }
451
SocketPair(int domain,int type,int protocol)452 Result<std::pair<SharedFD, SharedFD>> SharedFD::SocketPair(int domain, int type,
453 int protocol) {
454 SharedFD a, b;
455 if (!SharedFD::SocketPair(domain, type, protocol, &a, &b)) {
456 return CF_ERR("socketpair failed: " << strerror(errno));
457 }
458 return std::make_pair(std::move(a), std::move(b));
459 }
460
Open(const std::string & path,int flags,mode_t mode)461 SharedFD SharedFD::Open(const std::string& path, int flags, mode_t mode) {
462 return Open(path.c_str(), flags, mode);
463 }
464
Open(const char * path,int flags,mode_t mode)465 SharedFD SharedFD::Open(const char* path, int flags, mode_t mode) {
466 int fd = TEMP_FAILURE_RETRY(open(path, flags, mode));
467 if (fd == -1) {
468 return SharedFD(std::shared_ptr<FileInstance>(new FileInstance(fd, errno)));
469 } else {
470 return SharedFD(std::shared_ptr<FileInstance>(new FileInstance(fd, 0)));
471 }
472 }
473
InotifyFd(void)474 SharedFD SharedFD::InotifyFd(void) {
475 errno = 0;
476 int fd = TEMP_FAILURE_RETRY(inotify_init1(IN_CLOEXEC));
477 return SharedFD(std::shared_ptr<FileInstance>(new FileInstance(fd, errno)));
478 }
479
Creat(const std::string & path,mode_t mode)480 SharedFD SharedFD::Creat(const std::string& path, mode_t mode) {
481 return SharedFD::Open(path, O_CREAT|O_WRONLY|O_TRUNC, mode);
482 }
483
Fchdir(SharedFD shared_fd)484 int SharedFD::Fchdir(SharedFD shared_fd) {
485 if (!shared_fd.value_) {
486 return -1;
487 }
488 errno = 0;
489 int rval = TEMP_FAILURE_RETRY(fchdir(shared_fd->fd_));
490 shared_fd->errno_ = errno;
491 return rval;
492 }
493
Fifo(const std::string & path,mode_t mode)494 Result<SharedFD> SharedFD::Fifo(const std::string& path, mode_t mode) {
495 struct stat st {};
496 if (TEMP_FAILURE_RETRY(stat(path.c_str(), &st)) == 0) {
497 CF_EXPECTF(TEMP_FAILURE_RETRY(remove(path.c_str())) == 0,
498 "Failed to delete old file at '{}': '{}'", path,
499 strerror(errno));
500 }
501
502 CF_EXPECTF(TEMP_FAILURE_RETRY(mkfifo(path.c_str(), mode)) == 0,
503 "Failed to mkfifo('{}', {:o})", path, mode);
504 auto ret = Open(path, O_RDWR);
505 CF_EXPECTF(ret->IsOpen(), "Failed to open '{}': '{}'", path, ret->StrError());
506 return ret;
507 }
508
Socket(int domain,int socket_type,int protocol)509 SharedFD SharedFD::Socket(int domain, int socket_type, int protocol) {
510 int fd = TEMP_FAILURE_RETRY(socket(domain, socket_type, protocol));
511 if (fd == -1) {
512 return SharedFD(std::shared_ptr<FileInstance>(new FileInstance(fd, errno)));
513 } else {
514 return SharedFD(std::shared_ptr<FileInstance>(new FileInstance(fd, 0)));
515 }
516 }
517
Mkstemp(std::string * path)518 SharedFD SharedFD::Mkstemp(std::string* path) {
519 int fd = mkstemp(path->data());
520 if (fd == -1) {
521 return SharedFD(std::shared_ptr<FileInstance>(new FileInstance(fd, errno)));
522 } else {
523 return SharedFD(std::shared_ptr<FileInstance>(new FileInstance(fd, 0)));
524 }
525 }
526
ErrorFD(int error)527 SharedFD SharedFD::ErrorFD(int error) {
528 return SharedFD(std::shared_ptr<FileInstance>(new FileInstance(-1, error)));
529 }
530
SocketLocalClient(const std::string & name,bool abstract,int in_type)531 SharedFD SharedFD::SocketLocalClient(const std::string& name, bool abstract,
532 int in_type) {
533 return SocketLocalClient(name, abstract, in_type, 0);
534 }
535
SocketLocalClient(const std::string & name,bool abstract,int in_type,int timeout_seconds)536 SharedFD SharedFD::SocketLocalClient(const std::string& name, bool abstract,
537 int in_type, int timeout_seconds) {
538 struct sockaddr_un addr;
539 socklen_t addrlen;
540 MakeAddress(name.c_str(), abstract, &addr, &addrlen);
541 SharedFD rval = SharedFD::Socket(PF_UNIX, in_type, 0);
542 if (!rval->IsOpen()) {
543 return rval;
544 }
545 struct timeval timeout = {timeout_seconds, 0};
546 auto casted_addr = reinterpret_cast<sockaddr*>(&addr);
547 if (rval->ConnectWithTimeout(casted_addr, addrlen, &timeout) == -1) {
548 return SharedFD::ErrorFD(rval->GetErrno());
549 }
550 return rval;
551 }
552
SocketLocalClient(int port,int type)553 SharedFD SharedFD::SocketLocalClient(int port, int type) {
554 sockaddr_in addr{};
555 addr.sin_family = AF_INET;
556 addr.sin_port = htons(port);
557 addr.sin_addr.s_addr = htonl(INADDR_ANY);
558 auto rval = SharedFD::Socket(AF_INET, type, 0);
559 if (!rval->IsOpen()) {
560 return rval;
561 }
562 if (rval->Connect(reinterpret_cast<const sockaddr*>(&addr), sizeof addr) < 0) {
563 return SharedFD::ErrorFD(rval->GetErrno());
564 }
565 return rval;
566 }
567
SocketClient(const std::string & host,int port,int type,std::chrono::seconds timeout)568 SharedFD SharedFD::SocketClient(const std::string& host, int port, int type,
569 std::chrono::seconds timeout) {
570 sockaddr_in addr{};
571 addr.sin_family = AF_INET;
572 addr.sin_port = htons(port);
573 addr.sin_addr.s_addr = inet_addr(host.c_str());
574 auto rval = SharedFD::Socket(AF_INET, type, 0);
575 if (!rval->IsOpen()) {
576 return rval;
577 }
578 struct timeval timeout_timeval = {static_cast<time_t>(timeout.count()), 0};
579 if (rval->ConnectWithTimeout(reinterpret_cast<const sockaddr*>(&addr),
580 sizeof addr, &timeout_timeval) < 0) {
581 return SharedFD::ErrorFD(rval->GetErrno());
582 }
583 return rval;
584 }
585
Socket6Client(const std::string & host,const std::string & interface,int port,int type,std::chrono::seconds timeout)586 SharedFD SharedFD::Socket6Client(const std::string& host, const std::string& interface,
587 int port, int type, std::chrono::seconds timeout) {
588 sockaddr_in6 addr{};
589 addr.sin6_family = AF_INET6;
590 addr.sin6_port = htons(port);
591 inet_pton(AF_INET6, host.c_str(), &addr.sin6_addr);
592 auto rval = SharedFD::Socket(AF_INET6, type, 0);
593 if (!rval->IsOpen()) {
594 return rval;
595 }
596
597 if (!interface.empty()) {
598 #ifdef __linux__
599 ifreq ifr{};
600 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s", interface.c_str());
601
602 if (rval->SetSockOpt(SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof(ifr)) == -1) {
603 return SharedFD::ErrorFD(rval->GetErrno());
604 }
605 #elif defined(__APPLE__)
606 int idx = if_nametoindex(interface.c_str());
607 if (rval->SetSockOpt(IPPROTO_IP, IP_BOUND_IF, &idx, sizeof(idx)) == -1) {
608 return SharedFD::ErrorFD(rval->GetErrno());
609 }
610 #else
611 #error "Unsupported operating system"
612 #endif
613 }
614
615 struct timeval timeout_timeval = {static_cast<time_t>(timeout.count()), 0};
616 if (rval->ConnectWithTimeout(reinterpret_cast<const sockaddr*>(&addr),
617 sizeof addr, &timeout_timeval) < 0) {
618 return SharedFD::ErrorFD(rval->GetErrno());
619 }
620 return rval;
621 }
622
SocketLocalServer(int port,int type)623 SharedFD SharedFD::SocketLocalServer(int port, int type) {
624 struct sockaddr_in addr;
625 memset(&addr, 0, sizeof(addr));
626 addr.sin_family = AF_INET;
627 addr.sin_port = htons(port);
628 addr.sin_addr.s_addr = htonl(INADDR_ANY);
629 SharedFD rval = SharedFD::Socket(AF_INET, type, 0);
630 if(!rval->IsOpen()) {
631 return rval;
632 }
633 int n = 1;
634 if (rval->SetSockOpt(SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1) {
635 LOG(ERROR) << "SetSockOpt failed " << rval->StrError();
636 return SharedFD::ErrorFD(rval->GetErrno());
637 }
638 if(rval->Bind(reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) < 0) {
639 LOG(ERROR) << "Bind failed " << rval->StrError();
640 return SharedFD::ErrorFD(rval->GetErrno());
641 }
642 if (type == SOCK_STREAM || type == SOCK_SEQPACKET) {
643 if (rval->Listen(4) < 0) {
644 LOG(ERROR) << "Listen failed " << rval->StrError();
645 return SharedFD::ErrorFD(rval->GetErrno());
646 }
647 }
648 return rval;
649 }
650
SocketLocalServer(const std::string & name,bool abstract,int in_type,mode_t mode)651 SharedFD SharedFD::SocketLocalServer(const std::string& name, bool abstract,
652 int in_type, mode_t mode) {
653 // DO NOT UNLINK addr.sun_path. It does NOT have to be null-terminated.
654 // See man 7 unix for more details.
655 if (!abstract) {
656 (void)unlink(name.c_str());
657 }
658
659 struct sockaddr_un addr;
660 socklen_t addrlen;
661 MakeAddress(name.c_str(), abstract, &addr, &addrlen);
662 SharedFD rval = SharedFD::Socket(PF_UNIX, in_type, 0);
663 if (!rval->IsOpen()) {
664 return rval;
665 }
666
667 int n = 1;
668 if (rval->SetSockOpt(SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1) {
669 LOG(ERROR) << "SetSockOpt failed " << rval->StrError();
670 return SharedFD::ErrorFD(rval->GetErrno());
671 }
672 if (rval->Bind(reinterpret_cast<sockaddr*>(&addr), addrlen) == -1) {
673 LOG(ERROR) << "Bind failed; name=" << name << ": " << rval->StrError();
674 return SharedFD::ErrorFD(rval->GetErrno());
675 }
676
677 /* Only the bottom bits are really the socket type; there are flags too. */
678 constexpr int SOCK_TYPE_MASK = 0xf;
679 auto socket_type = in_type & SOCK_TYPE_MASK;
680
681 // Connection oriented sockets: start listening.
682 if (socket_type == SOCK_STREAM || socket_type == SOCK_SEQPACKET) {
683 // Follows the default from socket_local_server
684 if (rval->Listen(1) == -1) {
685 LOG(ERROR) << "Listen failed: " << rval->StrError();
686 return SharedFD::ErrorFD(rval->GetErrno());
687 }
688 }
689
690 if (!abstract) {
691 if (TEMP_FAILURE_RETRY(chmod(name.c_str(), mode)) == -1) {
692 LOG(ERROR) << "chmod failed: " << strerror(errno);
693 // However, continue since we do have a listening socket
694 }
695 }
696 return rval;
697 }
698
699 #ifdef __linux__
VsockServer(unsigned int port,int type,std::optional<int> vhost_user_vsock_listening_cid,unsigned int cid)700 SharedFD SharedFD::VsockServer(
701 unsigned int port, int type,
702 std::optional<int> vhost_user_vsock_listening_cid, unsigned int cid) {
703 #ifndef CUTTLEFISH_HOST
704 CHECK(!vhost_user_vsock_listening_cid)
705 << "vhost_user_vsock_listening_cid is supposed to be nullopt in the "
706 "guest";
707 #endif
708 if (vhost_user_vsock_listening_cid) {
709 // TODO(b/277909042): better path than /tmp/vsock_{}/vm.vsock_{}
710 return SharedFD::SocketLocalServer(
711 fmt::format("/tmp/vsock_{}_{}/vm.vsock_{}",
712 *vhost_user_vsock_listening_cid, std::to_string(getuid()),
713 port),
714 false /* abstract */, type, 0666 /* mode */);
715 }
716
717 auto vsock = SharedFD::Socket(AF_VSOCK, type, 0);
718 if (!vsock->IsOpen()) {
719 return vsock;
720 }
721 sockaddr_vm addr{};
722 addr.svm_family = AF_VSOCK;
723 addr.svm_port = port;
724 addr.svm_cid = cid;
725 auto casted_addr = reinterpret_cast<sockaddr*>(&addr);
726 if (vsock->Bind(casted_addr, sizeof(addr)) == -1) {
727 LOG(ERROR) << "Port " << port << " Bind failed (" << vsock->StrError()
728 << ")";
729 return SharedFD::ErrorFD(vsock->GetErrno());
730 }
731 if (type == SOCK_STREAM || type == SOCK_SEQPACKET) {
732 if (vsock->Listen(4) < 0) {
733 LOG(ERROR) << "Port" << port << " Listen failed (" << vsock->StrError()
734 << ")";
735 return SharedFD::ErrorFD(vsock->GetErrno());
736 }
737 }
738 return vsock;
739 }
740
VsockServer(int type,std::optional<int> vhost_user_vsock_listening_cid)741 SharedFD SharedFD::VsockServer(
742 int type, std::optional<int> vhost_user_vsock_listening_cid) {
743 return VsockServer(VMADDR_PORT_ANY, type, vhost_user_vsock_listening_cid);
744 }
745
VsockClient(unsigned int cid,unsigned int port,int type,bool vhost_user)746 SharedFD SharedFD::VsockClient(unsigned int cid, unsigned int port, int type,
747 bool vhost_user) {
748 #ifndef CUTTLEFISH_HOST
749 CHECK(!vhost_user) << "vhost_user is supposed to be false in the guest";
750 #endif
751 if (vhost_user) {
752 // TODO(b/277909042): better path than /tmp/vsock_{}/vm.vsock
753 auto client = SharedFD::SocketLocalClient(
754 fmt::format("/tmp/vsock_{}_{}/vm.vsock", cid, std::to_string(getuid())),
755 false /* abstract */, type);
756 const std::string msg = fmt::format("connect {}\n", port);
757 SendAll(client, msg);
758
759 const std::string expected_res = fmt::format("OK {}\n", port);
760 std::string actual_res(expected_res.length(), ' ');
761 if (ReadExact(client, &actual_res) != expected_res.length()) {
762 client->Close();
763 LOG(ERROR) << "cannot connect to " << cid << ":" << port;
764 return client;
765 }
766 if (actual_res != expected_res) {
767 client->Close();
768 LOG(ERROR) << "response from server: " << actual_res << ", but expect "
769 << expected_res;
770 return client;
771 }
772 return client;
773 }
774 auto vsock = SharedFD::Socket(AF_VSOCK, type, 0);
775 if (!vsock->IsOpen()) {
776 return vsock;
777 }
778 sockaddr_vm addr{};
779 addr.svm_family = AF_VSOCK;
780 addr.svm_port = port;
781 addr.svm_cid = cid;
782 auto casted_addr = reinterpret_cast<sockaddr*>(&addr);
783 if (vsock->Connect(casted_addr, sizeof(addr)) == -1) {
784 return SharedFD::ErrorFD(vsock->GetErrno());
785 }
786 return vsock;
787 }
788 #endif
789
lock() const790 SharedFD WeakFD::lock() const {
791 auto locked_file_instance = value_.lock();
792 if (locked_file_instance) {
793 return SharedFD(locked_file_instance);
794 }
795 return SharedFD();
796 }
797
ScopedMMap(void * ptr,size_t len)798 ScopedMMap::ScopedMMap(void* ptr, size_t len) : ptr_(ptr), len_(len) {}
799
ScopedMMap()800 ScopedMMap::ScopedMMap() : ptr_(MAP_FAILED), len_(0) {}
801
ScopedMMap(ScopedMMap && other)802 ScopedMMap::ScopedMMap(ScopedMMap&& other)
803 : ptr_(other.ptr_), len_(other.len_) {
804 other.ptr_ = MAP_FAILED;
805 other.len_ = 0;
806 }
807
~ScopedMMap()808 ScopedMMap::~ScopedMMap() {
809 if (ptr_ != MAP_FAILED) {
810 munmap(ptr_, len_);
811 }
812 }
813
ClosedInstance()814 /* static */ std::shared_ptr<FileInstance> FileInstance::ClosedInstance() {
815 return std::shared_ptr<FileInstance>(new FileInstance(-1, EBADF));
816 }
817
Bind(const struct sockaddr * addr,socklen_t addrlen)818 int FileInstance::Bind(const struct sockaddr* addr, socklen_t addrlen) {
819 errno = 0;
820 int rval = bind(fd_, addr, addrlen);
821 errno_ = errno;
822 return rval;
823 }
824
Connect(const struct sockaddr * addr,socklen_t addrlen)825 int FileInstance::Connect(const struct sockaddr* addr, socklen_t addrlen) {
826 errno = 0;
827 int rval = connect(fd_, addr, addrlen);
828 errno_ = errno;
829 return rval;
830 }
831
UNMANAGED_Dup()832 int FileInstance::UNMANAGED_Dup() {
833 errno = 0;
834 int rval = TEMP_FAILURE_RETRY(dup(fd_));
835 errno_ = errno;
836 return rval;
837 }
838
UNMANAGED_Dup2(int newfd)839 int FileInstance::UNMANAGED_Dup2(int newfd) {
840 errno = 0;
841 int rval = TEMP_FAILURE_RETRY(dup2(fd_, newfd));
842 errno_ = errno;
843 return rval;
844 }
845
Fcntl(int command,int value)846 int FileInstance::Fcntl(int command, int value) {
847 errno = 0;
848 int rval = TEMP_FAILURE_RETRY(fcntl(fd_, command, value));
849 errno_ = errno;
850 return rval;
851 }
852
Fsync()853 int FileInstance::Fsync() {
854 errno = 0;
855 int rval = TEMP_FAILURE_RETRY(fsync(fd_));
856 errno_ = errno;
857 return rval;
858 }
859
Flock(int operation)860 Result<void> FileInstance::Flock(int operation) {
861 errno = 0;
862 int rval = TEMP_FAILURE_RETRY(flock(fd_, operation));
863 errno_ = errno;
864 CF_EXPECT(rval == 0, StrError());
865 return {};
866 }
867
GetSockName(struct sockaddr * addr,socklen_t * addrlen)868 int FileInstance::GetSockName(struct sockaddr* addr, socklen_t* addrlen) {
869 errno = 0;
870 int rval = TEMP_FAILURE_RETRY(getsockname(fd_, addr, addrlen));
871 if (rval == -1) {
872 errno_ = errno;
873 }
874 return rval;
875 }
876
877 #ifdef __linux__
VsockServerPort()878 unsigned int FileInstance::VsockServerPort() {
879 struct sockaddr_vm vm_socket;
880 socklen_t length = sizeof(vm_socket);
881 GetSockName(reinterpret_cast<struct sockaddr*>(&vm_socket), &length);
882 return vm_socket.svm_port;
883 }
884 #endif
885
Ioctl(int request,void * val)886 int FileInstance::Ioctl(int request, void* val) {
887 errno = 0;
888 int rval = TEMP_FAILURE_RETRY(ioctl(fd_, request, val));
889 errno_ = errno;
890 return rval;
891 }
892
LinkAtCwd(const std::string & path)893 int FileInstance::LinkAtCwd(const std::string& path) {
894 std::string name = "/proc/self/fd/";
895 name += std::to_string(fd_);
896 errno = 0;
897 int rval =
898 linkat(-1, name.c_str(), AT_FDCWD, path.c_str(), AT_SYMLINK_FOLLOW);
899 errno_ = errno;
900 return rval;
901 }
902
Listen(int backlog)903 int FileInstance::Listen(int backlog) {
904 errno = 0;
905 int rval = listen(fd_, backlog);
906 errno_ = errno;
907 return rval;
908 }
909
LSeek(off_t offset,int whence)910 off_t FileInstance::LSeek(off_t offset, int whence) {
911 errno = 0;
912 off_t rval = TEMP_FAILURE_RETRY(lseek(fd_, offset, whence));
913 errno_ = errno;
914 return rval;
915 }
916
Recv(void * buf,size_t len,int flags)917 ssize_t FileInstance::Recv(void* buf, size_t len, int flags) {
918 errno = 0;
919 ssize_t rval = TEMP_FAILURE_RETRY(recv(fd_, buf, len, flags));
920 errno_ = errno;
921 return rval;
922 }
923
RecvMsg(struct msghdr * msg,int flags)924 ssize_t FileInstance::RecvMsg(struct msghdr* msg, int flags) {
925 errno = 0;
926 ssize_t rval = TEMP_FAILURE_RETRY(recvmsg(fd_, msg, flags));
927 errno_ = errno;
928 return rval;
929 }
930
Read(void * buf,size_t count)931 ssize_t FileInstance::Read(void* buf, size_t count) {
932 errno = 0;
933 ssize_t rval = TEMP_FAILURE_RETRY(read(fd_, buf, count));
934 errno_ = errno;
935 return rval;
936 }
937
938 #ifdef __linux__
EventfdRead(eventfd_t * value)939 int FileInstance::EventfdRead(eventfd_t* value) {
940 errno = 0;
941 auto rval = eventfd_read(fd_, value);
942 errno_ = errno;
943 return rval;
944 }
945 #endif
946
Send(const void * buf,size_t len,int flags)947 ssize_t FileInstance::Send(const void* buf, size_t len, int flags) {
948 errno = 0;
949 ssize_t rval = TEMP_FAILURE_RETRY(send(fd_, buf, len, flags));
950 errno_ = errno;
951 return rval;
952 }
953
SendMsg(const struct msghdr * msg,int flags)954 ssize_t FileInstance::SendMsg(const struct msghdr* msg, int flags) {
955 errno = 0;
956 ssize_t rval = TEMP_FAILURE_RETRY(sendmsg(fd_, msg, flags));
957 errno_ = errno;
958 return rval;
959 }
960
Shutdown(int how)961 int FileInstance::Shutdown(int how) {
962 errno = 0;
963 int rval = shutdown(fd_, how);
964 errno_ = errno;
965 return rval;
966 }
967
SetSockOpt(int level,int optname,const void * optval,socklen_t optlen)968 int FileInstance::SetSockOpt(int level, int optname, const void* optval,
969 socklen_t optlen) {
970 errno = 0;
971 int rval = setsockopt(fd_, level, optname, optval, optlen);
972 errno_ = errno;
973 return rval;
974 }
975
GetSockOpt(int level,int optname,void * optval,socklen_t * optlen)976 int FileInstance::GetSockOpt(int level, int optname, void* optval,
977 socklen_t* optlen) {
978 errno = 0;
979 int rval = getsockopt(fd_, level, optname, optval, optlen);
980 errno_ = errno;
981 return rval;
982 }
983
SetTerminalRaw()984 int FileInstance::SetTerminalRaw() {
985 errno = 0;
986 termios terminal_settings;
987 int rval = tcgetattr(fd_, &terminal_settings);
988 errno_ = errno;
989 if (rval < 0) {
990 return rval;
991 }
992 cfmakeraw(&terminal_settings);
993 rval = tcsetattr(fd_, TCSANOW, &terminal_settings);
994 errno_ = errno;
995 if (rval < 0) {
996 return rval;
997 }
998
999 // tcsetattr() success if any of the requested change success.
1000 // So double check whether everything is applied.
1001 termios raw_settings;
1002 rval = tcgetattr(fd_, &raw_settings);
1003 errno_ = errno;
1004 if (rval < 0) {
1005 return rval;
1006 }
1007 if (memcmp(&terminal_settings, &raw_settings, sizeof(terminal_settings))) {
1008 errno_ = EPROTO;
1009 return -1;
1010 }
1011 return rval;
1012 }
1013
StrError() const1014 std::string FileInstance::StrError() const {
1015 errno = 0;
1016 return std::string(strerror(errno_));
1017 }
1018
MMap(void * addr,size_t length,int prot,int flags,off_t offset)1019 ScopedMMap FileInstance::MMap(void* addr, size_t length, int prot, int flags,
1020 off_t offset) {
1021 errno = 0;
1022 auto ptr = mmap(addr, length, prot, flags, fd_, offset);
1023 errno_ = errno;
1024 return ScopedMMap(ptr, length);
1025 }
1026
Truncate(off_t length)1027 ssize_t FileInstance::Truncate(off_t length) {
1028 errno = 0;
1029 ssize_t rval = TEMP_FAILURE_RETRY(ftruncate(fd_, length));
1030 errno_ = errno;
1031 return rval;
1032 }
1033
Write(const void * buf,size_t count)1034 ssize_t FileInstance::Write(const void* buf, size_t count) {
1035 if (count == 0 && !IsRegular()) {
1036 return 0;
1037 }
1038 errno = 0;
1039 ssize_t rval = TEMP_FAILURE_RETRY(write(fd_, buf, count));
1040 errno_ = errno;
1041 return rval;
1042 }
1043
1044 #ifdef __linux__
EventfdWrite(eventfd_t value)1045 int FileInstance::EventfdWrite(eventfd_t value) {
1046 errno = 0;
1047 int rval = eventfd_write(fd_, value);
1048 errno_ = errno;
1049 return rval;
1050 }
1051 #endif
1052
IsATTY()1053 bool FileInstance::IsATTY() {
1054 errno = 0;
1055 int rval = isatty(fd_);
1056 errno_ = errno;
1057 return rval;
1058 }
1059
Futimens(const struct timespec times[2])1060 int FileInstance::Futimens(const struct timespec times[2]) {
1061 errno = 0;
1062 int rval = TEMP_FAILURE_RETRY(futimens(fd_, times));
1063 errno_ = errno;
1064 return rval;
1065 }
1066
1067 #ifdef __linux__
ProcFdLinkTarget() const1068 Result<std::string> FileInstance::ProcFdLinkTarget() const {
1069 std::stringstream output_composer;
1070 output_composer << "/proc/" << getpid() << "/fd/" << fd_;
1071 const std::string mem_fd_link = output_composer.str();
1072 std::string mem_fd_target;
1073 CF_EXPECT(
1074 android::base::Readlink(mem_fd_link, &mem_fd_target),
1075 "Getting link for the memory file \"" << mem_fd_link << "\" failed");
1076 return mem_fd_target;
1077 }
1078 #endif
1079
1080 // inotify related functions
InotifyAddWatch(const std::string & pathname,uint32_t mask)1081 int FileInstance::InotifyAddWatch(const std::string& pathname, uint32_t mask) {
1082 return inotify_add_watch(fd_, pathname.c_str(), mask);
1083 }
1084
InotifyRmWatch(int watch)1085 void FileInstance::InotifyRmWatch(int watch) {
1086 inotify_rm_watch(fd_, watch);
1087 }
1088
FileInstance(int fd,int in_errno)1089 FileInstance::FileInstance(int fd, int in_errno)
1090 : fd_(fd), errno_(in_errno), is_regular_file_(IsRegularFile(fd_)) {
1091 // Ensure every file descriptor managed by a FileInstance has the CLOEXEC
1092 // flag
1093 TEMP_FAILURE_RETRY(fcntl(fd, F_SETFD, FD_CLOEXEC));
1094 std::stringstream identity;
1095 identity << "fd=" << fd << " @" << this;
1096 identity_ = identity.str();
1097 }
1098
Accept(struct sockaddr * addr,socklen_t * addrlen) const1099 FileInstance* FileInstance::Accept(struct sockaddr* addr,
1100 socklen_t* addrlen) const {
1101 int fd = TEMP_FAILURE_RETRY(accept(fd_, addr, addrlen));
1102 if (fd == -1) {
1103 return new FileInstance(fd, errno);
1104 } else {
1105 return new FileInstance(fd, 0);
1106 }
1107 }
1108
1109 } // namespace cuttlefish
1110